Merge M19 cut time and cutting simulation into the Avalonia port work

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	OpenNest.Avalonia/MainWindow.axaml
This commit is contained in:
aj committed 2026-11-30 18:56:49 -05:00
commit a85b0cc45f
25 files changed
+2371 -299

No files matched your search

@@ -0,0 +1,301 @@
using System.Collections.Generic;
using OpenNest.CNC;
using OpenNest.CutOffs;
using OpenNest.Desktop.Interaction;
using OpenNest.Geometry;
using OpenNest.Math;
using SkiaSharp;
namespace OpenNest.Avalonia.Controls
{
/// <summary>
/// Plate &gt; Simulate Cutting over the plate, as the WinForms cut simulation overlay: the cut
/// trail grows behind the torch, travel is traced faintly in dashes, and parts (and cut-off
/// segments) the torch has not reached yet are drawn muted. Display only; the shared
/// <see cref="CutSimulationPlayback"/> holds the playhead.
/// </summary>
public sealed partial class PlateCanvas
{
// The finished trail is kept in world-space chunks of this many moves, built once each,
// so a frame only rebuilds the moves since the last full chunk.
private const int TrailChunkSize = 256;
private CutSimulationPlayback cutSimulation;
private SimulationTrail simulationTrail;
/// <summary>The playhead drawn over the plate, or null when not simulating.</summary>
public CutSimulationPlayback CutSimulation
{
get => cutSimulation;
set
{
cutSimulation = value;
simulationTrail = null;
InvalidateVisual();
}
}
// True for a part the torch has not started yet.
private bool IsPartPending(int partIndex) => cutSimulation?.IsPartPending(partIndex) == true;
// While simulating, each of the cut-off's trimmed segments is its own part, found by its
// drawing's reference, and mutes until the torch reaches it. False when not simulating.
private bool BuildSimulatedCutOff(Scene scene, CutOff cutOff)
{
if (cutSimulation?.IsActive != true)
return false;
for (var i = 0; i < plate.Parts.Count; i++)
{
var part = plate.Parts[i];
if (!ReferenceEquals(part.BaseDrawing, cutOff.Drawing))
continue;
var strokes = IsPartPending(i) ? scene.MutedCutOffStrokes : scene.CutOffStrokes;
strokes.AddRange(CutOff.CutStrokes(part.Program, part.Location));
}
return true;
}
private void BuildSimulation(Scene scene)
{
if (cutSimulation?.Simulation is not { Steps.Count: > 0 } sim)
return;
var time = cutSimulation.Time;
var index = sim.IndexAt(time);
var finished = System.Math.Clamp(index, 0, sim.Steps.Count);
if (simulationTrail == null || !ReferenceEquals(simulationTrail.Simulation, sim))
simulationTrail = new SimulationTrail(sim);
scene.Trail = simulationTrail.Chunks(finished);
if (index >= sim.Steps.Count)
{
scene.Head = new SimulationHead(sim.Steps[^1].End, null, 0);
return;
}
var step = sim.Steps[index];
var fraction = sim.FractionAt(index, time);
if (step.Kind != CutSimulationStepKind.Pierce && fraction > 0)
{
var path = new SKPath();
path.MoveTo((float)step.Start.X, (float)step.Start.Y);
AddMove(path, step, fraction);
scene.Current = (path, step.Kind);
}
scene.Head = new SimulationHead(step.PointAt(fraction), step.Kind, fraction);
}
// A move from where the path stands, cut short at fraction of its length. Arcs go in no
// more than half a turn at a time, so a full circle stays a circle.
private static void AddMove(SKPath path, CutSimulationStep step, double fraction)
{
if (!step.IsArc || step.Radius <= Tolerance.Epsilon)
{
var end = fraction >= 1 ? step.End : step.PointAt(fraction);
path.LineTo((float)end.X, (float)end.Y);
return;
}
var oval = new SKRect((float)(step.Center.X - step.Radius), (float)(step.Center.Y - step.Radius),
(float)(step.Center.X + step.Radius), (float)(step.Center.Y + step.Radius));
var sweep = step.Sweep * fraction;
var pieces = System.Math.Max(1, (int)System.Math.Ceiling(System.Math.Abs(sweep) / System.Math.PI));
for (var i = 0; i < pieces; i++)
{
var start = step.StartAngle + sweep * i / pieces;
path.ArcTo(oval, (float)Angle.ToDegrees(start), (float)Angle.ToDegrees(sweep / pieces), false);
}
}
private sealed record SimulationHead(Vector Location, CutSimulationStepKind? Kind, double Fraction);
/// <summary>One run of finished moves in world space: cuts, etches and travel apart.</summary>
private sealed class TrailChunk
{
public int Start;
public int End;
public readonly SKPath Cuts = new();
public readonly SKPath Scribes = new();
public readonly SKPath Travel = new();
}
/// <summary>
/// The finished moves of one timeline. Full chunks are built once and never changed, so
/// the render thread may draw them while the next frame is built.
/// </summary>
private sealed class SimulationTrail
{
private readonly List<TrailChunk> full = new();
public SimulationTrail(CutSimulation simulation)
{
Simulation = simulation;
}
public CutSimulation Simulation { get; }
/// <summary>The chunks drawing moves [0, <paramref name="finished"/>).</summary>
public IReadOnlyList<TrailChunk> Chunks(int finished)
{
// Scrubbing back drops the chunks past the playhead.
while (full.Count > 0 && full[^1].End > finished)
full.RemoveAt(full.Count - 1);
var built = full.Count == 0 ? 0 : full[^1].End;
while (built + TrailChunkSize <= finished)
{
full.Add(Build(built, built + TrailChunkSize));
built += TrailChunkSize;
}
var chunks = new List<TrailChunk>(full);
if (built < finished)
chunks.Add(Build(built, finished));
return chunks;
}
// Consecutive moves of a kind join into one figure, as the WinForms trail joins them.
private TrailChunk Build(int from, int to)
{
var chunk = new TrailChunk { Start = from, End = to };
int lastCut = -2, lastScribe = -2, lastTravel = -2;
for (var i = from; i < to; i++)
{
var step = Simulation.Steps[i];
switch (step.Kind)
{
case CutSimulationStepKind.Pierce:
continue;
case CutSimulationStepKind.Cut:
Add(chunk.Cuts, step, i, ref lastCut);
break;
case CutSimulationStepKind.Scribe:
Add(chunk.Scribes, step, i, ref lastScribe);
break;
default:
Add(chunk.Travel, step, i, ref lastTravel);
break;
}
}
return chunk;
}
private static void Add(SKPath path, CutSimulationStep step, int index, ref int last)
{
if (last != index - 1)
path.MoveTo((float)step.Start.X, (float)step.Start.Y);
last = index;
AddMove(path, step, 1);
}
}
private sealed partial class Scene
{
public readonly List<Line> MutedCutOffStrokes = new();
public IReadOnlyList<TrailChunk> Trail;
public (SKPath Path, CutSimulationStepKind Kind)? Current;
public SimulationHead Head;
}
private sealed partial class PlatePainter
{
private static readonly SKColor MutedFill = new(220, 220, 220); // Gainsboro
private static readonly SKColor MutedLine = new(128, 128, 128); // Gray
private static readonly SKColor MutedLabel = new(105, 105, 105); // DimGray
private static readonly SKColor TrailRapid = new(70, 150, 255, 150);
private static readonly SKColor TrailGlow = new(255, 140, 0, 70);
private static readonly SKColor TrailCut = new(255, 69, 0); // OrangeRed
private static readonly SKColor TrailScribe = new(186, 85, 211); // MediumOrchid
private static readonly SKColor HeadTravel = new(30, 144, 255); // DodgerBlue
private static readonly SKColor HeadGlow = new(255, 165, 0, 90); // Orange
private static readonly SKColor PierceRing = new(255, 215, 0); // Gold
private void DrawMutedCutOffs()
{
if (scene.MutedCutOffStrokes.Count == 0)
return;
using var pen = Stroke(MutedLine, 2, new float[] { 6, 2 });
foreach (var stroke in scene.MutedCutOffStrokes)
canvas.DrawLine(Screen(stroke.StartPoint), Screen(stroke.EndPoint), pen);
}
private void DrawSimulation()
{
if (scene.Head == null)
return;
using var rapid = WorldStroke(TrailRapid, 1, new float[] { 3, 1 });
using var glow = RoundStroke(TrailGlow, 6);
using var cut = RoundStroke(TrailCut, 2);
using var scribe = WorldStroke(TrailScribe, 1.5f);
canvas.Save();
canvas.Concat(ref matrix);
if (scene.Trail != null)
{
foreach (var chunk in scene.Trail)
canvas.DrawPath(chunk.Travel, rapid);
foreach (var chunk in scene.Trail)
{
canvas.DrawPath(chunk.Cuts, glow);
canvas.DrawPath(chunk.Cuts, cut);
}
foreach (var chunk in scene.Trail)
canvas.DrawPath(chunk.Scribes, scribe);
}
if (scene.Current is { } current)
{
switch (current.Kind)
{
case CutSimulationStepKind.Cut:
canvas.DrawPath(current.Path, glow);
canvas.DrawPath(current.Path, cut);
break;
case CutSimulationStepKind.Scribe:
canvas.DrawPath(current.Path, scribe);
break;
default:
canvas.DrawPath(current.Path, rapid);
break;
}
}
canvas.Restore();
DrawHead(scene.Head);
}
private SKPaint RoundStroke(SKColor color, float width)
{
var paint = WorldStroke(color, width);
paint.StrokeJoin = SKStrokeJoin.Round;
paint.StrokeCap = SKStrokeCap.Round;
return paint;
}
// The torch: a ringed crosshair, glowing while it cuts, with a fading ring while it pierces.
private void DrawHead(SimulationHead head)
{
var center = Screen(head.Location);
var color = head.Kind switch
{
CutSimulationStepKind.Cut or CutSimulationStepKind.Pierce => TrailCut,
CutSimulationStepKind.Scribe => TrailScribe,
_ => HeadTravel,
};
if (head.Kind == CutSimulationStepKind.Pierce)
{
var ring = 4 + 14 * (float)head.Fraction;
using var piercePen = Stroke(PierceRing.WithAlpha((byte)(255 * (1 - head.Fraction))), 2);
canvas.DrawCircle(center, ring, piercePen);
}
if (head.Kind is CutSimulationStepKind.Cut or CutSimulationStepKind.Pierce)
{
using var glowFill = Fill(HeadGlow);
canvas.DrawCircle(center, 9, glowFill);
}
const float radius = 5;
using var halo = Stroke(SKColors.White, 3);
using var pen = Stroke(color, 1.5f);
canvas.DrawCircle(center, radius, halo);
canvas.DrawCircle(center, radius, pen);
canvas.DrawLine(center.X - radius * 1.8f, center.Y, center.X + radius * 1.8f, center.Y, pen);
canvas.DrawLine(center.X, center.Y - radius * 1.8f, center.X, center.Y + radius * 1.8f, pen);
}
}
}
}
+18 -5
View File
@@ -347,7 +347,7 @@ namespace OpenNest.Avalonia.Controls
var color = ToSkColor(part.BaseDrawing.Color);
scene.Parts.Add(new PartItem(partPaths, part.Location, placed, color, palette.PartOutline(color),
(i + 1).ToString(), LabelPoint(part), selection.Contains(part),
ReferenceEquals(part, HoveredPart), part.BaseDrawing.IsCutOff));
ReferenceEquals(part, HoveredPart), part.BaseDrawing.IsCutOff, IsPartPending(i)));
}
// The place tool's copies, drawn selected and unnumbered over the plate, as WinForms.
if (tools.Current is PlaceTool { Previews: var previews })
@@ -361,7 +361,7 @@ namespace OpenNest.Avalonia.Controls
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));
Hovered: false, IsCutOff: false, Muted: false));
}
}
@@ -387,6 +387,7 @@ namespace OpenNest.Avalonia.Controls
BuildCommonLines(scene);
if (options.DrawSupport)
BuildSupport(scene);
BuildSimulation(scene);
BuildToolOverlays(scene);
BuildCutOffToolOverlays(scene);
}
@@ -399,6 +400,8 @@ namespace OpenNest.Avalonia.Controls
var program = cutOff.Drawing?.Program;
if (program == null || program.Codes.Count == 0)
continue;
if (!selection.Contains(cutOff) && BuildSimulatedCutOff(scene, cutOff))
continue;
var strokes = selection.Contains(cutOff) ? scene.SelectedCutOffStrokes : scene.CutOffStrokes;
strokes.AddRange(CutOff.CutStrokes(program, Vector.Zero));
}
@@ -695,7 +698,7 @@ namespace OpenNest.Avalonia.Controls
}
private sealed record PartItem(PartPaths Paths, Vector Location, Box Bounds, SKColor Color, SKColor Outline,
string Label, Vector LabelPoint, bool Selected, bool Hovered, bool IsCutOff);
string Label, Vector LabelPoint, bool Selected, bool Hovered, bool IsCutOff, bool Muted);
private sealed record SupportItem(IReadOnlyList<Vector> Contacts, Vector CenterOfGravity, bool Supported,
Vector? Tab);
@@ -868,9 +871,11 @@ namespace OpenNest.Avalonia.Controls
DrawPiercePoints();
DrawCutDirection();
DrawClamps();
DrawMutedCutOffs();
DrawCutOffs();
DrawCommonLines();
DrawSupport();
DrawSimulation();
DrawSelectionWindow();
DrawCutOffToolOverlays();
DrawToolOverlays();
@@ -977,16 +982,22 @@ namespace OpenNest.Avalonia.Controls
canvas.Concat(ref matrix);
canvas.Translate((float)item.Location.X, (float)item.Location.Y);
fill.Color = item.Selected ? palette.SelectedFill
// A part the cut simulation has not reached yet is drawn muted, in grays.
fill.Color = item.Muted ? MutedFill
: item.Selected ? palette.SelectedFill
: item.Hovered ? Lighten(item.Color) : item.Color;
canvas.DrawPath(item.Paths.Material, fill);
display.Color = item.Muted ? MutedLine : DisplayColor;
if (item.Paths.Display != null)
canvas.DrawPath(item.Paths.Display, display);
etch.Color = item.Muted ? MutedLine : palette.Etch;
canvas.DrawPath(item.Paths.Etch, etch);
// Keep real cuts visible even where an etch overlaps them.
cut.Color = item.Selected ? palette.SelectedOutline : item.Outline;
cut.Color = item.Muted ? MutedLine
: item.Selected ? palette.SelectedOutline : item.Outline;
canvas.DrawPath(item.Paths.Cut, cut);
// As on the desktop, only manually placed lead-ins are shown.
lead.Color = item.Muted ? MutedLine : LeadColor;
canvas.DrawPath(item.Paths.Lead, lead);
canvas.Restore();
@@ -999,6 +1010,7 @@ namespace OpenNest.Avalonia.Controls
continue;
var at = Screen(item.LabelPoint);
var baseline = at.Y - (metrics.Ascent + metrics.Descent) / 2;
text.Color = underline.Color = item.Muted ? MutedLabel : SKColors.Black;
canvas.DrawText(item.Label, at.X, baseline, text);
var lineY = baseline + System.Math.Max(1, metrics.UnderlinePosition ?? 1.5f);
canvas.DrawLine(at.X - width / 2, lineY, at.X + width / 2, lineY, underline);
@@ -1115,6 +1127,7 @@ namespace OpenNest.Avalonia.Controls
if (System.Math.Max(bounds.Width, bounds.Height) < diameter)
continue;
var at = Screen(item.LabelPoint);
disc.Color = item.Muted ? MutedLine : CutOffColor;
canvas.DrawCircle(at, diameter / 2, disc);
canvas.DrawText(item.Label, at.X, at.Y - (metrics.Ascent + metrics.Descent) / 2, text);
}
+375
View File
@@ -0,0 +1,375 @@
using System;
using System.Collections.Generic;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
using Avalonia.VisualTree;
using OpenNest.CNC;
using OpenNest.Data;
using OpenNest.Desktop;
using OpenNest.Desktop.Interaction;
namespace OpenNest.Avalonia
{
/// <summary>
/// Plate &gt; Simulate Cutting's playback controls, as the WinForms Cut Simulator: play and
/// pause at a speed, restart and end, step by part or cutout (and by move with the arrow
/// keys), scrub, and the time, part, drawing and motion at the playhead. The feeds, pierce,
/// acceleration and etch choice retime the cut as they change and are remembered on close.
/// Follows the nest's shown plate; the shared <see cref="CutSimulationPlayback"/> holds the
/// playhead and the plate view draws it.
/// </summary>
internal sealed class CutSimulatorWindow : Window
{
private const int TrackResolution = 1000;
private readonly NestView view;
private readonly CutSimulationPlayback playback = new();
private readonly DispatcherTimer timer = new() { Interval = TimeSpan.FromMilliseconds(30) };
private readonly Button playButton;
private readonly ComboBox speedBox;
private readonly Slider track;
private readonly TextBlock timeText, partText, drawingText, motionText;
private readonly NumberField feed, holeFeed, rapid, pierce;
private readonly ComboBox machineBox;
private readonly CheckBox skipEtch;
private readonly Units units;
private Plate plate;
private bool updatingTrack;
private bool rebuildQueued;
public CutSimulatorWindow(NestView view, IReadOnlyList<MachineConfig> machines)
{
this.view = view;
units = view.Tab.Document.Nest.Units;
Title = "Cut Simulator";
SizeToContent = SizeToContent.WidthAndHeight;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.Manual;
var restart = TransportButton("⏮", 44, 15, "Restart");
playButton = TransportButton("▶", 80, 22, "Play / pause (Space)");
playButton.Name = "Play";
var end = TransportButton("⏭", 44, 15, "Jump to end");
speedBox = new ComboBox { Name = "Speed", Width = 80, VerticalAlignment = VerticalAlignment.Center };
foreach (var speed in CutSimulationPlayback.Speeds)
speedBox.Items.Add(CutSimulationStatus.SpeedText(speed));
speedBox.SelectedIndex = CutSimulationPlayback.DefaultSpeedIndex;
var transport = Row(restart, playButton, end,
new TextBlock { Text = "Speed", VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(12, 0, 0, 0) },
speedBox);
var previousPart = JumpButton("◀◀ Part", "Back to the start of this part, or the part before (Page Up)");
var previousContour = JumpButton("◀ Cutout", "Back to the start of this cutout or perimeter, or the one before (Ctrl+Left)");
var nextContour = JumpButton("Cutout ▶", "Next cutout or perimeter (Ctrl+Right)");
var nextPart = JumpButton("Part ▶▶", "Next part (Page Down)");
var jumps = Row(previousPart, previousContour, nextContour, nextPart);
track = new Slider { Name = "Track", Minimum = 0, Maximum = TrackResolution, Focusable = true };
ToolTip.SetTip(track, "Drag to scrub through the cut (Left/Right step one move)");
timeText = new TextBlock { Name = "Time", FontWeight = FontWeight.Bold };
partText = new TextBlock { Name = "Part" };
// Two lines for long drawing names; longer ones trim and show in full on hover.
drawingText = new TextBlock
{
Name = "Drawing",
TextWrapping = TextWrapping.Wrap,
TextTrimming = TextTrimming.CharacterEllipsis,
MaxLines = 2,
};
motionText = new TextBlock { Name = "Motion" };
var status = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 8, RowSpacing = 2 };
AddStatusRow(status, 0, "Time", timeText);
AddStatusRow(status, 1, "Part", partText);
AddStatusRow(status, 2, "Drawing", drawingText);
AddStatusRow(status, 3, "Motion", motionText);
// Fixed width so changing text never resizes the window.
status.Width = 400;
status.HorizontalAlignment = HorizontalAlignment.Left;
var saved = CutTimeSettingsFile.Read();
var loaded = saved.ToCutParameters(units, SavedCutTimeSettings.ChooseMachine(machines, saved.Machine));
var rate = UnitsHelper.GetShortTimeUnitPair(units);
feed = new NumberField("Feed", loaded.Feedrate, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate, 0, rate, 130);
holeFeed = new NumberField("HoleFeed", loaded.HoleFeedrate ?? loaded.Feedrate, CutTimeEntry.MinimumRate,
CutTimeEntry.MaximumRate, 0, rate, 130);
rapid = new NumberField("Rapid", loaded.RapidTravelRate, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate, 0, rate, 130);
pierce = new NumberField("Pierce", loaded.PierceTime.TotalSeconds, 0, CutTimeEntry.SimulatorMaximumPierce, 1, "s", 130);
ToolTip.SetTip(feed.Box, "Feed for outside contours and cut-offs (the CI Fiber post's exterior, L4)");
ToolTip.SetTip(holeFeed.Box, "Feed for holes and other interior contours (the CI Fiber post's interior, L2)");
var rates = new Grid
{
ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto,Auto"),
RowDefinitions = new RowDefinitions("Auto,Auto"),
ColumnSpacing = 8,
RowSpacing = 6,
};
AddRate(rates, 0, 0, "Outside feed", feed);
AddRate(rates, 0, 2, "Hole feed", holeFeed);
AddRate(rates, 1, 0, "Rapid", rapid);
AddRate(rates, 1, 2, "Pierce", pierce);
var choices = CutTimeMachineChoice.For(machines);
machineBox = new ComboBox
{
Name = "Machine",
ItemsSource = choices,
SelectedIndex = CutTimeMachineChoice.SavedIndex(choices, saved.Machine),
MinWidth = 200,
VerticalAlignment = VerticalAlignment.Center,
};
ToolTip.SetTip(machineBox, "Machine whose acceleration limits time the moves (Tools > Machine Configuration)");
skipEtch = new CheckBox
{
Name = "SkipEtch",
Content = "Skip etch-only contours",
IsChecked = loaded.SkipScribe,
Margin = new Thickness(12, 0, 0, 0),
};
ToolTip.SetTip(skipEtch, "Leave out contours that only etch, as the CI Fiber post does by default");
var motion = Row(new TextBlock { Text = "Acceleration", VerticalAlignment = VerticalAlignment.Center },
machineBox, skipEtch);
var layout = new StackPanel { Margin = new Thickness(10), Spacing = 8 };
foreach (var part in new Control[] { transport, jumps, track, status, rates, motion })
layout.Children.Add(part);
Content = layout;
restart.Click += (_, _) => playback.Restart();
end.Click += (_, _) => playback.End();
playButton.Click += (_, _) => TogglePlay();
previousPart.Click += (_, _) => playback.PreviousPart();
previousContour.Click += (_, _) => playback.PreviousContour();
nextContour.Click += (_, _) => playback.NextContour();
nextPart.Click += (_, _) => playback.NextPart();
speedBox.SelectionChanged += (_, _) => ApplySpeed();
track.ValueChanged += (_, _) =>
{
if (!updatingTrack)
playback.Seek(track.Value / TrackResolution);
};
foreach (var field in new[] { feed, holeFeed, rapid, pierce })
field.Changed += (_, _) => Rebuild();
machineBox.SelectionChanged += (_, _) => Rebuild();
skipEtch.IsCheckedChanged += (_, _) => Rebuild();
timer.Tick += (_, _) => playback.Advance();
playback.Changed += OnPlaybackChanged;
ApplySpeed();
view.PlateView.CutSimulation = playback;
view.ViewChanged += OnViewChanged;
AttachPlate(view.PlateView.Plate);
Rebuild();
OnPlaybackChanged(this, EventArgs.Empty);
AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel);
Opened += (_, _) => PlaceAtOwnerCorner();
Closed += OnClosed;
}
/// <summary>The parameters the boxes time the cut with.</summary>
private CutParameters GetCutParameters() =>
CutTimeEntry.Parameters(feed.Value, holeFeed.Value, rapid.Value, pierce.Value, skipEtch.IsChecked == true,
units, (machineBox.SelectedItem as CutTimeMachineChoice)?.Machine);
private void ApplySpeed()
{
var index = System.Math.Clamp(speedBox.SelectedIndex, 0, CutSimulationPlayback.Speeds.Count - 1);
playback.Speed = CutSimulationPlayback.Speeds[index];
}
private void Rebuild()
{
if (plate == null)
{
playback.Clear();
return;
}
playback.Load(CutSimulation.Build(plate, GetCutParameters()));
}
// Parts may have moved since the timeline was built; moves raise no plate event.
private void TogglePlay() => playback.TogglePlay(Rebuild);
private void AttachPlate(Plate value)
{
if (plate != null)
{
plate.PartAdded -= OnPartsChanged;
plate.PartRemoved -= OnPartsChanged;
plate.PartsReordered -= OnPartsChanged;
}
plate = value;
if (plate != null)
{
plate.PartAdded += OnPartsChanged;
plate.PartRemoved += OnPartsChanged;
plate.PartsReordered += OnPartsChanged;
}
}
// A fill adds parts one at a time; rebuild once after the batch.
private void OnPartsChanged(object sender, EventArgs e)
{
if (rebuildQueued)
return;
rebuildQueued = true;
Dispatcher.UIThread.Post(() =>
{
rebuildQueued = false;
if (IsVisible)
Rebuild();
});
}
// The header's plate buttons stay live: the simulation follows the shown plate.
private void OnViewChanged(object sender, EventArgs e)
{
if (ReferenceEquals(view.PlateView.Plate, plate))
return;
AttachPlate(view.PlateView.Plate);
playback.Pause();
playback.Clear();
Rebuild();
}
private void OnPlaybackChanged(object sender, EventArgs e)
{
timer.IsEnabled = playback.IsPlaying;
playButton.Content = playback.IsPlaying ? "⏸" : "▶";
var status = CutSimulationStatus.For(playback, plate, units);
timeText.Text = status.Time;
partText.Text = status.Part;
drawingText.Text = status.Drawing;
ToolTip.SetTip(drawingText, string.IsNullOrEmpty(status.Drawing) ? null : status.Drawing);
motionText.Text = status.Motion;
updatingTrack = true;
track.Value = playback.Simulation is { Steps.Count: > 0 }
? System.Math.Round(TrackResolution * playback.Progress)
: 0;
updatingTrack = false;
view.PlateView.InvalidateVisual();
}
// As the WinForms simulator, while no number or list box has the keyboard: Escape
// closes, Space plays or pauses, Ctrl+arrows step cutouts, Page Up/Down parts, arrows
// moves and Home restarts.
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (FocusManager?.GetFocusedElement() is Visual focused && TakesKeys(focused))
return;
Action action = (e.Key, e.KeyModifiers) switch
{
(Key.Escape, KeyModifiers.None) => Close,
(Key.Space, KeyModifiers.None) => TogglePlay,
(Key.Right, KeyModifiers.Control) => playback.NextContour,
(Key.Left, KeyModifiers.Control) => playback.PreviousContour,
(Key.PageDown, KeyModifiers.None) => playback.NextPart,
(Key.PageUp, KeyModifiers.None) => playback.PreviousPart,
(Key.Right, KeyModifiers.None) => () => playback.StepMove(1),
(Key.Left, KeyModifiers.None) => () => playback.StepMove(-1),
(Key.Home, KeyModifiers.None) => playback.Restart,
_ => null,
};
if (action == null)
return;
e.Handled = true;
action();
}
private static bool TakesKeys(Visual focused)
{
for (var visual = focused; visual != null; visual = visual.GetVisualParent())
{
if (visual is NumericUpDown or ComboBox)
return true;
}
return false;
}
// Near the owner's bottom-right corner, over the plate, as WinForms places it.
private void PlaceAtOwnerCorner()
{
if (Owner is not Window owner)
return;
var scale = owner.DesktopScaling;
var corner = owner.PointToScreen(new Point(owner.ClientSize.Width, owner.ClientSize.Height));
var width = (int)(Bounds.Width * scale);
var height = (int)(Bounds.Height * scale);
Position = new PixelPoint(
System.Math.Max(owner.Position.X, corner.X - width - (int)(24 * scale)),
System.Math.Max(owner.Position.Y, corner.Y - height - (int)(48 * scale)));
}
private void OnClosed(object sender, EventArgs e)
{
CutTimeSettingsFile.Save(GetCutParameters(), (machineBox.SelectedItem as CutTimeMachineChoice)?.Machine);
timer.Stop();
playback.Changed -= OnPlaybackChanged;
playback.Clear();
view.ViewChanged -= OnViewChanged;
AttachPlate(null);
view.PlateView.CutSimulation = null;
}
private static Button TransportButton(string glyph, double width, double fontSize, string tip)
{
var button = new Button
{
Content = glyph,
Width = width,
Height = 40,
FontSize = fontSize,
HorizontalContentAlignment = HorizontalAlignment.Center,
VerticalContentAlignment = VerticalAlignment.Center,
Padding = new Thickness(0),
};
ToolTip.SetTip(button, tip);
return button;
}
private static Button JumpButton(string text, string tip)
{
var button = new Button { Content = text, MinWidth = 80, HorizontalContentAlignment = HorizontalAlignment.Center };
ToolTip.SetTip(button, tip);
return button;
}
private static StackPanel Row(params Control[] controls)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
foreach (var control in controls)
row.Children.Add(control);
return row;
}
private static void AddStatusRow(Grid grid, int row, string caption, TextBlock value)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
var label = new TextBlock { Text = caption, Foreground = Brushes.Gray };
Grid.SetRow(label, row);
grid.Children.Add(label);
Grid.SetRow(value, row);
Grid.SetColumn(value, 1);
grid.Children.Add(value);
}
private static void AddRate(Grid grid, int row, int column, string caption, NumberField field)
{
var label = new TextBlock { Text = caption, VerticalAlignment = VerticalAlignment.Center };
Grid.SetRow(label, row);
Grid.SetColumn(label, column);
grid.Children.Add(label);
Grid.SetRow(field.View, row);
Grid.SetColumn(field.View, column + 1);
grid.Children.Add(field.View);
}
}
}
+204
View File
@@ -0,0 +1,204 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using OpenNest.Data;
using OpenNest.Desktop;
namespace OpenNest.Avalonia
{
/// <summary>
/// The cut-time values Calculate Cut Time asks for, as the WinForms Cut Parameters form:
/// outside feed, rapid, pierce time, hole feed, the machine whose acceleration times the
/// moves (or full speed) and whether etch-only contours are skipped. It opens with the values
/// last used here, in the WinForms app or in either simulator, and saves them however it
/// closes, as WinForms does.
/// </summary>
internal sealed class CutTimeDialog : Window
{
private readonly NumberField feed;
private readonly NumberField rapid;
private readonly NumberField pierce;
private readonly NumberField holeFeed;
private readonly ComboBox machineBox;
private readonly CheckBox skipEtch;
private readonly Units units;
private readonly bool saveSettings;
private CutTimeDialog(Units units, IReadOnlyList<MachineConfig> machines, bool saveSettings)
{
this.units = units;
this.saveSettings = saveSettings;
Title = "Cut Parameters";
SizeToContent = SizeToContent.WidthAndHeight;
MinWidth = 380;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var saved = CutTimeSettingsFile.Read();
var choices = CutTimeMachineChoice.For(machines);
var loaded = saved.ToCutParameters(units, SavedCutTimeSettings.ChooseMachine(machines, saved.Machine));
var rate = UnitsHelper.GetShortTimeUnitPair(units);
feed = new NumberField("Feed", loaded.Feedrate, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate, 0, rate);
rapid = new NumberField("Rapid", loaded.RapidTravelRate, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate, 0, rate);
pierce = new NumberField("Pierce", loaded.PierceTime.TotalSeconds, 0, CutTimeEntry.DialogMaximumPierce, 1, "seconds");
holeFeed = new NumberField("HoleFeed", loaded.HoleFeedrate ?? loaded.Feedrate, CutTimeEntry.MinimumRate,
CutTimeEntry.MaximumRate, 0, rate);
machineBox = new ComboBox
{
Name = "Machine",
ItemsSource = choices,
SelectedIndex = CutTimeMachineChoice.SavedIndex(choices, saved.Machine),
HorizontalAlignment = HorizontalAlignment.Stretch,
};
skipEtch = new CheckBox { Name = "SkipEtch", Content = "Skip etch-only contours", IsChecked = loaded.SkipScribe };
var grid = new Grid
{
ColumnDefinitions = new ColumnDefinitions("Auto,*"),
RowDefinitions = new RowDefinitions("Auto,Auto,Auto,Auto,Auto,Auto"),
ColumnSpacing = 10,
RowSpacing = 8,
};
AddRow(grid, 0, "Outside feed :", feed.View);
AddRow(grid, 1, "Rapid Feedrate :", rapid.View);
AddRow(grid, 2, "Pierce Time :", pierce.View);
AddRow(grid, 3, "Hole feed :", holeFeed.View);
AddRow(grid, 4, "Acceleration :", machineBox);
Grid.SetRow(skipEtch, 5);
Grid.SetColumn(skipEtch, 1);
grid.Children.Add(skipEtch);
var accept = new Button { Name = "Accept", Content = "Accept", IsDefault = true, MinWidth = 80 };
accept.Click += (_, _) => Close(GetCutParameters());
var cancel = new Button { Name = "Cancel", Content = "Cancel", IsCancel = true, MinWidth = 80 };
cancel.Click += (_, _) => Close(null);
var buttons = new StackPanel
{
Orientation = Orientation.Horizontal,
Spacing = 8,
HorizontalAlignment = HorizontalAlignment.Right,
};
buttons.Children.Add(accept);
buttons.Children.Add(cancel);
var panel = new StackPanel { Margin = new Thickness(12), Spacing = 14 };
panel.Children.Add(grid);
panel.Children.Add(buttons);
Content = panel;
AddHandler(KeyDownEvent, (_, e) =>
{
if (e.Key != Key.Escape)
return;
e.Handled = true;
Close(null);
}, RoutingStrategies.Tunnel);
Opened += (_, _) => feed.Box.Focus();
// As WinForms: the values are remembered whether the dialog was accepted or not.
Closing += (_, _) =>
{
if (this.saveSettings)
CutTimeSettingsFile.Save(GetCutParameters(), Machine);
};
}
private MachineConfig Machine => (machineBox.SelectedItem as CutTimeMachineChoice)?.Machine;
private CutParameters GetCutParameters() =>
CutTimeEntry.Parameters(feed.Value, holeFeed.Value, rapid.Value, pierce.Value,
skipEtch.IsChecked == true, units, Machine);
private static void AddRow(Grid grid, int row, string label, Control field)
{
var text = new TextBlock { Text = label, VerticalAlignment = VerticalAlignment.Center };
Grid.SetRow(text, row);
grid.Children.Add(text);
Grid.SetRow(field, row);
Grid.SetColumn(field, 1);
grid.Children.Add(field);
}
/// <summary>
/// The parameters entered, in <paramref name="units"/>, or null when the dialog was
/// cancelled. <paramref name="saveSettings"/> false leaves the remembered values alone.
/// </summary>
public static Task<CutParameters> ShowAsync(
Window owner, Units units, IReadOnlyList<MachineConfig> machines, bool saveSettings = true) =>
new CutTimeDialog(units, machines, saveSettings).ShowDialog<CutParameters>(owner);
}
/// <summary>
/// A number box with its unit beside it, holding the last value typed when emptied and
/// keeping values within its range, as the WinForms boxes do.
/// </summary>
internal sealed class NumberField
{
private readonly decimal minimum;
private readonly decimal maximum;
private decimal last;
public NumberField(string name, double value, decimal minimum, decimal maximum, int decimals, string unit,
double width = 120)
{
this.minimum = minimum;
this.maximum = maximum;
last = CutTimeEntry.Clamp(value, minimum, maximum);
Box = new NumericUpDown
{
Name = name,
Minimum = minimum,
Maximum = maximum,
Increment = decimals == 0 ? 10 : 0.1m,
ClipValueToMinMax = true,
FormatString = decimals == 0 ? "0" : "0.0",
Value = last,
Width = width,
};
Box.ValueChanged += (_, e) =>
{
if (e.NewValue is not { } v)
return;
last = v;
Changed?.Invoke(this, EventArgs.Empty);
};
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
panel.Children.Add(Box);
panel.Children.Add(new TextBlock { Text = unit, VerticalAlignment = VerticalAlignment.Center });
View = panel;
}
public NumericUpDown Box { get; }
/// <summary>The box with its unit.</summary>
public Control View { get; }
public decimal Value => System.Math.Clamp(last, minimum, maximum);
/// <summary>Raised when a new value is entered.</summary>
public event EventHandler Changed;
}
/// <summary>
/// The cut-time values last used, in the user settings both apps share (WinForms names and
/// text, see <see cref="SavedCutTimeSettings"/>).
/// </summary>
internal static class CutTimeSettingsFile
{
public static SavedCutTimeSettings Read() =>
SavedCutTimeSettings.Read(UserSettingsFile.Read(UserSettingsFile.DefaultPath));
/// <summary>Remembers the feeds, pierce, etch choice and machine (null for full speed).</summary>
public static void Save(CutParameters parameters, MachineConfig machine) =>
UserSettingsFile.Update(UserSettingsFile.DefaultPath, settings =>
(SavedCutTimeSettings.Read(settings).With(parameters) with
{
Machine = SavedCutTimeSettings.MachineChoice(machine),
}).WriteTo(settings));
}
}
+66
View File
@@ -0,0 +1,66 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.LogicalTree;
namespace OpenNest.Avalonia
{
/// <summary>
/// Holds a nest view-only while it is inspected (the Cut Simulator), as the WinForms
/// inspection scope: every control of the window is disabled except the ones kept live (the
/// plate view and its header's plate and zoom buttons), the plate takes no edits and nothing
/// can be dropped on the window. Disposing puts each back as it was.
/// </summary>
internal sealed class InspectionLock : IDisposable
{
private readonly List<(Control Control, bool Enabled)> disabled = new();
private readonly List<(Control Control, bool AllowDrop)> drops = new();
private readonly Controls.PlateCanvas canvas;
private readonly bool wasLocked;
private bool disposed;
public InspectionLock(Window root, Controls.PlateCanvas canvas, IReadOnlyCollection<Control> keepLive)
{
this.canvas = canvas;
wasLocked = canvas.EditsLocked;
canvas.EditsLocked = true;
var live = keepLive.Prepend(canvas).Where(control => control != null).ToList();
Disable(root, live);
foreach (var control in new Control[] { root, canvas })
{
drops.Add((control, DragDrop.GetAllowDrop(control)));
DragDrop.SetAllowDrop(control, false);
}
}
private void Disable(ILogical parent, List<Control> live)
{
foreach (var child in parent.LogicalChildren.OfType<Control>().ToList())
{
if (live.Contains(child))
continue;
if (live.Any(control => control.GetLogicalAncestors().Contains(child)))
Disable(child, live);
else
{
disabled.Add((child, child.IsEnabled));
child.IsEnabled = false;
}
}
}
public void Dispose()
{
if (disposed)
return;
disposed = true;
foreach (var (control, enabled) in disabled)
control.IsEnabled = enabled;
foreach (var (control, allowDrop) in drops)
DragDrop.SetAllowDrop(control, allowDrop);
canvas.EditsLocked = wasLocked;
}
}
}
+115
View File
@@ -0,0 +1,115 @@
using System.Threading.Tasks;
using Avalonia.Input;
using Avalonia.Interactivity;
using OpenNest.Forms;
namespace OpenNest.Avalonia
{
/// <summary>
/// Plate &gt; Calculate Cut Time, Nest &gt; Calculate Cut Time and Plate &gt; Simulate Cutting (also
/// on the toolbar), as the WinForms main window. Calculate Cut Time asks for the feeds,
/// pierce, acceleration and etch choice, then shows the timing. The simulator holds the nest
/// view-only while it is open: only the plate view, its header's plate and zoom buttons and
/// the zoom keys stay live, and Escape closes it.
/// </summary>
public partial class MainWindow
{
private CutSimulatorWindow simulator;
private InspectionLock inspection;
private void UpdateCutTimeCommands()
{
var hasPlate = ActiveView?.PlateView.Plate != null;
PlateCutTimeMenuItem.IsEnabled = hasPlate;
SimulateCuttingMenuItem.IsEnabled = hasPlate;
SimulateCuttingButton.IsEnabled = hasPlate;
NestCutTimeMenuItem.IsEnabled = ActiveView != null;
}
private async void OnCalculatePlateCutTime(object sender, RoutedEventArgs e) => await CalculateCutTimeAsync(wholeNest: false);
private async void OnCalculateNestCutTime(object sender, RoutedEventArgs e) => await CalculateCutTimeAsync(wholeNest: true);
private async Task CalculateCutTimeAsync(bool wholeNest)
{
var view = ActiveView;
if (view == null || simulator != null || (!wholeNest && view.PlateView.Plate == null)
|| IsNesting(view.Tab, "calculating its cut time"))
return;
// As the WinForms machine list, read each time it opens.
var machines = await DesktopSettings.RefreshMachinesAsync();
if (closed)
return;
var nest = view.Tab.Document.Nest;
var parameters = await CutTimeDialog.ShowAsync(this, nest.Units, machines, saveSettings: !snapshotMode);
if (parameters == null || closed)
return;
var plate = view.PlateView.Plate;
if (!wholeNest && plate == null)
return;
var report = wholeNest
? CutTimeReport.ForNest(nest, parameters)
: CutTimeReport.ForPlate(plate, parameters, nest.Units);
await TimingDialog.ShowAsync(this, report);
}
private async void OnSimulateCutting(object sender, RoutedEventArgs e)
{
if (simulator != null)
{
simulator.Activate();
return;
}
var view = ActiveView;
if (view?.PlateView.Plate == null || IsNesting(view.Tab, "simulating its cutting"))
return;
var machines = await DesktopSettings.RefreshMachinesAsync();
// The nest may have changed or closed, or the simulator opened, while the machines were read.
if (closed || simulator != null || ActiveView != view || view.PlateView.Plate == null)
return;
// As WinForms: the plate tool ends and the nest is view-only until the simulator closes.
view.PlateView.Tools.EndTool();
view.CancelPickup();
inspection = new InspectionLock(this, view.PlateView, view.InspectionControls);
simulator = new CutSimulatorWindow(view, machines);
simulator.Closed += (_, _) =>
{
inspection?.Dispose();
inspection = null;
simulator = null;
};
simulator.Show(this);
}
/// <summary>
/// While the simulator is open, as the WinForms main window while inspecting: Escape
/// closes it, the zoom keys zoom, and other Ctrl, Alt and command shortcuts (which could
/// change the nest) are swallowed. True when the key was taken.
/// </summary>
private bool ProcessSimulatorKeys(KeyEventArgs e)
{
if (simulator == null)
return false;
var modifiers = e.KeyModifiers;
if (e.Key == Key.Escape && modifiers == KeyModifiers.None)
{
simulator.Close();
return true;
}
if (modifiers == KeyModifiers.Control && e.Key is Key.OemPlus or Key.Add)
{
OnZoomIn(null, null);
return true;
}
if (modifiers == KeyModifiers.Control && e.Key is Key.OemMinus or Key.Subtract)
{
OnZoomOut(null, null);
return true;
}
// F5 and F6 open the increment dialogs, whose menu items are locked.
return (modifiers & (KeyModifiers.Control | KeyModifiers.Alt | KeyModifiers.Meta)) != 0
|| e.Key is Key.F5 or Key.F6;
}
}
}
+7 -1
View File
@@ -55,6 +55,9 @@
<MenuItem x:Name="NestAutomaticCutOffMenuItem" Header="Automatic _Scrap Cutoffs (All Plates)..."
Click="OnNestAutomaticCutOff" />
<Separator />
<!-- Calculate Cut Time and Simulate Cutting: MainWindow.CutTime.cs. -->
<MenuItem x:Name="NestCutTimeMenuItem" Header="Calculate Cut _Time" Click="OnCalculateNestCutTime" />
<Separator />
<MenuItem x:Name="ClearNestMenuItem" Header="_Clear Nest..." Click="OnClearNest" />
</MenuItem>
<MenuItem Header="_Plate">
@@ -99,8 +102,10 @@
<MenuItem x:Name="CutCommonLinesTwiceMenuItem" Header="Cut Common Lines T_wice" ToggleType="CheckBox"
Click="OnCutCommonLinesTwice" />
</MenuItem>
<MenuItem x:Name="PlateCutTimeMenuItem" Header="Ca_lculate Cut Time" Click="OnCalculatePlateCutTime" />
<MenuItem x:Name="SimulateCuttingMenuItem" Header="_Simulate Cutting" Click="OnSimulateCutting" />
<Separator />
<MenuItem x:Name="ViewInCadMenuItem" Header="View in _CAD" Click="OnViewInCad" />
<MenuItem x:Name="ViewInCadMenuItem" Header="_View in CAD" Click="OnViewInCad" />
</MenuItem>
<MenuItem Header="_View">
<MenuItem x:Name="DrawRapidsMenuItem" Header="Draw _Rapids" ToggleType="CheckBox"
@@ -156,6 +161,7 @@
<Button x:Name="AutoNestButton" Content="Auto Nest" Click="OnAutoNest" />
<Button x:Name="SheetCutOffButton" Content="Sheet Cut-Off" Margin="8,0,0,0" Click="OnSheetCutOff" />
<Button x:Name="TrimExtendCutOffButton" Content="Trim/Extend Cut-Off" Click="OnTrimExtendCutOff" />
<Button x:Name="SimulateCuttingButton" Content="Simulate Cutting" Click="OnSimulateCutting" />
</StackPanel>
</Border>
+6
View File
@@ -329,6 +329,7 @@ namespace OpenNest.Avalonia
CutMenuItem.IsEnabled = view != null;
CopyMenuItem.IsEnabled = view != null;
UpdateExportCommands(view != null);
UpdateCutTimeCommands();
Title = view == null
? "OpenNest (Avalonia prototype)"
: $"{view.Tab.Name} - OpenNest (Avalonia prototype)";
@@ -677,6 +678,11 @@ namespace OpenNest.Avalonia
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (ProcessSimulatorKeys(e))
{
e.Handled = true;
return;
}
if (ProcessUndoKeys(e))
{
e.Handled = true;
+18
View File
@@ -0,0 +1,18 @@
using System.Collections.Generic;
using System.Linq;
using Avalonia.Controls;
namespace OpenNest.Avalonia
{
public partial class NestView
{
/// <summary>
/// What stays live while the nest is inspected, as the WinForms nest window's plate
/// buttons and zoom buttons: the plate view and the header above it.
/// </summary>
internal IReadOnlyCollection<Control> InspectionControls =>
new Control[] { Canvas, (Canvas.Parent as DockPanel)?.Children.OfType<Border>().FirstOrDefault() }
.Where(control => control != null)
.ToList();
}
}
+88
View File
@@ -0,0 +1,88 @@
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using OpenNest.Forms;
namespace OpenNest.Avalonia
{
/// <summary>
/// Calculate Cut Time's result, as the WinForms Timing Information window: cut time, cut and
/// rapid distance, pierces and intersections, then the feed, rapid and pierce time used.
/// </summary>
internal sealed class TimingDialog : Window
{
private TimingDialog(CutTimeReport report)
{
Title = "Timing Information";
SizeToContent = SizeToContent.WidthAndHeight;
MinWidth = 320;
CanResize = false;
ShowInTaskbar = false;
WindowStartupLocation = WindowStartupLocation.CenterOwner;
var rows = new (string Label, string Value, string Name)[]
{
("Cut Time :", report.CutTimeText, "CutTime"),
("Cut Distance :", report.CutDistanceText, "CutDistance"),
("Rapid Distance :", report.RapidDistanceText, "RapidDistance"),
("# of Pierces :", report.PierceCountText, "Pierces"),
("# of Intersections :", report.IntersectionCountText, "Intersections"),
(null, null, null),
("Feedrate :", report.FeedrateText, "Feedrate"),
("Rapid Feedrate :", report.RapidText, "Rapid"),
("Pierce Time :", report.PierceTimeText, "PierceTime"),
};
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 16, RowSpacing = 6 };
for (var i = 0; i < rows.Length; i++)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
var (label, value, name) = rows[i];
if (label == null)
{
var line = new Border { Height = 1, Background = Brushes.Silver, Margin = new Thickness(0, 4) };
Grid.SetRow(line, i);
Grid.SetColumnSpan(line, 2);
grid.Children.Add(line);
continue;
}
var caption = new TextBlock { Text = label };
Grid.SetRow(caption, i);
grid.Children.Add(caption);
var text = new TextBlock { Name = name, Text = value };
Grid.SetRow(text, i);
Grid.SetColumn(text, 1);
grid.Children.Add(text);
}
var close = new Button
{
Name = "Close",
Content = "Close",
IsDefault = true,
IsCancel = true,
MinWidth = 80,
HorizontalAlignment = HorizontalAlignment.Right,
};
close.Click += (_, _) => Close();
var panel = new StackPanel { Margin = new Thickness(12), Spacing = 14 };
panel.Children.Add(grid);
panel.Children.Add(close);
Content = panel;
AddHandler(KeyDownEvent, (_, e) =>
{
if (e.Key != Key.Escape)
return;
e.Handled = true;
Close();
}, RoutingStrategies.Tunnel);
}
public static Task ShowAsync(Window owner, CutTimeReport report) =>
new TimingDialog(report).ShowDialog(owner);
}
}
@@ -0,0 +1,186 @@
using System.Globalization;
using OpenNest.Data;
using OpenNest.Forms;
namespace OpenNest.Desktop.Tests.Forms;
public sealed class CutTimeReportTests : IDisposable
{
private readonly CultureInfo previous = CultureInfo.CurrentCulture;
public CutTimeReportTests() => CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
public void Dispose() => CultureInfo.CurrentCulture = previous;
private static CutParameters Entered(Units units = Units.Inches, MachineConfig? machine = null) =>
CutTimeEntry.Parameters(120, 60, 600, 1, true, units, machine);
// Two squares on the plate, two of the sheet cut.
private static Nest TwoSquares()
{
var nest = TestNests.TwoSquares();
nest.Plates[0].Quantity = 2;
return nest;
}
// The WinForms TimingForm computed these itself before the report was shared; the report
// must give the same numbers for the same inputs.
[Fact]
public void ForPlate_IsTheTimingTheWinFormsDialogShowed()
{
var nest = TwoSquares();
var plate = nest.Plates[0];
var parameters = Entered(machine: new MachineConfig { Units = UnitSystem.Inches });
var report = CutTimeReport.ForPlate(plate, parameters, nest.Units);
var info = Timing.GetTimingInfo(plate);
Assert.Equal(Timing.CalculateTime(plate, parameters), report.CutTime);
Assert.Equal(info.CutDistance, report.Info.CutDistance);
Assert.Equal(info.TravelDistance, report.Info.TravelDistance);
Assert.Equal(info.PierceCount, report.Info.PierceCount);
Assert.Equal(info.IntersectionCount, report.Info.IntersectionCount);
}
[Fact]
public void ForNest_AddsEveryPlate()
{
var nest = TwoSquares();
nest.Plates.Add(TestNests.TwoSquares().Plates[0]);
var parameters = Entered();
var report = CutTimeReport.ForNest(nest, parameters);
Assert.Equal(Timing.CalculateTime(nest, parameters), report.CutTime);
Assert.Equal(Timing.GetTimingInfo(nest).CutDistance, report.Info.CutDistance);
Assert.Equal(
Timing.CalculateTime(nest.Plates[0], parameters) + Timing.CalculateTime(nest.Plates[1], parameters),
report.CutTime);
}
// Full speed: each square's 40 in of hole contour at 60 in/min is 40 s, plus a 1 s pierce;
// two squares, two sheets, and the rapid between them at 600 in/min.
[Fact]
public void ForPlate_FullSpeed_TheHandWorkedTime()
{
var nest = TwoSquares();
var report = CutTimeReport.ForPlate(nest.Plates[0], Entered(), Units.Inches);
var rapid = TimeSpan.FromMinutes(20.0 / 600);
var sheet = 2 * (TimeSpan.FromSeconds(40) + TimeSpan.FromSeconds(1)) + rapid;
Assert.Equal(sheet.TotalSeconds * 2, report.CutTime.TotalSeconds, 6);
Assert.Equal("02m 48s", report.CutTimeText);
}
[Fact]
public void Texts_AreWordedAsTheWinFormsTimingWindow()
{
var nest = TwoSquares();
var report = CutTimeReport.ForPlate(nest.Plates[0], Entered(), Units.Inches);
// Quantity 2: two squares of 40 in, twice.
Assert.Equal("160 in", report.CutDistanceText);
Assert.Equal(report.Info.PierceCount.ToString(), report.PierceCountText);
Assert.Equal(report.Info.IntersectionCount.ToString(), report.IntersectionCountText);
Assert.Equal("120 in/min", report.FeedrateText);
Assert.Equal("600 in/min", report.RapidText);
Assert.Equal("01s", report.PierceTimeText);
}
[Fact]
public void Millimeters_ReadPerSecond()
{
Assert.Equal("250 mm/sec", CutTimeReport.RateText(250, Units.Millimeters));
Assert.Equal("12.3457 mm", CutTimeReport.DistanceText(12.345678, Units.Millimeters));
}
[Theory]
[InlineData(3723, "1h 02m 03s")]
[InlineData(90000, "25h 00m 00s")]
[InlineData(125, "02m 05s")]
[InlineData(45, "45s")]
[InlineData(5, "05s")]
[InlineData(0, "00s")]
public void FormatTime_AsTheWinFormsTimingWindow(int seconds, string expected) =>
Assert.Equal(expected, CutTimeReport.FormatTime(TimeSpan.FromSeconds(seconds)));
[Fact]
public void FormatTime_UnderAMinute_RoundsTheSeconds() =>
Assert.Equal("13s", CutTimeReport.FormatTime(TimeSpan.FromSeconds(12.6)));
[Fact]
public void Entry_TheWinFormsBoxValues()
{
var machine = new MachineConfig { Units = UnitSystem.Millimeters };
var parameters = CutTimeEntry.Parameters(250, 120.5m, 1000, 0.75m, false, Units.Inches, machine);
Assert.Equal(250, parameters.Feedrate);
Assert.Equal(120.5, parameters.HoleFeedrate);
Assert.Equal(1000, parameters.RapidTravelRate);
Assert.Equal(TimeSpan.FromSeconds(0.75), parameters.PierceTime);
Assert.False(parameters.SkipScribe);
Assert.Equal(Units.Inches, parameters.Units);
var expected = machine.GetMotionOrPlaceholder().ToProfile(UnitSystem.Millimeters, Units.Inches);
Assert.Equal(expected.CutAcceleration, parameters.Motion.CutAcceleration);
}
[Fact]
public void Entry_FullSpeed_HasNoMotion() =>
Assert.Null(CutTimeEntry.Parameters(1, 1, 1, 0, true, Units.Inches, null).Motion);
[Fact]
public void Entry_Clamp_TakesTheBoxRange()
{
Assert.Equal(CutTimeEntry.MaximumRate, CutTimeEntry.Clamp(20000, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate));
Assert.Equal(CutTimeEntry.MinimumRate, CutTimeEntry.Clamp(0, CutTimeEntry.MinimumRate, CutTimeEntry.MaximumRate));
Assert.Equal(0.5m, CutTimeEntry.Clamp(0.5, 0, CutTimeEntry.DialogMaximumPierce));
}
// The saved settings round trip through the boxes unchanged.
[Fact]
public void Entry_FromSavedSettings_GivesTheSavedParameters()
{
var saved = new SavedCutTimeSettings(250, 120.5m, 1000, 0.75m, false, SavedCutTimeSettings.FullSpeed);
var loaded = saved.ToCutParameters(Units.Inches, null);
var entered = CutTimeEntry.Parameters(
(decimal)loaded.Feedrate, (decimal)loaded.HoleFeedrate!.Value, (decimal)loaded.RapidTravelRate,
(decimal)loaded.PierceTime.TotalSeconds, loaded.SkipScribe, Units.Inches, null);
Assert.Equal(saved, saved.With(entered));
}
[Fact]
public void MachineChoices_FullSpeedFirst_ThenByName_MarkingPlaceholders()
{
var machines = new List<MachineConfig>
{
new() { Name = "Zeta", Motion = new MotionConfig() },
new() { Name = "alpha" },
};
var choices = CutTimeMachineChoice.For(machines);
Assert.Equal(["None (full speed)", "alpha (placeholder)", "Zeta"], choices.Select(c => c.ToString()));
Assert.Null(choices[0].GetMotion(Units.Inches));
Assert.NotNull(choices[1].GetMotion(Units.Inches));
}
[Fact]
public void MachineChoices_SavedIndex()
{
var id = Guid.NewGuid();
var choices = CutTimeMachineChoice.For(
[
new MachineConfig { Name = "b" },
new MachineConfig { Id = id, Name = "c" },
new MachineConfig { Name = "a" },
]);
Assert.Equal(3, CutTimeMachineChoice.SavedIndex(choices, id.ToString()));
Assert.Equal(1, CutTimeMachineChoice.SavedIndex(choices, ""));
Assert.Equal(0, CutTimeMachineChoice.SavedIndex(choices, SavedCutTimeSettings.FullSpeed));
Assert.Equal(0, CutTimeMachineChoice.SavedIndex(CutTimeMachineChoice.For([]), ""));
}
}
@@ -0,0 +1,354 @@
using System.Globalization;
using OpenNest.CNC;
using OpenNest.Desktop.Interaction;
using OpenNest.Geometry;
namespace OpenNest.Desktop.Tests.Interaction;
public sealed class CutSimulationPlaybackTests : IDisposable
{
private readonly CultureInfo previous = CultureInfo.CurrentCulture;
public CutSimulationPlaybackTests() => CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
public void Dispose() => CultureInfo.CurrentCulture = previous;
private static Plate TwoSquares() => TestNests.TwoSquares().Plates[0];
private static CutParameters FullSpeed(double feed = 60) => new()
{
Feedrate = feed,
HoleFeedrate = feed,
RapidTravelRate = 600,
PierceTime = TimeSpan.FromSeconds(1),
Units = Units.Inches,
};
private static CutSimulationPlayback Loaded(Plate plate, CutParameters? parameters = null)
{
var playback = new CutSimulationPlayback();
playback.Load(CutSimulation.Build(plate, parameters ?? FullSpeed()));
return playback;
}
[Fact]
public void Time_WithoutATimeline_StaysAtZero()
{
var playback = new CutSimulationPlayback();
var changes = 0;
playback.Changed += (_, _) => changes++;
playback.Time = TimeSpan.FromSeconds(5);
Assert.Equal(TimeSpan.Zero, playback.Time);
Assert.Equal(0, changes);
}
[Fact]
public void Time_StaysWithinTheTimeline()
{
var playback = Loaded(TwoSquares());
playback.Time = TimeSpan.FromHours(1);
Assert.Equal(playback.Simulation.TotalTime, playback.Time);
playback.Time = TimeSpan.FromSeconds(-1);
Assert.Equal(TimeSpan.Zero, playback.Time);
}
[Fact]
public void Advance_MovesBySpeedTimesWallTime_AndPausesAtTheEnd()
{
var playback = Loaded(TwoSquares());
playback.Speed = 5;
playback.Play();
Assert.True(playback.IsPlaying);
playback.Advance(TimeSpan.FromSeconds(2));
Assert.Equal(TimeSpan.FromSeconds(10), playback.Time);
playback.Advance(TimeSpan.FromHours(1));
Assert.Equal(playback.Simulation.TotalTime, playback.Time);
Assert.False(playback.IsPlaying);
}
[Fact]
public void Play_AtTheEnd_StartsOver()
{
var playback = Loaded(TwoSquares());
playback.End();
playback.Play();
Assert.Equal(TimeSpan.Zero, playback.Time);
Assert.True(playback.IsPlaying);
}
[Fact]
public void Play_WithNothingToCut_DoesNotStart()
{
var playback = Loaded(new Plate(new Size(48, 96)));
playback.Play();
Assert.False(playback.IsPlaying);
}
[Fact]
public void Load_Retimed_KeepsTheTorchWhereItWas()
{
var plate = TwoSquares();
var playback = Loaded(plate, FullSpeed(60));
playback.Time = TimeSpan.FromSeconds(15);
var before = playback.Simulation.ToolPositionAt(playback.Time);
playback.Load(CutSimulation.Build(plate, FullSpeed(120)));
var after = playback.Simulation.ToolPositionAt(playback.Time);
Assert.Equal(before.X, after.X, 6);
Assert.Equal(before.Y, after.Y, 6);
Assert.NotEqual(TimeSpan.FromSeconds(15), playback.Time);
}
[Fact]
public void Load_DifferentMoves_KeepsThePlayheadTime()
{
var plate = TwoSquares();
var playback = Loaded(plate);
playback.Time = TimeSpan.FromSeconds(15);
plate.Parts.RemoveAt(1);
playback.Load(CutSimulation.Build(plate, FullSpeed()));
Assert.Equal(TimeSpan.FromSeconds(15), playback.Time);
}
[Fact]
public void Load_Null_Pauses()
{
var playback = Loaded(TwoSquares());
playback.Play();
playback.Load(null!);
Assert.False(playback.IsPlaying);
Assert.False(playback.IsActive);
}
[Fact]
public void Parts_JumpForwardAndBack_Pausing()
{
var playback = Loaded(TwoSquares());
var sim = playback.Simulation;
Assert.Equal(2, sim.PartStarts.Count);
playback.Play();
// The first part starts the timeline, so the next is the second.
Assert.Equal(TimeSpan.Zero, sim.PartStarts[0]);
playback.NextPart();
Assert.False(playback.IsPlaying);
Assert.Equal(sim.PartStarts[1], playback.Time);
playback.NextPart();
Assert.Equal(sim.TotalTime, playback.Time);
playback.PreviousPart();
Assert.Equal(sim.PartStarts[1], playback.Time);
// Already at a part's start: back to the one before.
playback.PreviousPart();
Assert.Equal(sim.PartStarts[0], playback.Time);
}
[Fact]
public void Contours_JumpForwardAndBack()
{
var playback = Loaded(TwoSquares());
var sim = playback.Simulation;
playback.NextContour();
Assert.Equal(sim.ContourStarts[1], playback.Time);
playback.Time += TimeSpan.FromSeconds(1);
playback.PreviousContour();
Assert.Equal(sim.ContourStarts[1], playback.Time);
playback.PreviousContour();
Assert.Equal(sim.ContourStarts[0], playback.Time);
}
[Fact]
public void StepMove_GoesOneMoveAtATime()
{
var playback = Loaded(TwoSquares());
var steps = playback.Simulation.Steps;
playback.StepMove(1);
Assert.Equal(steps[1].StartTime, playback.Time);
playback.StepMove(1);
Assert.Equal(steps[2].StartTime, playback.Time);
// At a move's start, back to the one before; mid-move, back to its start.
playback.StepMove(-1);
Assert.Equal(steps[1].StartTime, playback.Time);
playback.Time = steps[2].StartTime + TimeSpan.FromTicks(steps[2].Duration.Ticks / 2);
playback.StepMove(-1);
Assert.Equal(steps[2].StartTime, playback.Time);
playback.Time = TimeSpan.Zero;
playback.StepMove(-1);
Assert.Equal(TimeSpan.Zero, playback.Time);
}
[Fact]
public void TogglePlay_RebuildsOnlyAtTheStartOrEnd()
{
var plate = TwoSquares();
var playback = Loaded(plate);
var rebuilds = 0;
void Rebuild()
{
rebuilds++;
playback.Load(CutSimulation.Build(plate, FullSpeed()));
}
playback.TogglePlay(Rebuild);
Assert.True(playback.IsPlaying);
Assert.Equal(1, rebuilds);
playback.TogglePlay(Rebuild);
Assert.False(playback.IsPlaying);
playback.Time = TimeSpan.FromSeconds(10);
playback.TogglePlay(Rebuild);
Assert.True(playback.IsPlaying);
Assert.Equal(1, rebuilds);
}
[Fact]
public void Restart_KeepsPlaying_EndPauses()
{
var playback = Loaded(TwoSquares());
playback.Time = TimeSpan.FromSeconds(10);
playback.Play();
playback.Restart();
Assert.Equal(TimeSpan.Zero, playback.Time);
Assert.True(playback.IsPlaying);
playback.End();
Assert.False(playback.IsPlaying);
Assert.Equal(playback.Simulation.TotalTime, playback.Time);
}
[Fact]
public void Seek_AndProgress_AreFractionsOfTheTimeline()
{
var playback = Loaded(TwoSquares());
playback.Seek(0.5);
Assert.Equal(playback.Simulation.TotalTime / 2, playback.Time);
Assert.Equal(0.5, playback.Progress, 6);
}
[Fact]
public void IsPartPending_UntilTheTorchReachesThePart()
{
var playback = Loaded(TwoSquares());
var sim = playback.Simulation;
playback.Time = TimeSpan.Zero;
Assert.True(playback.IsPartPending(1));
// On the travel to the second part, it has not been touched yet.
var travel = sim.Steps.First(s => s.PartIndex == 1 && s.Kind == CutSimulationStepKind.Rapid);
playback.Time = travel.StartTime + TimeSpan.FromTicks(travel.Duration.Ticks / 2);
Assert.False(playback.IsPartPending(0));
Assert.True(playback.IsPartPending(1));
playback.Time = sim.PartStarts[1] + TimeSpan.FromSeconds(0.5);
Assert.False(playback.IsPartPending(1));
playback.End();
Assert.False(playback.IsPartPending(1));
}
[Fact]
public void Clear_DropsTheTimelineAndStops()
{
var playback = Loaded(TwoSquares());
playback.Play();
playback.Clear();
Assert.Null(playback.Simulation);
Assert.False(playback.IsPlaying);
Assert.Equal(TimeSpan.Zero, playback.Time);
Assert.False(playback.IsPartPending(0));
}
[Fact]
public void Speeds_StartAtFiveTimes()
{
Assert.Equal(CutSimulationPlayback.DefaultSpeed, CutSimulationPlayback.Speeds[CutSimulationPlayback.DefaultSpeedIndex]);
Assert.Equal("5×", CutSimulationStatus.SpeedText(5));
Assert.Equal("250×", CutSimulationStatus.SpeedText(250));
}
[Fact]
public void Status_NothingToCut()
{
var status = CutSimulationStatus.For(new CutSimulationPlayback(), null!, Units.Inches);
Assert.Equal(new CutSimulationStatus("Nothing to cut", "", "", ""), status);
}
[Fact]
public void Status_Cutting_ShowsTheFeedPerMinute()
{
var plate = TwoSquares();
var playback = Loaded(plate);
// Mid-way along the first part's cut, past its pierce.
var cut = playback.Simulation.Steps.First(s => s.Kind == CutSimulationStepKind.Cut);
playback.Time = cut.StartTime + TimeSpan.FromTicks(cut.Duration.Ticks / 2);
var status = CutSimulationStatus.For(playback, plate, Units.Inches);
Assert.Equal($"{CutTimeFormat(playback.Time)} / {CutTimeFormat(playback.Simulation.TotalTime)}", status.Time);
Assert.Equal("1 of 2", status.Part);
Assert.Equal("square", status.Drawing);
Assert.Equal("Cutting · 60 in/min", status.Motion);
}
[Fact]
public void Status_Piercing_HasNoSpeed()
{
var plate = TwoSquares();
var playback = Loaded(plate);
var pierce = playback.Simulation.Steps.First(s => s.Kind == CutSimulationStepKind.Pierce);
playback.Time = pierce.StartTime + TimeSpan.FromTicks(pierce.Duration.Ticks / 2);
Assert.Equal("Piercing", CutSimulationStatus.For(playback, plate, Units.Inches).Motion);
}
[Fact]
public void Status_Done()
{
var plate = TwoSquares();
var playback = Loaded(plate);
playback.End();
var status = CutSimulationStatus.For(playback, plate, Units.Inches);
Assert.Equal("2 of 2", status.Part);
Assert.Equal("", status.Drawing);
Assert.Equal("Done", status.Motion);
}
[Fact]
public void FeedText_MillimetersPerSecond() =>
Assert.Equal("25 mm/sec", CutSimulationStatus.FeedText(25, Units.Millimeters));
private static string CutTimeFormat(TimeSpan time) => OpenNest.Forms.CutTimeReport.FormatTime(time);
}
+28
View File
@@ -30,4 +30,32 @@ internal static class TestNests
nest.Plates.Add(plate);
return nest;
}
/// <summary>
/// A nest with one 48x96 plate holding two 10x10 squares drawn as imported part programs are
/// (incremental, counterclockwise from the corner), the second 20 to the right of the first.
/// </summary>
public static Nest TwoSquares()
{
var program = new Program(Mode.Incremental);
program.Codes.Add(new RapidMove(new Vector(0, 0)));
program.Codes.Add(new LinearMove(new Vector(10, 0)));
program.Codes.Add(new LinearMove(new Vector(0, 10)));
program.Codes.Add(new LinearMove(new Vector(-10, 0)));
program.Codes.Add(new LinearMove(new Vector(0, -10)));
var drawing = new Drawing("square", program);
drawing.Quantity.Required = 2;
var plate = new Plate(new Size(48, 96));
plate.Parts.Add(new Part(drawing));
var second = new Part(drawing);
second.Offset(new Vector(20, 0));
plate.Parts.Add(second);
var nest = new Nest { Name = "test" };
nest.Drawings.Add(drawing);
nest.Plates.Add(plate);
return nest;
}
}
+39
View File
@@ -0,0 +1,39 @@
using System;
using OpenNest.Data;
namespace OpenNest.Desktop;
/// <summary>
/// The cut-time values entered in Calculate Cut Time or the simulator, with the ranges their
/// WinForms boxes take: feeds and rapid from 1 to 9999 per time unit, pierce seconds from 0 to
/// 100 in the dialog and to 999 in the simulator.
/// </summary>
public static class CutTimeEntry
{
public const decimal MinimumRate = 1;
public const decimal MaximumRate = 9999;
public const decimal DialogMaximumPierce = 100;
public const decimal SimulatorMaximumPierce = 999;
/// <summary>A value shown in a box from <paramref name="minimum"/> to <paramref name="maximum"/>.</summary>
public static decimal Clamp(double value, decimal minimum, decimal maximum) =>
System.Math.Clamp((decimal)value, minimum, maximum);
/// <summary>
/// The parameters the entered values time with in <paramref name="units"/>, with
/// <paramref name="machine"/>'s acceleration (null for full speed).
/// </summary>
public static CutParameters Parameters(
decimal feed, decimal holeFeed, decimal rapid, decimal pierceSeconds, bool skipEtch,
Units units, MachineConfig machine) =>
new()
{
Feedrate = (double)feed,
HoleFeedrate = (double)holeFeed,
RapidTravelRate = (double)rapid,
PierceTime = TimeSpan.FromSeconds((double)pierceSeconds),
SkipScribe = skipEtch,
Units = units,
Motion = CutTimeMachineChoice.Motion(machine, units),
};
}
+58
View File
@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using OpenNest.Data;
namespace OpenNest.Desktop;
/// <summary>
/// One entry of the cut-time Acceleration list: a machine whose acceleration limits time the
/// moves, or none for full speed everywhere. Named as the WinForms list names them: a machine
/// with no saved motion values is marked "(placeholder)".
/// </summary>
public sealed record CutTimeMachineChoice(MachineConfig Machine)
{
public const string FullSpeedText = "None (full speed)";
public override string ToString() =>
Machine == null ? FullSpeedText
: Machine.Motion == null ? $"{Machine.Name} (placeholder)"
: Machine.Name;
/// <summary>Full speed first, then <paramref name="machines"/> by name.</summary>
public static List<CutTimeMachineChoice> For(IEnumerable<MachineConfig> machines)
{
ArgumentNullException.ThrowIfNull(machines);
var choices = new List<CutTimeMachineChoice> { new((MachineConfig)null) };
choices.AddRange(SavedCutTimeSettings.SortedByName(machines).Select(m => new CutTimeMachineChoice(m)));
return choices;
}
/// <summary>
/// The index in <paramref name="choices"/> of the remembered choice (<see
/// cref="SavedCutTimeSettings.Machine"/>): the first machine until one is saved, full speed
/// when saved so or when there are no machines.
/// </summary>
public static int SavedIndex(IReadOnlyList<CutTimeMachineChoice> choices, string saved)
{
ArgumentNullException.ThrowIfNull(choices);
var machine = SavedCutTimeSettings.ChooseMachine(
choices.Where(c => c.Machine != null).Select(c => c.Machine), saved);
for (var i = 0; i < choices.Count; i++)
{
if (ReferenceEquals(choices[i].Machine, machine))
return i;
}
return 0;
}
/// <summary>The machine's limits in <paramref name="units"/>, or null for full speed.</summary>
public MotionProfile GetMotion(Units units) => Motion(Machine, units);
/// <summary>
/// <paramref name="machine"/>'s limits (its placeholder without saved ones) in
/// <paramref name="units"/>, or null for full speed.
/// </summary>
public static MotionProfile Motion(MachineConfig machine, Units units) =>
machine?.GetMotionOrPlaceholder().ToProfile(machine.Units, units);
}
+99
View File
@@ -0,0 +1,99 @@
using System;
namespace OpenNest.Forms
{
/// <summary>
/// What Calculate Cut Time shows for a plate or a nest, worded as the WinForms timing window:
/// the time from <see cref="Timing.CalculateTime(Plate, CutParameters)"/> (the simulation
/// with acceleration, plus clamp removal, over the quantity) and the distances and counts from
/// <see cref="Timing.GetTimingInfo(Plate)"/>. Numbers are in the current culture.
/// </summary>
public sealed class CutTimeReport
{
private CutTimeReport(Units units, CutParameters parameters, TimingInfo info, TimeSpan cutTime)
{
Units = units;
Parameters = parameters;
Info = info;
CutTime = cutTime;
}
public Units Units { get; }
public CutParameters Parameters { get; }
public TimingInfo Info { get; }
public TimeSpan CutTime { get; }
/// <summary>Plate &gt; Calculate Cut Time: <paramref name="plate"/> in its nest's <paramref name="units"/>.</summary>
public static CutTimeReport ForPlate(Plate plate, CutParameters parameters, Units units)
{
ArgumentNullException.ThrowIfNull(plate);
ArgumentNullException.ThrowIfNull(parameters);
return new CutTimeReport(units, parameters, Timing.GetTimingInfo(plate), Timing.CalculateTime(plate, parameters));
}
/// <summary>Nest &gt; Calculate Cut Time: every plate of <paramref name="nest"/>.</summary>
public static CutTimeReport ForNest(Nest nest, CutParameters parameters)
{
ArgumentNullException.ThrowIfNull(nest);
ArgumentNullException.ThrowIfNull(parameters);
return new CutTimeReport(nest.Units, parameters, Timing.GetTimingInfo(nest), Timing.CalculateTime(nest, parameters));
}
public string CutTimeText => FormatTime(CutTime);
public string CutDistanceText => DistanceText(Info.CutDistance, Units);
public string RapidDistanceText => DistanceText(Info.TravelDistance, Units);
public string PierceCountText => Info.PierceCount.ToString();
public string IntersectionCountText => Info.IntersectionCount.ToString();
/// <summary>The outside feed, as the timing window's "Feedrate".</summary>
public string FeedrateText => RateText(Parameters.Feedrate, Units);
public string RapidText => RateText(Parameters.RapidTravelRate, Units);
public string PierceTimeText => FormatTime(Parameters.PierceTime);
/// <summary>A distance rounded to four places with the unit, as "12.3457 in".</summary>
public static string DistanceText(double distance, Units units) =>
string.Format("{0} {1}", System.Math.Round(distance, 4), UnitsHelper.GetShortString(units));
/// <summary>A rate with its unit pair, as "250 in/min".</summary>
public static string RateText(double rate, Units units) =>
string.Format("{0} {1}/{2}", rate, UnitsHelper.GetShortString(units), UnitsHelper.GetShortTimeUnit(units));
/// <summary>
/// "1h 02m 03s" from an hour, "02m 03s" from a minute, otherwise whole seconds as "45s"
/// (at least two digits).
/// </summary>
public static string FormatTime(TimeSpan time)
{
var hrs = time.Days * 24 + time.Hours;
var min = time.Minutes;
var sec = time.Seconds;
var msg = string.Empty;
if (hrs > 0)
{
msg += hrs.ToString() + "h ";
msg += min.ToString().PadLeft(2, '0') + "m ";
msg += sec.ToString().PadLeft(2, '0') + "s";
}
else if (min > 0)
{
msg += min.ToString().PadLeft(2, '0') + "m ";
msg += sec.ToString().PadLeft(2, '0') + "s";
}
else
msg += time.TotalSeconds.ToString("n0").PadLeft(2, '0') + "s";
return msg;
}
}
}
@@ -0,0 +1,233 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using OpenNest.CNC;
namespace OpenNest.Desktop.Interaction;
/// <summary>
/// The Cut Simulator's playhead over a <see cref="CutSimulation"/>, without drawing: the time,
/// play and pause at a speed, the jumps between parts, cutouts and moves, and which parts the
/// torch has not reached. The host runs a timer that calls <see cref="Advance()"/> while
/// <see cref="IsPlaying"/> and redraws after each change.
/// </summary>
public sealed class CutSimulationPlayback
{
/// <summary>The simulator's speed choices, as multiples of real time.</summary>
public static IReadOnlyList<double> Speeds { get; } = new double[] { 1, 2, 5, 10, 25, 50, 100, 250 };
/// <summary>The speed the simulator starts at.</summary>
public const double DefaultSpeed = 5;
/// <summary>The index of <see cref="DefaultSpeed"/> in <see cref="Speeds"/>.</summary>
public static int DefaultSpeedIndex => 2;
private readonly Stopwatch clock = new();
private CutSimulation simulation;
private TimeSpan time;
private bool playing;
/// <summary>Raised when the playhead, play state or timeline changes.</summary>
public event EventHandler Changed;
public CutSimulation Simulation => simulation;
public bool IsActive => simulation != null;
public bool IsPlaying => playing;
/// <summary>Simulated time per wall-clock time.</summary>
public double Speed { get; set; } = 10;
/// <summary>The playhead, kept within the timeline; nothing changes without one.</summary>
public TimeSpan Time
{
get => time;
set
{
if (simulation == null)
return;
time = value < TimeSpan.Zero ? TimeSpan.Zero : value > simulation.TotalTime ? simulation.TotalTime : value;
Changed?.Invoke(this, EventArgs.Empty);
}
}
/// <summary>
/// Shows <paramref name="value"/>, keeping the torch where it was when the moves are the same
/// (new rates or acceleration only retime them), else keeping the playhead's time.
/// </summary>
public void Load(CutSimulation value)
{
var anchored = Anchor(simulation, value, time);
simulation = value;
Time = anchored;
if (simulation == null)
Pause();
Changed?.Invoke(this, EventArgs.Empty);
}
/// <summary>Where <paramref name="time"/> on <paramref name="old"/> falls on <paramref name="next"/>.</summary>
public static TimeSpan Anchor(CutSimulation old, CutSimulation next, TimeSpan time)
{
if (old == null || next == null || old.Steps.Count == 0 || old.Steps.Count != next.Steps.Count)
return time;
var index = old.IndexAt(time);
if (index >= old.Steps.Count)
return next.TotalTime;
return next.TimeAt(index, old.FractionAt(index, time));
}
/// <summary>Plays from the playhead, or from the start once it is at the end.</summary>
public void Play()
{
if (simulation == null || simulation.Steps.Count == 0)
return;
if (time >= simulation.TotalTime)
Time = TimeSpan.Zero;
clock.Restart();
playing = true;
Changed?.Invoke(this, EventArgs.Empty);
}
public void Pause()
{
if (!playing)
return;
playing = false;
clock.Reset();
Changed?.Invoke(this, EventArgs.Empty);
}
/// <summary>Drops the timeline and stops.</summary>
public void Clear()
{
playing = false;
clock.Reset();
simulation = null;
time = TimeSpan.Zero;
Changed?.Invoke(this, EventArgs.Empty);
}
/// <summary>Moves the playhead by the wall time since the last advance (or since Play).</summary>
public void Advance()
{
var elapsed = clock.Elapsed;
clock.Restart();
Advance(elapsed);
}
/// <summary>
/// Moves the playhead by <paramref name="wallElapsed"/> times <see cref="Speed"/>, pausing at
/// the end.
/// </summary>
public void Advance(TimeSpan wallElapsed)
{
if (simulation == null)
return;
var next = time + TimeSpan.FromTicks((long)(wallElapsed.Ticks * Speed));
time = next > simulation.TotalTime ? simulation.TotalTime : next;
Changed?.Invoke(this, EventArgs.Empty);
if (time >= simulation.TotalTime)
Pause();
}
/// <summary>
/// The play button: pauses while playing; otherwise plays, first calling
/// <paramref name="rebuild"/> (parts may have moved, which raises no plate event) when there
/// is no timeline or the playhead is at its start or end.
/// </summary>
public void TogglePlay(Action rebuild)
{
if (playing)
{
Pause();
return;
}
if (simulation == null || time <= TimeSpan.Zero || time >= simulation.TotalTime)
rebuild?.Invoke();
Play();
}
/// <summary>Back to the start (Home), still playing if it was.</summary>
public void Restart() => Time = TimeSpan.Zero;
/// <summary>Pauses at the end.</summary>
public void End()
{
Pause();
Time = simulation?.TotalTime ?? TimeSpan.Zero;
}
public void NextContour() => Jump(sim => sim.NextContour(time));
public void PreviousContour() => Jump(sim => sim.PreviousContour(time));
public void NextPart() => Jump(sim => sim.NextPart(time));
public void PreviousPart() => Jump(sim => sim.PreviousPart(time));
// Jumps pause so the jumped-to contour stays on screen.
private void Jump(Func<CutSimulation, TimeSpan> target)
{
if (simulation is not { } sim || sim.Steps.Count == 0)
return;
Pause();
Time = target(sim);
}
/// <summary>
/// Pauses at the start of the next move (<paramref name="direction"/> &gt; 0), or back at the
/// start of the current move, or of the one before when already there.
/// </summary>
public void StepMove(int direction)
{
var sim = simulation;
if (sim == null || sim.Steps.Count == 0)
return;
Pause();
var index = System.Math.Clamp(sim.IndexAt(time), 0, sim.Steps.Count);
var atStart = index < sim.Steps.Count && time == sim.Steps[index].StartTime;
var target = direction > 0 ? index + 1 : atStart ? index - 1 : index;
Time = target <= 0 ? TimeSpan.Zero
: target >= sim.Steps.Count ? sim.TotalTime
: sim.Steps[target].StartTime;
}
/// <summary>The playhead as a fraction of the timeline (0 without one).</summary>
public double Progress =>
simulation is { } sim && sim.TotalTime > TimeSpan.Zero ? time / sim.TotalTime : 0;
/// <summary>Moves the playhead to <paramref name="fraction"/> of the timeline (a scrub).</summary>
public void Seek(double fraction)
{
if (simulation != null)
Time = simulation.TotalTime * fraction;
}
/// <summary>True for a part the torch has not started yet.</summary>
public bool IsPartPending(int partIndex)
{
if (simulation == null)
return false;
var index = simulation.IndexAt(time);
if (index >= simulation.Steps.Count)
return false;
if (index < 0)
return true;
var current = simulation.Steps[index];
// Travel toward a part has not touched it yet.
return partIndex > current.PartIndex
|| partIndex == current.PartIndex && current.Kind == CutSimulationStepKind.Rapid && !PartStarted(index);
}
private bool PartStarted(int index)
{
var part = simulation.Steps[index].PartIndex;
for (var i = index - 1; i >= 0 && simulation.Steps[i].PartIndex == part; i--)
{
if (simulation.Steps[i].Kind != CutSimulationStepKind.Rapid)
return true;
}
return false;
}
}
@@ -0,0 +1,56 @@
using System;
using OpenNest.CNC;
using OpenNest.Forms;
namespace OpenNest.Desktop.Interaction;
/// <summary>
/// The Cut Simulator's status rows, worded as the WinForms simulator: the time as "elapsed /
/// total", the part as "n of m", its drawing, and the motion with the speed at the playhead.
/// </summary>
public sealed record CutSimulationStatus(string Time, string Part, string Drawing, string Motion)
{
public const string NothingToCut = "Nothing to cut";
/// <summary>The rows for <paramref name="playback"/> on <paramref name="plate"/> in <paramref name="units"/>.</summary>
public static CutSimulationStatus For(CutSimulationPlayback playback, Plate plate, Units units)
{
ArgumentNullException.ThrowIfNull(playback);
var sim = playback.Simulation;
if (sim == null || sim.Steps.Count == 0)
return new CutSimulationStatus(NothingToCut, string.Empty, string.Empty, string.Empty);
var time = playback.Time;
var timeText = $"{CutTimeReport.FormatTime(time)} / {CutTimeReport.FormatTime(sim.TotalTime)}";
var index = sim.IndexAt(time);
if (index >= sim.Steps.Count)
return new CutSimulationStatus(timeText, $"{sim.PartCount} of {sim.PartCount}", string.Empty, "Done");
var step = sim.Steps[index];
var drawing = plate != null && step.PartIndex < plate.Parts.Count ? plate.Parts[step.PartIndex].BaseDrawing?.Name : null;
var state = step.Kind switch
{
CutSimulationStepKind.Rapid => "Rapid",
CutSimulationStepKind.Pierce => "Piercing",
CutSimulationStepKind.Scribe => "Scribing",
_ => "Cutting",
};
if (step.Kind != CutSimulationStepKind.Pierce)
state += $" · {FeedText(step.SpeedAt(time - step.StartTime), units)}";
return new CutSimulationStatus(timeText, $"{step.PartIndex + 1} of {sim.PartCount}", drawing ?? string.Empty, state);
}
/// <summary>
/// A speed in units per second as the feed reads: inch feeds per minute, millimeter feeds per
/// second, as <see cref="Timing"/> uses them.
/// </summary>
public static string FeedText(double unitsPerSecond, Units units)
{
var rate = units == Units.Millimeters ? unitsPerSecond : unitsPerSecond * 60;
return $"{rate:n0} {UnitsHelper.GetShortTimeUnitPair(units)}";
}
/// <summary>The speed list's text for <paramref name="speed"/>, as "5×".</summary>
public static string SpeedText(double speed) => $"{speed:g}×";
}
+53 -94
View File
@@ -6,6 +6,7 @@ using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Windows.Forms;
using OpenNest.CNC;
using OpenNest.Desktop.Interaction;
using OpenNest.Geometry;
using OpenNest.Math;
@@ -26,10 +27,8 @@ internal sealed class CutSimulationOverlay : IDisposable
private readonly PlateView view;
private readonly Timer timer;
private readonly Timer settleTimer;
private readonly Stopwatch clock = new();
private readonly Stopwatch sinceZoom = new();
private CutSimulation simulation;
private TimeSpan time;
private readonly CutSimulationPlayback playback = new();
// The finished trail, rendered once at the scale it was built for, so panning and playback
// only blit it and draw the moves since. Null when the whole timeline would be too large an
@@ -52,26 +51,43 @@ internal sealed class CutSimulationOverlay : IDisposable
settleTimer.Stop();
view.Invalidate();
};
// The timer runs while the playhead plays, which stops itself at the end.
playback.Changed += (_, _) =>
{
if (timer.Enabled != playback.IsPlaying)
timer.Enabled = playback.IsPlaying;
};
}
/// <summary>Raised when the playhead, play state or timeline changes.</summary>
public event EventHandler Changed;
public event EventHandler Changed
{
add => playback.Changed += value;
remove => playback.Changed -= value;
}
public CutSimulation Simulation => simulation;
public bool IsActive => simulation != null;
public bool IsPlaying => timer.Enabled;
public double Speed { get; set; } = 10;
/// <summary>The playhead the simulator steps; each change through this overlay also redraws.</summary>
public CutSimulationPlayback Playback => playback;
public CutSimulation Simulation => playback.Simulation;
public bool IsActive => playback.IsActive;
public bool IsPlaying => playback.IsPlaying;
public double Speed
{
get => playback.Speed;
set => playback.Speed = value;
}
public TimeSpan Time
{
get => time;
get => playback.Time;
set
{
if (simulation == null)
if (playback.Simulation == null)
return;
time = value < TimeSpan.Zero ? TimeSpan.Zero : value > simulation.TotalTime ? simulation.TotalTime : value;
playback.Time = value;
view.Invalidate();
Changed?.Invoke(this, EventArgs.Empty);
}
}
@@ -81,128 +97,71 @@ internal sealed class CutSimulationOverlay : IDisposable
/// </summary>
public void Load(CutSimulation value)
{
var anchored = Anchor(simulation, value, time);
simulation = value;
ResetTrail();
Time = anchored;
if (simulation == null)
Pause();
playback.Load(value);
view.Invalidate();
Changed?.Invoke(this, EventArgs.Empty);
}
private static TimeSpan Anchor(CutSimulation old, CutSimulation next, TimeSpan time)
{
if (old == null || next == null || old.Steps.Count == 0 || old.Steps.Count != next.Steps.Count)
return time;
var index = old.IndexAt(time);
if (index >= old.Steps.Count)
return next.TotalTime;
return next.TimeAt(index, old.FractionAt(index, time));
}
public void Play()
{
if (simulation == null || simulation.Steps.Count == 0)
return;
if (time >= simulation.TotalTime)
Time = TimeSpan.Zero;
clock.Restart();
timer.Start();
Changed?.Invoke(this, EventArgs.Empty);
playback.Play();
view.Invalidate();
}
public void Pause()
public void Pause() => playback.Pause();
/// <summary>Runs <paramref name="action"/> on the playhead, then redraws.</summary>
public void Step(Action<CutSimulationPlayback> action)
{
if (!timer.Enabled)
return;
timer.Stop();
clock.Reset();
Changed?.Invoke(this, EventArgs.Empty);
action(playback);
view.Invalidate();
}
public void Clear()
{
timer.Stop();
simulation = null;
time = TimeSpan.Zero;
playback.Clear();
ResetTrail();
view.Invalidate();
Changed?.Invoke(this, EventArgs.Empty);
}
private void Tick()
{
Advance();
playback.Advance();
view.Invalidate();
}
// Moves the playhead by the wall time since the last advance. Paints call it too: WM_TIMER
// is only delivered when no paint is pending, so a pan's stream of repaints starves the timer.
private void Advance()
{
var elapsed = clock.Elapsed;
clock.Restart();
var next = time + TimeSpan.FromTicks((long)(elapsed.Ticks * Speed));
time = next > simulation.TotalTime ? simulation.TotalTime : next;
Changed?.Invoke(this, EventArgs.Empty);
if (time >= simulation.TotalTime)
Pause();
}
/// <summary>True for a part the torch has not started yet.</summary>
public bool IsPartPending(int partIndex)
{
if (simulation == null)
return false;
var index = simulation.IndexAt(time);
if (index >= simulation.Steps.Count)
return false;
if (index < 0)
return true;
var current = simulation.Steps[index];
// Travel toward a part has not touched it yet.
return partIndex > current.PartIndex
|| partIndex == current.PartIndex && current.Kind == CutSimulationStepKind.Rapid && !PartStarted(index);
}
private bool PartStarted(int index)
{
var part = simulation.Steps[index].PartIndex;
for (var i = index - 1; i >= 0 && simulation.Steps[i].PartIndex == part; i--)
{
if (simulation.Steps[i].Kind != CutSimulationStepKind.Rapid)
return true;
}
return false;
}
public bool IsPartPending(int partIndex) => playback.IsPartPending(partIndex);
public void Draw(Graphics graphics)
{
if (simulation == null || simulation.Steps.Count == 0)
if (Simulation == null || Simulation.Steps.Count == 0)
return;
// Paints advance too: WM_TIMER is only delivered when no paint is pending, so a pan's
// stream of repaints starves the timer.
if (IsPlaying)
Advance();
playback.Advance();
var state = graphics.Save();
try
{
graphics.SmoothingMode = SmoothingMode.AntiAlias;
var dpi = view.DeviceDpi / 96f;
var index = simulation.IndexAt(time);
var finished = System.Math.Clamp(index, 0, simulation.Steps.Count);
var time = playback.Time;
var index = Simulation.IndexAt(time);
var finished = System.Math.Clamp(index, 0, Simulation.Steps.Count);
using var pens = new TrailPens(dpi);
DrawTrail(graphics, pens, finished);
if (index >= simulation.Steps.Count)
if (index >= Simulation.Steps.Count)
{
DrawHead(graphics, simulation.Steps[^1].End, null, 0, dpi);
DrawHead(graphics, Simulation.Steps[^1].End, null, 0, dpi);
return;
}
var step = simulation.Steps[index];
var fraction = simulation.FractionAt(index, time);
var step = Simulation.Steps[index];
var fraction = Simulation.FractionAt(index, time);
var partial = Points(step, fraction);
if (partial.Length > 1)
{
@@ -293,7 +252,7 @@ internal sealed class CutSimulationOverlay : IDisposable
trailPhase = phase;
var bounds = RectangleF.Empty;
foreach (var step in simulation.Steps)
foreach (var step in Simulation.Steps)
{
if (step.Kind != CutSimulationStepKind.Pierce)
bounds = bounds.IsEmpty ? StepBounds(step) : RectangleF.Union(bounds, StepBounds(step));
@@ -328,7 +287,7 @@ internal sealed class CutSimulationOverlay : IDisposable
for (var i = from; i < to; i++)
{
var step = simulation.Steps[i];
var step = Simulation.Steps[i];
if (step.Kind == CutSimulationStepKind.Pierce)
continue;
+5 -14
View File
@@ -1,5 +1,6 @@
using System;
using System.Windows.Forms;
using OpenNest.Desktop;
using NumericUpDown = OpenNest.Controls.NumericUpDown;
namespace OpenNest.Forms
@@ -57,7 +58,7 @@ namespace OpenNest.Forms
}
private static decimal Clamp(System.Windows.Forms.NumericUpDown box, double value) =>
System.Math.Clamp((decimal)value, box.Minimum, box.Maximum);
CutTimeEntry.Clamp(value, box.Minimum, box.Maximum);
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
@@ -86,18 +87,8 @@ namespace OpenNest.Forms
holeFeedBox.Suffix = " " + suffix;
}
public CutParameters GetCutParameters()
{
return new CutParameters()
{
Feedrate = (double)numericUpDown1.Value,
HoleFeedrate = (double)holeFeedBox.Value,
RapidTravelRate = (double)numericUpDown2.Value,
PierceTime = TimeSpan.FromSeconds((double)numericUpDown3.Value),
SkipScribe = skipEtchBox.Checked,
Units = units,
Motion = machineBox.GetMotion(units),
};
}
public CutParameters GetCutParameters() =>
CutTimeEntry.Parameters(numericUpDown1.Value, holeFeedBox.Value, numericUpDown2.Value,
numericUpDown3.Value, skipEtchBox.Checked, units, machineBox.Machine);
}
}
+31 -106
View File
@@ -1,8 +1,11 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using OpenNest.CNC;
using OpenNest.Controls;
using OpenNest.Desktop;
using OpenNest.Desktop.Interaction;
using NumericUpDown = OpenNest.Controls.NumericUpDown;
namespace OpenNest.Forms
@@ -16,7 +19,7 @@ namespace OpenNest.Forms
public sealed class CutSimulatorForm : Form
{
private const int TrackResolution = 1000;
private static readonly double[] Speeds = { 1, 2, 5, 10, 25, 50, 100, 250 };
private static readonly IReadOnlyList<double> Speeds = CutSimulationPlayback.Speeds;
private readonly EditNestForm nestForm;
private readonly CutSimulationOverlay overlay;
@@ -55,8 +58,8 @@ namespace OpenNest.Forms
endButton = TransportButton("⏭", 44, 12f);
speedBox = new ComboBox { DropDownStyle = ComboBoxStyle.DropDownList, Width = 70, Anchor = AnchorStyles.Left };
foreach (var speed in Speeds)
speedBox.Items.Add($"{speed:g}×");
speedBox.SelectedIndex = Array.IndexOf(Speeds, 5.0);
speedBox.Items.Add(CutSimulationStatus.SpeedText(speed));
speedBox.SelectedIndex = CutSimulationPlayback.DefaultSpeedIndex;
previousPartButton = JumpButton("◀◀ Part");
previousContourButton = JumpButton("◀ Cutout");
@@ -147,17 +150,13 @@ namespace OpenNest.Forms
layout.Controls.Add(motion);
Controls.Add(layout);
restartButton.Click += (_, _) => overlay.Time = TimeSpan.Zero;
endButton.Click += (_, _) =>
{
overlay.Pause();
overlay.Time = overlay.Simulation?.TotalTime ?? TimeSpan.Zero;
};
restartButton.Click += (_, _) => overlay.Step(p => p.Restart());
endButton.Click += (_, _) => overlay.Step(p => p.End());
playButton.Click += (_, _) => TogglePlay();
previousPartButton.Click += (_, _) => Jump(sim => sim.PreviousPart(overlay.Time));
previousContourButton.Click += (_, _) => Jump(sim => sim.PreviousContour(overlay.Time));
nextContourButton.Click += (_, _) => Jump(sim => sim.NextContour(overlay.Time));
nextPartButton.Click += (_, _) => Jump(sim => sim.NextPart(overlay.Time));
previousPartButton.Click += (_, _) => overlay.Step(p => p.PreviousPart());
previousContourButton.Click += (_, _) => overlay.Step(p => p.PreviousContour());
nextContourButton.Click += (_, _) => overlay.Step(p => p.NextContour());
nextPartButton.Click += (_, _) => overlay.Step(p => p.NextPart());
speedBox.SelectedIndexChanged += (_, _) => overlay.Speed = Speeds[speedBox.SelectedIndex];
trackBar.Scroll += (_, _) => Seek();
feedBox.ValueChanged += (_, _) => Rebuild();
@@ -217,15 +216,6 @@ namespace OpenNest.Forms
private static Button JumpButton(string text) =>
new() { Text = text, AutoSize = true, MinimumSize = new Size(80, 0) };
// Jumps pause so the jumped-to contour stays on screen.
private void Jump(Func<CutSimulation, TimeSpan> target)
{
if (overlay.Simulation is not { } sim || sim.Steps.Count == 0)
return;
overlay.Pause();
overlay.Time = target(sim);
}
private static Label StatusCaption(string text) =>
new() { Text = text, AutoSize = true, ForeColor = SystemColors.GrayText, Margin = new Padding(3, 2, 8, 2) };
@@ -245,16 +235,8 @@ namespace OpenNest.Forms
new() { Text = text, AutoSize = true, Margin = new Padding(3, 7, 0, 0), Anchor = AnchorStyles.Left };
private CutParameters GetCutParameters() =>
new()
{
Feedrate = (double)feedBox.Value,
HoleFeedrate = (double)holeFeedBox.Value,
SkipScribe = skipEtchBox.Checked,
RapidTravelRate = (double)rapidBox.Value,
PierceTime = TimeSpan.FromSeconds((double)pierceBox.Value),
Units = nestForm.Nest.Units,
Motion = machineBox.GetMotion(nestForm.Nest.Units),
};
CutTimeEntry.Parameters(feedBox.Value, holeFeedBox.Value, rapidBox.Value, pierceBox.Value,
skipEtchBox.Checked, nestForm.Nest.Units, machineBox.Machine);
private void Rebuild()
{
@@ -311,39 +293,17 @@ namespace OpenNest.Forms
private void NestForm_FormClosed(object sender, FormClosedEventArgs e) => Close();
private void TogglePlay()
{
if (overlay.IsPlaying)
{
overlay.Pause();
return;
}
// Parts may have moved since the timeline was built; moves raise no plate event.
if (overlay.Simulation == null || overlay.Time <= TimeSpan.Zero || overlay.Time >= overlay.Simulation.TotalTime)
Rebuild();
overlay.Play();
}
// Parts may have moved since the timeline was built; moves raise no plate event.
private void TogglePlay() => overlay.Step(p => p.TogglePlay(Rebuild));
private void Seek()
{
if (updatingTrack || overlay.Simulation == null)
return;
overlay.Time = overlay.Simulation.TotalTime * ((double)trackBar.Value / TrackResolution);
overlay.Step(p => p.Seek((double)trackBar.Value / TrackResolution));
}
private void StepMove(int direction)
{
var sim = overlay.Simulation;
if (sim == null || sim.Steps.Count == 0)
return;
overlay.Pause();
var index = System.Math.Clamp(sim.IndexAt(overlay.Time), 0, sim.Steps.Count);
var atStart = index < sim.Steps.Count && overlay.Time == sim.Steps[index].StartTime;
var target = direction > 0 ? index + 1 : atStart ? index - 1 : index;
overlay.Time = target <= 0 ? TimeSpan.Zero
: target >= sim.Steps.Count ? sim.TotalTime
: sim.Steps[target].StartTime;
}
private void StepMove(int direction) => overlay.Step(p => p.StepMove(direction));
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
@@ -358,16 +318,16 @@ namespace OpenNest.Forms
TogglePlay();
return true;
case Keys.Control | Keys.Right:
Jump(sim => sim.NextContour(overlay.Time));
overlay.Step(p => p.NextContour());
return true;
case Keys.Control | Keys.Left:
Jump(sim => sim.PreviousContour(overlay.Time));
overlay.Step(p => p.PreviousContour());
return true;
case Keys.PageDown:
Jump(sim => sim.NextPart(overlay.Time));
overlay.Step(p => p.NextPart());
return true;
case Keys.PageUp:
Jump(sim => sim.PreviousPart(overlay.Time));
overlay.Step(p => p.PreviousPart());
return true;
case Keys.Right:
StepMove(1);
@@ -376,7 +336,7 @@ namespace OpenNest.Forms
StepMove(-1);
return true;
case Keys.Home:
overlay.Time = TimeSpan.Zero;
overlay.Step(p => p.Restart());
return true;
}
}
@@ -391,49 +351,14 @@ namespace OpenNest.Forms
var sim = overlay.Simulation;
playButton.Text = overlay.IsPlaying ? "⏸" : "▶";
if (sim == null || sim.Steps.Count == 0)
{
timeLabel.Text = "Nothing to cut";
partLabel.Text = drawingLabel.Text = stateLabel.Text = string.Empty;
SetTrack(0);
return;
}
var time = overlay.Time;
timeLabel.Text = $"{TimingForm.GetTimeMsg(time)} / {TimingForm.GetTimeMsg(sim.TotalTime)}";
SetTrack(sim.TotalTime > TimeSpan.Zero ? (int)System.Math.Round(TrackResolution * (time / sim.TotalTime)) : 0);
var index = sim.IndexAt(time);
if (index >= sim.Steps.Count)
{
partLabel.Text = $"{sim.PartCount} of {sim.PartCount}";
drawingLabel.Text = string.Empty;
stateLabel.Text = "Done";
return;
}
var step = sim.Steps[index];
var drawing = plate != null && step.PartIndex < plate.Parts.Count ? plate.Parts[step.PartIndex].BaseDrawing?.Name : null;
partLabel.Text = $"{step.PartIndex + 1} of {sim.PartCount}";
drawingLabel.Text = drawing ?? string.Empty;
var state = step.Kind switch
{
CutSimulationStepKind.Rapid => "Rapid",
CutSimulationStepKind.Pierce => "Piercing",
CutSimulationStepKind.Scribe => "Scribing",
_ => "Cutting",
};
if (step.Kind != CutSimulationStepKind.Pierce)
state += $" · {FeedText(step.SpeedAt(time - step.StartTime))}";
stateLabel.Text = state;
}
// Speeds are per second; inch feeds read per minute, as Timing uses them.
private string FeedText(double unitsPerSecond)
{
var units = nestForm.Nest.Units;
var rate = units == Units.Millimeters ? unitsPerSecond : unitsPerSecond * 60;
return $"{rate:n0} {UnitsHelper.GetShortTimeUnitPair(units)}";
var status = CutSimulationStatus.For(overlay.Playback, plate, nestForm.Nest.Units);
timeLabel.Text = status.Time;
partLabel.Text = status.Part;
drawingLabel.Text = status.Drawing;
stateLabel.Text = status.Motion;
SetTrack(sim is { Steps.Count: > 0 } && sim.TotalTime > TimeSpan.Zero
? (int)System.Math.Round(TrackResolution * (overlay.Time / sim.TotalTime))
: 0);
}
private void SetTrack(int value)
+6 -18
View File
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using OpenNest.Data;
using OpenNest.Desktop;
@@ -13,37 +12,26 @@ namespace OpenNest.Forms
/// </summary>
internal sealed class CutTimeMachineBox : ComboBox
{
private sealed record Choice(MachineConfig Machine)
{
public override string ToString() =>
Machine == null ? "None (full speed)"
: Machine.Motion == null ? $"{Machine.Name} (placeholder)"
: Machine.Name;
}
public CutTimeMachineBox()
{
DropDownStyle = ComboBoxStyle.DropDownList;
Width = 200;
var machines = SavedCutTimeSettings.SortedByName(MachineSettings.LoadMachines());
Items.Add(new Choice(null));
foreach (var machine in machines)
Items.Add(new Choice(machine));
var choices = CutTimeMachineChoice.For(MachineSettings.LoadMachines());
foreach (var choice in choices)
Items.Add(choice);
var saved = SavedMachine(machines);
SelectedItem = Items.Cast<Choice>().First(c => c.Machine == saved);
SelectedIndex = CutTimeMachineChoice.SavedIndex(choices, Properties.Settings.Default.CutTimeMachine);
}
/// <summary>The remembered machine, the first one until a choice is saved, or null for full speed.</summary>
public static MachineConfig SavedMachine(IEnumerable<MachineConfig> machines) =>
SavedCutTimeSettings.ChooseMachine(machines, Properties.Settings.Default.CutTimeMachine);
public MachineConfig Machine => (SelectedItem as Choice)?.Machine;
public MachineConfig Machine => (SelectedItem as CutTimeMachineChoice)?.Machine;
/// <summary>The chosen machine's limits in <paramref name="units"/>, or null for full speed.</summary>
public MotionProfile GetMotion(Units units) =>
Machine?.GetMotionOrPlaceholder().ToProfile(Machine.Units, units);
public MotionProfile GetMotion(Units units) => CutTimeMachineChoice.Motion(Machine, units);
public void SaveChoice()
{
+4 -15
View File
@@ -1195,31 +1195,20 @@ namespace OpenNest.Forms
}
public void CalculateCurrentPlateCutTime() =>
ShowCutTime(() => Timing.GetTimingInfo(PlateView.Plate), cutparams => Timing.CalculateTime(PlateView.Plate, cutparams));
ShowCutTime(cutparams => CutTimeReport.ForPlate(PlateView.Plate, cutparams, Nest.Units));
public void CalculateNestCutTime() =>
ShowCutTime(() => Timing.GetTimingInfo(Nest), cutparams => Timing.CalculateTime(Nest, cutparams));
ShowCutTime(cutparams => CutTimeReport.ForNest(Nest, cutparams));
private void ShowCutTime(Func<TimingInfo> getInfo, Func<CutParameters, TimeSpan> calculateTime)
private void ShowCutTime(Func<CutParameters, CutTimeReport> report)
{
var cutParamsForm = new CutParametersForm();
cutParamsForm.Units = Nest.Units;
if (cutParamsForm.ShowDialog() == DialogResult.OK)
{
var cutparams = cutParamsForm.GetCutParameters();
var info = getInfo();
var time = calculateTime(cutparams);
var timingForm = new TimingForm();
timingForm.Units = Nest.Units;
timingForm.SetCutDistance(info.CutDistance);
timingForm.SetCutTime(time);
timingForm.SetIntersectionCount(info.IntersectionCount);
timingForm.SetPierceCount(info.PierceCount);
timingForm.SetRapidDistance(info.TravelDistance);
timingForm.SetCutParameters(cutparams);
timingForm.SetReport(report(cutParamsForm.GetCutParameters()));
timingForm.ShowDialog();
}
}
+18 -45
View File
@@ -1,4 +1,4 @@
using System;
using System;
using System.Windows.Forms;
namespace OpenNest.Forms
@@ -19,20 +19,12 @@ namespace OpenNest.Forms
public void SetCutDistance(double dist)
{
cutDistanceLabel.Text = string.Format(
"{0} {1}",
System.Math.Round(dist, 4),
UnitsHelper.GetShortString(Units)
);
cutDistanceLabel.Text = CutTimeReport.DistanceText(dist, Units);
}
public void SetRapidDistance(double dist)
{
rapidDistanceLabel.Text = string.Format(
"{0} {1}",
System.Math.Round(dist, 4),
UnitsHelper.GetShortString(Units)
);
rapidDistanceLabel.Text = CutTimeReport.DistanceText(dist, Units);
}
public void SetIntersectionCount(int count)
@@ -47,44 +39,25 @@ namespace OpenNest.Forms
public void SetCutParameters(CutParameters cutparams)
{
feedrateLabel.Text = string.Format(
"{0} {1}/{2}",
cutparams.Feedrate,
UnitsHelper.GetShortString(Units),
UnitsHelper.GetShortTimeUnit(Units)
);
rapidLabel.Text = string.Format(
"{0} {1}/{2}",
cutparams.RapidTravelRate,
UnitsHelper.GetShortString(Units),
UnitsHelper.GetShortTimeUnit(Units)
);
feedrateLabel.Text = CutTimeReport.RateText(cutparams.Feedrate, Units);
rapidLabel.Text = CutTimeReport.RateText(cutparams.RapidTravelRate, Units);
pierceTimeLabel.Text = GetTimeMsg(cutparams.PierceTime);
}
public static string GetTimeMsg(TimeSpan time)
/// <summary>Shows everything <paramref name="report"/> holds, in its units.</summary>
public void SetReport(CutTimeReport report)
{
int hrs = time.Days * 24 + time.Hours;
int min = time.Minutes;
int sec = time.Seconds;
string msg = string.Empty;
if (hrs > 0)
{
msg += hrs.ToString() + "h ";
msg += min.ToString().PadLeft(2, '0') + "m ";
msg += sec.ToString().PadLeft(2, '0') + "s";
}
else if (min > 0)
{
msg += min.ToString().PadLeft(2, '0') + "m ";
msg += sec.ToString().PadLeft(2, '0') + "s";
}
else
msg += time.TotalSeconds.ToString("n0").PadLeft(2, '0') + "s";
return msg;
Units = report.Units;
cutTimeLabel.Text = report.CutTimeText;
cutDistanceLabel.Text = report.CutDistanceText;
rapidDistanceLabel.Text = report.RapidDistanceText;
interectionsLabel.Text = report.IntersectionCountText;
piercesLabel.Text = report.PierceCountText;
feedrateLabel.Text = report.FeedrateText;
rapidLabel.Text = report.RapidText;
pierceTimeLabel.Text = report.PierceTimeText;
}
public static string GetTimeMsg(TimeSpan time) => CutTimeReport.FormatTime(time);
}
}
+3 -1
View File
@@ -2,7 +2,9 @@
Calculate Cut Time, Plate > Simulate Cutting and the [nest report](nest-reports.md) share one
timing model (`OpenNest.Core/CNC/CutSimulation.cs`, `ContourTiming.cs`, `MotionPlanner.cs`),
and the last-used settings are shared through `SavedCutParameters`.
and the last-used settings are shared through `SavedCutTimeSettings` (`OpenNest.Desktop`), which
both desktop apps read and write in the user settings. Both apps word the timing through
`CutTimeReport` and play the simulator through `CutSimulationPlayback`.
## Inputs