Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

DXF: write and read a Bézier at its own degree (#5269) (#5281)

CamWighte8a6a5d3ff04
diff --git a/crates/engine/src/cmd/sheet_dxf_tests.rs b/crates/engine/src/cmd/sheet_dxf_tests.rs
index 992bb8c9be..7533e283dc 100644
--- a/crates/engine/src/cmd/sheet_dxf_tests.rs
+++ b/crates/engine/src/cmd/sheet_dxf_tests.rs
@@ -165,6 +165,40 @@ fn a_spline_cut_out_is_the_splines_it_was() {
assert!((areas[0] - plate).abs() < 1e-6, "{areas:?} {plate}");
}
+#[test]
+fn a_g4_blend_cut_out_is_one_spline_of_degree_nine_and_closes() {
+ // Three sides of a 20 × 20 square, closed on the right by a G4 blend from (40, 20) to (40, 40):
+ // one Bézier of degree 9 over ten control points (solidcraft#5269).
+ let mut s = plate_with(&[]);
+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Cut"}));
+ let mut line =
+ |a: [i32; 2], b: [i32; 2]| run(&mut s, "sketch.line", json!({"points": [a, b]}))["curves"][0].as_str().unwrap_or_default().to_string();
+ let (bottom, top) = (line([20, 20], [40, 20]), line([40, 40], [20, 40]));
+ line([20, 40], [20, 20]);
+ run(&mut s, "sketch.blend_curve", json!({"a": format!("{bottom}.end"), "b": format!("{top}.start"), "continuity": "g4"}));
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.extrude", json!({"sketch": "Cut", "through_all": true, "operation": "cut", "direction": "symmetric"}));
+ let hole: Vec<Seg2> = loops(&s).get(1).map(|l| l.segs.clone()).unwrap_or_default();
+ let blend: Vec<Vec2> = hole.iter().find_map(|g| if let Seg2::Bezier { n: 9, p } = g { Some(p[..10].to_vec()) } else { None }).unwrap_or_default();
+ assert_eq!((blend.len(), hole.len()), (10, 4), "{hole:?}");
+
+ // One SPLINE of degree 9 with all ten control points: its ends are the blend's own.
+ let dxf = export(&mut s, json!({}));
+ let es = entities(&dxf);
+ assert_eq!((count(&es, "LINE"), count(&es, "SPLINE"), es.len()), (7, 1, 8));
+ let spline = es.iter().find(|e| e.0 == "SPLINE").unwrap();
+ assert_eq!((values(spline, 70), values(spline, 71), values(spline, 72), values(spline, 73)), (vec![8.0], vec![9.0], vec![20.0], vec![10.0]));
+ let ctrl: Vec<Vec2> = values(spline, 10).into_iter().zip(values(spline, 20)).map(|(x, y)| Vec2::new(x, y)).collect();
+ assert!(ctrl.len() == 10 && ctrl.iter().zip(&blend).all(|(a, b)| a.dist(*b) < 1e-9), "{ctrl:?} {blend:?}");
+ let ends = [ctrl[0], ctrl[9]];
+ assert!(ends.contains(&Vec2::new(40.0, 20.0)) && ends.contains(&Vec2::new(40.0, 40.0)), "{ends:?}");
+
+ // The cut-out closes, so the same plate and the same cut-out come back.
+ let areas = reimported_areas(&dxf);
+ let plate = s.model.state().sheets[0].flat_regions().unwrap_or_default()[0].area();
+ assert!(areas.len() == 2 && (areas[0] - plate).abs() < 1e-6 && (areas[1] - (6000.0 - plate)).abs() < 1e-6, "{areas:?} {plate}");
+}
+
#[test]
fn text_is_splines_and_lines_not_chords() {
let mut s = plate_with(&[("sketch.text", json!({"text": "AB", "at": [30, 20], "height": 12}))]);
diff --git a/crates/engine/src/cmd/sketch_import.rs b/crates/engine/src/cmd/sketch_import.rs
index 83632df19f..22f8362a5c 100644
--- a/crates/engine/src/cmd/sketch_import.rs
+++ b/crates/engine/src/cmd/sketch_import.rs
@@ -239,4 +239,18 @@ mod tests {
s.execute("sketch.finish", &json!({})).unwrap();
}
}
+
+ /// A degree-9 SPLINE (solidcraft#5269) with fewer control points than its degree needs still
+ /// comes in as one spline over all its points, which the sketch draws at the degree they allow.
+ #[test]
+ fn a_degree_nine_spline_with_few_control_points_comes_in_whole() {
+ let mut s = Session::default();
+ for n in 2..=10 {
+ let points: String = (0..n).map(|i| format!("10\n{i}\n20\n{}\n", i % 2)).collect();
+ let dxf = format!("0\nSECTION\n2\nENTITIES\n0\nSPLINE\n71\n9\n{points}0\nENDSEC\n0\nEOF\n");
+ let r = s.execute("sketch.insert_dxf", &json!({"text": dxf})).unwrap();
+ assert_eq!(r["curves"], 1, "{n} points: {r}");
+ s.execute("sketch.finish", &json!({})).unwrap();
+ }
+ }
}
diff --git a/crates/io/src/dxf.rs b/crates/io/src/dxf.rs
index df792bd7bd..45ec371279 100644
--- a/crates/io/src/dxf.rs
+++ b/crates/io/src/dxf.rs
@@ -7,7 +7,7 @@
use std::collections::HashMap;
-use solidcraft_geom::Vec2;
+use solidcraft_geom::{MAX_BEZIER_DEGREE, Vec2};
use crate::sketch2d::{Geom2, MAX_DRAWING_BYTES, MAX_ENTITIES, bulge_arc};
use crate::{IoError, Result};
@@ -265,7 +265,8 @@ fn convert(ents: &[Ent], k: f64, blocks: &HashMap<String, (Vec2, Vec<Ent>)>, dep
}
}
"SPLINE" => {
- let degree = e.get(71).unwrap_or(3.0).clamp(1.0, 7.0) as u8;
+ // The degrees a sketch spline takes (a G4 blend's Bézier is degree 9).
+ let degree = e.get(71).unwrap_or(3.0).clamp(1.0, MAX_BEZIER_DEGREE as f64) as u8;
let (fx, fy) = (e.all(11), e.all(21));
let (cx, cy) = (e.all(10), e.all(20));
if fx.len() >= 2 && fx.len() == fy.len() {
@@ -473,6 +474,10 @@ mod tests {
"0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n90\n99999999\n0\nENDSEC\n0\nEOF\n".into(),
"0\nSECTION\n2\nENTITIES\n0\nCIRCLE\n10\nnan\n20\ninf\n40\n-1\n0\nENDSEC\n0\nEOF\n".into(),
"0\nSECTION\n2\nENTITIES\n0\nCIRCLE\n10\n1e400\n20\n1e400\n40\n1e400\n0\nENDSEC\n0\nEOF\n".into(),
+ // SPLINE degrees past any spline's, below 1, and above its control points' count.
+ "0\nSECTION\n2\nENTITIES\n0\nSPLINE\n71\n255\n10\n0\n20\n0\n10\n1\n20\n1\n0\nENDSEC\n0\nEOF\n".into(),
+ "0\nSECTION\n2\nENTITIES\n0\nSPLINE\n71\n-5\n10\n0\n20\n0\n10\n1\n20\n1\n0\nENDSEC\n0\nEOF\n".into(),
+ "0\nSECTION\n2\nENTITIES\n0\nSPLINE\n71\n1e400\n10\n0\n20\n0\n0\nENDSEC\n0\nEOF\n".into(),
format!("0\nSECTION\n2\nBLOCKS\n{}0\nENDSEC\n0\nEOF\n", "0\nBLOCK\n2\nb\n0\nENDBLK\n".repeat(300)),
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\na\n1\nINSERT\n2\na\n0\nENDBLK\n0\nENDSEC\n0\nEOF\n".into(),
format!("0\nSECTION\n2\nENTITIES\n{}0\nENDSEC\n0\nEOF\n", "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n".repeat(5000)),
@@ -489,6 +494,24 @@ mod tests {
}
}
+ /// A SPLINE keeps its degree up to the 9 a sketch spline (a G4 blend) has (solidcraft#5269); a
+ /// degree past that is held to 9, and one that isn't a finite number (which the reader drops)
+ /// reads as a missing one, 3.
+ #[test]
+ fn a_splines_degree_is_read_up_to_nine() {
+ let spline = |degree: Option<&str>| {
+ let points: String = (0..10).map(|i| format!("10\n{i}\n20\n{}\n", i % 3)).collect();
+ let degree = degree.map(|d| format!("71\n{d}\n")).unwrap_or_default();
+ format!("0\nSECTION\n2\nENTITIES\n0\nSPLINE\n{degree}{points}0\nENDSEC\n0\nEOF\n")
+ };
+ for (given, read) in
+ [(Some("9"), 9), (Some("8"), 8), (Some("7"), 7), (Some("10"), 9), (Some("0"), 1), (Some("nan"), 3), (Some("inf"), 3), (None, 3)]
+ {
+ let back = read_dxf(&spline(given)).unwrap();
+ assert!(matches!(&back[..], [Geom2::Spline { pts, control: true, degree }] if *degree == read && pts.len() == 10), "{given:?}: {back:?}");
+ }
+ }
+
#[test]
fn round_trip_and_polyline_bulges() {
let g = vec![
diff --git a/crates/io/src/dxf_out.rs b/crates/io/src/dxf_out.rs
index fff56ea64d..7fa080f1fe 100644
--- a/crates/io/src/dxf_out.rs
+++ b/crates/io/src/dxf_out.rs
@@ -13,7 +13,7 @@
use std::f64::consts::TAU;
use std::fmt::Write as _;
-use solidcraft_geom::{Loop2, Seg2, Vec2};
+use solidcraft_geom::{Loop2, MAX_BEZIER_DEGREE, Seg2, Vec2};
/// A layer's linetype, defined in the file's LTYPE table so a viewer needs nothing else.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -112,7 +112,8 @@ pub struct DxfEntity {
}
/// The entity of one profile segment, exactly: a line, an arc (a circle when it is a whole
-/// turn), an elliptical arc for a conic of weight below 1, a spline for a Bézier or any other conic.
+/// turn), an elliptical arc for a conic of weight below 1, a spline for any other conic, and for a
+/// Bézier a spline of its own degree over all its control points.
pub fn seg_shape(s: &Seg2) -> DxfShape {
match *s {
Seg2::Line { a, b } => DxfShape::Line(a, b),
@@ -128,7 +129,7 @@ pub fn seg_shape(s: &Seg2) -> DxfShape {
None => bezier_spline(&[a, apex, b], ((w - 1.0).abs() > 1e-12).then(|| vec![1.0, w, 1.0])),
},
Seg2::Cubic { p0, p1, p2, p3 } => bezier_spline(&[p0, p1, p2, p3], None),
- Seg2::Bezier { n, p } => bezier_spline(p.get(..=(n as usize).clamp(1, 7)).unwrap_or(&p), None),
+ Seg2::Bezier { n, p } => bezier_spline(p.get(..=(n as usize).clamp(1, MAX_BEZIER_DEGREE)).unwrap_or(&p), None),
}
}
@@ -676,6 +677,26 @@ mod tests {
assert!(knots[..6].iter().all(|k| *k == 0.0) && knots[6..].iter().all(|k| *k == 1.0) && ctrl[5] == q[5]);
}
+ #[test]
+ fn a_bezier_is_a_spline_of_its_own_degree_over_all_its_control_points() {
+ let mut q = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL];
+ for (i, s) in q.iter_mut().enumerate() {
+ *s = Vec2::new(i as f64, (i * i) as f64);
+ }
+ // Every degree a Bézier piece can have, up to a G4 blend's 9: n + 1 control points, all of
+ // them, and 2(n + 1) clamped knots.
+ for n in 4..=solidcraft_geom::MAX_BEZIER_DEGREE as u8 {
+ let k = usize::from(n) + 1;
+ let DxfShape::Spline { degree, knots, ctrl, weights } = seg_shape(&Seg2::Bezier { n, p: q }) else { panic!("degree {n}") };
+ assert_eq!((degree, knots.len(), weights), (n, 2 * k, None), "degree {n}");
+ assert_eq!(ctrl, q[..k], "degree {n}");
+ }
+ // A degree no piece can have (hostile data) is held to what the piece holds, never past it.
+ let shape = |n: u8| seg_shape(&Seg2::Bezier { n, p: q });
+ assert!(matches!(shape(0), DxfShape::Spline { degree: 1, ref ctrl, .. } if ctrl.len() == 2));
+ assert!(matches!(shape(u8::MAX), DxfShape::Spline { degree: 9, ref ctrl, .. } if ctrl[..] == q[..]));
+ }
+
#[test]
fn drawings_carry_version_units_extents_and_handles() {
let ents = vec![
@@ -760,6 +781,17 @@ mod tests {
// The cubic: degree and control points.
let Geom2::Spline { pts, control: true, degree: 3 } = &back[5] else { panic!("{:?}", back[5]) };
assert!(pts.iter().zip(&cubic).all(|(a, b)| a.dist(*b) < 1e-9) && pts.len() == 4);
+ // A degree-9 Bézier (a G4 blend) comes back at its own degree over all ten points.
+ let mut q = [Vec2::ZERO; solidcraft_geom::MAX_BEZIER_CTRL];
+ for (i, s) in q.iter_mut().enumerate() {
+ *s = Vec2::new(i as f64, (i % 3) as f64);
+ }
+ let nine = write_dxf_drawing(&[], &[DxfEntity { layer: "0".into(), shape: seg_shape(&Seg2::Bezier { n: 9, p: q }) }]);
+ let back_nine = read_dxf(&nine).unwrap();
+ assert!(
+ matches!(&back_nine[..], [Geom2::Spline { pts, control: true, degree: 9 }] if pts.len() == 10 && pts.iter().zip(&q).all(|(a, b)| a.dist(*b) < 1e-9)),
+ "{back_nine:?}"
+ );
// The numbers in the file itself, which the reader does not keep: the ellipse...
let file = entities(&dxf);