From 095b4d6e724b7cf0e45098ad761afb4e16e8e4a4 Mon Sep 17 00:00:00 2001 From: AJ Isaacs Date: Sun, 18 Oct 2026 16:36:43 -0400 Subject: [PATCH] feat: time cuts with machine acceleration limits A Grbl-style lookahead planner re-times the cut simulation with trapezoidal acceleration, junction-deviation corner speeds and a centripetal cap on arcs. Machines gain cut/rapid acceleration and corner deviation in Machine Configuration, with placeholder values until the controller's are entered. The simulator and Calculate Cut Time pick the machine (or full speed), and the simulator shows the live head speed. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + OpenNest.Core/CNC/CutSimulation.cs | 93 +++++++++++++-- OpenNest.Core/CNC/MotionPlanner.cs | 140 ++++++++++++++++++++++ OpenNest.Core/CutParameters.cs | 6 + OpenNest.Core/MotionProfile.cs | 20 ++++ OpenNest.Core/Timing.cs | 17 +++ OpenNest.Data/MachineConfig.cs | 5 + OpenNest.Data/MotionConfig.cs | 42 +++++++ OpenNest.Tests/CNC/MotionPlannerTests.cs | 144 +++++++++++++++++++++++ OpenNest.Tests/Data/MotionConfigTests.cs | 62 ++++++++++ OpenNest/Forms/CutParametersForm.cs | 21 +++- OpenNest/Forms/CutSimulatorForm.cs | 24 +++- OpenNest/Forms/CutTimeMachineBox.cs | 52 ++++++++ OpenNest/Forms/EditNestForm.cs | 4 +- OpenNest/Forms/MachineConfigForm.cs | 57 ++++++++- OpenNest/Forms/MachineSettings.cs | 32 +++++ OpenNest/Forms/MainForm.Tools.cs | 8 +- OpenNest/Properties/Settings.Designer.cs | 12 ++ OpenNest/Properties/Settings.settings | 3 + OpenNest/app.config | 3 + README.md | 2 +- docs/cut-time-estimates.md | 37 ++++++ 22 files changed, 762 insertions(+), 23 deletions(-) create mode 100644 OpenNest.Core/CNC/MotionPlanner.cs create mode 100644 OpenNest.Core/MotionProfile.cs create mode 100644 OpenNest.Data/MotionConfig.cs create mode 100644 OpenNest.Tests/CNC/MotionPlannerTests.cs create mode 100644 OpenNest.Tests/Data/MotionConfigTests.cs create mode 100644 OpenNest/Forms/CutTimeMachineBox.cs create mode 100644 docs/cut-time-estimates.md diff --git a/AGENTS.md b/AGENTS.md index fa3528d6..def038df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -63,6 +63,7 @@ Read the relevant contract before changing its behavior: - [Material-overlap diagnostics](docs/geometry/visual-overlap-check.md) - [Automatic cutoffs and sequencing](docs/automatic-scrap-cutoffs.md) - [Pre-post verification](docs/post-verification.md) +- [Cut-time estimates](docs/cut-time-estimates.md): simulator/Calculate Cut Time acceleration planner and placeholder machine limits - [Cincinnati CL](docs/cincinnati-post-output.md) and [CI Fiber](docs/cincinnati-ci-fiber-post-output.md) - [Fill verification](docs/performance/fill-verification.md): opt-in benchmarks, frozen oracles, Debug-only counters and predictor initialization. Zero Release counters do not prove work removal. - [Desktop auto-update](docs/auto-update.md): Velopack feed, `UpdateFeedUrl` setting and `Deploy-OpenNest.ps1`. diff --git a/OpenNest.Core/CNC/CutSimulation.cs b/OpenNest.Core/CNC/CutSimulation.cs index 311ebafd..43c25d9d 100644 --- a/OpenNest.Core/CNC/CutSimulation.cs +++ b/OpenNest.Core/CNC/CutSimulation.cs @@ -37,9 +37,79 @@ namespace OpenNest.CNC public double Sweep { get; init; } public double Length { get; init; } public TimeSpan StartTime { get; internal set; } - public TimeSpan Duration { get; init; } + public TimeSpan Duration { get; internal set; } public TimeSpan EndTime => StartTime + Duration; + /// + /// Planned speed profile in units per second: accelerate from + /// to , then decelerate to . A zero + /// moves at constant speed for the whole step. + /// + public double EntrySpeed { get; internal set; } + public double CruiseSpeed { get; internal set; } + public double ExitSpeed { get; internal set; } + public double Acceleration { get; internal set; } + + /// Fraction (0..1) of this step's distance covered into it. + public double ProgressAt(TimeSpan elapsed) + { + if (Duration <= TimeSpan.Zero) + return elapsed >= TimeSpan.Zero ? 1 : 0; + if (Acceleration <= 0 || Length <= 0) + return System.Math.Clamp(elapsed / Duration, 0, 1); + return System.Math.Clamp(DistanceAt(elapsed.TotalSeconds) / Length, 0, 1); + } + + /// Head speed in units per second into this step. + public double SpeedAt(TimeSpan elapsed) + { + if (Kind == CutSimulationStepKind.Pierce || Duration <= TimeSpan.Zero) + return 0; + if (Acceleration <= 0) + return Length / Duration.TotalSeconds; + + var t = System.Math.Clamp(elapsed.TotalSeconds, 0, Duration.TotalSeconds); + var (accelEnd, cruiseEnd) = PhaseEnds(); + if (t < accelEnd) + return EntrySpeed + Acceleration * t; + if (t < cruiseEnd) + return CruiseSpeed; + return System.Math.Max(0, CruiseSpeed - Acceleration * (t - cruiseEnd)); + } + + private (double AccelEnd, double CruiseEnd) PhaseEnds() + { + var accelTime = (CruiseSpeed - EntrySpeed) / Acceleration; + var accelDistance = (CruiseSpeed * CruiseSpeed - EntrySpeed * EntrySpeed) / (2 * Acceleration); + var decelDistance = (CruiseSpeed * CruiseSpeed - ExitSpeed * ExitSpeed) / (2 * Acceleration); + var cruise = CruiseSpeed > 0 ? System.Math.Max(0, Length - accelDistance - decelDistance) / CruiseSpeed : 0; + return (accelTime, accelTime + cruise); + } + + private double DistanceAt(double t) + { + var (accelEnd, cruiseEnd) = PhaseEnds(); + var accelDistance = EntrySpeed * accelEnd + Acceleration * accelEnd * accelEnd / 2; + if (t < accelEnd) + return EntrySpeed * t + Acceleration * t * t / 2; + if (t < cruiseEnd) + return accelDistance + CruiseSpeed * (t - accelEnd); + var decel = t - cruiseEnd; + return accelDistance + CruiseSpeed * (cruiseEnd - accelEnd) + CruiseSpeed * decel - Acceleration * decel * decel / 2; + } + + /// Unit direction of travel at the start (0) or end (1) of the step. + internal Vector TangentAt(double fraction) + { + if (IsArc) + { + var angle = StartAngle + Sweep * fraction; + var sign = System.Math.Sign(Sweep); + return new Vector(-System.Math.Sin(angle) * sign, System.Math.Cos(angle) * sign); + } + return Length > 0 ? new Vector((End.X - Start.X) / Length, (End.Y - Start.Y) / Length) : Vector.Zero; + } + /// The tool position after (0..1) of this step. public Vector PointAt(double fraction) { @@ -61,8 +131,9 @@ namespace OpenNest.CNC /// /// A replayable timeline of a plate's tool motion in cutting order, timed with the - /// same feed, rapid and pierce rules as . Display only: - /// it does not model acceleration, per-motion feed overrides or clamp removal. + /// same feed, rapid and pierce rules as , + /// plus acceleration when set (see ). + /// It does not model jerk, per-motion feed overrides or clamp removal. /// public sealed class CutSimulation { @@ -153,6 +224,9 @@ namespace OpenNest.CNC builder.AddProgram(part.Program, part.Location, ref mode, ref pos); } + if (parameters.Motion != null) + MotionPlanner.Plan(builder.Steps, parameters); + return new CutSimulation(builder.Steps, plate.Parts.Count); } @@ -179,13 +253,18 @@ namespace OpenNest.CNC return lo; } - /// Fraction (0..1) of step completed at . + /// + /// Fraction (0..1) of step completed at : + /// distance for motion, elapsed time for a pierce. + /// public double FractionAt(int index, TimeSpan time) { var step = steps[index]; - if (step.Duration <= TimeSpan.Zero) - return time >= step.StartTime ? 1 : 0; - return System.Math.Clamp((time - step.StartTime) / step.Duration, 0, 1); + if (step.Kind == CutSimulationStepKind.Pierce) + return step.Duration <= TimeSpan.Zero + ? time >= step.StartTime ? 1 : 0 + : System.Math.Clamp((time - step.StartTime) / step.Duration, 0, 1); + return step.ProgressAt(time - step.StartTime); } public Vector ToolPositionAt(TimeSpan time) diff --git a/OpenNest.Core/CNC/MotionPlanner.cs b/OpenNest.Core/CNC/MotionPlanner.cs new file mode 100644 index 00000000..ce9880ee --- /dev/null +++ b/OpenNest.Core/CNC/MotionPlanner.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; + +namespace OpenNest.CNC +{ + /// + /// Re-times s with trapezoidal acceleration, in the style of + /// Grbl's lookahead planner. Each cutting run (moves between a pierce and the next travel) + /// starts and ends at rest. Corners slow to a junction-deviation speed, arcs are capped at + /// their centripetal limit, and a backward then forward pass keeps every change of speed + /// within the acceleration. Travel and pierces are planned on their own, from rest to rest. + /// + public static class MotionPlanner + { + private const double Straight = 0.999999; + + public static void Plan(List steps, CutParameters parameters) + { + ArgumentNullException.ThrowIfNull(steps); + ArgumentNullException.ThrowIfNull(parameters); + var motion = parameters.Motion ?? throw new ArgumentException("No motion profile.", nameof(parameters)); + + var start = 0; + while (start < steps.Count) + { + var end = start + 1; + if (IsCutting(steps[start])) + { + while (end < steps.Count && IsCutting(steps[end]) && steps[end].Kind == steps[start].Kind) + end++; + PlanRun(steps, start, end, NominalSpeed(parameters.Feedrate, parameters.Units), motion.CutAcceleration, motion.CornerDeviation); + } + else if (steps[start].Kind == CutSimulationStepKind.Rapid) + { + PlanRun(steps, start, end, NominalSpeed(parameters.RapidTravelRate, parameters.Units), motion.RapidAcceleration, 0); + } + start = end; + } + + var clock = TimeSpan.Zero; + foreach (var step in steps) + { + step.StartTime = clock; + clock += step.Duration; + } + } + + private static bool IsCutting(CutSimulationStep step) => + step.Kind is CutSimulationStepKind.Cut or CutSimulationStepKind.Scribe; + + // Feed rates follow Timing.CalculateTime: inch rates are per minute, millimeter rates per second. + private static double NominalSpeed(double rate, Units units) => + units == Units.Millimeters ? rate : rate / 60; + + private static void PlanRun(List steps, int start, int end, double nominal, double acceleration, double deviation) + { + if (acceleration <= 0 || nominal <= 0) + return; // Keep the constant-speed timing. + + var count = end - start; + var maxSpeed = new double[count]; + var entry = new double[count + 1]; // entry[count] is the run's exit: at rest. + + for (var i = 0; i < count; i++) + { + var step = steps[start + i]; + maxSpeed[i] = step.IsArc && step.Radius > 0 + ? System.Math.Min(nominal, System.Math.Sqrt(acceleration * step.Radius)) + : nominal; + entry[i] = i == 0 ? 0 : JunctionSpeed(steps[start + i - 1], step, acceleration, deviation, System.Math.Min(maxSpeed[i - 1], maxSpeed[i])); + } + + // Backward: every step must be able to slow to the next one's entry. + for (var i = count - 1; i >= 0; i--) + entry[i] = System.Math.Min(entry[i], Reachable(entry[i + 1], acceleration, steps[start + i].Length)); + + // Forward: and to reach that entry from its own. + for (var i = 0; i < count; i++) + entry[i + 1] = System.Math.Min(entry[i + 1], Reachable(entry[i], acceleration, steps[start + i].Length)); + + for (var i = 0; i < count; i++) + Profile(steps[start + i], entry[i], entry[i + 1], maxSpeed[i], acceleration); + } + + private static double Reachable(double speed, double acceleration, double length) => + System.Math.Sqrt(speed * speed + 2 * acceleration * length); + + /// + /// The fastest the head may pass from into : + /// v² = a·δ·sin(θ/2) / (1 − sin(θ/2)), θ being the angle the path turns through. + /// + internal static double JunctionSpeed(CutSimulationStep previous, CutSimulationStep next, double acceleration, double deviation, double cap) + { + var exit = previous.TangentAt(1); + var enter = next.TangentAt(0); + var cosTheta = -(exit.X * enter.X + exit.Y * enter.Y); + + if (cosTheta < -Straight) + return cap; + if (cosTheta > Straight || deviation <= 0) + return 0; + + var sinHalf = System.Math.Sqrt(0.5 * (1 - cosTheta)); + var speed = System.Math.Sqrt(acceleration * deviation * sinHalf / (1 - sinHalf)); + return System.Math.Min(cap, speed); + } + + private static void Profile(CutSimulationStep step, double entry, double exit, double maxSpeed, double acceleration) + { + var length = step.Length; + if (length <= 0) + { + step.Duration = TimeSpan.Zero; + return; + } + + var cruise = maxSpeed; + var accelDistance = (cruise * cruise - entry * entry) / (2 * acceleration); + var decelDistance = (cruise * cruise - exit * exit) / (2 * acceleration); + if (accelDistance + decelDistance > length) + { + // Too short to reach full speed: a triangle peaking where the two ramps meet. + cruise = System.Math.Sqrt((2 * acceleration * length + entry * entry + exit * exit) / 2); + cruise = System.Math.Max(cruise, System.Math.Max(entry, exit)); + accelDistance = (cruise * cruise - entry * entry) / (2 * acceleration); + decelDistance = (cruise * cruise - exit * exit) / (2 * acceleration); + } + + var cruiseDistance = System.Math.Max(0, length - accelDistance - decelDistance); + var seconds = (cruise - entry) / acceleration + (cruise - exit) / acceleration + + (cruise > 0 ? cruiseDistance / cruise : 0); + + step.EntrySpeed = entry; + step.CruiseSpeed = cruise; + step.ExitSpeed = exit; + step.Acceleration = acceleration; + step.Duration = TimeSpan.FromSeconds(seconds); + } + } +} diff --git a/OpenNest.Core/CutParameters.cs b/OpenNest.Core/CutParameters.cs index 8e538ac4..3294af4f 100644 --- a/OpenNest.Core/CutParameters.cs +++ b/OpenNest.Core/CutParameters.cs @@ -11,6 +11,12 @@ public class CutParameters public string PostProcessor { get; set; } public Units Units { get; set; } + /// + /// Acceleration limits; null estimates every move at full speed. Applied by + /// and the plate/nest overloads of . + /// + public MotionProfile Motion { get; set; } + public static CutParameters Default => new() { diff --git a/OpenNest.Core/MotionProfile.cs b/OpenNest.Core/MotionProfile.cs new file mode 100644 index 00000000..67051753 --- /dev/null +++ b/OpenNest.Core/MotionProfile.cs @@ -0,0 +1,20 @@ +namespace OpenNest; + +/// +/// A machine's motion limits for cut-time estimates, in the units of the +/// it is attached to (inches or millimeters, per second squared). +/// +public class MotionProfile +{ + /// Acceleration while cutting or scribing, and the centripetal limit on arcs. + public double CutAcceleration { get; set; } + + /// Acceleration for head-up travel. + public double RapidAcceleration { get; set; } + + /// + /// Junction deviation: how far the path may round a corner, which sets how fast the head + /// may take it. Zero stops at every corner. + /// + public double CornerDeviation { get; set; } +} diff --git a/OpenNest.Core/Timing.cs b/OpenNest.Core/Timing.cs index 0b0f14c9..775c3818 100644 --- a/OpenNest.Core/Timing.cs +++ b/OpenNest.Core/Timing.cs @@ -75,6 +75,23 @@ namespace OpenNest info.TravelDistance += entity.Length; } + /// + /// A plate's cut time over its quantity. With it is the + /// accelerated timeline; otherwise every move runs at full speed. + /// + public static TimeSpan CalculateTime(Plate plate, CutParameters cutParams) + { + if (cutParams.Motion == null) + return CalculateTime(GetTimingInfo(plate), cutParams); + + var sheet = CutSimulation.Build(plate, cutParams).TotalTime + + TimeSpan.FromMinutes(plate.ClampRemovalMinutes); + return sheet * plate.Quantity; + } + + public static TimeSpan CalculateTime(Nest nest, CutParameters cutParams) => + nest.Plates.Aggregate(TimeSpan.Zero, (total, plate) => total + CalculateTime(plate, cutParams)); + public static TimeSpan CalculateTime(TimingInfo info, CutParameters cutParams) { var time = new TimeSpan(); diff --git a/OpenNest.Data/MachineConfig.cs b/OpenNest.Data/MachineConfig.cs index 40a05e66..d8f62785 100644 --- a/OpenNest.Data/MachineConfig.cs +++ b/OpenNest.Data/MachineConfig.cs @@ -11,6 +11,11 @@ public class MachineConfig public UnitSystem Units { get; set; } = UnitSystem.Inches; public List Materials { get; set; } = new(); + /// Acceleration limits; null until entered, when stands in. + public MotionConfig? Motion { get; set; } + + public MotionConfig GetMotionOrPlaceholder() => Motion ?? MotionConfig.Placeholder(Units); + public ThicknessConfig? GetParameters(string material, double thickness) => GetParameters(material, null, thickness); diff --git a/OpenNest.Data/MotionConfig.cs b/OpenNest.Data/MotionConfig.cs new file mode 100644 index 00000000..8872f8c7 --- /dev/null +++ b/OpenNest.Data/MotionConfig.cs @@ -0,0 +1,42 @@ +namespace OpenNest.Data; + +/// +/// A machine's acceleration limits for cut-time estimates, in the machine's units +/// (in/s² or mm/s², and in or mm for the corner deviation). +/// +public class MotionConfig +{ + private const double MillimetersPerInch = 25.4; + + public double CutAcceleration { get; set; } + public double RapidAcceleration { get; set; } + public double CornerDeviation { get; set; } + + /// + /// Stand-in limits for a machine whose controller values are not on file yet: about + /// 0.5 G cutting, 1 G travel and a 0.001 in (0.025 mm) corner deviation. Replace them + /// with the controller's own settings. + /// + public static MotionConfig Placeholder(UnitSystem units) => + units == UnitSystem.Millimeters + ? new MotionConfig { CutAcceleration = 4900, RapidAcceleration = 9800, CornerDeviation = 0.025 } + : new MotionConfig { CutAcceleration = 193, RapidAcceleration = 386, CornerDeviation = 0.001 }; + + /// These limits converted from to the nest's units. + public MotionProfile ToProfile(UnitSystem from, Units to) + { + var scale = (from, to) switch + { + (UnitSystem.Inches, Units.Millimeters) => MillimetersPerInch, + (UnitSystem.Millimeters, Units.Inches) => 1 / MillimetersPerInch, + _ => 1, + }; + + return new MotionProfile + { + CutAcceleration = CutAcceleration * scale, + RapidAcceleration = RapidAcceleration * scale, + CornerDeviation = CornerDeviation * scale, + }; + } +} diff --git a/OpenNest.Tests/CNC/MotionPlannerTests.cs b/OpenNest.Tests/CNC/MotionPlannerTests.cs new file mode 100644 index 00000000..3d63ca24 --- /dev/null +++ b/OpenNest.Tests/CNC/MotionPlannerTests.cs @@ -0,0 +1,144 @@ +using OpenNest.CNC; +using OpenNest.Geometry; + +namespace OpenNest.Tests.CNC; + +public class MotionPlannerTests +{ + // 600 in/min = 10 in/s; reaching it at 100 in/s² takes 0.1 s over 0.5 in. + private static CutParameters Parameters(double deviation = 0, double rapidAcceleration = 100) => new() + { + Feedrate = 600, + RapidTravelRate = 1200, + PierceTime = TimeSpan.Zero, + Units = Units.Inches, + Motion = new MotionProfile + { + CutAcceleration = 100, + RapidAcceleration = rapidAcceleration, + CornerDeviation = deviation, + }, + }; + + private static CutSimulation Simulate(CutParameters parameters, params ICode[] codes) + { + var program = new Program(); + program.Codes.Add(new RapidMove(0, 0)); + foreach (var code in codes) + program.Codes.Add(code); + var plate = new Plate(48, 96); + plate.Parts.Add(new Part(new Drawing("part", program), Vector.Zero)); + return CutSimulation.Build(plate, parameters); + } + + private static double CutSeconds(CutSimulation sim) => + sim.Steps.Where(s => s.Kind == CutSimulationStepKind.Cut).Sum(s => s.Duration.TotalSeconds); + + [Fact] + public void LongLineRampsUpCruisesAndRampsDown() + { + var sim = Simulate(Parameters(), new LinearMove(10, 0)); + + // 0.1 s up + 9 in at 10 in/s + 0.1 s down. + Assert.Equal(1.1, CutSeconds(sim), 6); + var line = sim.Steps.Single(s => s.Kind == CutSimulationStepKind.Cut); + Assert.Equal(0.5, line.ProgressAt(line.Duration / 2), 6); + Assert.Equal(0.05, line.ProgressAt(TimeSpan.FromSeconds(0.1)), 6); // 0.5 in ramp of 10 in + Assert.Equal(10, line.SpeedAt(line.Duration / 2), 6); + } + + [Fact] + public void ShortLineNeverReachesFeed() + { + var sim = Simulate(Parameters(), new LinearMove(0.5, 0)); + + var line = sim.Steps.Single(s => s.Kind == CutSimulationStepKind.Cut); + Assert.Equal(System.Math.Sqrt(50), line.CruiseSpeed, 6); + Assert.Equal(2 * System.Math.Sqrt(50) / 100, line.Duration.TotalSeconds, 6); // TimeSpan ticks are 100 ns + } + + [Fact] + public void CollinearMovesDoNotSlowBetweenThem() + { + var sim = Simulate(Parameters(), new LinearMove(5, 0), new LinearMove(10, 0)); + + Assert.Equal(1.1, CutSeconds(sim), 6); + } + + [Fact] + public void CornersSlowByTheirDeviation() + { + var square = new ICode[] { new LinearMove(10, 0), new LinearMove(10, 10), new LinearMove(0, 10), new LinearMove(0, 0) }; + + var stopping = CutSeconds(Simulate(Parameters(deviation: 0), square)); + var rounding = CutSeconds(Simulate(Parameters(deviation: 0.01), square)); + + Assert.Equal(4.4, stopping, 6); // every corner comes to rest + Assert.InRange(rounding, 4.2 + 1e-6, 4.4 - 1e-6); + // 90°: v² = a·δ·sin45° / (1 − sin45°) + var expected = System.Math.Sqrt(100 * 0.01 * System.Math.Sqrt(0.5) / (1 - System.Math.Sqrt(0.5))); + var second = Simulate(Parameters(deviation: 0.01), square).Steps.Where(s => s.Kind == CutSimulationStepKind.Cut).ElementAt(1); + Assert.Equal(expected, second.EntrySpeed, 6); + } + + [Fact] + public void SmallArcsAreCappedByCentripetalAcceleration() + { + var sim = Simulate(Parameters(), new RapidMove(0.1, 0), new ArcMove(new Vector(0.1, 0), Vector.Zero, RotationType.CCW)); + + var arc = sim.Steps.Single(s => s.IsArc); + Assert.Equal(System.Math.Sqrt(100 * 0.1), arc.CruiseSpeed, 6); // well under 10 in/s + } + + [Fact] + public void TravelUsesTheRapidAcceleration() + { + var program = new Program(); + program.Codes.Add(new RapidMove(20, 0)); + var plate = new Plate(48, 96); + plate.Parts.Add(new Part(new Drawing("part", program), Vector.Zero)); + + var sim = CutSimulation.Build(plate, Parameters(rapidAcceleration: 200)); + + // 20 in/s reached in 0.1 s over 1 in each way, 18 in at full speed. + var rapid = sim.Steps.Single(); + Assert.Equal(0.1 + 0.9 + 0.1, rapid.Duration.TotalSeconds, 6); + } + + [Fact] + public void PlateTimeUsesTheTimelineTimesQuantity() + { + var program = new Program(); + program.Codes.Add(new RapidMove(0, 0)); + program.Codes.Add(new LinearMove(10, 0)); + var plate = new Plate(48, 96) { Quantity = 3 }; + plate.Parts.Add(new Part(new Drawing("part", program), Vector.Zero)); + var nest = new Nest(); + nest.Plates.Add(plate); + + var time = Timing.CalculateTime(nest, Parameters()); + + Assert.Equal(3 * 1.1, time.TotalSeconds, 6); + } + + [Fact] + public void AccelerationOnlyEverAddsTime() + { + var codes = new ICode[] + { + new LinearMove(4, 0), + new ArcMove(new Vector(6, 2), new Vector(4, 2), RotationType.CCW), + new LinearMove(6, 6), + new LinearMove(0, 0), + }; + var constant = Parameters(); + constant.Motion = null; + + var plain = Simulate(constant, codes); + var planned = Simulate(Parameters(deviation: 0.005), codes); + + Assert.True(planned.TotalTime > plain.TotalTime); + Assert.Equal(plain.Steps.Count, planned.Steps.Count); + Assert.Equal(planned.Steps[^1].EndTime, planned.TotalTime); + } +} diff --git a/OpenNest.Tests/Data/MotionConfigTests.cs b/OpenNest.Tests/Data/MotionConfigTests.cs new file mode 100644 index 00000000..0aef2712 --- /dev/null +++ b/OpenNest.Tests/Data/MotionConfigTests.cs @@ -0,0 +1,62 @@ +using OpenNest.Data; + +namespace OpenNest.Tests.Data; + +public class MotionConfigTests : IDisposable +{ + private readonly string _testDir = Path.Combine(Path.GetTempPath(), "OpenNestTests", Guid.NewGuid().ToString()); + + public void Dispose() + { + if (Directory.Exists(_testDir)) + Directory.Delete(_testDir, true); + } + + [Fact] + public void MachineWithoutMotionFallsBackToUnitPlaceholders() + { + var inch = new MachineConfig { Units = UnitSystem.Inches }; + var metric = new MachineConfig { Units = UnitSystem.Millimeters }; + + Assert.Null(inch.Motion); + Assert.Equal(193, inch.GetMotionOrPlaceholder().CutAcceleration); + Assert.Equal(4900, metric.GetMotionOrPlaceholder().CutAcceleration); + } + + [Fact] + public void MotionRoundTripsAndOlderFilesLoadWithoutIt() + { + var provider = new LocalJsonProvider(_testDir); + var machine = new MachineConfig + { + Name = "Laser", + Motion = new MotionConfig { CutAcceleration = 250, RapidAcceleration = 500, CornerDeviation = 0.002 }, + }; + var older = new MachineConfig { Name = "Older" }; + + provider.SaveMachine(machine); + provider.SaveMachine(older); + + var loaded = provider.GetMachine(machine.Id)!; + Assert.Equal(250, loaded.Motion!.CutAcceleration); + Assert.Equal(500, loaded.Motion.RapidAcceleration); + Assert.Equal(0.002, loaded.Motion.CornerDeviation); + Assert.Null(provider.GetMachine(older.Id)!.Motion); + Assert.DoesNotContain("motionOrPlaceholder", File.ReadAllText(Path.Combine(_testDir, $"{machine.Id}.json"))); + } + + [Theory] + [InlineData(UnitSystem.Inches, Units.Inches, 1)] + [InlineData(UnitSystem.Inches, Units.Millimeters, 25.4)] + [InlineData(UnitSystem.Millimeters, Units.Inches, 1 / 25.4)] + public void ProfileConvertsToTheNestUnits(UnitSystem machine, Units nest, double scale) + { + var motion = new MotionConfig { CutAcceleration = 100, RapidAcceleration = 200, CornerDeviation = 0.01 }; + + var profile = motion.ToProfile(machine, nest); + + Assert.Equal(100 * scale, profile.CutAcceleration, 9); + Assert.Equal(200 * scale, profile.RapidAcceleration, 9); + Assert.Equal(0.01 * scale, profile.CornerDeviation, 9); + } +} diff --git a/OpenNest/Forms/CutParametersForm.cs b/OpenNest/Forms/CutParametersForm.cs index b049262d..a4dcf34c 100644 --- a/OpenNest/Forms/CutParametersForm.cs +++ b/OpenNest/Forms/CutParametersForm.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Windows.Forms; namespace OpenNest.Forms @@ -6,11 +6,27 @@ namespace OpenNest.Forms public partial class CutParametersForm : Form { private Units units; + private readonly CutTimeMachineBox machineBox; public CutParametersForm() { InitializeComponent(); Units = OpenNest.Units.Inches; + + machineBox = new CutTimeMachineBox { Anchor = AnchorStyles.Left | AnchorStyles.Right }; + var label = new Label + { + Text = "Acceleration:", + AutoSize = true, + Anchor = AnchorStyles.Left | AnchorStyles.Right, + }; + tableLayoutPanel1.RowCount = 4; + tableLayoutPanel1.RowStyles.Clear(); + for (var i = 0; i < 4; i++) + tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 25F)); + tableLayoutPanel1.Controls.Add(label, 0, 3); + tableLayoutPanel1.Controls.Add(machineBox, 1, 3); + Height += LogicalToDeviceUnits(40); } protected override void OnLoad(EventArgs e) @@ -29,7 +45,7 @@ namespace OpenNest.Forms Properties.Settings.Default.LastFeedrate = numericUpDown1.Value; Properties.Settings.Default.LastRapidFeedrate = numericUpDown2.Value; Properties.Settings.Default.LastPierceTime = numericUpDown3.Value; - Properties.Settings.Default.Save(); + machineBox.SaveChoice(); } public Units Units @@ -58,6 +74,7 @@ namespace OpenNest.Forms RapidTravelRate = (double)numericUpDown2.Value, PierceTime = TimeSpan.FromSeconds((double)numericUpDown3.Value), Units = units, + Motion = machineBox.GetMotion(units), }; } } diff --git a/OpenNest/Forms/CutSimulatorForm.cs b/OpenNest/Forms/CutSimulatorForm.cs index 7b02f821..328d4477 100644 --- a/OpenNest/Forms/CutSimulatorForm.cs +++ b/OpenNest/Forms/CutSimulatorForm.cs @@ -24,6 +24,7 @@ namespace OpenNest.Forms private readonly TrackBar trackBar; private readonly Label timeLabel, partLabel, stateLabel; private readonly NumericUpDown feedBox, rapidBox, pierceBox; + private readonly CutTimeMachineBox machineBox; private Plate plate; private bool updatingTrack; private bool rebuildQueued; @@ -100,6 +101,10 @@ namespace OpenNest.Forms RateLabel("Pierce"), pierceBox, }); + machineBox = new CutTimeMachineBox(); + var motion = new FlowLayoutPanel { AutoSize = true, Dock = DockStyle.Fill, WrapContents = false }; + motion.Controls.AddRange(new Control[] { RateLabel("Acceleration"), machineBox }); + var layout = new TableLayoutPanel { Dock = DockStyle.Fill, @@ -112,6 +117,7 @@ namespace OpenNest.Forms layout.Controls.Add(trackBar); layout.Controls.Add(status); layout.Controls.Add(rates); + layout.Controls.Add(motion); Controls.Add(layout); restartButton.Click += (_, _) => overlay.Time = TimeSpan.Zero; @@ -130,6 +136,7 @@ namespace OpenNest.Forms feedBox.ValueChanged += (_, _) => Rebuild(); rapidBox.ValueChanged += (_, _) => Rebuild(); pierceBox.ValueChanged += (_, _) => Rebuild(); + machineBox.SelectedIndexChanged += (_, _) => Rebuild(); var tips = new ToolTip(); tips.SetToolTip(restartButton, "Restart"); @@ -139,6 +146,7 @@ namespace OpenNest.Forms tips.SetToolTip(previousContourButton, "Back to the start of this cutout or perimeter, or the one before (Ctrl+Left)"); tips.SetToolTip(nextContourButton, "Next cutout or perimeter (Ctrl+Right)"); tips.SetToolTip(nextPartButton, "Next part (Page Down)"); + tips.SetToolTip(machineBox, "Machine whose acceleration limits time the moves (Tools > Machine Configuration)"); tips.SetToolTip(trackBar, "Drag to scrub through the cut (Left/Right step one move)"); overlay.Speed = Speeds[speedBox.SelectedIndex]; @@ -183,6 +191,7 @@ namespace OpenNest.Forms RapidTravelRate = (double)rapidBox.Value, PierceTime = TimeSpan.FromSeconds((double)pierceBox.Value), Units = nestForm.Nest.Units, + Motion = machineBox.GetMotion(nestForm.Nest.Units), }; private void Rebuild() @@ -343,13 +352,24 @@ namespace OpenNest.Forms var step = sim.Steps[index]; var drawing = plate != null && step.PartIndex < plate.Parts.Count ? plate.Parts[step.PartIndex].BaseDrawing?.Name : null; partLabel.Text = $"Part {step.PartIndex + 1} of {sim.PartCount}" + (string.IsNullOrEmpty(drawing) ? "" : $" ({drawing})"); - stateLabel.Text = step.Kind switch + 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)}"; } private void SetTrack(int value) @@ -364,7 +384,7 @@ namespace OpenNest.Forms Properties.Settings.Default.LastFeedrate = feedBox.Value; Properties.Settings.Default.LastRapidFeedrate = rapidBox.Value; Properties.Settings.Default.LastPierceTime = pierceBox.Value; - Properties.Settings.Default.Save(); + machineBox.SaveChoice(); overlay.Changed -= Overlay_Changed; nestForm.PlateChanged -= NestForm_PlateChanged; diff --git a/OpenNest/Forms/CutTimeMachineBox.cs b/OpenNest/Forms/CutTimeMachineBox.cs new file mode 100644 index 00000000..b1493275 --- /dev/null +++ b/OpenNest/Forms/CutTimeMachineBox.cs @@ -0,0 +1,52 @@ +using System; +using System.Linq; +using System.Windows.Forms; +using OpenNest.Data; + +namespace OpenNest.Forms +{ + /// + /// Chooses which machine's acceleration limits time the cut, or none for full speed + /// everywhere. Remembers the choice; until one is made, the first machine is used. + /// + internal sealed class CutTimeMachineBox : ComboBox + { + private const string ConstantSpeed = "none"; + + 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; + + Items.Add(new Choice(null)); + foreach (var machine in MachineSettings.LoadMachines().OrderBy(m => m.Name, StringComparer.CurrentCultureIgnoreCase)) + Items.Add(new Choice(machine)); + + var saved = Properties.Settings.Default.CutTimeMachine; + var choices = Items.Cast().ToList(); + SelectedItem = saved == ConstantSpeed + ? choices[0] + : choices.FirstOrDefault(c => c.Machine?.Id.ToString() == saved) ?? choices.ElementAtOrDefault(1) ?? choices[0]; + } + + public MachineConfig Machine => (SelectedItem as Choice)?.Machine; + + /// The chosen machine's limits in , or null for full speed. + public MotionProfile GetMotion(Units units) => + Machine?.GetMotionOrPlaceholder().ToProfile(Machine.Units, units); + + public void SaveChoice() + { + Properties.Settings.Default.CutTimeMachine = Machine?.Id.ToString() ?? ConstantSpeed; + Properties.Settings.Default.Save(); + } + } +} diff --git a/OpenNest/Forms/EditNestForm.cs b/OpenNest/Forms/EditNestForm.cs index e7595295..07e09530 100644 --- a/OpenNest/Forms/EditNestForm.cs +++ b/OpenNest/Forms/EditNestForm.cs @@ -890,7 +890,7 @@ namespace OpenNest.Forms { var cutparams = cutParamsForm.GetCutParameters(); var info = Timing.GetTimingInfo(PlateView.Plate); - var time = Timing.CalculateTime(info, cutparams); + var time = Timing.CalculateTime(PlateView.Plate, cutparams); var timingForm = new TimingForm(); timingForm.Units = Nest.Units; @@ -932,7 +932,7 @@ namespace OpenNest.Forms { var cutparams = cutParamsForm.GetCutParameters(); var info = Timing.GetTimingInfo(Nest); - var time = Timing.CalculateTime(info, cutparams); + var time = Timing.CalculateTime(Nest, cutparams); var timingForm = new TimingForm(); timingForm.Units = Nest.Units; diff --git a/OpenNest/Forms/MachineConfigForm.cs b/OpenNest/Forms/MachineConfigForm.cs index 4f7592c2..4267eeef 100644 --- a/OpenNest/Forms/MachineConfigForm.cs +++ b/OpenNest/Forms/MachineConfigForm.cs @@ -250,8 +250,8 @@ namespace OpenNest.Forms return; var confirm = MessageBox.Show( - "Changing units does not convert existing thickness, kerf and lead " - + "values — they will keep their current numbers. Continue?", + "Changing units does not convert existing thickness, kerf, lead and " + + "motion values — they will keep their current numbers. Continue?", "Change Units", MessageBoxButtons.YesNo, MessageBoxIcon.Warning @@ -267,9 +267,62 @@ namespace OpenNest.Forms AddField(layout, ref row, "Units:", unitsCombo); group.Controls.Add(layout); + // Docked to the top, so the last added sits first. + _detailPanel.Controls.Add(BuildMotionGroup(machine)); _detailPanel.Controls.Add(group); } + private GroupBox BuildMotionGroup(MachineConfig machine) + { + var group = CreateGroup("Motion (cut time estimates)"); + var layout = CreateDetailLayout(); + var row = 0; + var shown = machine.GetMotionOrPlaceholder(); + var note = new Label + { + AutoSize = true, + MaximumSize = new Size(420, 0), + ForeColor = SystemColors.GrayText, + }; + + void UpdateNote() => + note.Text = machine.Motion == null + ? "Placeholder values. Enter the controller's acceleration and corner settings." + : "Used by Simulate Cutting and Calculate Cut Time."; + + // The first edit stores the placeholder values along with the change. + void Set(Action apply) + { + machine.Motion ??= new MotionConfig + { + CutAcceleration = shown.CutAcceleration, + RapidAcceleration = shown.RapidAcceleration, + CornerDeviation = shown.CornerDeviation, + }; + apply(machine.Motion); + UpdateNote(); + MarkDirty(); + } + + string AccelerationSuffix(object _) => LengthUnitSuffix(null) + "/s²"; + + AddField(layout, ref row, "Cut acceleration:", + CreateLabeledNumeric(shown.CutAcceleration, v => Set(m => m.CutAcceleration = v), 0, AccelerationSuffix, 100000, 10)); + AddField(layout, ref row, "Rapid acceleration:", + CreateLabeledNumeric(shown.RapidAcceleration, v => Set(m => m.RapidAcceleration = v), 0, AccelerationSuffix, 100000, 10)); + AddField(layout, ref row, "Corner deviation:", + CreateLabeledNumeric(shown.CornerDeviation, v => Set(m => m.CornerDeviation = v), 4, LengthUnitSuffix, 10, 0.0005m)); + + UpdateNote(); + layout.RowCount = row + 1; + layout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + layout.Controls.Add(note, 0, row); + layout.SetColumnSpan(note, 2); + + group.Controls.Add(layout); + return group; + } + private void ShowMaterialGroupDetails(string groupName) { var label = new Label diff --git a/OpenNest/Forms/MachineSettings.cs b/OpenNest/Forms/MachineSettings.cs index 28a7e6f6..3d8369ba 100644 --- a/OpenNest/Forms/MachineSettings.cs +++ b/OpenNest/Forms/MachineSettings.cs @@ -1,3 +1,6 @@ +using System; +using System.Collections.Generic; +using System.IO; using System.Windows.Forms; using OpenNest.Data; @@ -10,6 +13,35 @@ namespace OpenNest.Forms internal static class MachineSettings { private static bool clampSettingsWarned; + + /// The machine configurations edited in Tools > Machine Configuration. + public static LocalJsonProvider CreateMachineProvider() + { + var provider = new LocalJsonProvider(Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "OpenNest", + "Machines")); + provider.EnsureDefaults(); + return provider; + } + + /// Every readable machine configuration, for choosing acceleration limits. + public static List LoadMachines() + { + var machines = new List(); + try + { + var provider = CreateMachineProvider(); + foreach (var summary in provider.GetMachines()) + { + if (provider.GetMachine(summary.Id) is { } machine) + machines.Add(machine); + } + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + return machines; + } private static bool defaultsWarned; /// diff --git a/OpenNest/Forms/MainForm.Tools.cs b/OpenNest/Forms/MainForm.Tools.cs index 2a846af6..49389f65 100644 --- a/OpenNest/Forms/MainForm.Tools.cs +++ b/OpenNest/Forms/MainForm.Tools.cs @@ -190,13 +190,7 @@ namespace OpenNest.Forms private void MachineConfig_Click(object sender, EventArgs e) { - var appDataPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "OpenNest", - "Machines" - ); - var provider = new LocalJsonProvider(appDataPath); - provider.EnsureDefaults(); + var provider = MachineSettings.CreateMachineProvider(); using (var form = new MachineConfigForm(provider)) { form.ShowDialog(this); diff --git a/OpenNest/Properties/Settings.Designer.cs b/OpenNest/Properties/Settings.Designer.cs index d64b84f4..c9564053 100644 --- a/OpenNest/Properties/Settings.Designer.cs +++ b/OpenNest/Properties/Settings.Designer.cs @@ -220,6 +220,18 @@ namespace OpenNest.Properties { this["LastPierceTime"] = value; } } + + [global::System.Configuration.UserScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("")] + public string CutTimeMachine { + get { + return ((string)(this["CutTimeMachine"])); + } + set { + this["CutTimeMachine"] = value; + } + } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] diff --git a/OpenNest/Properties/Settings.settings b/OpenNest/Properties/Settings.settings index 5537cc9b..6b1317d1 100644 --- a/OpenNest/Properties/Settings.settings +++ b/OpenNest/Properties/Settings.settings @@ -53,6 +53,9 @@ 0 + + + diff --git a/OpenNest/app.config b/OpenNest/app.config index ee4f6f04..be8321c7 100644 --- a/OpenNest/app.config +++ b/OpenNest/app.config @@ -53,6 +53,9 @@ 0 + + + diff --git a/README.md b/README.md index 8df595bb..b167a115 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ A Windows desktop application for CNC nesting — imports DXF drawings, arranges - **Nesting** — automatic multi-plate/multi-material jobs, interlocking pair evaluation, and built-in or plug-in engines. [Choose an engine](docs/nesting-engines.md). - **Plate operations** — manual sheet cut-offs, [plate- or nest-wide automatic scrap cutoffs with a minimum tail-to-keep setting](docs/automatic-scrap-cutoffs.md), oversized-part splitting (straight, weld-gap tabs, spike-groove), interactive editing, and spacing-aware pushes that can slide along or away from touching parts. - **Visual overlap check** — highlight shared material on the active plate, rechecked automatically after edits, including containment and cutouts, with area shading, pair markers, and hover details through View > Overlap Check. [Usage and limitations](docs/geometry/visual-overlap-check.md). -- **Cut simulator** — Plate > Simulate Cutting replays the active plate in cut order: the torch traces each cut, rapid and pierce at adjustable feed, rapid and pierce settings, with play/pause, scrubbing, 1×–250× speed and previous/next part (Page Up/Down) and cutout (Ctrl+Left/Right) jumps. Parts the torch has not reached stay greyed. Timing follows Calculate Cut Time (no acceleration or per-move feed overrides). +- **Cut simulator** — Plate > Simulate Cutting replays the active plate in cut order: the torch traces each cut, rapid and pierce at adjustable feed, rapid and pierce settings, with play/pause, scrubbing, 1×–250× speed and previous/next part (Page Up/Down) and cutout (Ctrl+Left/Right) jumps. Parts the torch has not reached stay greyed. It and Calculate Cut Time use the chosen machine's acceleration and corner limits from Machine Configuration (placeholder values until you enter the controller's). [Timing model](docs/cut-time-estimates.md). - **CNC output** — configurable lead-ins/outs and tabs, contour editing, user-defined G-code variables (`$name` → `#200+` machine variables), plugin post-processors (Cincinnati CL-707/800/900/940/CLX included). [Pre-post verification](docs/post-verification.md) checks overlaps, missing lead-ins, and rapid crossings, with explicit risk acknowledgment required to bypass warnings. ## Requirements diff --git a/docs/cut-time-estimates.md b/docs/cut-time-estimates.md new file mode 100644 index 00000000..a023b04c --- /dev/null +++ b/docs/cut-time-estimates.md @@ -0,0 +1,37 @@ +# Cut-time estimates + +Calculate Cut Time and Plate > Simulate Cutting share one timing model +(`OpenNest.Core/CNC/CutSimulation.cs`, `MotionPlanner.cs`). + +## Inputs + +- **Feed, rapid and pierce** from the dialog or simulator. Inch rates are per minute; + millimeter rates are per second (the existing `Timing.CalculateTime` convention). +- **Acceleration** from a machine in Tools > Machine Configuration (`MachineConfig.Motion`, + in the machine's units and converted to the nest's). The choice is remembered in the + `CutTimeMachine` user setting. Until any machine is chosen, the first machine is used. + "None (full speed)" gives the old constant-speed estimate. +- A machine with no saved motion values uses `MotionConfig.Placeholder`: about 0.5 G cutting, + 1 G travel and a 0.001 in (0.025 mm) corner deviation. These are stand-ins, not measured + values, and the picker labels such machines "(placeholder)". + +## Model + +- Moves are walked in plate cutting order. Rapids, Display-layer moves and Tab spans are head-up + travel. A cut that follows travel gets a pierce dwell. Scribes are not pierced. +- Each cutting run (between a pierce and the next travel) starts and ends at rest. Travel moves + are planned separately and also go from rest to rest. +- Each move follows a trapezoidal profile: it accelerates, cruises at the feed and decelerates. A + move too short to reach the feed peaks where the two ramps meet. +- Corner speed uses the junction-deviation formula `v² = a·δ·sin(θ/2) / (1 − sin(θ/2))`. A zero + deviation stops at every corner. Collinear joints do not slow. +- Arcs are capped at the centripetal limit `√(a·r)`, using the cut acceleration. +- A backward pass and then a forward pass keep every speed change within the acceleration + (Grbl-style lookahead). + +Not modeled: jerk (S-curves), controller-specific lookahead limits, per-move feed overrides and +power ramping. With real controller values, expect roughly 5–15% error. Calibrate by comparing +a known program against the machine's own run time. + +With acceleration, the plate time is the simulation total plus clamp-removal minutes, times the +plate quantity. Distances and counts in the timing dialog still come from `Timing.GetTimingInfo`.