Export Current View as DXF includes shown sketches (#3708) (#3780)

* claim: #3708

* Export Current View as DXF includes shown sketches (#3708)

The view export refused a design with only a sketch and left shown
sketches out when bodies were present. It now draws the sketches the
viewport shows (profile curves only: no construction geometry, points,
dimensions or constraints) on a SKETCH layer, one entity per curve.
Finished sketches are hidden behind bodies through the body-edge
occlusion; the active sketch is drawn on top, as in the viewport.
Sketch points use the same projection, budgets and cancellation.

The export is refused only when there is neither a visible body nor a
shown sketch curve; the dialog and the command share that check
(cmd::view_dxf_exportable).

---------

Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
raykholo
2026-10-21 23:09:57 +00:00
committed by GitHub
parent b289dc2421
commit ba4f7864ff
34 changed files with 313 additions and 62 deletions
+1
View File
@@ -40,6 +40,7 @@ pub(crate) use features::profiles as feature_profiles;
pub(crate) use features::{EdgeRefForm, edge_ref_form, sketch_key};
pub use features::{auto_operation, extrude_reach};
pub use sketch_modify::trim_piece;
pub use view_dxf::sketch::exportable as view_dxf_exportable;
mod component_link;
mod config;
mod file;
+32 -6
View File
@@ -1,5 +1,5 @@
//! A drawing of the visible bodies from a supplied viewport camera. No screen pixels, grid,
//! selection highlights or tessellation diagonals are exported.
//! A drawing of the visible bodies and shown sketches from a supplied viewport camera. No
//! screen pixels, grid, selection highlights or tessellation diagonals are exported.
#[path = "view_dxf_meshes.rs"]
mod meshes;
@@ -7,8 +7,11 @@ mod meshes;
mod progress;
#[path = "view_dxf_projection.rs"]
mod projection;
#[path = "view_dxf_sketch.rs"]
pub(super) mod sketch;
use serde_json::{Value, json};
use solidcraft_geom::Vec2;
use solidcraft_io::{DxfEntity, DxfLayer, DxfLinetype, DxfShape};
use solidcraft_render::Camera;
@@ -20,7 +23,7 @@ const CMD: &str = "file.export_view_dxf";
pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new(CMD, "Export Current View as DXF", export)
.icon("export")
.noundo()
.params("camera: Camera (current view); hidden?: omit|dashed (default omit); tolerance?: 0.0001..1 mm (curve chord tolerance, default 0.01); path?: .dxf file (else returns dxf text). Visible placed bodies only; 2D LINE/LWPOLYLINE entities on VISIBLE/HIDDEN layers, mm; perspective projected onto the camera target plane; no viewport crop or overlays.")];
.params("camera: Camera (current view); hidden?: omit|dashed (default omit); tolerance?: 0.0001..1 mm (curve chord tolerance, default 0.01); path?: .dxf file (else returns dxf text). Visible placed bodies and shown sketches' profile curves (no construction geometry, points, dimensions or constraints); 2D LINE/LWPOLYLINE entities on VISIBLE/HIDDEN layers (sketch curves on SKETCH), mm; finished sketches are hidden behind bodies, the active sketch is drawn on top; perspective projected onto the camera target plane; no viewport crop or overlays.")];
fn export(s: &mut Session, p: &Value) -> Result<Value> {
let cam: Camera =
@@ -39,6 +42,9 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::String(v)) if v == "dashed" => true,
_ => return Err(bad(CMD, "hidden must be omit or dashed")),
};
if !sketch::exportable(s) {
return Err(bad(CMD, "no visible bodies or sketches to export"));
}
let tolerance = match p.get("tolerance") {
None => 0.01,
Some(v) => v.as_f64().filter(|t| (0.0001..=1.0).contains(t)).ok_or_else(|| bad(CMD, "tolerance must be 0.0001..1 mm"))?,
@@ -54,7 +60,7 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
progress::Stage::new("dxf_meshes", 1).check().map_err(|e| bad(CMD, e))?;
let meshes = meshes::prepare(s, tolerance)?;
let prepare_ms = started.elapsed().as_secs_f64() * 1000.;
let drawing = projection::drawing(&meshes, &cam).map_err(|e| bad(CMD, e))?;
let drawing = projection::drawing(&meshes, &sketch::parts(s, tolerance).map_err(|e| bad(CMD, e))?, &cam).map_err(|e| bad(CMD, e))?;
let writing = progress::Stage::new("dxf_write", 1);
writing.check().map_err(|e| bad(CMD, e))?;
let mut visible = 0;
@@ -73,14 +79,18 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
};
entities.push(DxfEntity { layer: layer.into(), shape: DxfShape::Line(line.a, line.b) });
}
let entities = projection::connect(entities);
let mut entities = projection::connect(entities);
let sketch = sketch_entities(drawing.sketch, dashed, &mut entities);
let mut layers = vec![DxfLayer::new("VISIBLE", 7)];
if dashed {
layers.push(DxfLayer { linetype: DxfLinetype::Hidden, ..DxfLayer::new("HIDDEN", 8) });
}
if sketch > 0 {
layers.push(DxfLayer::new("SKETCH", 5));
}
let text = solidcraft_io::write_dxf_drawing(&layers, &entities);
writing.check().map_err(|e| bad(CMD, e))?;
let mut result = json!({"visible":visible,"hidden":hidden,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}});
let mut result = json!({"visible":visible,"hidden":hidden,"sketch":sketch,"units":"mm","tolerance":tolerance,"projection":if cam.fov > 0.0 {"perspective"} else {"orthographic"}});
result["stats"] = json!({"bodies":meshes.placements.len(),"shared_meshes":meshes.meshes.len(),"triangles":meshes.triangles,
"mesh_bytes":meshes.bytes,"worker_limit":meshes::WORKERS,"segments":drawing.segments,"occlusion_work":drawing.work,
"prepare_ms":prepare_ms,"projection_ms":drawing.projection_ms,"occlusion_ms":drawing.occlusion_ms});
@@ -94,6 +104,22 @@ fn export(s: &mut Session, p: &Value) -> Result<Value> {
Ok(result)
}
/// Sketch runs as entities: visible ones on SKETCH, hidden ones dashed on HIDDEN or omitted.
/// Returns the number of SKETCH entities.
fn sketch_entities(paths: Vec<projection::Path>, dashed: bool, entities: &mut Vec<DxfEntity>) -> usize {
let mut count = 0;
for path in paths.into_iter().filter(|p| dashed || !p.hidden) {
let layer = if path.hidden { "HIDDEN" } else { "SKETCH" };
count += usize::from(!path.hidden);
let shape = match <[Vec2; 2]>::try_from(path.points) {
Ok([a, b]) => DxfShape::Line(a, b),
Err(points) => DxfShape::Polyline { points },
};
entities.push(DxfEntity { layer: layer.into(), shape });
}
count
}
#[cfg(test)]
#[path = "view_dxf_tests.rs"]
mod tests;
-3
View File
@@ -123,9 +123,6 @@ pub(super) fn prepare(s: &Session, tolerance: f64) -> Result<Scene> {
let keep = groups.get(group).is_some_and(|g| g.first == index);
items.push(Item { body, group, keep, transform });
}
if items.is_empty() {
return Err(bad(CMD, "no visible bodies to export"));
}
let progress = Stage::new("dxf_meshes", items.len());
let bytes = AtomicUsize::new(0);
let results = map_with_local_pools(&items, WORKERS, |item| {
+11 -2
View File
@@ -16,10 +16,19 @@ pub(super) struct Drawing {
pub segments: usize,
pub projection_ms: f64,
pub occlusion_ms: f64,
/// Shown sketch curves: one path per visible or hidden run of each curve.
pub sketch: Vec<Path>,
}
pub(super) fn drawing(meshes: &super::meshes::Scene, cam: &Camera) -> Result<Drawing, &'static str> {
scene::drawing(meshes, cam)
/// A connected run of a projected sketch curve.
#[derive(Clone, Debug)]
pub(super) struct Path {
pub points: Vec<Vec2>,
pub hidden: bool,
}
pub(super) fn drawing(meshes: &super::meshes::Scene, sketch: &[super::sketch::Part], cam: &Camera) -> Result<Drawing, &'static str> {
scene::drawing(meshes, sketch, cam)
}
/// Keep the hidden curves connected: restarting a dash on every short chord would make a
+72 -5
View File
@@ -12,7 +12,8 @@ use solidcraft_render::Camera;
use super::super::meshes::{Placement, Scene, WORKERS, claim, transformed_bounds};
use super::super::progress::Stage;
use super::{Drawing, Line, bounds, clip, key, merge_lines, occluded, overlap, xy};
use super::super::sketch::Part;
use super::{Drawing, Line, Path, bounds, clip, key, merge_lines, occluded, overlap, xy};
const TOO_COMPLEX: &str = "view exceeds export work budget; hide bodies or increase tolerance";
const MAX_LINES: usize = 1_000_000;
@@ -405,12 +406,13 @@ impl Query<'_, '_> {
}
}
pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result<Drawing, &'static str> {
pub(super) fn drawing(scene: &Scene, sketch: &[Part], cam: &Camera) -> Result<Drawing, &'static str> {
let start = Instant::now();
let scale = scene
.placements
.iter()
.filter_map(|p| scene.meshes.get(p.mesh).map(|m| transformed_bounds(m, &p.transform)))
.chain(sketch.iter().map(|p| bounds(p.points.iter().copied())))
.fold(Aabb3::EMPTY, |b, p| b.union(&p))
.diagonal()
.max(1.);
@@ -510,7 +512,72 @@ pub(super) fn drawing(scene: &Scene, cam: &Camera) -> Result<Drawing, &'static s
let work = results.iter().map(|(_, n)| *n).sum();
let lines = merge_lines(results.into_iter().flat_map(|(lines, _)| lines).collect(), eps);
progress.check()?;
Ok(Drawing { lines, work, segments: segment_count, projection_ms, occlusion_ms: start.elapsed().as_secs_f64() * 1000. })
// Shown sketch curves: finished sketches are split where bodies cover them, like body
// edges; the active sketch is drawn on top, as in the viewport. Each curve run stays one
// path per visible or hidden stretch, so a circle remains one polyline.
let progress = Stage::new("dxf_occlusion", sketch.len());
let results = parallel(sketch, |part| {
progress.check()?;
let mut budget = Budget::new(&global, &progress);
let mut paths: Vec<Path> = Vec::new();
let mut previous: Option<Vec3> = None;
for p in &part.points {
let b = view.project(*p)?;
let Some(a) = previous.replace(b) else { continue };
if xy(a).dist(xy(b)) <= eps {
continue;
}
if !claim(&count, 1, MAX_SEGMENTS) {
return Err(TOO_COMPLEX);
}
let mut covered = Coverage::default();
if !part.on_top && !instances.nodes.is_empty() {
let mut query = Query {
shared: &shared,
scene,
projected: &projected,
instances: &instances,
view: &view,
depth_eps,
a,
b,
bounds: bounds([a, b]),
covered,
budget: &mut budget,
};
query.instance_node(0)?;
covered = query.covered;
}
let mut cursor = 0.;
let mut emit = |lo: f64, hi: f64, hidden: bool| -> Result<(), &'static str> {
let (p, q) = (xy(a + (b - a) * lo), xy(a + (b - a) * hi));
if p.dist(q) <= eps {
return Ok(());
}
if let Some(path) = paths.last_mut().filter(|path| path.hidden == hidden && path.points.last().is_some_and(|e| e.dist(p) <= eps)) {
path.points.push(q);
} else {
if !claim(&output, 1, MAX_LINES) {
return Err(TOO_COMPLEX);
}
paths.push(Path { points: vec![p, q], hidden });
}
Ok(())
};
for (lo, hi) in covered.spans {
emit(cursor, lo, false)?;
emit(lo, hi, true)?;
cursor = hi;
}
emit(cursor, 1., false)?;
}
progress.advance(1)?;
Ok((paths, budget.spent))
})?;
let work = results.iter().fold(work, |n: usize, (_, spent)| n.saturating_add(*spent));
let sketch = results.into_iter().flat_map(|(paths, _)| paths).collect();
progress.check()?;
Ok(Drawing { lines, work, segments: count.load(Ordering::Relaxed), projection_ms, occlusion_ms: start.elapsed().as_secs_f64() * 1000., sketch })
}
#[cfg(test)]
@@ -581,7 +648,7 @@ mod tests {
for fov in [0., 0.6] {
let cam = Camera { target: Vec3::new(4., 3., 1.), yaw, pitch, roll, fov, distance: 100., ..Default::default() };
let expected = super::super::reference_drawing(&flat, &cam).unwrap();
let actual = drawing(&scene, &cam).unwrap();
let actual = drawing(&scene, &[], &cam).unwrap();
assert_eq!(canonical(actual.lines), canonical(expected), "yaw={yaw}, pitch={pitch}, fov={fov}");
}
}
@@ -619,7 +686,7 @@ mod tests {
let scene = Scene { meshes: vec![Arc::new(mesh)], placements, triangles: 1_200_000, bytes: 0 };
let mut cam = Camera { target: Vec3::new(95., 55., 0.), fov: 0., distance: 300., ..Default::default() };
cam.set_view(StandardView::Top);
let result = drawing(&scene, &cam).unwrap();
let result = drawing(&scene, &[], &cam).unwrap();
assert_eq!(scene.meshes.len(), 1);
assert_eq!(result.lines.len(), 240);
assert!(result.lines.iter().all(|l| !l.hidden));
+89
View File
@@ -0,0 +1,89 @@
//! Shown sketches in the view drawing: the curves the viewport draws for each sketch it shows
//! (`view::sketch_shown`), as world polylines. Only profile curves are exported: drawn 2D
//! curves, text outlines and drawn 3D-sketch curves. Construction geometry, centerlines,
//! projected references, points, dimensions and constraints are viewport overlays and are left
//! out. The active sketch is drawn on top, as the viewport draws it.
use solidcraft_geom::{Plane, Vec3};
use solidcraft_sketch::Sketch;
use super::progress::Stage;
use crate::Session;
use crate::view::{sketch_curve_visible, sketch_shown};
/// Sampled sketch points kept for one export, at most.
const MAX_POINTS: usize = 4_000_000;
/// One connected run of a sketch curve in world coordinates.
pub(super) struct Part {
pub points: Vec<Vec3>,
/// Drawn over the bodies (the sketch being edited) rather than hidden behind them.
pub on_top: bool,
}
fn profile_curve(sk: &Sketch, i: usize) -> bool {
sketch_curve_visible(sk, i) && sk.curves.get(i).is_some_and(|c| !c.construction && !c.centerline && (c.link.is_none() || sk.is_text_curve(i)))
}
fn has_profile(sk: &Sketch) -> bool {
(0..sk.curves.len()).any(|i| profile_curve(sk, i)) || sk.wires.iter().any(|w| w.fit.len() > 1 && w.pts.len() > 1)
}
/// Does the current view have anything `file.export_view_dxf` draws: a visible body or a shown
/// sketch with a profile curve? The export dialog asks this before choosing a file.
pub fn exportable(s: &Session) -> bool {
let world = s.world_state();
world.bodies.iter().any(|b| s.body_visible(&b.name)) || world.sketches.iter().any(|ss| sketch_shown(s, ss.feature) && has_profile(&ss.sketch))
}
/// A curve's boundary segments joined end to end, so a circle (two half arcs) is one run.
fn curve_parts(sk: &Sketch, i: usize, plane: &Plane, tolerance: f64) -> Vec<Vec<Vec3>> {
let mut parts: Vec<Vec<Vec3>> = Vec::new();
for seg in sk.segs(i) {
let points: Vec<Vec3> = seg.polyline(tolerance).iter().map(|p| plane.to_world(*p)).collect();
let Some(first) = points.first().copied() else { continue };
match parts.last_mut() {
Some(run) if run.last().is_some_and(|end| end.dist(first) <= tolerance * 1e-3) => run.extend(points.into_iter().skip(1)),
_ => parts.push(points),
}
}
parts
}
/// The shown sketches' profile curves, sampled at the export's chord `tolerance`.
pub(super) fn parts(s: &Session, tolerance: f64) -> Result<Vec<Part>, &'static str> {
let world = s.world_state();
let shown: Vec<_> = world.sketches.iter().filter(|ss| sketch_shown(s, ss.feature)).collect();
let progress = Stage::new("dxf_projection", shown.len());
let mut result = Vec::new();
let mut total = 0usize;
let mut add = |points: Vec<Vec3>, on_top: bool, result: &mut Vec<Part>| -> Result<(), &'static str> {
if points.len() < 2 {
return Ok(());
}
if points.iter().any(|p| !p.is_finite()) {
return Err("sketch contains invalid coordinates");
}
total = total.saturating_add(points.len());
if total > MAX_POINTS {
return Err("view exceeds export memory budget; hide sketches or increase tolerance");
}
result.push(Part { points, on_top });
Ok(())
};
for ss in shown {
progress.check()?;
let on_top = s.active_sketch == Some(ss.feature);
let sk = &ss.sketch;
for i in (0..sk.curves.len()).filter(|i| profile_curve(sk, *i)) {
for points in curve_parts(sk, i, &ss.plane, tolerance) {
add(points, on_top, &mut result)?;
}
}
// 3D-sketch curves are in world coordinates already; included references are not drawn.
for w in sk.wires.iter().filter(|w| w.fit.len() > 1) {
add(w.pts.clone(), on_top, &mut result)?;
}
progress.advance(1)?;
}
Ok(result)
}
+61
View File
@@ -172,3 +172,64 @@ fn view_dxf_keeps_every_occurrence_while_sharing_geometry() {
assert!(centers.len() >= 3, "{centers:?}");
assert!(std::sync::Arc::ptr_eq(&doc, &s.doc));
}
#[test]
fn view_dxf_exports_a_sketch_only_design_on_the_sketch_layer() {
let mut s = Session::default();
assert!(s.execute(CMD, &json!({"camera":camera(StandardView::Top)})).is_err());
run(&mut s, "sketch.create", json!({"plane":"XY"}));
run(&mut s, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[60,40]}));
run(&mut s, "sketch.circle.center", json!({"center":[30,20],"radius":8}));
for finish in [false, true] {
if finish {
run(&mut s, "sketch.finish", json!({}));
}
let v = export(&mut s, camera(StandardView::Top), "omit");
// Four rectangle sides and one circle, each its own entity.
assert_eq!(v["sketch"], 5, "{v}");
let geometry = solidcraft_io::read_dxf(v["dxf"].as_str().unwrap()).unwrap();
let (mut sides, mut circle) = (Vec::new(), 0);
for g in geometry {
let solidcraft_io::Geom2::Line(a, b) = g else { panic!("{g:?}") };
// The drawing is centred on the camera target (20, 15).
let on_circle = |p: Vec2| ((p - Vec2::new(10., 5.)).len() - 8.).abs() < 0.02;
if on_circle(a) && on_circle(b) {
circle += 1;
} else {
sides.push((a.dist(b) * 1000.).round() as i64);
}
}
sides.sort_unstable();
assert_eq!(sides, [40_000, 40_000, 60_000, 60_000], "finish={finish}");
assert!(circle > 16, "{circle}");
}
}
#[test]
fn view_dxf_hides_finished_sketches_behind_bodies_but_draws_the_active_sketch_on_top() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length":40,"width":30,"height":10}));
run(&mut s, "sketch.create", json!({"plane":{"origin":[0,0,-5],"x_dir":[1,0,0],"y_dir":[0,1,0]}}));
run(&mut s, "sketch.line", json!({"points":[[-20,15],[60,15]]}));
// The box's edges run along y = 0 and y = 30; only the sketch line lies on y = 15 (0 in the
// drawing, which is centred on the camera target; the top view is tilted a hair).
let length = |v: &Value| {
let lines = solidcraft_io::read_dxf(v["dxf"].as_str().unwrap()).unwrap();
lines
.iter()
.filter_map(|g| if let solidcraft_io::Geom2::Line(a, b) = g { Some((*a, *b)) } else { None })
.filter(|(a, b)| a.y.abs() < 1e-3 && b.y.abs() < 1e-3)
.map(|(a, b)| a.dist(b))
.sum::<f64>()
};
let active = export(&mut s, camera(StandardView::Top), "omit");
assert_eq!(active["sketch"], 1, "{active}");
assert!((length(&active) - 80.).abs() < 1e-3 && active["dxf"].as_str().unwrap().contains("SKETCH"));
run(&mut s, "sketch.finish", json!({}));
let finished = export(&mut s, camera(StandardView::Top), "omit");
assert_eq!(finished["sketch"], 2, "{finished}");
assert!((length(&finished) - 40.).abs() < 1e-3, "{}", length(&finished));
let dashed = export(&mut s, camera(StandardView::Top), "dashed");
assert_eq!(dashed["sketch"], 2);
assert!((length(&dashed) - 80.).abs() < 1e-3, "{}", length(&dashed));
}