diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.Simulation.cs b/OpenNest.Avalonia/Controls/PlateCanvas.Simulation.cs new file mode 100644 index 00000000..85cca2b7 --- /dev/null +++ b/OpenNest.Avalonia/Controls/PlateCanvas.Simulation.cs @@ -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 +{ + /// + /// Plate > 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 + /// holds the playhead. + /// + 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; + + /// The playhead drawn over the plate, or null when not simulating. + 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); + + /// One run of finished moves in world space: cuts, etches and travel apart. + 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(); + } + + /// + /// 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. + /// + private sealed class SimulationTrail + { + private readonly List full = new(); + + public SimulationTrail(CutSimulation simulation) + { + Simulation = simulation; + } + + public CutSimulation Simulation { get; } + + /// The chunks drawing moves [0, ). + public IReadOnlyList 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(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 MutedCutOffStrokes = new(); + public IReadOnlyList 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); + } + } + } +} diff --git a/OpenNest.Avalonia/Controls/PlateCanvas.cs b/OpenNest.Avalonia/Controls/PlateCanvas.cs index b8cb4131..0f875f1c 100644 --- a/OpenNest.Avalonia/Controls/PlateCanvas.cs +++ b/OpenNest.Avalonia/Controls/PlateCanvas.cs @@ -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); } @@ -398,6 +399,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)); } @@ -687,7 +690,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 Contacts, Vector CenterOfGravity, bool Supported, Vector? Tab); @@ -860,9 +863,11 @@ namespace OpenNest.Avalonia.Controls DrawPiercePoints(); DrawCutDirection(); DrawClamps(); + DrawMutedCutOffs(); DrawCutOffs(); DrawCommonLines(); DrawSupport(); + DrawSimulation(); DrawSelectionWindow(); DrawToolOverlays(); } @@ -968,16 +973,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(); @@ -990,6 +1001,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); @@ -1106,6 +1118,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); } diff --git a/OpenNest.Avalonia/CutSimulatorWindow.cs b/OpenNest.Avalonia/CutSimulatorWindow.cs new file mode 100644 index 00000000..04123edd --- /dev/null +++ b/OpenNest.Avalonia/CutSimulatorWindow.cs @@ -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 +{ + /// + /// Plate > 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 holds the + /// playhead and the plate view draws it. + /// + 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 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; + } + + /// The parameters the boxes time the cut with. + 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); + } + } +} diff --git a/OpenNest.Avalonia/CutTimeDialog.cs b/OpenNest.Avalonia/CutTimeDialog.cs new file mode 100644 index 00000000..33b8ff03 --- /dev/null +++ b/OpenNest.Avalonia/CutTimeDialog.cs @@ -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 +{ + /// + /// 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. + /// + 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 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); + } + + /// + /// The parameters entered, in , or null when the dialog was + /// cancelled. false leaves the remembered values alone. + /// + public static Task ShowAsync( + Window owner, Units units, IReadOnlyList machines, bool saveSettings = true) => + new CutTimeDialog(units, machines, saveSettings).ShowDialog(owner); + } + + /// + /// 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. + /// + 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; } + + /// The box with its unit. + public Control View { get; } + + public decimal Value => System.Math.Clamp(last, minimum, maximum); + + /// Raised when a new value is entered. + public event EventHandler Changed; + } + + /// + /// The cut-time values last used, in the user settings both apps share (WinForms names and + /// text, see ). + /// + internal static class CutTimeSettingsFile + { + public static SavedCutTimeSettings Read() => + SavedCutTimeSettings.Read(UserSettingsFile.Read(UserSettingsFile.DefaultPath)); + + /// Remembers the feeds, pierce, etch choice and machine (null for full speed). + 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)); + } +} diff --git a/OpenNest.Avalonia/InspectionLock.cs b/OpenNest.Avalonia/InspectionLock.cs new file mode 100644 index 00000000..bae38896 --- /dev/null +++ b/OpenNest.Avalonia/InspectionLock.cs @@ -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 +{ + /// + /// 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. + /// + 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 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 live) + { + foreach (var child in parent.LogicalChildren.OfType().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; + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.CutTime.cs b/OpenNest.Avalonia/MainWindow.CutTime.cs new file mode 100644 index 00000000..e735a015 --- /dev/null +++ b/OpenNest.Avalonia/MainWindow.CutTime.cs @@ -0,0 +1,115 @@ +using System.Threading.Tasks; +using Avalonia.Input; +using Avalonia.Interactivity; +using OpenNest.Forms; + +namespace OpenNest.Avalonia +{ + /// + /// Plate > Calculate Cut Time, Nest > Calculate Cut Time and Plate > 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. + /// + 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); + } + + /// + /// 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. + /// + 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; + } + } +} diff --git a/OpenNest.Avalonia/MainWindow.axaml b/OpenNest.Avalonia/MainWindow.axaml index f8788efa..8a91df8b 100644 --- a/OpenNest.Avalonia/MainWindow.axaml +++ b/OpenNest.Avalonia/MainWindow.axaml @@ -49,6 +49,9 @@ + + + @@ -88,6 +91,8 @@ + + @@ -140,6 +145,7 @@