fix(posts): Cincinnati CL sub-program frames, head raises and dead settings

Part sub-program calls restored the sheet frame with G92 at the part
corner while the tool sat at the sub-program's last endpoint, shifting
every later part. The call now raises the head, rapids back to local 0,0
and restores there. Parts share a sub-program only when their posted
toolpaths match, so per-part lead-ins are kept.

Suppressed moves are left uncut: the cut resumes with a rapid past them.

Head raises go before the rapid that leaves a feature, one per rapid:
the safety raise now precedes the rapid to a new part instead of
following its first feature, and sub-program mode no longer posts M47
then M47 P2000. M47Mode.Auto posts M47 before rapids longer than
M47OverrideDistanceThreshold and /M47 otherwise. ExteriorM47 applies to
the contour spanning the part's cut extents.

The sheet GOTO targets FeatureLineNumberStart and is omitted without line
numbers. PrepareForNest pre-selects only the gas- and thickness-matching
library. Part programs are read through absolute copies, never switched
to absolute in place.

Removes the unimplemented UseSheetSubprograms, CoordModeBetweenParts and
ProcessParameterMode (G89Mode); old configs still load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-10-19 01:56:28 -04:00
1 parent 5dc13a03ae
commit 2b3f8e7b52
16 files changed
+1203 -544

No files matched your search

