mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 13:32:45 -05:00
Merge main into fix/dxf-group-block-reference
This commit is contained in:
commit
23ca546e3d
3 files changed
+233
-10
No files matched your search
@@ -178,7 +178,7 @@ pub(crate) struct Converter {
|
||||
|
||||
const PATTERN_HATCH: &str = "pattern hatches come in as their boundaries";
|
||||
const GRADIENT_HATCH: &str = "gradient hatches are filled with their first colour";
|
||||
const MESHES: &str = "3D polygon meshes and polyface meshes are left out";
|
||||
const MESH_VERTICES: &str = "polygon meshes and polyface mesh faces whose vertices are missing are left out";
|
||||
const BIG_ARRAY: &str = "array inserts are limited to 10,000 copies each";
|
||||
const MANY_ARRAYS: &str = "array inserts are limited to 2,000,000 copies in all";
|
||||
const FAR_AWAY: &str = "entities with coordinates out of range are left out";
|
||||
@@ -233,14 +233,20 @@ impl Converter {
|
||||
path(ellipse(m.common.extrusion, *center, *major, *ratio, *start, *end)?)
|
||||
}
|
||||
model::EntityKind::LwPolyline(p) => lwpolyline(p, ocs),
|
||||
model::EntityKind::Polyline(p) => self.polyline(p, ocs),
|
||||
model::EntityKind::Polyline(p) => self.polyline(p, &g, ocs),
|
||||
model::EntityKind::Spline(s) => path(spline(s)?),
|
||||
model::EntityKind::Solid { corners } | model::EntityKind::Trace { corners } => {
|
||||
let [a, b, c, d] = corners.map(point);
|
||||
// The corners zigzag: the outline runs 1, 2, 4, 3.
|
||||
Some(Geom::Path { bp: transformed(polygon(&[a, b, d, c]), ocs), fill: true, width: 0.0 })
|
||||
}
|
||||
model::EntityKind::Face3d { corners, .. } => path(polygon(&corners.map(point))),
|
||||
model::EntityKind::Face3d { corners, hidden_edges } => {
|
||||
// Bit n of group 70 hides the edge from corner n.
|
||||
let corners: Vec<(Point, bool)> = corners.iter().enumerate().map(|(i, c)| (point(*c), hidden_edges & (1 << i) == 0)).collect();
|
||||
let mut bp = BezPath::new();
|
||||
face(&mut bp, &corners);
|
||||
(!bp.elements().is_empty()).then_some(bp).and_then(path)
|
||||
}
|
||||
model::EntityKind::Hatch(h) => self.hatch(h, ocs),
|
||||
model::EntityKind::Text(t) => text(t, &g, false, ocs).map(Geom::Text),
|
||||
model::EntityKind::MText(t) => mtext(t, e.tags).map(Geom::Text),
|
||||
@@ -253,10 +259,11 @@ impl Converter {
|
||||
}
|
||||
}
|
||||
|
||||
fn polyline(&mut self, p: &model::Polyline, ocs: Affine) -> Option<Geom> {
|
||||
if p.is_mesh() || p.is_polyface() {
|
||||
self.warn(MESHES);
|
||||
return None;
|
||||
fn polyline(&mut self, p: &model::Polyline, g: &Groups<'_>, ocs: Affine) -> Option<Geom> {
|
||||
// Meshes are in world coordinates, seen from above.
|
||||
if p.is_polyface() || p.is_mesh() {
|
||||
let bp = if p.is_polyface() { self.polyface(p) } else { self.mesh(p, g) }?;
|
||||
return Some(Geom::Path { bp, fill: false, width: 0.0 });
|
||||
}
|
||||
// Spline frame control points and polyface faces aren't on the line.
|
||||
let verts: Vec<Vertex> =
|
||||
@@ -267,6 +274,60 @@ impl Converter {
|
||||
Some(Geom::Path { bp, fill: false, width: p.start_width.max(0.0) })
|
||||
}
|
||||
|
||||
/// A polyface mesh's faces: each one's visible edges, closed when all of them are.
|
||||
fn polyface(&mut self, p: &model::Polyline) -> Option<BezPath> {
|
||||
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_face()).map(|v| point(v.location)).collect();
|
||||
let mut bp = BezPath::new();
|
||||
for f in p.vertices.iter().filter(|v| v.is_face()) {
|
||||
// Vertex numbers count from 1, negative when the edge from that vertex is hidden;
|
||||
// 0 ends a triangle's list.
|
||||
let corners: Option<Vec<(Point, bool)>> = f
|
||||
.face
|
||||
.iter()
|
||||
.take_while(|n| **n != 0)
|
||||
.map(|n| {
|
||||
let i = usize::try_from(n.unsigned_abs()).ok()?.checked_sub(1)?;
|
||||
Some((*points.get(i)?, *n > 0))
|
||||
})
|
||||
.collect();
|
||||
match corners {
|
||||
Some(corners) => face(&mut bp, &corners),
|
||||
None => self.warn(MESH_VERTICES),
|
||||
}
|
||||
}
|
||||
(!bp.elements().is_empty()).then_some(bp)
|
||||
}
|
||||
|
||||
/// A polygon mesh as its M lines and N lines. Its vertices go row by row (N to a row); a
|
||||
/// smoothed mesh holds its surface's vertices (groups 73 and 74 count them) after the frame.
|
||||
fn mesh(&mut self, p: &model::Polyline, g: &Groups<'_>) -> Option<BezPath> {
|
||||
let points: Vec<Point> = p.vertices.iter().filter(|v| !v.is_spline_frame()).map(|v| point(v.location)).collect();
|
||||
let size = |m: i64, n: i64| {
|
||||
let (m, n) = (usize::try_from(m).ok()?, usize::try_from(n).ok()?);
|
||||
(m > 0 && n > 0 && m.checked_mul(n) == Some(points.len())).then_some((m, n))
|
||||
};
|
||||
let (frame, surface) = ((p.m, p.n), (g.i_or(73, 0), g.i_or(74, 0)));
|
||||
// Without the frame's vertices only the surface's counts describe the grid.
|
||||
let dims = if p.vertices.iter().any(model::Vertex::is_spline_frame) {
|
||||
size(surface.0, surface.1)
|
||||
} else {
|
||||
size(frame.0, frame.1).or_else(|| size(surface.0, surface.1))
|
||||
};
|
||||
let Some((m, n)) = dims else {
|
||||
self.warn(MESH_VERTICES);
|
||||
return None;
|
||||
};
|
||||
let mut bp = BezPath::new();
|
||||
for row in points.chunks(n) {
|
||||
line(&mut bp, row, p.flags & 32 != 0);
|
||||
}
|
||||
for col in 0..n {
|
||||
let pts: Vec<Point> = (0..m).map(|r| points[r * n + col]).collect();
|
||||
line(&mut bp, &pts, p.closed());
|
||||
}
|
||||
(!bp.elements().is_empty()).then_some(bp)
|
||||
}
|
||||
|
||||
fn insert(&mut self, ins: &model::Insert, followers: &[model::Record<'_>], ocs: Affine) -> Option<Geom> {
|
||||
let block = Some(ins.block.trim()).filter(|b| !b.is_empty())?.to_uppercase();
|
||||
let [sx, sy, _] = ins.scale;
|
||||
@@ -398,6 +459,46 @@ fn polygon(pts: &[Point]) -> BezPath {
|
||||
bp
|
||||
}
|
||||
|
||||
/// Adds the line through `pts` to `bp`, closed if `closed` (nothing for fewer than two points).
|
||||
fn line(bp: &mut BezPath, pts: &[Point], closed: bool) {
|
||||
if pts.len() < 2 {
|
||||
return;
|
||||
}
|
||||
for (i, p) in pts.iter().enumerate() {
|
||||
if i == 0 { bp.move_to(*p) } else { bp.line_to(*p) }
|
||||
}
|
||||
if closed {
|
||||
bp.close_path();
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a face's outline to `bp`: its corners with whether the edge from each to the next is
|
||||
/// visible. All visible, the outline is closed; otherwise each run of visible edges is an open
|
||||
/// line.
|
||||
fn face(bp: &mut BezPath, corners: &[(Point, bool)]) {
|
||||
let pts: Vec<Point> = corners.iter().map(|c| c.0).collect();
|
||||
let Some(hidden) = corners.iter().position(|c| !c.1) else {
|
||||
line(bp, &pts, true);
|
||||
return;
|
||||
};
|
||||
// Start after a hidden edge, so that no run is split where the list wraps.
|
||||
let n = corners.len();
|
||||
let mut run: Vec<Point> = Vec::new();
|
||||
for k in 1..=n {
|
||||
let i = (hidden + k) % n;
|
||||
if corners[i].1 {
|
||||
if run.is_empty() {
|
||||
run.push(pts[i]);
|
||||
}
|
||||
run.push(pts[(i + 1) % n]);
|
||||
} else {
|
||||
line(bp, &run, false);
|
||||
run.clear();
|
||||
}
|
||||
}
|
||||
line(bp, &run, false);
|
||||
}
|
||||
|
||||
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
@@ -248,6 +248,125 @@ fn polyline_bulges_are_exact_arcs() {
|
||||
assert!((b.y1 - height(&doc)).abs() < 1e-4, "the arc's chord is at y 0: {b:?}");
|
||||
}
|
||||
|
||||
/// The straight segments of the paths of the one object a drawing brings in, in drawing
|
||||
/// coordinates (y up), each with its ends in order, sorted.
|
||||
fn drawn_edges(r: &Imported) -> Vec<[(i64, i64); 2]> {
|
||||
let doc = &r.document;
|
||||
assert_eq!(doc.layers[0].children().map_or(0, Vec::len), 1, "one object: {:?}", r.warnings);
|
||||
let h = height(doc);
|
||||
let at = |p: Point| (p.x.round() as i64, (h - p.y).round() as i64);
|
||||
let mut edges = vec![];
|
||||
for n in leaves(doc) {
|
||||
let NodeKind::Path { path, .. } = &n.kind else { panic!("not a path: {:?}", n.kind) };
|
||||
for s in path.to_bezpath().segments() {
|
||||
let kurbo::PathSeg::Line(l) = s else { panic!("not a line: {s:?}") };
|
||||
edges.push([at(l.p0), at(l.p1)]);
|
||||
}
|
||||
}
|
||||
sorted(edges)
|
||||
}
|
||||
|
||||
/// Edges with their ends in order, sorted.
|
||||
fn sorted(mut e: Vec<[(i64, i64); 2]>) -> Vec<[(i64, i64); 2]> {
|
||||
for x in &mut e {
|
||||
x.sort_unstable();
|
||||
}
|
||||
e.sort_unstable();
|
||||
e
|
||||
}
|
||||
|
||||
fn vertex(flags: &'static str, x: &'static str, y: &'static str, z: &'static str) -> [(i32, &'static str); 5] {
|
||||
[(0, "VERTEX"), (70, flags), (10, x), (20, y), (30, z)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polyface_meshes_draw_their_faces_visible_edges_from_above() {
|
||||
// A square at two heights as two triangles sharing a hidden diagonal, and a face naming a
|
||||
// vertex the mesh doesn't have.
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "64"), (71, "4"), (72, "3")];
|
||||
for (x, y, z) in [("0", "0", "5"), ("10", "0", "5"), ("10", "10", "0"), ("0", "10", "0")] {
|
||||
e.extend(vertex("192", x, y, z));
|
||||
}
|
||||
for f in [["1", "2", "-3"], ["3", "4", "-1"], ["1", "2", "9"]] {
|
||||
e.extend(vertex("128", "0", "0", "0"));
|
||||
e.extend([(71, f[0]), (72, f[1]), (73, f[2])]);
|
||||
}
|
||||
e.push((0, "SEQEND"));
|
||||
let r = open(&entities(&e), &points());
|
||||
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
|
||||
assert_eq!(drawn_edges(&r), square, "the outline without the diagonal");
|
||||
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
|
||||
// With every edge visible, each face is a closed outline.
|
||||
let e: Vec<(i32, &str)> = e.iter().map(|&(c, v)| (c, v.trim_start_matches('-'))).collect();
|
||||
let r = open(&entities(&e), &points());
|
||||
let diagonal = drawn_edges(&r).iter().filter(|e| **e == [(0, 0), (10, 10)]).count();
|
||||
assert_eq!(diagonal, 2, "the diagonal, once per face");
|
||||
let faces = leaves(&r.document);
|
||||
assert_eq!(faces.len(), 2);
|
||||
assert!(faces.iter().all(|f| f.path_data().is_some_and(|p| p.subpaths.iter().all(|s| s.closed))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_meshes_draw_their_m_and_n_lines_from_above() {
|
||||
// Rows of 3 vertices: N runs along x, M along y.
|
||||
let grid = |flags: &'static str, m: &'static str, n: &'static str, rows: &[&'static str]| {
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, flags), (71, m), (72, n)];
|
||||
for y in rows {
|
||||
for x in ["0", "10", "20"] {
|
||||
e.extend(vertex("64", x, y, "7"));
|
||||
}
|
||||
}
|
||||
e.push((0, "SEQEND"));
|
||||
e
|
||||
};
|
||||
let edges = |e: &[(i32, &str)]| drawn_edges(&open(&entities(e), &points()));
|
||||
let rows = vec![[(0, 0), (10, 0)], [(10, 0), (20, 0)], [(0, 10), (10, 10)], [(10, 10), (20, 10)]];
|
||||
let cols = vec![[(0, 0), (0, 10)], [(10, 0), (10, 10)], [(20, 0), (20, 10)]];
|
||||
let open_grid = sorted([rows.clone(), cols.clone()].concat());
|
||||
assert_eq!(edges(&grid("16", "2", "3", &["0", "10"])), open_grid);
|
||||
// Closed in N (32): each row joins its last vertex to its first.
|
||||
let wrap = vec![[(20, 0), (0, 0)], [(20, 10), (0, 10)]];
|
||||
assert_eq!(edges(&grid("48", "2", "3", &["0", "10"])), sorted([rows, cols, wrap].concat()));
|
||||
// Closed in M (1): each column joins its last vertex to its first.
|
||||
let tall = edges(&grid("17", "3", "3", &["0", "10", "20"]));
|
||||
for e in [[(0, 0), (0, 20)], [(10, 0), (10, 20)], [(20, 0), (20, 20)]] {
|
||||
assert_eq!(tall.iter().filter(|x| **x == e).count(), 1, "{e:?} in {tall:?}");
|
||||
}
|
||||
// A smoothed mesh draws its surface (73 by 74 vertices), not the frame before it, even when
|
||||
// the frame (3 by 2) has as many vertices.
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "POLYLINE"), (66, "1"), (70, "20"), (71, "3"), (72, "2"), (73, "2"), (74, "3"), (75, "6")];
|
||||
for (x, y) in [("-50", "-50"), ("50", "-50"), ("-50", "0"), ("50", "0"), ("-50", "50"), ("50", "50")] {
|
||||
e.extend(vertex("80", x, y, "0"));
|
||||
}
|
||||
e.extend_from_slice(&grid("16", "2", "3", &["0", "10"])[5..]);
|
||||
assert_eq!(edges(&e), open_grid);
|
||||
// When the surface counts (2 by 4) don't fit, the frame's (3 by 2) don't describe the surface
|
||||
// vertices either: the mesh is left out with a warning.
|
||||
let i = e.iter().position(|t| *t == (74, "3")).unwrap_or_else(|| panic!("no group 74 in {e:?}"));
|
||||
e[i] = (74, "4");
|
||||
let r = open(&entities(&e), &points());
|
||||
assert!(leaves(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
|
||||
// Vertices that don't fill the grid: the mesh is left out with a warning.
|
||||
let r = open(&entities(&grid("16", "2", "4", &["0", "10"])), &points());
|
||||
assert!(leaves(&r.document).is_empty());
|
||||
assert!(r.warnings.iter().any(|w| w.contains("vertices are missing")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_d_faces_leave_out_their_hidden_edges() {
|
||||
let edges = |hidden: &'static str| {
|
||||
let mut e: Vec<(i32, &str)> = vec![(0, "3DFACE"), (70, hidden)];
|
||||
e.extend([(10, "0"), (20, "0"), (11, "10"), (21, "0"), (12, "10"), (22, "10"), (13, "0"), (23, "10")]);
|
||||
drawn_edges(&open(&entities(&e), &points()))
|
||||
};
|
||||
let square = sorted(vec![[(0, 0), (10, 0)], [(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]);
|
||||
assert_eq!(edges("0"), square);
|
||||
// Bit 0 hides the edge from the first corner, bit 2 the one from the third.
|
||||
assert_eq!(edges("1"), sorted(vec![[(10, 0), (10, 10)], [(10, 10), (0, 10)], [(0, 10), (0, 0)]]));
|
||||
assert_eq!(edges("5"), sorted(vec![[(10, 0), (10, 10)], [(0, 10), (0, 0)]]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nurbs_splines_stay_within_a_hundredth() {
|
||||
// A rational quadratic circle of radius 100: nine weighted control points.
|
||||
|
||||
+6
-3
@@ -12709,10 +12709,13 @@ artboard's bottom-left corner; `mergeLayers` puts all art on one layer. Each DXF
|
||||
(off and frozen layers hidden, locked ones locked, non-plotting ones non-printing). Lines, polylines (arc segments from
|
||||
bulges), circles, arcs, ellipses, splines (NURBS, within a millionth of their size), solids and hatches become paths (solid
|
||||
hatches filled, pattern hatches as their boundaries), text and multiline text point type, named blocks symbols
|
||||
(one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. Indexed colours
|
||||
(one per look when their art takes colour "by block"), anonymous blocks such as dimensions groups. 3D faces, polyface
|
||||
meshes and polygon meshes are seen from above, their height dropped: a 3D face or a polyface mesh's face becomes the
|
||||
lines of its visible edges (closed when every edge is visible), and a polygon mesh one path of its M and N lines
|
||||
(smoothed meshes draw their surface's vertices). Indexed colours
|
||||
(7 is black on paper), true colour, lineweights (`scaleLineweights` scales them with the art), linetypes and
|
||||
transparency resolve through layers and blocks. What is left out (viewports, images, meshes, unknown entities) is
|
||||
listed in `warnings`. ASCII and binary DXF files are read.
|
||||
transparency resolve through layers and blocks. What is left out (viewports, images, meshes and mesh faces whose
|
||||
vertices are missing, unknown entities) is listed in `warnings`. ASCII and binary DXF files are read.
|
||||
|
||||
DWG drawings (by content or the `.dwg` extension) open, place and answer `document.dxfInfo` the same way, with the
|
||||
same `dxf` options: craft-dwg converts the drawing to DXF (acadrust 0.6.6, MPL-2.0) and the DXF reader reads that.
|
||||
|
||||
Reference in new issue
Block a user