feat(cad-converter): export DXF, DWG or SVG with bend lines that import reads back

The CAD Converter's Export button only wrote DXF (or SVG) with every entity on
layer 0 and no bends, so a re-imported export lost its bends and turned the
bend etch marks into cut geometry. Exporting now goes through a new
OpenNest.IO CadExporter:

- DXF R14-2018, DWG 2004-2018 or SVG. ACadSharp cannot write DWG 2007, and
  its DWG 2000/R14 output loses entities and layers, so those are not offered.
- Entities keep their layers; etch marks land on ETCH, which import drops and
  regenerates from the bends. A line picked as a bend is written only as it.
- DXF/DWG bends are BEND-layer CENTER lines with an "UP 90° R 0.06" MText note,
  the form SolidWorksBendDetector reads. Pre-2007 files escape non-ASCII note
  text as \U+XXXX, since ACadSharp reads raw non-ASCII back mangled.
- SVG bends are lines in a BEND group with data-bend-* attributes; the SVG
  reader now returns them as bends (scaled with the drawing units) instead of
  dropping the layer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ajandClaude Opus 5.5 committed 2026-11-18 08:23:13 -05:00
1 parent c10abfe996
commit 45e7d6f1c8
11 files changed
+826 -95

No files matched your search

+1 -1
View File
@@ -65,7 +65,7 @@ Releases: follow [the release procedure](docs/releasing.md) and `scripts/Publish
Read the relevant contract before changing its behavior:
- [Nest file format](docs/nest-file-format.md)
- [SVG import and export](docs/svg-import-export.md): SVG numbers are not drawing units; import never guesses a scale
- [SVG import and export](docs/svg-import-export.md): SVG numbers are not drawing units; import never guesses a scale. It also covers the CAD Converter's DXF/DWG/SVG export, whose bends import reads back
- [Irregular stock](docs/irregular-stock.md): outlined sheets, what honors the outline and what refuses it
- [Directional slides](docs/geometry/directional-slides.md) and [pair-spacing limits](docs/geometry/pair-spacing.md)
- [Lead-in placement](docs/geometry/lead-in-placement.md) (including the planner's eroded pierce for cutouts too small for their lead-in and the stop at a feature's center line) and [pierce zones](docs/geometry/pierce-zone.md): opt-in `PierceDiameter` clearance, the hole pole fallback and the planner's perimeter scrap fallback
+71
View File
@@ -0,0 +1,71 @@
using System.Globalization;
using OpenNest.Bending;
using OpenNest.Geometry;
using OpenNest.Math;
namespace OpenNest.IO.Bending
{
/// <summary>
/// The note an export writes beside a bend line, in the form
/// <see cref="SolidWorksBendDetector"/> reads back ("UP 90° R 0.06").
/// </summary>
internal static class BendNote
{
/// <summary>
/// The bend's own note when it has one, otherwise one built from its direction, angle
/// and radius; null when the direction is unknown, since the detector pairs a note with
/// its line by the word UP or DOWN.
/// </summary>
public static string Text(Bend bend)
{
if (!string.IsNullOrWhiteSpace(bend.NoteText))
return bend.NoteText;
var direction = bend.Direction switch
{
BendDirection.Up => "UP",
BendDirection.Down => "DOWN",
_ => null,
};
if (direction == null)
return null;
var text = direction;
if (bend.Angle.HasValue)
text += $" {Number(bend.Angle.Value)}°";
if (bend.Radius.HasValue)
text += $" R {Number(bend.Radius.Value)}";
return text;
}
/// <summary>A readable text height; the detector accepts a note within two heights of its line.</summary>
public static double Height(Units units) => units == Units.Millimeters ? 3.0 : 0.125;
/// <summary>
/// Where the note sits: just off the middle of the line, turned along it so it reads
/// left to right. The angle is in radians.
/// </summary>
public static (Vector Position, double Angle) Placement(Bend bend, double height)
{
var angle = bend.StartPoint.AngleTo(bend.EndPoint);
if (angle > Angle.HalfPI + Tolerance.Epsilon)
angle -= System.Math.PI;
else if (angle <= -Angle.HalfPI + Tolerance.Epsilon)
angle += System.Math.PI;
var gap = height * 0.25;
var middle = new Vector(
(bend.StartPoint.X + bend.EndPoint.X) / 2,
(bend.StartPoint.Y + bend.EndPoint.Y) / 2
);
var position = new Vector(
middle.X - PortableMath.Sin(angle) * gap,
middle.Y + PortableMath.Cos(angle) * gap
);
return (position, angle);
}
private static string Number(double value) =>
value.ToString("0.######", CultureInfo.InvariantCulture);
}
}
+283
View File
@@ -0,0 +1,283 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ACadSharp;
using ACadSharp.Entities;
using ACadSharp.IO;
using ACadSharp.Tables;
using ACadSharp.Types.Units;
using CSMath;
using OpenNest.Bending;
using OpenNest.Geometry;
using OpenNest.IO.Bending;
using OpenNest.Math;
using AcadLayer = ACadSharp.Tables.Layer;
using GeoEntity = OpenNest.Geometry.Entity;
namespace OpenNest.IO
{
/// <summary>
/// Writes a drawing's source entities and bends as DXF, DWG or SVG, so that
/// <see cref="CadImporter"/> reads the same geometry and bends back. Each entity keeps its
/// layer; bends go on <c>BEND</c> as center lines with a note in the form the bend detector
/// reads. Bend-source lines are written only as their bends.
/// </summary>
public static class CadExporter
{
public const string BendLayerName = "BEND";
/// <summary>
/// The DWG versions that read back as written. ACadSharp cannot write DWG 2007 (AC1021),
/// and its DWG 2000 (AC1015) and R14 (AC1014) output loses entities and their layers.
/// </summary>
public static readonly IReadOnlyList<ACadVersion> DwgVersions = new[]
{
ACadVersion.AC1032,
ACadVersion.AC1027,
ACadVersion.AC1024,
ACadVersion.AC1018,
};
// Characters AutoCAD does not allow in a layer name.
private static readonly char[] InvalidLayerCharacters = "<>/\\\":;?*|=,`".ToCharArray();
/// <summary>
/// Writes <paramref name="path"/> in the format its extension names: .svg, .dwg or
/// otherwise DXF. <paramref name="version"/> applies to DXF and DWG.
/// </summary>
public static void Export(
string path,
IEnumerable<GeoEntity> entities,
IEnumerable<Bend> bends,
Units units,
ACadVersion version = ACadVersion.AC1032
)
{
var bendList = bends?.ToList() ?? new List<Bend>();
var written = Written(entities, bendList);
if (Svg.IsSvg(path))
{
Svg.ExportEntities(written, bendList, path, units);
return;
}
var dwg = Path.GetExtension(path).Equals(".dwg", StringComparison.OrdinalIgnoreCase);
if (dwg && !DwgVersions.Contains(version))
throw new NotSupportedException($"DWG {version} cannot be written.");
var document = BuildDocument(written, bendList, units, version);
using var stream = File.Create(path);
if (dwg)
{
using var writer = new DwgWriter(stream, document);
writer.Write();
}
else
{
using var writer = new DxfWriter(stream, document, false);
writer.Write();
}
}
/// <summary>Builds the CAD document <see cref="Export"/> writes as DXF or DWG.</summary>
public static CadDocument BuildDocument(
IEnumerable<GeoEntity> entities,
IEnumerable<Bend> bends,
Units units,
ACadVersion version = ACadVersion.AC1032
)
{
var bendList = bends?.ToList() ?? new List<Bend>();
var document = new CadDocument(version);
document.Header.InsUnits =
units == Units.Millimeters ? UnitsType.Millimeters : UnitsType.Inches;
var layers = new Dictionary<string, AcadLayer>(StringComparer.OrdinalIgnoreCase);
foreach (var entity in Written(entities, bendList))
Add(document, entity, LayerOf(document, layers, entity.Layer?.Name));
if (bendList.Count == 0)
return document;
var bendLayer = LayerOf(document, layers, BendLayerName);
var center = CenterLineType(document, units);
var height = BendNote.Height(units);
foreach (var bend in bendList)
{
document.Entities.Add(
new ACadSharp.Entities.Line
{
StartPoint = Xyz(bend.StartPoint),
EndPoint = Xyz(bend.EndPoint),
Layer = bendLayer,
LineType = center,
}
);
var note = BendNote.Text(bend);
if (note == null)
continue;
var (position, angle) = BendNote.Placement(bend, height);
document.Entities.Add(
new MText
{
InsertPoint = Xyz(position),
Value = IsUnicode(version) ? note : EscapeNonAscii(note),
Height = height,
// MText takes its rotation as the direction of its X axis.
AlignmentPoint = new XYZ(PortableMath.Cos(angle), PortableMath.Sin(angle), 0),
AttachmentPoint = AttachmentPointType.BottomCenter,
Layer = bendLayer,
}
);
}
return document;
}
// Rapids are not drawing geometry, and a line picked as a bend is written as that bend.
private static List<GeoEntity> Written(IEnumerable<GeoEntity> entities, List<Bend> bends)
{
var bendSources = new HashSet<GeoEntity>(
bends.Where(b => b.SourceEntity != null).Select(b => b.SourceEntity)
);
return entities
.Where(e => e.Layer != SpecialLayers.Rapid && !bendSources.Contains(e))
.ToList();
}
private static void Add(CadDocument document, GeoEntity entity, AcadLayer layer)
{
switch (entity)
{
case Geometry.Line line:
document.Entities.Add(
new ACadSharp.Entities.Line
{
StartPoint = Xyz(line.StartPoint),
EndPoint = Xyz(line.EndPoint),
Layer = layer,
}
);
break;
case Geometry.Arc arc:
var startAngle = arc.StartAngle;
var endAngle = arc.EndAngle;
if (arc.IsReversed)
OpenNest.Math.Generic.Swap(ref startAngle, ref endAngle);
document.Entities.Add(
new ACadSharp.Entities.Arc
{
Center = Xyz(arc.Center),
Radius = arc.Radius,
StartAngle = startAngle,
EndAngle = endAngle,
Layer = layer,
}
);
break;
case Geometry.Circle circle:
document.Entities.Add(
new ACadSharp.Entities.Circle
{
Center = Xyz(circle.Center),
Radius = circle.Radius,
Layer = layer,
}
);
break;
case Geometry.Shape shape:
foreach (var child in shape.Entities)
Add(document, child, layer);
break;
}
}
private static AcadLayer LayerOf(
CadDocument document,
Dictionary<string, AcadLayer> layers,
string name
)
{
name = LayerName(name);
if (layers.TryGetValue(name, out var layer))
return layer;
if (!document.Layers.TryGetValue(name, out layer))
{
layer = new AcadLayer(name) { Color = LayerColor(name) };
document.Layers.Add(layer);
}
layers.Add(name, layer);
return layer;
}
private static string LayerName(string name)
{
if (string.IsNullOrWhiteSpace(name))
return AcadLayer.DefaultName;
var characters = name.Trim().ToCharArray();
for (var i = 0; i < characters.Length; i++)
{
if (Array.IndexOf(InvalidLayerCharacters, characters[i]) >= 0 || char.IsControl(characters[i]))
characters[i] = '_';
}
return new string(characters);
}
private static Color LayerColor(string name)
{
if (name.Equals(BendLayerName, StringComparison.OrdinalIgnoreCase))
return new Color(2);
if (name.Equals(Bend.EtchLayer.Name, StringComparison.OrdinalIgnoreCase))
return new Color(3);
if (name.Equals(SpecialLayers.Scribe.Name, StringComparison.OrdinalIgnoreCase))
return new Color(6);
return new Color(7);
}
// AutoCAD's CENTER pattern, scaled for millimeter drawings like its ISO linetypes.
private static LineType CenterLineType(CadDocument document, Units units)
{
const string name = "CENTER";
if (document.LineTypes.TryGetValue(name, out var existing))
return existing;
var scale = units == Units.Millimeters ? 25.4 : 1.0;
var lineType = new LineType(name) { Description = "Center ____ _ ____ _ ____" };
foreach (var length in new[] { 1.25, -0.25, 0.25, -0.25 })
lineType.AddSegment(new LineType.Segment { Length = length * scale });
document.LineTypes.Add(lineType);
return lineType;
}
// Files before 2007 are not Unicode, and ACadSharp reads their non-ASCII text back
// wrongly, so notes there use MText's \U+XXXX escapes, which the bend detector decodes.
private static bool IsUnicode(ACadVersion version) =>
version is ACadVersion.AC1021 or ACadVersion.AC1024 or ACadVersion.AC1027 or ACadVersion.AC1032;
private static string EscapeNonAscii(string text)
{
var escaped = new System.Text.StringBuilder(text.Length);
foreach (var character in text)
{
if (character < 128)
escaped.Append(character);
else
escaped.Append($"\\U+{(int)character:X4}");
}
return escaped.ToString();
}
private static XYZ Xyz(Vector point) => new XYZ(point.X, point.Y, 0);
}
}
+3 -1
View File
@@ -48,7 +48,9 @@ namespace OpenNest.IO
}
var bends = new List<Bend>();
if (options.DetectBends && dxf.Document != null)
if (options.DetectBends && dxf.Bends != null)
bends = dxf.Bends;
else if (options.DetectBends && dxf.Document != null)
{
bends =
options.BendDetectorName == null
+7
View File
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using ACadSharp;
using OpenNest.Bending;
using OpenNest.Geometry;
namespace OpenNest.IO
@@ -14,6 +15,12 @@ namespace OpenNest.IO
/// </summary>
public List<Entity> RawEntities { get; set; } = new();
public CadDocument Document { get; set; }
/// <summary>
/// Bends the file states outright, as an SVG's BEND layer does; null when bends are
/// detected from <see cref="Document"/> instead.
/// </summary>
public List<Bend> Bends { get; set; }
public List<string> Warnings { get; set; } = new();
}
}
+97 -2
View File
@@ -5,9 +5,11 @@ using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using OpenNest.Bending;
using OpenNest.CNC;
using OpenNest.Converters;
using OpenNest.Geometry;
using OpenNest.IO.Bending;
using OpenNest.Math;
namespace OpenNest.IO
@@ -19,6 +21,10 @@ namespace OpenNest.IO
public static class Svg
{
internal const string PlateLayerName = "PLATE";
internal const string BendDirectionAttribute = "data-bend-direction";
internal const string BendAngleAttribute = "data-bend-angle";
internal const string BendRadiusAttribute = "data-bend-radius";
internal const string BendNoteAttribute = "data-bend-note";
private static readonly XNamespace Ns = "http://www.w3.org/2000/svg";
@@ -87,10 +93,36 @@ namespace OpenNest.IO
ExportEntities(entities, stream, units);
}
public static void ExportEntities(IEnumerable<Entity> entities, Stream stream, Units units)
public static void ExportEntities(IEnumerable<Entity> entities, Stream stream, Units units) =>
ExportEntities(entities, null, stream, units);
/// <summary>
/// Writes entities as <see cref="ExportEntities(IEnumerable{Entity}, Stream, Units)"/>
/// does, plus each bend as a <c>line</c> in a <c>BEND</c> group whose <c>data-bend-*</c>
/// attributes import reads back, with its note as text for people.
/// </summary>
public static void ExportEntities(
IEnumerable<Entity> entities,
IEnumerable<Bend> bends,
string path,
Units units
)
{
using var stream = File.Create(path);
ExportEntities(entities, bends, stream, units);
}
public static void ExportEntities(
IEnumerable<Entity> entities,
IEnumerable<Bend> bends,
Stream stream,
Units units
)
{
var list = entities.ToList();
var bounds = list.Count > 0 ? list.GetBoundingBox() : new Box(0, 0, 1, 1);
var bendList = bends?.ToList() ?? new List<Bend>();
var extents = list.Concat(bendList.Select(b => (Entity)b.ToLine())).ToList();
var bounds = extents.Count > 0 ? extents.GetBoundingBox() : new Box(0, 0, 1, 1);
// Half of each stroke falls outside the outermost geometry; keep it on the page.
var margin = System.Math.Max(System.Math.Max(bounds.Length, bounds.Width), 1) * 0.01;
@@ -115,6 +147,9 @@ namespace OpenNest.IO
foreach (var layer in list.GroupBy(e => e.Layer?.Name ?? Layer.Default.Name))
root.Add(LayerGroup(layer.Key, layer.ToList()));
if (bendList.Count > 0)
root.Add(BendGroup(bendList, units));
new XDocument(new XDeclaration("1.0", "utf-8", null), root).Save(stream);
}
@@ -167,6 +202,66 @@ namespace OpenNest.IO
return group;
}
private static XElement BendGroup(List<Bend> bends, Units units)
{
const string color = "#c0a000";
var group = new XElement(
Ns + "g",
new XAttribute("data-layer", CadExporter.BendLayerName),
new XAttribute("stroke", color)
);
var height = BendNote.Height(units);
foreach (var bend in bends)
{
var line = new XElement(
Ns + "line",
new XAttribute("x1", Number(bend.StartPoint.X)),
new XAttribute("y1", Number(-bend.StartPoint.Y)),
new XAttribute("x2", Number(bend.EndPoint.X)),
new XAttribute("y2", Number(-bend.EndPoint.Y)),
new XAttribute("stroke-width", "1"),
new XAttribute("stroke-dasharray", "12 3 3 3"),
new XAttribute("vector-effect", "non-scaling-stroke")
);
if (bend.Direction != BendDirection.Unknown)
line.Add(new XAttribute(BendDirectionAttribute, bend.Direction.ToString().ToLowerInvariant()));
if (bend.Angle.HasValue)
line.Add(new XAttribute(BendAngleAttribute, Number(bend.Angle.Value)));
if (bend.Radius.HasValue)
line.Add(new XAttribute(BendRadiusAttribute, Number(bend.Radius.Value)));
var note = BendNote.Text(bend);
if (!string.IsNullOrWhiteSpace(bend.NoteText))
line.Add(new XAttribute(BendNoteAttribute, bend.NoteText));
group.Add(line);
if (note == null)
continue;
// SVG's Y points down, so the note's turn is the other way round.
var (position, angle) = BendNote.Placement(bend, height);
var x = Number(position.X);
var y = Number(-position.Y);
group.Add(
new XElement(
Ns + "text",
new XAttribute("x", x),
new XAttribute("y", y),
new XAttribute("font-size", Number(height)),
new XAttribute("font-family", "sans-serif"),
new XAttribute("text-anchor", "middle"),
new XAttribute("fill", color),
new XAttribute("stroke", "none"),
new XAttribute("transform", $"rotate({Number(-Angle.ToDegrees(angle))} {x} {y})"),
note
)
);
}
return group;
}
private static void MoveTo(StringBuilder data, Vector point, ref Vector position)
{
if (!position.IsValid() || position.DistanceTo(point) >= Tolerance.Epsilon)
+70 -1
View File
@@ -8,6 +8,7 @@ using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using OpenNest.Bending;
using OpenNest.Geometry;
using OpenNest.Math;
@@ -56,6 +57,7 @@ namespace OpenNest.IO
private readonly List<Line> lines = new List<Line>();
private readonly List<Arc> arcs = new List<Arc>();
private readonly List<Circle> circles = new List<Circle>();
private readonly List<Bend> bends = new List<Bend>();
private readonly HashSet<XElement> activeUses = new HashSet<XElement>();
private SvgReader(XElement root, double tolerance)
@@ -241,6 +243,7 @@ namespace OpenNest.IO
{
Entities = entities,
RawEntities = raw,
Bends = bends,
Warnings = skipped
.OrderBy(s => s.Key, StringComparer.Ordinal)
.Select(s => $"Skipped {s.Value} <{s.Key}> element(s); convert them to paths to import them.")
@@ -270,7 +273,9 @@ namespace OpenNest.IO
case "a":
case "switch":
var layer = LayerOf(element, parentLayer);
if (!IsSkippedLayer(layer.Name))
if (IsBendLayer(layer.Name))
ReadBends(element, transform);
else if (!IsSkippedLayer(layer.Name))
WalkChildren(element, transform, layer);
break;
@@ -356,6 +361,70 @@ namespace OpenNest.IO
|| string.Equals(name, SpecialLayers.Rapid.Name, StringComparison.OrdinalIgnoreCase)
|| string.Equals(name, Svg.PlateLayerName, StringComparison.OrdinalIgnoreCase);
private static bool IsBendLayer(string name) =>
string.Equals(name, CadExporter.BendLayerName, StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Every <c>line</c> on a BEND layer is a bend, as a center line on a DXF's BEND layer
/// is; OpenNest's export adds its direction, angle, radius and note as
/// <c>data-bend-*</c> attributes. Other shapes and text there are only for people.
/// </summary>
private void ReadBends(XElement group, SvgTransform transform)
{
foreach (var child in group.Elements())
{
if (child.Name.Namespace != svgNamespace || IsHidden(child))
continue;
var placed = transform.Then(SvgTransform.Parse(child.Attribute("transform")?.Value));
if (child.Name.LocalName == "g")
{
ReadBends(child, placed);
continue;
}
if (child.Name.LocalName != "line" || HasRelativeSize(child, "x1", "y1", "x2", "y2"))
continue;
var start = placed.Apply(new Vector(Measure(child, "x1") ?? 0, Measure(child, "y1") ?? 0));
var end = placed.Apply(new Vector(Measure(child, "x2") ?? 0, Measure(child, "y2") ?? 0));
if (start.DistanceTo(end) < Tolerance.Epsilon)
continue;
var direction = Enum.TryParse<BendDirection>(
child.Attribute(Svg.BendDirectionAttribute)?.Value,
ignoreCase: true,
out var parsed
) && Enum.IsDefined(parsed)
? parsed
: BendDirection.Unknown;
var radius = Number(child, Svg.BendRadiusAttribute);
bends.Add(
new Bend
{
StartPoint = start,
EndPoint = end,
Direction = direction,
Angle = Number(child, Svg.BendAngleAttribute),
// The radius is a length in the file's units, like the line.
Radius = radius * placed.ScaleFactor,
NoteText = child.Attribute(Svg.BendNoteAttribute)?.Value,
}
);
}
}
private static double? Number(XElement element, string attribute) =>
double.TryParse(
element.Attribute(attribute)?.Value,
NumberStyles.Float,
CultureInfo.InvariantCulture,
out var value
) && double.IsFinite(value)
? value
: null;
private void WalkUse(XElement use, SvgTransform transform, Layer layer)
{
var href = use.Attributes().FirstOrDefault(a => a.Name.LocalName == "href")?.Value;
@@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using ACadSharp;
using OpenNest.Bending;
using OpenNest.Geometry;
using OpenNest.IO;
using Xunit;
namespace OpenNest.Tests.IO
{
public class CadExportRoundTripTests : IDisposable
{
private readonly string folder = Directory.CreateTempSubdirectory("cad-export-tests").FullName;
public void Dispose() => Directory.Delete(folder, true);
public static IEnumerable<object[]> Formats()
{
foreach (var version in new[]
{
ACadVersion.AC1032, ACadVersion.AC1027, ACadVersion.AC1024, ACadVersion.AC1021,
ACadVersion.AC1018, ACadVersion.AC1015, ACadVersion.AC1014,
})
yield return new object[] { ".dxf", version };
foreach (var version in CadExporter.DwgVersions)
yield return new object[] { ".dwg", version };
yield return new object[] { ".svg", ACadVersion.AC1032 };
}
// A 20 x 10 blank with a hole, an etch layer mark and a second, scribed layer.
private static List<Entity> Blank(double scale = 1)
{
var cut = new Layer("CUT");
var entities = new List<Entity>
{
new Line(new Vector(0, 0), new Vector(20 * scale, 0)),
new Line(new Vector(20 * scale, 0), new Vector(20 * scale, 10 * scale)),
new Line(new Vector(20 * scale, 10 * scale), new Vector(0, 10 * scale)),
new Line(new Vector(0, 10 * scale), new Vector(0, 0)),
new Circle(new Vector(10 * scale, 5 * scale), 1 * scale),
};
foreach (var entity in entities)
entity.Layer = cut;
return entities;
}
private static List<Bend> Bends(double scale = 1) =>
new List<Bend>
{
// No note: export builds one from the direction, angle and radius.
new Bend
{
StartPoint = new Vector(5 * scale, 0),
EndPoint = new Vector(5 * scale, 10 * scale),
Direction = BendDirection.Up,
Angle = 90,
Radius = 0.06 * scale,
},
// Drawn right to left, with its source note kept as written.
new Bend
{
StartPoint = new Vector(16 * scale, 10 * scale),
EndPoint = new Vector(16 * scale, 0),
Direction = BendDirection.Down,
Angle = 45,
Radius = 0.03 * scale,
NoteText = "DOWN 45° R 0.03",
},
};
private string Export(string extension, ACadVersion version, List<Entity> entities, List<Bend> bends, Units units)
{
var path = Path.Combine(folder, $"part-{version}{extension}");
var withEtch = entities.ToList();
Bend.UpdateEtchEntities(withEtch, bends);
CadExporter.Export(path, withEtch, bends, units, version);
return path;
}
[Theory]
[MemberData(nameof(Formats))]
public void BendsAndGeometryReadBack(string extension, ACadVersion version)
{
var bends = Bends();
var path = Export(extension, version, Blank(), bends, Units.Inches);
var result = CadImporter.Import(path, new CadImportOptions { DrawingUnits = Units.Inches });
Assert.Equal(bends.Count, result.Bends.Count);
foreach (var expected in bends)
{
var actual = Assert.Single(result.Bends, b => SameLine(b, expected));
Assert.Equal(expected.Direction, actual.Direction);
Assert.Equal(expected.Angle.Value, actual.Angle.Value, 6);
Assert.Equal(expected.Radius.Value, actual.Radius.Value, 6);
}
Assert.Equal("DOWN 45° R 0.03", result.Bends.Single(b => b.Direction == BendDirection.Down).NoteText);
// Etch marks are dropped and made again from the bends, never read as cut geometry.
var cut = result.Entities.Where(e => e.Layer?.Name != Bend.EtchLayer.Name).ToList();
Assert.Equal(4, cut.OfType<Line>().Count());
Assert.Single(cut.OfType<Circle>());
Assert.All(cut, e => Assert.Equal("CUT", e.Layer.Name));
Assert.Equal(2, result.Entities.Count(e => e.Layer?.Name == Bend.EtchLayer.Name));
}
[Theory]
[InlineData(".dxf")]
[InlineData(".dwg")]
[InlineData(".svg")]
public void MillimeterBendsReadBack(string extension)
{
var bends = Bends(25.4);
var path = Export(extension, ACadVersion.AC1032, Blank(25.4), bends, Units.Millimeters);
var result = CadImporter.Import(path, new CadImportOptions { DrawingUnits = Units.Millimeters });
Assert.Equal(2, result.Bends.Count);
Assert.All(bends, expected => Assert.Contains(result.Bends, b => SameLine(b, expected)));
Assert.Equal(1.524, result.Bends.Single(b => b.Direction == BendDirection.Up).Radius.Value, 6);
}
[Fact]
public void SvgBendsScaleWithTheDrawingUnits()
{
var path = Export(".svg", ACadVersion.AC1032, Blank(), Bends(), Units.Inches);
var result = CadImporter.Import(path, new CadImportOptions { DrawingUnits = Units.Millimeters });
var up = result.Bends.Single(b => b.Direction == BendDirection.Up);
Assert.Equal(5 * 25.4, up.StartPoint.X, 6);
Assert.Equal(10 * 25.4, up.Length, 6);
Assert.Equal(0.06 * 25.4, up.Radius.Value, 6);
Assert.Equal(90, up.Angle.Value, 6);
}
[Theory]
[InlineData(".dxf")]
[InlineData(".dwg")]
[InlineData(".svg")]
public void LinePickedAsABendIsWrittenOnlyAsTheBend(string extension)
{
var entities = Blank();
var picked = new Line(new Vector(8, 0), new Vector(8, 10)) { Layer = new Layer("CUT"), IsVisible = false };
entities.Add(picked);
var bends = new List<Bend>
{
new Bend
{
StartPoint = picked.StartPoint,
EndPoint = picked.EndPoint,
Direction = BendDirection.Up,
Angle = 90,
Radius = 0.06,
SourceEntity = picked,
},
};
var path = Export(extension, ACadVersion.AC1032, entities, bends, Units.Inches);
var result = CadImporter.Import(path, new CadImportOptions { DrawingUnits = Units.Inches });
Assert.Single(result.Bends);
Assert.Equal(4, result.Entities.OfType<Line>().Count(e => e.Layer?.Name == "CUT"));
}
[Theory]
[InlineData(".dxf")]
[InlineData(".svg")]
public void BendWithoutADirectionStaysABend(string extension)
{
var bend = new Bend
{
StartPoint = new Vector(5, 0),
EndPoint = new Vector(5, 10),
Direction = BendDirection.Unknown,
};
var path = Export(extension, ACadVersion.AC1032, Blank(), new List<Bend> { bend }, Units.Inches);
var result = CadImporter.Import(path, new CadImportOptions { DrawingUnits = Units.Inches });
var actual = Assert.Single(result.Bends);
Assert.True(SameLine(actual, bend));
Assert.Equal(BendDirection.Unknown, actual.Direction);
}
[Fact]
public void SvgBendLinesCarryTheirValues()
{
var path = Export(".svg", ACadVersion.AC1032, Blank(), Bends(), Units.Inches);
var svg = XNamespace.Get("http://www.w3.org/2000/svg");
var group = XDocument.Load(path).Root.Elements(svg + "g")
.Single(g => (string)g.Attribute("data-layer") == "BEND");
var up = group.Elements(svg + "line").First();
Assert.Equal("up", (string)up.Attribute("data-bend-direction"));
Assert.Equal("90", (string)up.Attribute("data-bend-angle"));
Assert.Equal("0.06", (string)up.Attribute("data-bend-radius"));
Assert.Contains(group.Elements(svg + "text"), t => t.Value == "UP 90° R 0.06");
}
[Fact]
public void DwgCannotBeWrittenAs2007()
{
var path = Path.Combine(folder, "part.dwg");
Assert.Throws<NotSupportedException>(
() => CadExporter.Export(path, Blank(), Bends(), Units.Inches, ACadVersion.AC1021)
);
}
[Fact]
public void LayerNamesAutoCadRejectsAreReplaced()
{
var entities = Blank();
foreach (var entity in entities)
entity.Layer = new Layer("Cut: outside");
var document = CadExporter.BuildDocument(entities, null, Units.Inches);
Assert.True(document.Layers.Contains("Cut_ outside"));
}
private static bool SameLine(Bend a, Bend b) =>
(a.StartPoint.DistanceTo(b.StartPoint) < 1e-6 && a.EndPoint.DistanceTo(b.EndPoint) < 1e-6)
|| (a.StartPoint.DistanceTo(b.EndPoint) < 1e-6 && a.EndPoint.DistanceTo(b.StartPoint) < 1e-6);
}
}
+14 -14
View File
@@ -31,7 +31,7 @@ namespace OpenNest.Forms
lblEntityCount = new System.Windows.Forms.Label();
btnSplit = new System.Windows.Forms.Button();
btnSimplify = new System.Windows.Forms.Button();
btnExportDxf = new System.Windows.Forms.Button();
btnExport = new System.Windows.Forms.Button();
btnHoleTable = new System.Windows.Forms.Button();
chkShowOriginal = new System.Windows.Forms.CheckBox();
chkLabels = new System.Windows.Forms.CheckBox();
@@ -171,7 +171,7 @@ namespace OpenNest.Forms
detailBar.Controls.Add(lblEntityCount);
detailBar.Controls.Add(btnSplit);
detailBar.Controls.Add(btnSimplify);
detailBar.Controls.Add(btnExportDxf);
detailBar.Controls.Add(btnExport);
detailBar.Controls.Add(btnHoleTable);
detailBar.Controls.Add(chkShowOriginal);
detailBar.Controls.Add(chkLabels);
@@ -275,18 +275,18 @@ namespace OpenNest.Forms
btnSimplify.Text = "Simplify...";
btnSimplify.Click += OnSimplifyClick;
//
// btnExportDxf
// btnExport
//
btnExportDxf.AutoSize = true;
btnExportDxf.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnExportDxf.Font = new System.Drawing.Font("Segoe UI", 9F);
btnExportDxf.Location = new System.Drawing.Point(444, 6);
btnExportDxf.Margin = new System.Windows.Forms.Padding(0, 0, 10, 0);
btnExportDxf.Name = "btnExportDxf";
btnExportDxf.Size = new System.Drawing.Size(76, 27);
btnExportDxf.TabIndex = 8;
btnExportDxf.Text = "Export DXF";
btnExportDxf.Click += OnExportDxfClick;
btnExport.AutoSize = true;
btnExport.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
btnExport.Font = new System.Drawing.Font("Segoe UI", 9F);
btnExport.Location = new System.Drawing.Point(444, 6);
btnExport.Margin = new System.Windows.Forms.Padding(0, 0, 10, 0);
btnExport.Name = "btnExport";
btnExport.Size = new System.Drawing.Size(76, 27);
btnExport.TabIndex = 8;
btnExport.Text = "Export...";
btnExport.Click += OnExportClick;
//
// btnHoleTable
//
@@ -445,7 +445,7 @@ namespace OpenNest.Forms
private System.Windows.Forms.TextBox txtCustomer;
private System.Windows.Forms.Button btnSplit;
private System.Windows.Forms.Button btnSimplify;
private System.Windows.Forms.Button btnExportDxf;
private System.Windows.Forms.Button btnExport;
private System.Windows.Forms.Button btnHoleTable;
private System.Windows.Forms.CheckBox chkShowOriginal;
private System.Windows.Forms.CheckBox chkLabels;
+42 -73
View File
@@ -1341,9 +1341,26 @@ namespace OpenNest.Forms
entityView1.Invalidate();
}
private const int SvgExportFilterIndex = 8;
// The Export choices in dialog order; a null version is SVG.
private static readonly (string Label, string Extension, ACadSharp.ACadVersion? Version)[] ExportFormats =
{
("DXF 2018", ".dxf", ACadSharp.ACadVersion.AC1032),
("DXF 2013", ".dxf", ACadSharp.ACadVersion.AC1027),
("DXF 2010", ".dxf", ACadSharp.ACadVersion.AC1024),
("DXF 2007", ".dxf", ACadSharp.ACadVersion.AC1021),
("DXF 2004", ".dxf", ACadSharp.ACadVersion.AC1018),
("DXF 2000", ".dxf", ACadSharp.ACadVersion.AC1015),
("DXF R14", ".dxf", ACadSharp.ACadVersion.AC1014),
("DWG 2018", ".dwg", ACadSharp.ACadVersion.AC1032),
("DWG 2013", ".dwg", ACadSharp.ACadVersion.AC1027),
("DWG 2010", ".dwg", ACadSharp.ACadVersion.AC1024),
("DWG 2004", ".dwg", ACadSharp.ACadVersion.AC1018),
("SVG", ".svg", null),
};
private void OnExportDxfClick(object sender, EventArgs e)
// Writes the current drawing with its layers and bends, so importing the file again
// gives back the same geometry and bends.
private void OnExportClick(object sender, EventArgs e)
{
var item = CurrentItem;
if (item == null)
@@ -1351,87 +1368,39 @@ namespace OpenNest.Forms
using var dlg = new SaveFileDialog
{
Filter =
"DXF 2018 (*.dxf)|*.dxf|"
+ "DXF 2013 (*.dxf)|*.dxf|"
+ "DXF 2010 (*.dxf)|*.dxf|"
+ "DXF 2007 (*.dxf)|*.dxf|"
+ "DXF 2004 (*.dxf)|*.dxf|"
+ "DXF 2000 (*.dxf)|*.dxf|"
+ "DXF R14 (*.dxf)|*.dxf|"
+ "SVG (*.svg)|*.svg",
Filter = string.Join(
"|",
ExportFormats.Select(f => $"{f.Label} (*{f.Extension})|*{f.Extension}")
),
FileName = Path.ChangeExtension(item.Name, ".dxf"),
};
if (dlg.ShowDialog() != DialogResult.OK)
return;
if (dlg.FilterIndex == SvgExportFilterIndex)
var format = ExportFormats[System.Math.Clamp(dlg.FilterIndex, 1, ExportFormats.Length) - 1];
var path = Path.ChangeExtension(dlg.FileName, format.Extension);
try
{
Svg.ExportEntities(item.Entities, Path.ChangeExtension(dlg.FileName, ".svg"), DrawingUnits);
return;
CadExporter.Export(
path,
item.Entities,
item.Bends,
DrawingUnits,
format.Version ?? ACadSharp.ACadVersion.AC1032
);
}
var version = dlg.FilterIndex switch
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or NotSupportedException)
{
2 => ACadSharp.ACadVersion.AC1027,
3 => ACadSharp.ACadVersion.AC1024,
4 => ACadSharp.ACadVersion.AC1021,
5 => ACadSharp.ACadVersion.AC1018,
6 => ACadSharp.ACadVersion.AC1015,
7 => ACadSharp.ACadVersion.AC1014,
_ => ACadSharp.ACadVersion.AC1032,
};
var doc = new ACadSharp.CadDocument(version);
foreach (var entity in item.Entities)
{
switch (entity)
{
case Geometry.Line line:
doc.Entities.Add(
new ACadSharp.Entities.Line
{
StartPoint = new CSMath.XYZ(
line.StartPoint.X,
line.StartPoint.Y,
0
),
EndPoint = new CSMath.XYZ(line.EndPoint.X, line.EndPoint.Y, 0),
}
);
break;
case Geometry.Arc arc:
var startAngle = arc.StartAngle;
var endAngle = arc.EndAngle;
if (arc.IsReversed)
OpenNest.Math.Generic.Swap(ref startAngle, ref endAngle);
doc.Entities.Add(
new ACadSharp.Entities.Arc
{
Center = new CSMath.XYZ(arc.Center.X, arc.Center.Y, 0),
Radius = arc.Radius,
StartAngle = startAngle,
EndAngle = endAngle,
}
);
break;
case Geometry.Circle circle:
doc.Entities.Add(
new ACadSharp.Entities.Circle
{
Center = new CSMath.XYZ(circle.Center.X, circle.Center.Y, 0),
Radius = circle.Radius,
}
);
break;
}
MessageBox.Show(
this,
$"Could not export \"{Path.GetFileName(path)}\": {ex.Message}",
"Export",
MessageBoxButtons.OK,
MessageBoxIcon.Error
);
}
using var writer = new ACadSharp.IO.DxfWriter(dlg.FileName, doc, false);
writer.Write();
}
#endregion
+7 -3
View File
@@ -24,10 +24,14 @@ Import takes path centerlines: `path`, `rect` (with rounded corners), `circle`,
- Malformed path data fails the import instead of importing part of a shape.
- Elements with `display` none or `visibility` hidden or collapse are skipped, as are definition elements such as `defs` and `clipPath`. `<style>` sheets are not read, so CSS-class hiding is not honored.
- Text, images, nested `svg`, `use` of a `symbol`, and shapes sized in percentages are skipped and listed in `CadImportResult.Warnings`.
- Layers come from `data-layer`, an Inkscape layer label, or the `id` of a top-level group (Illustrator). `BEND`, `ETCH`, `SCRIBE`, `RAPID` and `PLATE` are dropped, so an exported plate reads back as its parts.
- Layers come from `data-layer`, an Inkscape layer label, or the `id` of a top-level group (Illustrator). `ETCH`, `SCRIBE`, `RAPID` and `PLATE` are dropped, so an exported plate reads back as its parts.
- The file's DTD may parse, because older Illustrator files declare namespaces in one, but external fetches are off and entity expansion is capped.
- There is no bend detection: it reads a CAD document, which an SVG does not have.
- Each `line` on a `BEND` layer is a bend, as a center line on a DXF's `BEND` layer is; nothing else there is read. Its `data-bend-direction` (`up` or `down`), `data-bend-angle` (degrees), `data-bend-radius` (scaled like the line) and `data-bend-note` fill in the bend when present. `CadImportOptions.DetectBends` false ignores them; the detector choice does not apply.
## What export writes
`ExportProgram`, `ExportPlate` and `ExportEntities` write one `<g data-layer>` per layer. `width` and `height` are in the given units and match the `viewBox`, so one user unit is one drawing unit and the file needs no scale prompt. Arcs stay `A` commands. The plate outline and edge spacing go on `PLATE`. Plate export leaves out the rapids DXF draws between parts.
`ExportProgram`, `ExportPlate` and `ExportEntities` write one `<g data-layer>` per layer; the `ExportEntities` overload that takes bends adds a `BEND` group with each bend's `line` and `data-bend-*` attributes, plus its note as text for people. `width` and `height` are in the given units and match the `viewBox`, so one user unit is one drawing unit and the file needs no scale prompt. Arcs stay `A` commands. The plate outline and edge spacing go on `PLATE`. Plate export leaves out the rapids DXF draws between parts.
## CAD Converter export
**Export...** writes the current drawing with `CadExporter`: DXF R14 to 2018, DWG 2004 to 2018 or SVG. Entities keep their layers. Bends go on `BEND` as `CENTER` lines with an MText note such as `UP 90° R 0.06`, the form `SolidWorksBendDetector` reads, so importing the file again gives back the same bends; a line picked as a bend is written only as that bend. Etch marks go on `ETCH`, which import drops and makes again from the bends. Files before 2007 write non-ASCII note characters as `\U+XXXX` escapes. ACadSharp cannot write DWG 2007, and its DWG R14 and 2000 output loses entities and layers, so those are not offered.