@@ -17,13 +17,26 @@ public sealed class FeatureContext
public string PartName { get; set; } = "";
public bool IsFirstFeatureOfPart { get; set; }
public bool IsLastFeatureOnSheet { get; set; }
/// <summary>
/// True when the rapid after this feature goes to a different part, so its head
/// raise is the safety head raise.
/// </summary>
public bool IsSafetyHeadraise { get; set; }
/// <summary>True when this feature cuts the part's exterior (selects ExteriorM47).</summary>
public bool IsExteriorFeature { get; set; }
public bool IsEtch { get; set; }
public string LibraryFile { get; set; } = "";
public double CutDistance { get; set; }
public double SheetDiagonal { get; set; }
/// <summary>
/// Rapid travel from this feature's end to the next pierce, used by
/// <see cref="M47Mode.Auto"/>. Null when unknown.
/// </summary>
public double? RapidDistance { get; set; }
/// <summary>
/// Part location on the plate. Added to all output X/Y coordinates
/// so part-relative programs become plate-absolute under G90.
@@ -93,19 +106,16 @@ public sealed class CincinnatiFeatureWriter
writer.WriteLine(CoordinateFormatter.Comment($"PART: {ctx.PartName}"));
// 3. G89 process params
if (_config.ProcessParameterMode == G89Mode.LibraryFile)
var lib = ctx.LibraryFile;
if (!string.IsNullOrEmpty(lib))
{
var lib = ctx.LibraryFile;
if (!string.IsNullOrEmpty(lib))
{
var speedClass = _speedClassifier.Classify(ctx.CutDistance, ctx.SheetDiagonal);
var cutDist = _speedClassifier.FormatCutDist(ctx.CutDistance, ctx.SheetDiagonal);
writer.WriteLine($"G89 P{lib} ({speedClass} {cutDist})");
}
else
{
writer.WriteLine("(WARNING: No library found)");
}
var speedClass = _speedClassifier.Classify(ctx.CutDistance, ctx.SheetDiagonal);
var cutDist = _speedClassifier.FormatCutDist(ctx.CutDistance, ctx.SheetDiagonal);
writer.WriteLine($"G89 P{lib} ({speedClass} {cutDist})");
}
else
{
writer.WriteLine("(WARNING: No library found)");
}
// 4. Pierce/beam on — G85 for etch (no pierce), G84 for cut
@@ -322,25 +332,14 @@ public sealed class CincinnatiFeatureWriter
private void WriteM47(TextWriter writer, FeatureContext ctx)
{
if (ctx.IsSafetyHeadraise && _config.SafetyHeadraiseDistance.HasValue)
{
writer.WriteLine($"M47 P{_config.SafetyHeadraiseDistance.Value} (Safety Headraise)");
return;
}
var mode = ctx.IsExteriorFeature ? _config.ExteriorM47 : _config.InteriorM47;
switch (mode)
{
case M47Mode.Always:
writer.WriteLine("M47");
break;
case M47Mode.BlockDelete:
writer.WriteLine("/M47");
break;
case M47Mode.None:
break;
}
var line = CincinnatiHeadRaise.Line(
_config,
ctx.IsSafetyHeadraise,
ctx.IsExteriorFeature,
ctx.RapidDistance
);
if (line != null)
writer.WriteLine(line);
}
private static string GetLinearFeedVariable(LayerType layer)
@@ -0,0 +1,37 @@
namespace OpenNest.Posts.Cincinnati;
/// <summary>
/// Chooses the M47 head raise (§3.47) written before the rapid that leaves a feature.
/// </summary>
internal static class CincinnatiHeadRaise
{
/// <param name="isSafetyHeadraise">True when the rapid goes to a different part.</param>
/// <param name="isExterior">True when the feature just cut is a part exterior.</param>
/// <param name="rapidDistance">Travel to the next pierce; null when unknown.</param>
/// <returns>The block to write, or null for no head raise.</returns>
internal static string Line(
CincinnatiPostConfig config,
bool isSafetyHeadraise,
bool isExterior,
double? rapidDistance
)
{
if (isSafetyHeadraise && config.SafetyHeadraiseDistance.HasValue)
return $"M47 P{config.SafetyHeadraiseDistance.Value} (Safety Headraise)";
var mode = isExterior ? config.ExteriorM47 : config.InteriorM47;
return mode switch
{
M47Mode.Always => "M47",
M47Mode.BlockDelete => "/M47",
M47Mode.Auto => IsLongRapid(config, rapidDistance) ? "M47" : "/M47",
_ => null,
};
}
// Unknown travel, or no threshold configured, always gets the full raise.
private static bool IsLongRapid(CincinnatiPostConfig config, double? rapidDistance) =>
config.M47OverrideDistanceThreshold is not { } threshold
|| rapidDistance is not { } distance
|| distance > threshold;
}
@@ -7,10 +7,18 @@ using OpenNest.Geometry;
namespace OpenNest.Posts.Cincinnati;
/// <summary>
/// A posted part sub-program and where one part's program frame puts its origin.
/// </summary>
/// <param name="Number">Posted sub-program number.</param>
/// <param name="Program">The normalized, absolute program the sub-program is written from.</param>
/// <param name="Corner">The sub-program origin in the part's program frame.</param>
public sealed record PartSubprogram(int Number, Program Program, Vector Corner);
/// <summary>
/// Writes a Cincinnati-format part sub-program definition.
/// Each sub-program contains the complete cutting sequence for one unique part geometry
/// (drawing + rotation), with coordinates normalized to origin (0,0).
/// Each sub-program contains the complete cutting sequence for one unique posted part
/// toolpath, with coordinates normalized to origin (0,0).
/// Called via M98 from sheet sub-programs.
/// </summary>
public sealed class CincinnatiPartSubprogramWriter
@@ -51,6 +59,7 @@ public sealed class CincinnatiPartSubprogramWriter
// Classify and order: etch features first, then cut features
var ordered = FeatureUtils.ClassifyAndOrder(allFeatures);
var exterior = FeatureUtils.FindExterior(ordered);
w.WriteLine("(*****************************************************)");
w.WriteLine($":{subNumber}");
@@ -81,11 +90,14 @@ public sealed class CincinnatiPartSubprogramWriter
IsFirstFeatureOfPart = false,
IsLastFeatureOnSheet = isLastFeature,
IsSafetyHeadraise = false,
IsExteriorFeature = false,
IsExteriorFeature = exterior[i],
IsEtch = isEtch,
LibraryFile = isEtch ? etchLibrary : cutLibrary,
CutDistance = cutDistance,
SheetDiagonal = sheetDiagonal,
RapidDistance = isLastFeature
? null
: FeatureUtils.EndPoint(codes).DistanceTo(FeatureUtils.StartPoint(ordered[i + 1].codes)),
};
_featureWriter.Write(w, ctx);
@@ -102,22 +114,19 @@ public sealed class CincinnatiPartSubprogramWriter
internal static void EnsureLeadingRapid(Program pgm) => FeatureUtils.InsertLeadingRapid(pgm.Codes);
/// <summary>
/// Creates a sub-program key for matching parts to their sub-programs.
/// </summary>
internal static (int drawingId, long rotationKey) SubprogramKey(Part part) =>
(part.BaseDrawing.Id, (long)System.Math.Round(part.Rotation * 1e6));
/// <summary>
/// Scans all plates and builds a mapping of unique part geometries to sub-program numbers,
/// along with their normalized programs for writing.
/// Scans all plates and assigns each non-cutoff part the sub-program for its posted
/// toolpath: parts share a sub-program only when their normalized programs, lead-ins
/// included, post identically under the same drawing name. Part programs are copied,
/// never modified.
/// </summary>
internal static (
Dictionary<(int, long), int> mapping,
Dictionary<Part, PartSubprogram> mapping,
List<(int subNum, string name, Program program)> entries
) BuildRegistry(IEnumerable<Plate> plates, int startNumber)
{
var mapping = new Dictionary<(int, long), int>();
var mapping = new Dictionary<Part, PartSubprogram>(ReferenceEqualityComparer.Instance);
var entries = new List<(int, string, Program)>();
var contentIndex = new Dictionary<string, (int subNum, Program program)>();
var nextSubNum = startNumber;
foreach (var plate in plates)
@@ -126,32 +135,44 @@ public sealed class CincinnatiPartSubprogramWriter
{
if (part.BaseDrawing.IsCutOff)
continue;
var key = SubprogramKey(part);
if (!mapping.ContainsKey(key))
var pgm = PostedCopy(part.Program);
var bbox = pgm.BoundingBox();
pgm.Offset(-bbox.Location.X, -bbox.Location.Y);
// If the program has no leading rapid, the feature writer
// will use the first motion endpoint as the pierce point,
// losing the first contour segment. Insert a synthetic rapid
// at the contour's return point (last motion endpoint) so
// the full contour is preserved.
EnsureLeadingRapid(pgm);
var name = part.BaseDrawing.Name;
var key = name + "\n" + ProgramToCanonical(pgm);
if (!contentIndex.TryGetValue(key, out var entry))
{
var subNum = nextSubNum++;
mapping[key] = subNum;
var pgm = part.Program.Clone() as Program;
pgm.Mode = Mode.Absolute;
var bbox = pgm.BoundingBox();
pgm.Offset(-bbox.Location.X, -bbox.Location.Y);
// If the program has no leading rapid, the feature writer
// will use the first motion endpoint as the pierce point,
// losing the first contour segment. Insert a synthetic rapid
// at the contour's return point (last motion endpoint) so
// the full contour is preserved.
EnsureLeadingRapid(pgm);
entries.Add((subNum, part.BaseDrawing.Name, pgm));
entry = (nextSubNum++, pgm);
contentIndex[key] = entry;
entries.Add((entry.subNum, name, pgm));
}
mapping[part] = new PartSubprogram(entry.subNum, entry.program, bbox.Location);
}
}
return (mapping, entries);
}
// An absolute copy with suppressed moves left uncut, as the post writes it.
private static Program PostedCopy(Program program)
{
var copy = FeatureUtils.ToAbsoluteCopy(program);
var codes = FeatureUtils.RemoveSuppressed(copy.Codes);
copy.Codes.Clear();
copy.Codes.AddRange(codes);
return copy;
}
/// <summary>
/// Builds a nest-level registry of unique hole sub-programs from every hole call in
/// the plates' parts and in the part sub-program copies. Calls are keyed by their
@@ -179,10 +200,10 @@ public sealed class CincinnatiPartSubprogramWriter
{
if (code is not SubProgramCall { Program: not null } call)
continue;
if (mapping.ContainsKey(call.Program))
if (mapping.ContainsKey(call.Program) || !FeatureUtils.HasCut(call.Program))
continue;
var absolute = FeatureUtils.ToAbsoluteCopy(call.Program);
var absolute = PostedCopy(call.Program);
EnsureLeadingRapid(absolute);
var canonical = ProgramToCanonical(absolute);
@@ -232,6 +253,11 @@ public sealed class CincinnatiPartSubprogramWriter
);
else if (code is RapidMove rm)
sb.Append(CultureInfo.InvariantCulture, $"R{rm.EndPoint.X:F6},{rm.EndPoint.Y:F6}");
else if (code is SubProgramCall { Program: not null } call)
sb.Append(
CultureInfo.InvariantCulture,
$"S{call.Offset.X:F6},{call.Offset.Y:F6}[{ProgramToCanonical(PostedCopy(call.Program))}]"
);
}
return sb.ToString();
}
@@ -5,33 +5,6 @@ using System.Linq;
namespace OpenNest.Posts.Cincinnati
{
/// <summary>
/// Specifies how coordinate positioning is handled between parts.
/// </summary>
public enum CoordinateMode
{
/// <summary>Set absolute position.</summary>
G92,
/// <summary>Use relative/incremental positioning.</summary>
G91,
/// <summary>Use machine coordinate system.</summary>
G53,
}
/// <summary>
/// Specifies how G89 (hole drilling/tapping parameters) are provided.
/// </summary>
public enum G89Mode
{
/// <summary>Use external library file for G89 parameters.</summary>
LibraryFile,
/// <summary>Explicitly define G89 parameters in the program.</summary>
Explicit,
}
/// <summary>
/// Specifies where kerf compensation is applied.
/// </summary>
@@ -57,17 +30,20 @@ namespace OpenNest.Posts.Cincinnati
}
/// <summary>
/// Specifies how M47 (optional stop) commands are used.
/// Specifies how the M47 head raise before each rapid is posted.
/// </summary>
public enum M47Mode
{
/// <summary>Always include M47.</summary>
Always,
/// <summary>Include M47 with block delete functionality.</summary>
/// <summary>Post /M47, which the operator can skip with block delete.</summary>
BlockDelete,
/// <summary>Automatically determine M47 placement.</summary>
/// <summary>
/// M47 before rapids longer than the M47 override distance threshold, /M47 before
/// shorter ones. Without a threshold every raise is M47.
/// </summary>
Auto,
/// <summary>Do not use M47.</summary>
@@ -120,11 +96,6 @@ namespace OpenNest.Posts.Cincinnati
[Description("Starting line number for features.")]
public int FeatureLineNumberStart { get; set; } = 1;
[Category("2. Subprograms")]
[DisplayName("Use Sheet Subprograms")]
[Description("Use subprograms for sheet operations.")]
public bool UseSheetSubprograms { get; set; } = true;
[Category("2. Subprograms")]
[DisplayName("Sheet Subprogram Start")]
[Description("Starting subprogram number for sheet operations.")]
@@ -147,16 +118,6 @@ namespace OpenNest.Posts.Cincinnati
[Description("Subprogram number for variable declarations.")]
public int VariableDeclarationSubprogram { get; set; } = 100;
[Category("3. Positioning")]
[DisplayName("Coordinate Mode Between Parts")]
[Description("How coordinate positioning is handled between parts (G92, G91, or G53).")]
public CoordinateMode CoordModeBetweenParts { get; set; } = CoordinateMode.G92;
[Category("4. Process")]
[DisplayName("Process Parameter Mode")]
[Description("How G89 parameters are provided (LibraryFile or Explicit).")]
public G89Mode ProcessParameterMode { get; set; } = G89Mode.LibraryFile;
[Category("4. Process")]
[DisplayName("Default Assist Gas")]
[Description("Default assist gas when Nest.AssistGas is empty.")]
@@ -199,22 +160,28 @@ namespace OpenNest.Posts.Cincinnati
[Category("6. M47 (Optional Stop)")]
[DisplayName("Interior M47")]
[Description("How M47 is used in interior cuts.")]
[Description("How M47 is posted after features other than a part's exterior, such as cutouts and etch.")]
public M47Mode InteriorM47 { get; set; } = M47Mode.Always;
[Category("6. M47 (Optional Stop)")]
[DisplayName("Exterior M47")]
[Description("How M47 is used in exterior cuts.")]
[Description(
"How M47 is posted after a part's exterior: the cut contour spanning the part's cut extents, or a part sub-program call."
)]
public M47Mode ExteriorM47 { get; set; } = M47Mode.Always;
[Category("6. M47 (Optional Stop)")]
[DisplayName("M47 Override Distance Threshold")]
[Description("Distance threshold for M47 override. Null = no override.")]
[Description(
"Auto M47 mode: rapids to the next pierce longer than this get M47, shorter ones /M47. Program units. Null = Auto always posts M47."
)]
public double? M47OverrideDistanceThreshold { get; set; } = null;
[Category("7. Safety")]
[DisplayName("Safety Headraise Distance")]
[Description("Safety head raise distance in machine units. Null = disabled.")]
[Description(
"Safety head raise distance in machine units, posted as M47 P<distance> before the rapid to a different part. Null = disabled."
)]
public int? SafetyHeadraiseDistance { get; set; } = 2000;
[Category("8. Pallet")]
@@ -309,21 +276,6 @@ namespace OpenNest.Posts.Cincinnati
)]
[TypeConverter(typeof(MaterialLibraryNameConverter))]
public string SelectedLibrary { get; set; } = "";
public string FindBestLibrary(string materialName, double thickness)
{
if (MaterialLibraries == null || string.IsNullOrEmpty(materialName))
return "";
return MaterialLibraries
.Where(e =>
string.Equals(e.Material, materialName, StringComparison.OrdinalIgnoreCase)
)
.OrderBy(e => System.Math.Abs(e.Thickness - thickness))
.Select(e => e.Library)
.FirstOrDefault()
?? "";
}
}
public class MaterialLibraryEntry
@@ -38,11 +38,24 @@ namespace OpenNest.Posts.Cincinnati
.Where(s => !string.IsNullOrWhiteSpace(s));
}
/// <summary>
/// Pre-selects the library auto-resolution would post for this nest (material,
/// thickness within tolerance and assist gas), so the configuration dialog shows
/// it. With no matching entry the selection is cleared rather than guessed.
/// </summary>
public void PrepareForNest(Nest nest)
{
var materialName = nest?.Material?.Name ?? "";
var thickness = nest?.Thickness ?? 0.0;
Config.SelectedLibrary = Config.FindBestLibrary(materialName, thickness);
Config.SelectedLibrary = "";
if (nest == null)
return;
var entry = MaterialLibraryResolver.FindCutEntry(
Config.MaterialLibraries,
nest.Material?.Name ?? "",
nest.Thickness,
MaterialLibraryResolver.ResolveGas(nest, Config)
);
Config.SelectedLibrary = entry?.Library ?? "";
}
public CincinnatiPostProcessor()
@@ -105,7 +118,7 @@ namespace OpenNest.Posts.Cincinnati
);
// 5. Build part sub-program registry (if enabled)
Dictionary<(int, long), int> partSubprograms = null;
Dictionary<Part, PartSubprogram> partSubprograms = null;
List<(int subNum, string name, Program program)> subprogramEntries = null;
if (Config.UsePartSubprograms)
@@ -57,10 +57,7 @@ public sealed class CincinnatiPreambleWriter
w.WriteLine("M42");
if (
_config.ProcessParameterMode == G89Mode.LibraryFile
&& !string.IsNullOrEmpty(initialLibrary)
)
if (!string.IsNullOrEmpty(initialLibrary))
w.WriteLine($"G89 P{initialLibrary}");
w.WriteLine($"M98 P{_config.VariableDeclarationSubprogram} (Variable Declaration)");
@@ -1,9 +1,9 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using OpenNest.CNC;
using OpenNest.Geometry;
namespace OpenNest.Posts.Cincinnati;
@@ -38,8 +38,8 @@ public sealed class CincinnatiSheetWriter
/// <param name="cutLibrary">Resolved G89 library file for cut operations.</param>
/// <param name="etchLibrary">Resolved G89 library file for etch operations.</param>
/// <param name="partSubprograms">
/// Optional mapping of (drawingId, rotationKey) to sub-program number.
/// When provided, non-cutoff parts are emitted as M98 calls instead of inline features.
/// Optional mapping of parts (by reference) to their posted part sub-programs.
/// When provided, mapped non-cutoff parts are emitted as M98 calls instead of inline features.
/// </param>
public void Write(
TextWriter w,
@@ -49,7 +49,7 @@ public sealed class CincinnatiSheetWriter
int subNumber,
string cutLibrary,
string etchLibrary,
Dictionary<(int, long), int> partSubprograms = null,
IReadOnlyDictionary<Part, PartSubprogram> partSubprograms = null,
Dictionary<(int drawingId, string varName), int> userVarMapping = null
)
{
@@ -87,36 +87,18 @@ public sealed class CincinnatiSheetWriter
w.WriteLine("M47");
if (!string.IsNullOrEmpty(cutLibrary))
w.WriteLine($"G89 P{cutLibrary}");
w.WriteLine("GOTO1( Goto Feature )");
// The operator edits this target to restart at a feature. It names the first
// feature's line number, which exists only when line numbers are posted.
if (_config.UseLineNumbers)
w.WriteLine($"GOTO{_config.FeatureLineNumberStart}( Goto Feature )");
// 3. Plate order is the cut sequence, cut-offs included: manual, cut-first
// and automatic sequencing all set it, so the post must not reorder.
var allParts = plate.Parts.ToList();
var items = BuildItems(plate.Parts, partSubprograms);
// 4. Emit parts
if (partSubprograms != null)
WritePartsWithSubprograms(
w,
allParts,
cutLibrary,
etchLibrary,
sheetDiagonal,
width,
length,
partSubprograms,
userVarMapping
);
else
WritePartsInline(
w,
allParts,
cutLibrary,
etchLibrary,
sheetDiagonal,
width,
length,
userVarMapping
);
WriteItems(w, items, cutLibrary, etchLibrary, sheetDiagonal, width, length, userVarMapping);
// 5. Footer
w.WriteLine("M42");
@@ -125,182 +107,135 @@ public sealed class CincinnatiSheetWriter
w.WriteLine($"M99 (END OF {nestName}.{layoutIndex:D3})");
}
private void WritePartsWithSubprograms(
/// <summary>
/// One posted step of the sheet: a part feature, a hole call or a part sub-program
/// call. Points are in sheet coordinates.
/// </summary>
private sealed class SheetItem
{
public Part Part { get; init; }
public List<ICode> Codes { get; init; }
public bool IsEtch { get; init; }
public bool IsExterior { get; init; }
public PartSubprogram Subprogram { get; init; }
/// <summary>First rapid target: the sub-program corner, else the first pierce.</summary>
public Vector Entry { get; init; }
public Vector Start { get; init; }
public Vector End { get; init; }
/// <summary>Where the tool leaves from: back at the corner after a sub-program call.</summary>
public Vector Exit { get; init; }
}
private static List<SheetItem> BuildItems(
IEnumerable<Part> parts,
IReadOnlyDictionary<Part, PartSubprogram> partSubprograms
)
{
var items = new List<SheetItem>();
foreach (var part in parts)
{
if (
partSubprograms != null
&& !part.BaseDrawing.IsCutOff
&& partSubprograms.TryGetValue(part, out var sub)
)
{
var subFeatures = FeatureUtils.ClassifyAndOrder(
FeatureUtils.SplitByRapids(sub.Program.Codes)
);
if (subFeatures.Count == 0)
continue;
var corner = part.Location + sub.Corner;
items.Add(
new SheetItem
{
Part = part,
Subprogram = sub,
Entry = corner,
Start = corner + FeatureUtils.StartPoint(subFeatures[0].codes),
End = corner + FeatureUtils.EndPoint(subFeatures[^1].codes),
Exit = corner,
}
);
continue;
}
var features = FeatureUtils.SplitAndClassify(part);
var exterior = FeatureUtils.FindExterior(features);
for (var f = 0; f < features.Count; f++)
{
var (codes, isEtch) = features[f];
var start = part.Location + FeatureUtils.StartPoint(codes);
var end = part.Location + FeatureUtils.EndPoint(codes);
items.Add(
new SheetItem
{
Part = part,
Codes = codes,
IsEtch = isEtch,
IsExterior = exterior[f],
Entry = start,
Start = start,
End = end,
Exit = end,
}
);
}
}
return items;
}
private void WriteItems(
TextWriter w,
List<Part> allParts,
List<SheetItem> items,
string cutLibrary,
string etchLibrary,
double sheetDiagonal,
double plateWidth,
double plateLength,
Dictionary<(int, long), int> partSubprograms,
Dictionary<(int drawingId, string varName), int> userVarMapping
)
{
var lastPartName = "";
var featureIndex = 0;
for (var p = 0; p < allParts.Count; p++)
for (var i = 0; i < items.Count; i++)
{
var part = allParts[p];
var item = items[i];
var part = item.Part;
var partName = part.BaseDrawing.Name;
var isNewPart = partName != lastPartName;
var isSafetyHeadraise = isNewPart && lastPartName != "";
var isLastPart = p == allParts.Count - 1;
var isFirstFeatureOfPart = partName != lastPartName;
var next = i + 1 < items.Count ? items[i + 1] : null;
var isLastFeature = next == null;
var key = CincinnatiPartSubprogramWriter.SubprogramKey(part);
partSubprograms.TryGetValue(key, out var subNum);
var hasSubprogram = !part.BaseDrawing.IsCutOff && subNum != 0;
// A head raise belongs before the rapid that leaves this item, so the safety
// raise goes on a part's last item when a different part follows.
var isSafetyHeadraise = next != null && next.Part.BaseDrawing.Name != partName;
double? rapidDistance =
next == null
? null
: item.End.DistanceTo(item.Exit)
+ item.Exit.DistanceTo(next.Entry)
+ next.Entry.DistanceTo(next.Start);
lastPartName = partName;
if (hasSubprogram)
if (item.Subprogram != null)
{
WriteSubprogramCall(
w,
part,
subNum,
featureIndex,
item,
i,
partName,
isSafetyHeadraise,
isLastPart
rapidDistance,
isLastFeature
);
featureIndex++;
}
else
{
// Inline features for cutoffs or parts without sub-programs
var features = FeatureUtils.SplitAndClassify(part);
for (var f = 0; f < features.Count; f++)
{
var (codes, isEtch) = features[f];
var isLastFeature = isLastPart && f == features.Count - 1;
// SubProgramCall features are emitted as M98 hole calls
if (codes.Count == 1 && codes[0] is SubProgramCall holeCall)
{
CincinnatiHoleCallWriter.Write(
w,
holeCall,
part.Location,
featureIndex,
isLastFeature,
_config,
_fmt,
_holeSubprograms,
isNewPart && f == 0 ? partName : null,
isSafetyHeadraise && f == 0
);
featureIndex++;
lastPartName = partName;
continue;
}
var featureNumber =
featureIndex == 0
? _config.FeatureLineNumberStart
: 1000 + featureIndex + 1;
var cutDistance = FeatureUtils.ComputeCutDistance(codes);
var ctx = new FeatureContext
{
Codes = codes,
FeatureNumber = featureNumber,
PartName = partName,
IsFirstFeatureOfPart = isNewPart && f == 0,
IsLastFeatureOnSheet = isLastFeature,
IsSafetyHeadraise = isSafetyHeadraise && f == 0,
IsExteriorFeature = false,
IsEtch = isEtch,
LibraryFile = isEtch ? etchLibrary : cutLibrary,
CutDistance = cutDistance,
SheetDiagonal = sheetDiagonal,
PartLocation = part.Location,
UserVariableMapping = userVarMapping,
DrawingId = part.BaseDrawing.Id,
IsCutOff = part.BaseDrawing.IsCutOff,
PlateWidth = plateWidth,
PlateLength = plateLength,
};
_featureWriter.Write(w, ctx);
featureIndex++;
}
continue;
}
lastPartName = partName;
}
}
private void WriteSubprogramCall(
TextWriter w,
Part part,
int subNum,
int featureIndex,
string partName,
bool isSafetyHeadraise,
bool isLastPart
)
{
// Safety headraise before rapid to new part
if (isSafetyHeadraise && _config.SafetyHeadraiseDistance.HasValue)
w.WriteLine($"M47 P{_config.SafetyHeadraiseDistance.Value} (Safety Headraise)");
// Rapid to part position (bounding box lower-left)
var featureNumber =
featureIndex == 0 ? _config.FeatureLineNumberStart : 1000 + featureIndex + 1;
var sb = new StringBuilder();
if (_config.UseLineNumbers)
sb.Append($"N{featureNumber} ");
sb.Append($"G0 X{_fmt.FormatCoord(part.Left)} Y{_fmt.FormatCoord(part.Bottom)}");
w.WriteLine(sb.ToString());
// Part name comment
w.WriteLine(CoordinateFormatter.Comment($"PART: {partName}"));
// Set local coordinate system at part position
w.WriteLine("G92 X0 Y0");
// Call part sub-program
w.WriteLine($"M98 P{subNum} ({partName})");
// Restore sheet coordinate system
w.WriteLine($"G92 X{_fmt.FormatCoord(part.Left)} Y{_fmt.FormatCoord(part.Bottom)}");
// Head raise (unless last part on sheet)
if (!isLastPart)
w.WriteLine("M47");
}
private void WritePartsInline(
TextWriter w,
List<Part> allParts,
string cutLibrary,
string etchLibrary,
double sheetDiagonal,
double plateWidth,
double plateLength,
Dictionary<(int drawingId, string varName), int> userVarMapping
)
{
// Split and classify features, ordering etch before cut per part
var features = new List<(Part part, List<ICode> codes, bool isEtch)>();
foreach (var part in allParts)
{
var partFeatures = FeatureUtils.SplitAndClassify(part);
foreach (var (codes, isEtch) in partFeatures)
features.Add((part, codes, isEtch));
}
// Emit features
var lastPartName = "";
for (var i = 0; i < features.Count; i++)
{
var (part, codes, isEtch) = features[i];
var partName = part.BaseDrawing.Name;
var isFirstFeatureOfPart = partName != lastPartName;
var isSafetyHeadraise = partName != lastPartName && lastPartName != "";
var isLastFeature = i == features.Count - 1;
var codes = item.Codes;
// SubProgramCall features are emitted as M98 hole calls
if (codes.Count == 1 && codes[0] is SubProgramCall holeCall)
@@ -317,27 +252,23 @@ public sealed class CincinnatiSheetWriter
isFirstFeatureOfPart ? partName : null,
isSafetyHeadraise
);
lastPartName = partName;
continue;
}
var featureNumber = i == 0 ? _config.FeatureLineNumberStart : 1000 + i + 1;
var cutDistance = FeatureUtils.ComputeCutDistance(codes);
var ctx = new FeatureContext
{
Codes = codes,
FeatureNumber = featureNumber,
FeatureNumber = FeatureNumber(i),
PartName = partName,
IsFirstFeatureOfPart = isFirstFeatureOfPart,
IsLastFeatureOnSheet = isLastFeature,
IsSafetyHeadraise = isSafetyHeadraise,
IsExteriorFeature = false,
IsEtch = isEtch,
LibraryFile = isEtch ? etchLibrary : cutLibrary,
CutDistance = cutDistance,
IsExteriorFeature = item.IsExterior,
IsEtch = item.IsEtch,
LibraryFile = item.IsEtch ? etchLibrary : cutLibrary,
CutDistance = FeatureUtils.ComputeCutDistance(codes),
SheetDiagonal = sheetDiagonal,
RapidDistance = rapidDistance,
PartLocation = part.Location,
UserVariableMapping = userVarMapping,
DrawingId = part.BaseDrawing.Id,
@@ -347,7 +278,59 @@ public sealed class CincinnatiSheetWriter
};
_featureWriter.Write(w, ctx);
lastPartName = partName;
}
}
private int FeatureNumber(int index) =>
index == 0 ? _config.FeatureLineNumberStart : 1000 + index + 1;
/// <summary>
/// Calls a part sub-program in a G92 frame at the part corner (§1.92). After the
/// call the head is raised, the tool rapids back to local 0,0 and G92 gives that
/// point its sheet coordinates again, so the frame is restored where the tool really
/// is. The last part skips the restore: nothing moves before the next sheet
/// re-anchors with G92 X#5021 Y#5022.
/// </summary>
private void WriteSubprogramCall(
TextWriter w,
SheetItem item,
int index,
string partName,
bool isSafetyHeadraise,
double? rapidDistance,
bool isLastPart
)
{
var x = _fmt.FormatCoord(item.Entry.X);
var y = _fmt.FormatCoord(item.Entry.Y);
// Rapid to the sub-program origin (the part's toolpath corner)
var sb = new StringBuilder();
if (_config.UseLineNumbers)
sb.Append($"N{FeatureNumber(index)} ");
sb.Append($"G0 X{x} Y{y}");
w.WriteLine(sb.ToString());
// Part name comment
w.WriteLine(CoordinateFormatter.Comment($"PART: {partName}"));
// Set local coordinate system at part position
w.WriteLine("G92 X0 Y0");
// Call part sub-program
w.WriteLine($"M98 P{item.Subprogram.Number} ({partName})");
if (isLastPart)
return;
// One head raise covers the rapid back and the rapid on. The part is complete,
// so the raise follows the exterior M47 mode.
var raise = CincinnatiHeadRaise.Line(_config, isSafetyHeadraise, true, rapidDistance);
if (raise != null)
w.WriteLine(raise);
// Restore the sheet coordinate system at the corner
w.WriteLine("G0 X0 Y0");
w.WriteLine($"G92 X{x} Y{y}");
}
}
+191 -3
View File
@@ -78,17 +78,205 @@ public static class FeatureUtils
/// <summary>
/// Splits a part's program into features by rapids, classifies each as etch or cut,
/// and orders etch features before cut features.
/// and orders etch features before cut features. The part's program is not modified.
/// </summary>
public static List<(List<ICode> codes, bool isEtch)> SplitAndClassify(Part part)
{
part.Program.Mode = Mode.Absolute;
var codes = new List<ICode>(part.Program.Codes);
var codes = RemoveSuppressed(AbsoluteCodes(part.Program));
InsertLeadingRapid(codes);
return ClassifyAndOrder(SplitByRapids(codes));
}
/// <summary>
/// Returns <paramref name="program"/>'s codes in absolute mode without changing the
/// program. Hole calls are the program's own instances, so lookups by hole program
/// reference still match; every other code of an incremental program is a copy.
/// </summary>
public static List<ICode> AbsoluteCodes(Program program)
{
if (program.Mode == Mode.Absolute)
return new List<ICode>(program.Codes);
var copy = ToAbsoluteCopy(program);
var codes = new List<ICode>(copy.Codes.Count);
for (var i = 0; i < copy.Codes.Count; i++)
codes.Add(copy.Codes[i] is SubProgramCall ? program.Codes[i] : copy.Codes[i]);
return codes;
}
/// <summary>
/// Leaves suppressed moves uncut, matching the other posts and the cut simulation.
/// Absolute codes only. A cut that resumes after a suppressed run starts with a
/// rapid to the run's end, so the gap is crossed with the beam off rather than cut
/// as a chord. Rapids left with nothing to cut, and hole calls whose moves are all
/// suppressed, are dropped so they cannot post an empty pierce.
/// </summary>
public static List<ICode> RemoveSuppressed(List<ICode> codes)
{
var kept = new List<ICode>(codes.Count);
Vector? resumeAt = null;
foreach (var code in codes)
{
if (code is Motion { Suppressed: true } suppressed)
{
resumeAt = suppressed.EndPoint;
continue;
}
if (code is SubProgramCall call && !HasCut(call.Program))
continue;
if (resumeAt.HasValue && code is Motion and not RapidMove)
kept.Add(new RapidMove(resumeAt.Value));
resumeAt = null;
kept.Add(code);
}
var result = new List<ICode>(kept.Count);
for (var i = 0; i < kept.Count; i++)
{
if (kept[i] is RapidMove && !CutFollows(kept, i + 1))
continue;
result.Add(kept[i]);
}
return result;
}
// True when a cutting move comes before the next rapid or hole call.
private static bool CutFollows(List<ICode> codes, int start)
{
for (var i = start; i < codes.Count; i++)
{
if (codes[i] is RapidMove or SubProgramCall)
return false;
if (codes[i] is Motion)
return true;
}
return false;
}
/// <summary>True when <paramref name="program"/> has an unsuppressed cutting move.</summary>
public static bool HasCut(Program program)
{
if (program == null)
return false;
foreach (var code in program.Codes)
{
if (code is Motion { Suppressed: false } and not RapidMove)
return true;
if (code is SubProgramCall call && HasCut(call.Program))
return true;
}
return false;
}
/// <summary>
/// The pierce point of a feature in its program's frame: its first rapid, or for a
/// hole call the hole's first pierce shifted to the call offset.
/// </summary>
public static Vector StartPoint(List<ICode> feature)
{
if (feature.Count == 1 && feature[0] is SubProgramCall call && call.Program != null)
return call.Offset + StartPoint(AbsoluteCodes(call.Program));
foreach (var code in feature)
{
if (code is RapidMove rapid)
return rapid.EndPoint;
}
foreach (var code in feature)
{
if (code is Motion motion)
return motion.EndPoint;
}
return Vector.Zero;
}
/// <summary>Where the tool stops at the end of a feature, in its program's frame.</summary>
public static Vector EndPoint(List<ICode> feature)
{
if (feature.Count == 1 && feature[0] is SubProgramCall call && call.Program != null)
return call.Offset + EndPoint(AbsoluteCodes(call.Program));
for (var i = feature.Count - 1; i >= 0; i--)
{
if (feature[i] is Motion motion)
return motion.EndPoint;
}
return Vector.Zero;
}
/// <summary>
/// Marks each part's exterior features: cut features whose cut moves (lead moves
/// excluded) span the extents of all the part's cut moves. Etch features and hole
/// calls are never exterior. A part whose outline is cut in pieces has none.
/// </summary>
public static bool[] FindExterior(IReadOnlyList<(List<ICode> codes, bool isEtch)> features)
{
var bounds = new Box[features.Count];
Box all = null;
for (var i = 0; i < features.Count; i++)
{
var (codes, isEtch) = features[i];
if (isEtch || (codes.Count == 1 && codes[0] is SubProgramCall))
continue;
bounds[i] = CutBounds(codes);
if (bounds[i] != null)
all = all == null ? bounds[i] : Union(all, bounds[i]);
}
var result = new bool[features.Count];
for (var i = 0; i < features.Count; i++)
result[i] = bounds[i] != null && SameExtents(bounds[i], all);
return result;
}
private static Box CutBounds(List<ICode> codes)
{
var cut = new Program(Mode.Absolute);
var position = Vector.Zero;
var inCut = false;
foreach (var code in codes)
{
if (code is not Motion motion)
continue;
var layer = motion switch
{
LinearMove linear => linear.Layer,
ArcMove arc => arc.Layer,
_ => LayerType.Leadin,
};
var isCut = motion is not RapidMove && layer is not (LayerType.Leadin or LayerType.Leadout);
if (isCut)
{
if (!inCut)
cut.Codes.Add(new RapidMove(position));
cut.Codes.Add(motion);
}
inCut = isCut;
position = motion.EndPoint;
}
return cut.Codes.Count == 0 ? null : cut.BoundingBox();
}
private static Box Union(Box a, Box b)
{
var left = System.Math.Min(a.Left, b.Left);
var bottom = System.Math.Min(a.Bottom, b.Bottom);
var right = System.Math.Max(a.Right, b.Right);
var top = System.Math.Max(a.Top, b.Top);
return new Box(left, bottom, right - left, top - bottom);
}
private static bool SameExtents(Box a, Box b) =>
a.Left.IsEqualTo(b.Left)
&& a.Right.IsEqualTo(b.Right)
&& a.Bottom.IsEqualTo(b.Bottom)
&& a.Top.IsEqualTo(b.Top);
/// <summary>
/// If the first contour motion has no rapid before it, the feature writer would
/// pierce at that motion's endpoint and lose the first segment. Inserts a synthetic
@@ -24,13 +24,26 @@ public sealed class MaterialLibraryResolver
if (!string.IsNullOrEmpty(_selectedLibrary))
return EnsureLibExtension(_selectedLibrary);
var entry = _materialLibraries.FirstOrDefault(e =>
var entry = FindCutEntry(_materialLibraries, materialName, thickness, gas);
return EnsureLibExtension(entry?.Library ?? "");
}
/// <summary>
/// The first cut library entry for this material, thickness (within tolerance) and
/// assist gas, or null when none matches.
/// </summary>
public static MaterialLibraryEntry FindCutEntry(
IEnumerable<MaterialLibraryEntry> entries,
string materialName,
double thickness,
string gas
)
{
return entries?.FirstOrDefault(e =>
string.Equals(e.Material, materialName, StringComparison.OrdinalIgnoreCase)
&& System.Math.Abs(e.Thickness - thickness) <= ThicknessTolerance
&& string.Equals(e.Gas, gas, StringComparison.OrdinalIgnoreCase)
);
return EnsureLibExtension(entry?.Library ?? "");
}
public string ResolveEtchLibrary(string gas)
@@ -4,13 +4,10 @@
"PostedAccuracy": 4,
"UseLineNumbers": true,
"FeatureLineNumberStart": 1,
"UseSheetSubprograms": true,
"SheetSubprogramStart": 101,
"UsePartSubprograms": false,
"PartSubprogramStart": 200,
"VariableDeclarationSubprogram": 100,
"CoordModeBetweenParts": "G92",
"ProcessParameterMode": "LibraryFile",
"DefaultAssistGas": "O2",
"DefaultEtchGas": "N2",
"UseExactStopMode": false,