mirror of
https://github.com/ajisaacs/OpenNest.git
synced 2026-12-06 04:10:34 -05:00
Plan Cutting's heat-aware order is now one setting, "Don't start above (°C rise)" (CuttingParameters.HeatStartLimit, 0 = off, saved per material and thickness), with the same rule for single parts and for the lines of large grids: before each next piece, estimate the temperature where it starts when the tool gets there; cut the plain order's next piece when it is at or under the limit, else the nearest piece under it, else the coolest. A move across parts already cut is a heat jump, reached with the head raised and counted in HeatRaises; parts that cannot take a raise are reached head-down only when nothing else is ready. The weighted block layouts and the grid prototype's static switch and Alternate mode are gone; every-other-line on the washer grid falls out of the rule. The rule counts the heat of the part just cut: leaving it out halved the raises on a 0.06 in sheet but left the starts' P90 at 32-36 C instead of about 3 C. Re-plans after a learned order rule replay the parts already cut into the estimate and the crossing test, and an order the heat never moved stays the plain one, so a limit the estimate never reaches changes nothing. Measured (HeatOrderMeasurementTests, docs/plate-heat-map.md): washer grid line starts 63 -> 6 C for +1.5% travel and 1-2 raises; 0.06 in sheet zone P95 -25% for +10-15% travel, +2% cut time; 0.25 in sheet at 10 C zone P95 -18% for +15% travel (the old weight: -10% for +51%). No fallback raises. Limit 0 is byte-identical (characterization digests, problem-nest part-order and grid areas pass). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
442 lines
21 KiB
C#
442 lines
21 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using OpenNest.CNC.Thermal;
|
|
using OpenNest.Geometry;
|
|
|
|
namespace OpenNest.Engine.CuttingPlanning;
|
|
|
|
/// <summary>
|
|
/// What a heat-aware part order needs: the start limit (the estimated temperature rise, in °C,
|
|
/// above which the next part or line is not started), the sheet's material and thickness, and the
|
|
/// feeds and pierce time the cut is timed with.
|
|
/// </summary>
|
|
internal sealed record CuttingHeat(double StartLimit, ThermalParameters Thermal, CutParameters Times)
|
|
{
|
|
/// <summary>Null unless a positive limit, a thickness and usable feeds make heat matter.</summary>
|
|
internal static CuttingHeat For(double startLimit, ThermalParameters thermal, CutParameters times) =>
|
|
double.IsFinite(startLimit) && startLimit > 0 && thermal is { Thickness: > 0 } && double.IsFinite(thermal.Thickness)
|
|
&& times is { Feedrate: > 0, RapidTravelRate: > 0 } && double.IsFinite(times.Feedrate)
|
|
&& double.IsFinite(times.RapidTravelRate)
|
|
? new(startLimit, thermal, times) : null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// One part as the heat-aware order sees it: where the tool reaches and leaves it, its cut extent
|
|
/// (where its heat goes and what a rapid passes over once it is cut), its cut length and pierces,
|
|
/// and whether it may be reached with the head raised: only a part whose program the planner
|
|
/// writes, since the rapid into a program kept as given cannot be marked.
|
|
/// </summary>
|
|
internal readonly record struct CuttingHeatItem(Vector Arrival, Vector Exit, Box Extent, double CutLength, int Pierces,
|
|
bool CanRaise = true);
|
|
|
|
/// <summary>
|
|
/// Keeps Plan Cutting from starting work where the cut so far left the sheet hot. The work comes
|
|
/// in pieces in a plain order: single parts along the plain tour, or the lines of a large grid's
|
|
/// serpentine (<see cref="CuttingGridOrder.Lines"/>), each cut in order from whichever end lies
|
|
/// nearer. Before each piece the rule estimates the temperature where it starts when the tool gets
|
|
/// there (<see cref="HeatEstimate"/>): the plain order's next piece is cut when it is at or under
|
|
/// <see cref="CuttingHeat.StartLimit"/>; otherwise the nearest piece under the limit, counting
|
|
/// <see cref="RaiseSeconds"/> for a move across cut parts; otherwise the coolest. A move whose
|
|
/// straight rapid passes over a part already cut is a heat jump: the search reaches that piece's
|
|
/// first part with the head raised. A part that cannot take a raise is reached across cut parts
|
|
/// head-down only when no other piece is ready. A proposal like the plain order: the search still
|
|
/// checks every motion along it. See docs/plate-heat-map.md#sequencing.
|
|
/// </summary>
|
|
internal static class CuttingHeatOrder
|
|
{
|
|
/// <summary>What a jump's head raise and lowering is taken to cost, in seconds.</summary>
|
|
internal const double RaiseSeconds = 2;
|
|
|
|
/// <param name="plain">The plain tour of the parts.</param>
|
|
/// <param name="items">Every part's data, by ordinal.</param>
|
|
/// <param name="prerequisites">Each part's prerequisites, by ordinal; those outside the tour are ignored.</param>
|
|
/// <param name="cutBefore">When the rest of a plate is planned again, the parts already cut, in
|
|
/// order from <paramref name="origin"/>: their heat counts and a rapid over them is a jump.</param>
|
|
/// <param name="movedBefore">Whether the heat moved the order of the parts already cut.</param>
|
|
/// <returns>The order, the parts it jumps to across parts already cut, and whether the heat moved
|
|
/// it. An order the heat never moved, here or before, is the plain one with no jumps.</returns>
|
|
internal static (int[] Order, int[] Jumps, bool Moved) Plan(int[] plain, Vector start,
|
|
IReadOnlyList<CuttingHeatItem> items, IReadOnlyList<IReadOnlyCollection<int>> prerequisites, CuttingHeat heat,
|
|
CancellationToken token, IReadOnlyList<int> cutBefore = null, Vector origin = default, bool movedBefore = false)
|
|
{
|
|
if (heat == null || plain.Length < 2)
|
|
return (plain, [], false);
|
|
return Walk(plain.Select(part => new[] { part }).ToArray(), false, start, items, prerequisites, heat,
|
|
HeatEstimate.MaxDeposits, token, cutBefore ?? [], origin, movedBefore);
|
|
}
|
|
|
|
/// <summary>The start-limit rule over a grid's serpentine lines, each cut from its nearer end.</summary>
|
|
internal static (int[] Order, int[] Jumps, bool Moved) PlanLines(int[][] lines, Vector start,
|
|
IReadOnlyList<CuttingHeatItem> items, CuttingHeat heat, CancellationToken token) =>
|
|
Walk(lines, true, start, items, null, heat, int.MaxValue, token, [], start, false);
|
|
|
|
private static (int[] Order, int[] Jumps, bool Moved) Walk(int[][] pieces, bool reversible, Vector start,
|
|
IReadOnlyList<CuttingHeatItem> items, IReadOnlyList<IReadOnlyCollection<int>> prerequisites, CuttingHeat heat,
|
|
int maxDeposits, CancellationToken token, IReadOnlyList<int> cutBefore, Vector origin, bool movedBefore)
|
|
{
|
|
var plain = (pieces.SelectMany(piece => piece).ToArray(), Array.Empty<int>(), false);
|
|
var state = new WalkState(pieces, items, prerequisites, cutBefore);
|
|
var estimate = new HeatEstimate(heat, maxDeposits);
|
|
var replayed = origin;
|
|
foreach (var part in cutBefore)
|
|
{
|
|
estimate.Cut(items[part], estimate.TravelSeconds(replayed.DistanceTo(items[part].Arrival)));
|
|
replayed = items[part].Exit;
|
|
}
|
|
var limit = heat.StartLimit;
|
|
var order = new List<int>(pieces.Sum(piece => piece.Length));
|
|
var jumps = new List<int>();
|
|
var position = start;
|
|
var lastPiece = -1;
|
|
var lastPart = cutBefore.Count != 0 ? cutBefore[^1] : -1;
|
|
var moved = false;
|
|
for (var step = 0; step < pieces.Length; step++)
|
|
{
|
|
token.ThrowIfCancellationRequested();
|
|
var chosen = Successor(state, lastPiece, lastPart, reversible, position, estimate, limit, ref moved)
|
|
?? Nearest(state, reversible, position, lastPart, estimate, limit);
|
|
if (chosen is not { } next)
|
|
return plain; // A prerequisite outside any piece: keep the plain order.
|
|
var parts = next.Reversed ? pieces[next.Piece].Reverse().ToArray() : pieces[next.Piece];
|
|
if (next.Jump)
|
|
jumps.Add(parts[0]);
|
|
foreach (var part in parts)
|
|
{
|
|
var item = items[part];
|
|
estimate.Cut(item, estimate.TravelSeconds(position.DistanceTo(item.Arrival)));
|
|
order.Add(part);
|
|
position = item.Exit;
|
|
lastPart = part;
|
|
}
|
|
state.Finish(next.Piece);
|
|
lastPiece = next.Piece;
|
|
}
|
|
// The crossing test alone never moves the plain order: its legs are the search's to judge.
|
|
return moved || movedBefore ? (order.ToArray(), jumps.ToArray(), moved) : plain;
|
|
}
|
|
|
|
private readonly record struct Choice(int Piece, bool Reversed, bool Jump);
|
|
|
|
// The plain order's next piece, when it is ready, under the limit and reached without crossing
|
|
// a part already cut; moved is set when it is over the limit.
|
|
private static Choice? Successor(WalkState state, int lastPiece, int lastPart, bool reversible,
|
|
Vector position, HeatEstimate estimate, double limit, ref bool moved)
|
|
{
|
|
var next = state.NextAfter(lastPiece);
|
|
if (next < 0 || !state.Ready(next))
|
|
return null;
|
|
var reversed = reversible && state.NearerEnd(next, position);
|
|
var first = state.First(next, reversed);
|
|
var item = state.Items[first];
|
|
var travel = estimate.TravelSeconds(position.DistanceTo(item.Arrival));
|
|
if (estimate.TemperatureAt(item.Arrival, estimate.Time + travel) > limit)
|
|
{
|
|
moved = true;
|
|
return null;
|
|
}
|
|
// Taken here only head-down; a leg across cut parts is weighed against the others. The
|
|
// plain order's own leg is as the plain order would cut it but for the parts this order
|
|
// cut ahead of it, and those cut before a replan, which the plain order did not know.
|
|
var plainLeg = next == lastPiece + 1 && !reversed;
|
|
return !state.Crosses(position, item.Arrival, lastPart, first, plainLeg ? next : -1)
|
|
? new Choice(next, reversed, false) : null;
|
|
}
|
|
|
|
// The nearest ready piece under the limit, a raise counted as RaiseSeconds; else the coolest.
|
|
// Pieces whose first part cannot take a raise and is reached across cut parts come last.
|
|
private static Choice? Nearest(WalkState state, bool reversible, Vector position, int lastPart,
|
|
HeatEstimate estimate, double limit)
|
|
{
|
|
var candidates = new List<(int Piece, bool Reversed, int First, double Travel)>();
|
|
foreach (var piece in state.Remaining())
|
|
{
|
|
if (!state.Ready(piece))
|
|
continue;
|
|
foreach (var reversed in reversible && state.Pieces[piece].Length > 1 ? [false, true] : new[] { false })
|
|
{
|
|
var first = state.First(piece, reversed);
|
|
candidates.Add((piece, reversed, first,
|
|
estimate.TravelSeconds(position.DistanceTo(state.Items[first].Arrival))));
|
|
}
|
|
}
|
|
if (candidates.Count == 0)
|
|
return null;
|
|
candidates.Sort((a, b) => a.Travel != b.Travel ? a.Travel.CompareTo(b.Travel)
|
|
: a.Piece != b.Piece ? a.Piece.CompareTo(b.Piece) : a.Reversed.CompareTo(b.Reversed));
|
|
var temperatures = new double[candidates.Count];
|
|
var known = new bool[candidates.Count];
|
|
double Temperature(int index)
|
|
{
|
|
if (!known[index])
|
|
{
|
|
var c = candidates[index];
|
|
temperatures[index] = estimate.TemperatureAt(state.Items[c.First].Arrival, estimate.Time + c.Travel);
|
|
known[index] = true;
|
|
}
|
|
return temperatures[index];
|
|
}
|
|
// 0: reached head-down, 1: a jump, 2: blocked (crosses cut parts, cannot be raised).
|
|
var kinds = new int[candidates.Count];
|
|
int Kind(int index)
|
|
{
|
|
if (kinds[index] == 0)
|
|
{
|
|
var c = candidates[index];
|
|
kinds[index] = !state.Crosses(position, state.Items[c.First].Arrival, lastPart, c.First) ? 1
|
|
: state.Items[c.First].CanRaise ? 2 : 3;
|
|
}
|
|
return kinds[index] - 1;
|
|
}
|
|
Choice Take(int index) => new(candidates[index].Piece, candidates[index].Reversed, Kind(index) == 1);
|
|
|
|
var best = -1;
|
|
var bestCost = double.PositiveInfinity;
|
|
var blockedCool = -1;
|
|
for (var i = 0; i < candidates.Count && candidates[i].Travel < bestCost; i++)
|
|
{
|
|
if (Temperature(i) > limit)
|
|
continue;
|
|
var kind = Kind(i);
|
|
if (kind == 2)
|
|
{
|
|
if (blockedCool < 0)
|
|
blockedCool = i;
|
|
continue;
|
|
}
|
|
var cost = candidates[i].Travel + (kind == 1 ? RaiseSeconds : 0);
|
|
if (cost < bestCost)
|
|
(best, bestCost) = (i, cost);
|
|
}
|
|
if (best >= 0)
|
|
return Take(best);
|
|
// None under the limit can be reached: the coolest that can, nearest first on ties.
|
|
var byTemperature = Enumerable.Range(0, candidates.Count).OrderBy(Temperature).ThenBy(i => i).ToArray();
|
|
foreach (var index in byTemperature)
|
|
if (Kind(index) != 2)
|
|
return Take(index);
|
|
return Take(blockedCool >= 0 ? blockedCool : byTemperature[0]);
|
|
}
|
|
|
|
// The pieces cut so far and the parts in them, for readiness and the crossing test.
|
|
private sealed class WalkState
|
|
{
|
|
private readonly bool[] done;
|
|
private readonly bool[] cutParts;
|
|
private readonly HashSet<int> inWalk;
|
|
private readonly IReadOnlyList<IReadOnlyCollection<int>> prerequisites;
|
|
private readonly Box[] boxes;
|
|
private readonly List<int> finished = [];
|
|
private readonly IReadOnlyList<int> cutBefore;
|
|
private int firstRemaining;
|
|
|
|
internal WalkState(int[][] pieces, IReadOnlyList<CuttingHeatItem> items,
|
|
IReadOnlyList<IReadOnlyCollection<int>> prerequisites, IReadOnlyList<int> cutBefore)
|
|
{
|
|
this.cutBefore = cutBefore;
|
|
Pieces = pieces;
|
|
Items = items;
|
|
this.prerequisites = prerequisites;
|
|
done = new bool[pieces.Length];
|
|
cutParts = new bool[items.Count];
|
|
inWalk = pieces.SelectMany(piece => piece).ToHashSet();
|
|
boxes = pieces.Select(piece => piece.Length == 1 ? items[piece[0]].Extent
|
|
: piece.Select(part => items[part].Extent).ToList().GetBoundingBox()).ToArray();
|
|
}
|
|
|
|
internal int[][] Pieces { get; }
|
|
|
|
internal IReadOnlyList<CuttingHeatItem> Items { get; }
|
|
|
|
internal void Finish(int piece)
|
|
{
|
|
done[piece] = true;
|
|
foreach (var part in Pieces[piece])
|
|
cutParts[part] = true;
|
|
finished.Add(piece);
|
|
while (firstRemaining < done.Length && done[firstRemaining])
|
|
firstRemaining++;
|
|
}
|
|
|
|
internal IEnumerable<int> Remaining()
|
|
{
|
|
for (var piece = firstRemaining; piece < done.Length; piece++)
|
|
if (!done[piece])
|
|
yield return piece;
|
|
}
|
|
|
|
// The first piece not yet cut after the given one in the plain order, or -1.
|
|
internal int NextAfter(int piece)
|
|
{
|
|
for (var next = System.Math.Max(piece + 1, firstRemaining); next < done.Length; next++)
|
|
if (!done[next])
|
|
return next;
|
|
return -1;
|
|
}
|
|
|
|
// Whether every prerequisite of the piece's parts, other than its own, is cut.
|
|
internal bool Ready(int piece)
|
|
{
|
|
if (prerequisites == null)
|
|
return true;
|
|
var parts = Pieces[piece];
|
|
foreach (var part in parts)
|
|
foreach (var prerequisite in prerequisites[part])
|
|
if (!cutParts[prerequisite] && inWalk.Contains(prerequisite) && Array.IndexOf(parts, prerequisite) < 0)
|
|
return false;
|
|
return true;
|
|
}
|
|
|
|
internal bool NearerEnd(int piece, Vector position)
|
|
{
|
|
var parts = Pieces[piece];
|
|
return parts.Length > 1
|
|
&& position.DistanceTo(Items[parts[^1]].Arrival) < position.DistanceTo(Items[parts[0]].Arrival);
|
|
}
|
|
|
|
internal int First(int piece, bool reversed) => reversed ? Pieces[piece][^1] : Pieces[piece][0];
|
|
|
|
// Whether the straight move passes over the cut extent of a part already cut, other than
|
|
// the part it leaves and the part it reaches; with an index of the plain order, only parts
|
|
// cut after it in that order count, besides those cut before the walk.
|
|
internal bool Crosses(Vector from, Vector to, int leaving, int reaching, int inOrderBefore = -1)
|
|
{
|
|
foreach (var part in cutBefore)
|
|
if (part != leaving && part != reaching && SegmentHitsBox(from, to, Items[part].Extent))
|
|
return true;
|
|
foreach (var piece in finished)
|
|
{
|
|
if (piece < inOrderBefore)
|
|
continue;
|
|
if (!SegmentHitsBox(from, to, boxes[piece]))
|
|
continue;
|
|
foreach (var part in Pieces[piece])
|
|
if (part != leaving && part != reaching && SegmentHitsBox(from, to, Items[part].Extent))
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Liang-Barsky clipping of the segment against the box.
|
|
internal static bool SegmentHitsBox(Vector from, Vector to, Box box)
|
|
{
|
|
var t0 = 0.0;
|
|
var t1 = 1.0;
|
|
var dx = to.X - from.X;
|
|
var dy = to.Y - from.Y;
|
|
return Clip(-dx, from.X - box.Left) && Clip(dx, box.Right - from.X)
|
|
&& Clip(-dy, from.Y - box.Bottom) && Clip(dy, box.Top - from.Y);
|
|
|
|
bool Clip(double p, double q)
|
|
{
|
|
if (System.Math.Abs(p) < 1e-12)
|
|
return q >= 0;
|
|
var r = q / p;
|
|
if (p < 0)
|
|
{
|
|
if (r > t1)
|
|
return false;
|
|
if (r > t0)
|
|
t0 = r;
|
|
}
|
|
else
|
|
{
|
|
if (r < t0)
|
|
return false;
|
|
if (r < t1)
|
|
t1 = r;
|
|
}
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// A cheap stand-in for <see cref="PlateHeatSimulation"/> for choosing an order: each cut part
|
|
/// leaves a Gaussian blob of the heat its cut put in (absorbed power times its torch-on time),
|
|
/// as wide as the part to begin with, widening as the heat conducts (4αΔt) and fading with the
|
|
/// loss from both faces. Torch-on time is the part's cut length at the outside feed plus its
|
|
/// pierces; travel runs at the rapid rate. It ignores kerfs, dropped slugs and the support bed.
|
|
/// Like the grid model, its temperatures are relative, for comparing orders.
|
|
/// </summary>
|
|
internal sealed class HeatEstimate
|
|
{
|
|
/// <summary>
|
|
/// The most recent parts whose heat is summed; older blobs have spread into a near-uniform
|
|
/// background that hardly changes which part is next.
|
|
/// </summary>
|
|
internal const int MaxDeposits = 200;
|
|
|
|
private readonly Queue<Deposit> deposits = new();
|
|
private readonly double diffusivity;
|
|
private readonly double heatCapacity;
|
|
private readonly double loss;
|
|
private readonly double squareMeters;
|
|
private readonly double absorbedPower;
|
|
private readonly double feedRate;
|
|
private readonly double rapidRate;
|
|
private readonly double pierceSeconds;
|
|
private readonly int maxDeposits;
|
|
|
|
internal HeatEstimate(CuttingHeat heat, int maxDeposits = MaxDeposits)
|
|
{
|
|
this.maxDeposits = maxDeposits;
|
|
var thermal = heat.Thermal;
|
|
var meters = thermal.MetersPerUnit;
|
|
var material = thermal.Material;
|
|
diffusivity = material.Diffusivity / (meters * meters);
|
|
heatCapacity = material.Density * material.SpecificHeat * thermal.Thickness * meters;
|
|
loss = 2 * thermal.SurfaceCoefficient / heatCapacity;
|
|
squareMeters = meters * meters;
|
|
absorbedPower = thermal.AbsorbedPower;
|
|
var perSecond = thermal.Units == Units.Millimeters ? 1.0 : 1.0 / 60;
|
|
feedRate = heat.Times.Feedrate * perSecond;
|
|
rapidRate = heat.Times.RapidTravelRate * perSecond;
|
|
pierceSeconds = System.Math.Max(0, heat.Times.PierceTime.TotalSeconds);
|
|
}
|
|
|
|
/// <summary>Seconds into the cut, after the parts cut so far.</summary>
|
|
internal double Time { get; private set; }
|
|
|
|
internal double TravelSeconds(double distance) => distance / rapidRate;
|
|
|
|
internal double TorchSeconds(CuttingHeatItem item) =>
|
|
System.Math.Max(0, item.CutLength) / feedRate + System.Math.Max(0, item.Pierces) * pierceSeconds;
|
|
|
|
/// <summary>Travels <paramref name="travelSeconds"/> to the part, then cuts it, laying down its heat.</summary>
|
|
internal void Cut(CuttingHeatItem item, double travelSeconds)
|
|
{
|
|
var torch = TorchSeconds(item);
|
|
Time += travelSeconds + torch;
|
|
if (torch <= 0)
|
|
return;
|
|
if (deposits.Count == maxDeposits)
|
|
deposits.Dequeue();
|
|
var extent = item.Extent;
|
|
deposits.Enqueue(new(extent.Center, absorbedPower * torch, Time,
|
|
(extent.Width * extent.Width + extent.Length * extent.Length) / 4));
|
|
}
|
|
|
|
/// <summary>The estimated temperature rise, in °C, at <paramref name="at"/> and <paramref name="time"/>.</summary>
|
|
internal double TemperatureAt(Vector at, double time)
|
|
{
|
|
var total = 0.0;
|
|
foreach (var deposit in deposits)
|
|
{
|
|
var elapsed = System.Math.Max(0, time - deposit.Time);
|
|
var spread2 = 4 * diffusivity * elapsed + deposit.Spread2;
|
|
if (spread2 <= 0)
|
|
continue;
|
|
var dx = at.X - deposit.Center.X;
|
|
var dy = at.Y - deposit.Center.Y;
|
|
total += deposit.Energy / (heatCapacity * System.Math.PI * spread2 * squareMeters)
|
|
* System.Math.Exp(-(dx * dx + dy * dy) / spread2 - loss * elapsed);
|
|
}
|
|
return total;
|
|
}
|
|
|
|
private readonly record struct Deposit(Vector Center, double Energy, double Time, double Spread2);
|
|
}
|
|
}
|