Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions attribution/pending/26882-freecad-sketch-only-fixtures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
| File | Author | Source | Licence |
|---|---|---|---|
| crates/io/src/native_cad/fixtures/sketch_only.FCStd | SolidCraft contributors | original test part (a PartDesign body holding one sketch, a constrained rectangle and circle, with no solid) saved by FreeCAD 26.3 run as an external program (`make_sketch_only_fcstd.py` beside it); no third-party geometry | MIT OR Apache-2.0 |
| crates/io/src/native_cad/fixtures/empty_body.FCStd | SolidCraft contributors | original test file (an empty PartDesign body) saved by FreeCAD 26.3 run as an external program (`make_sketch_only_fcstd.py` beside it); no third-party geometry | MIT OR Apache-2.0 |
1 change: 1 addition & 0 deletions crates/cadmpeg/src/freecad_history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ fn arenas_of(model: &cadmpeg_ir::document::Model) -> Result<Arenas, String> {
placements: HashMap::new(),
pattern_axes: HashMap::new(),
edge_points: HashMap::new(),
faces: model.faces.len(),
})
}

Expand Down
3 changes: 3 additions & 0 deletions crates/cadmpeg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ pub struct DesignHistory {
/// id), in model coordinates: its carrier at the middle of its range. An edge whose point
/// cannot be computed is absent.
pub edge_points: std::collections::HashMap<String, solidcraft_kernel::api::record::Vec3>,
/// How many B-rep faces the file's model holds. None: the file has no solid or surface to
/// import, only sketches or other edges.
pub faces: usize,
}

/// A component placement of a [`MeshScene`].
Expand Down
93 changes: 89 additions & 4 deletions crates/engine/src/cmd/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pub static COMMANDS: &[CommandSpec] = &[
"name? (the feature's and the component's); ",
"up?: z|y (default z: the file's axes are kept; y: the file has Y up, so the import's component is turned a quarter turn about X, Y becoming Z → stand_up: its occurrence); ",
"names?: auto|solid|product|instance (default auto: keep meaningful solid names, replace placeholders with the nearest named product, else instance; solid: the solid's own name; product: the part's name; instance: the occurrence's name, else the product's); ",
"history?: features|solids for a FreeCAD file (default features: its sketches and the Pad, Pocket, Revolution, Groove, Fillet, Chamfer and primitive features that use them are rebuilt as features in the new component, when every one can be and they build what the file holds → features_added, history: \"features\"; else, or with solids, the file's solids come in as an Import feature, and a warning says why the history was not rebuilt; with features, the file's sketches then come in beside the solids as editable sketches → features_added, history: \"sketches\"); ",
"history?: features|solids for a FreeCAD file (default features: its sketches and the Pad, Pocket, Revolution, Groove, Fillet, Chamfer and primitive features that use them are rebuilt as features in the new component, when every one can be and they build what the file holds → features_added, history: \"features\"; else, or with solids, the file's solids come in as an Import feature, and a warning says why the history was not rebuilt; with features, the file's sketches then come in beside the solids as editable sketches → features_added, history: \"sketches\"; a file with no solid or surface, only sketches, brings its sketches alone in the new component, with no bodies and a warning that it has no solids → features_added, history: \"sketches\"; with solids, such a file is refused, saying so); ",
"reader?: solidcraft|cadmpeg for a .step/.stp, .igs/.iges, FreeCAD or Rhino file (default solidcraft: SolidCraft's own STEP or IGES reader, which keeps the STEP text (an IGES file restated as STEP), a FreeCAD or Rhino file's solids restated as STEP by cadmpeg's STEP writer first; cadmpeg: cadmpeg's model read straight into B-rep records, with no STEP text in between, a STEP or IGES file decoded by cadmpeg's STEP or IGES decoder, to compare the two; `flatten` works with either); ",
"body_index?: zero-based STEP body occurrence in the reader's order, counting a body that cannot be read and each placement of a repeated part (.step/.stp, SolidCraft reader only); only that body is converted, with its placement and product names, and the design keeps the choice; an index past the last body, or a file or reader that cannot select, is refused; default: every body; ",
"matrix?: [12 or 16 numbers] (where the new component's occurrence sits in the active component, after `up`: a rigid row-major 3x4 rotation-and-translation or 4x4 matrix, flat or as rows, as occurrence.move takes it, its translation column (entries 4, 8 and 12) numbers or length expressions: one that names a parameter is kept, and the import follows the parameter when it changes (a grounded one stays); a scale, shear or mirror is refused before the file is read); ",
Expand Down Expand Up @@ -801,8 +801,14 @@ fn add_step_bytes(
Err(why) => not_rebuilt = Some(format!("the feature history was not rebuilt, so the file's solids were imported instead: {why}")),
}
}
let mut sf = solidcraft_io::step_import_feature_selection(bytes, path, options.names, options.reader, options.body_index)
.map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
let mut sf = match solidcraft_io::step_import_feature_selection(bytes, path, options.names, options.reader, options.body_index) {
Ok(sf) => sf,
// A FreeCAD file with no solid or surface to import, only sketches (#26882).
Err(e) => match solidcraft_io::is_freecad_path(path).then(|| solidcraft_io::native_cad_shapeless_sketches(bytes, path)).flatten() {
Some(sketches) => return add_sketches_alone(s, path, name, options, sketches, bytes),
None => return Err(EngineError::Other(format!("{path}: {e}"))),
},
};
let freecad_history = not_rebuilt.is_some();
sf.warnings.splice(0..0, not_rebuilt);
let mut reply = add_read_step(s, path, name, options, sf, bytes, profiled)?;
Expand Down Expand Up @@ -1103,6 +1109,81 @@ fn add_rebuilt(
serde_json::to_value(reply).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}

/// A FreeCAD file with no solid or surface to import, only sketches (#26882): with the history
/// asked for, its sketches (`sketches`, or why none can be read) come in alone, editable, in a new
/// component named after the file, as [`add_freecad_sketches`] brings them beside a file's solids
/// → `history: "sketches"`, their ids in `features_added`, no bodies, and a warning that the file
/// has no solids. With `history: solids`, or when no sketch can be read, the file is refused with
/// a message that says what it holds. If adding the sketches fails, the design stays as it was.
fn add_sketches_alone(
s: &mut Session,
path: &str,
name: Option<&str>,
options: &StepOptions,
sketches: std::result::Result<solidcraft_io::NativeDesign, String>,
bytes: &[u8],
) -> Result<Value> {
let design = match sketches {
Err(why) => return Err(EngineError::Other(format!("{path}: this FreeCAD file has no solid and no sketch that can be read ({why})"))),
Ok(_) if !options.history => {
return Err(EngineError::Other(format!(
"{path}: this FreeCAD file has no solids, only sketches, and history: solids leaves its sketches out"
)));
}
Ok(design) => design,
};
let before = DesignSnapshot::of(s);
let cname = import::component_name(path, name);
let added = import::add_design(s, &design, &cname).and_then(|(ids, placed)| {
let turned = if options.y_up { turn_up(s, &placed)? } else { None };
Ok((ids, placed, turned))
});
let (ids, placed, turned) = match added {
Ok(added) => added,
Err(e) => {
before.restore(s);
return Err(EngineError::Other(format!("{path}: the file has no solids, and its sketches could not be imported: {e}")));
}
};
let feature = *ids.first().ok_or_else(|| EngineError::Other(format!("{path}: the file's sketches made no feature")))?;
let mut warnings = vec!["the file has no solids, so only its sketches were imported".to_string()];
warnings.extend(design.warnings.iter().cloned());
let reply = StepInserted {
path: path.to_string(),
feature,
name: placed.name.clone(),
bodies: Vec::new(),
created_bodies: Vec::new(),
warnings,
history: Some("sketches".to_string()),
features_added: Some(ids),
// No STEP text was read: name the program the file was read from.
system: "FreeCAD".to_string(),
content_sha256: {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(bytes))
},
exporter: None,
exporter_up: None,
component: placed.component,
component_name: placed.name.clone(),
occurrence: placed.occurrence,
subcomponents: None,
rigid_members: None,
stand_up: turned,
group: None,
transform: None,
envelope: None,
profile: None,
param_warnings: Vec::new(),
split_root: None,
split_files: None,
surface_bodies: Vec::new(),
step_import: None,
};
serde_json::to_value(reply).map_err(|e| EngineError::Other(format!("{path}: {e}")))
}

/// The bodies an import feature built, by name.
fn created_bodies(s: &Session, feature: u64) -> Vec<String> {
s.model.state().bodies.iter().filter(|b| b.feature == feature).map(|b| b.name.clone()).collect()
Expand Down Expand Up @@ -2380,6 +2461,7 @@ fn open(s: &mut Session, p: &Value) -> Result<Value> {
content_sha256: r.content_sha256,
import_reused: r.import_reused,
history: r.history,
features_added: r.features_added,
board_path: r.board_path,
board_solid: r.board_solid,
param_warnings: Vec::new(),
Expand Down Expand Up @@ -2673,9 +2755,12 @@ struct ImportedFile {
content_sha256: Option<String>,
#[serde(default)]
import_reused: Option<bool>,
/// FreeCAD and `history: features` only: the rebuilt history came in.
/// FreeCAD only: the rebuilt history (`features`) or the sketches (`sketches`) came in.
#[serde(default)]
history: Option<String>,
/// With `history`: the ids of the features it added.
#[serde(default)]
features_added: Option<Vec<u64>>,
#[serde(default)]
board_path: Option<String>,
#[serde(default)]
Expand Down
9 changes: 7 additions & 2 deletions crates/engine/src/schema/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1587,10 +1587,15 @@ pub struct OpenedFile {
/// saved-model cache, false when the file was imported afresh.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub import_reused: Option<bool>,
/// A FreeCAD file only: `"features"` when its sketches and features were rebuilt; absent
/// when its solids came in as one Import feature.
/// A FreeCAD file only: `"features"` when its sketches and features were rebuilt;
/// `"sketches"` when its sketches came in beside its solids, or alone when it has none;
/// absent when its solids came in alone as one Import feature.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub history: Option<String>,
/// A FreeCAD file only, with `history`: the ids of the features the rebuild added (with
/// `sketches`, the sketches).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub features_added: Option<Vec<u64>>,
/// A KiCad PCB opened from a project file: the board file that was read.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub board_path: Option<String>,
Expand Down
45 changes: 45 additions & 0 deletions crates/engine/src/tests/native_cad_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ const BLOCK_FCSTD: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/b
const BLOCK_3DM: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/block.3dm");
const BRACKET_FCSTD: &[u8] = solidcraft_io::BRACKET_FCSTD;
const SHELLED_FCSTD: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/shelled.FCStd");
const SKETCH_ONLY_FCSTD: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/sketch_only.FCStd");
const EMPTY_BODY_FCSTD: &[u8] = include_bytes!("../../../io/src/native_cad/fixtures/empty_body.FCStd");

/// `bytes` saved as `name` in a fresh temp directory.
fn file(tag: &str, name: &str, bytes: &[u8]) -> (std::path::PathBuf, String) {
Expand Down Expand Up @@ -212,6 +214,49 @@ fn an_unrebuilt_freecad_history_brings_its_sketches_beside_the_solids() {
let _ = std::fs::remove_dir_all(&dir);
}

/// A FreeCAD file with a sketch and no solid (#26882) comes in as its sketch alone, through
/// `file.insert_step` and `doc.open` and with either reader: a component named after the file
/// holds the editable sketch (its 30 x 20 mm rectangle and 4 mm circle), with no bodies and a
/// warning that the file has no solids. `history: solids` refuses it, saying it holds only
/// sketches, and a file with no sketch either is refused, saying so; neither leaves anything behind.
#[test]
fn a_freecad_file_with_only_a_sketch_brings_the_sketch_alone() {
let (dir, path) = file("sketchonly", "sketch_only.FCStd", SKETCH_ONLY_FCSTD);
for reader in ["solidcraft", "cadmpeg"] {
for cmd in ["file.insert_step", "doc.open"] {
let mut s = Session::default();
let r = run(&mut s, cmd, json!({"path": path, "reader": reader}));
let at = format!("{cmd} reader={reader}: {r}");
assert_eq!((r["history"].as_str(), r["component_name"].as_str()), (Some("sketches"), Some("sketch_only")), "{at}");
assert!(r["bodies"].as_array().is_some_and(Vec::is_empty), "{at}");
assert!(r["warnings"][0].as_str().is_some_and(|w| w.contains("no solids")), "{at}");
let component = r["component"].as_u64().unwrap();
let [f] = s.doc.features.as_slice() else { panic!("one feature, no Import feature: {at}") };
let solidcraft_doc::FeatureKind::Sketch { sketch, .. } = &f.kind else { panic!("{}: {at}", f.kind.type_name()) };
assert_eq!((f.name.as_str(), f.component), ("Outline", component), "{at}");
let circles = sketch.curves.iter().filter(|c| matches!(c.kind, solidcraft_doc::sketch::CurveKind::Circle { .. })).count();
assert_eq!((sketch.curves.len(), circles), (5, 1), "{at}");
assert!(sketch.constraints.iter().any(|c| c.kind.value().is_some_and(|v| (v - 30.0).abs() < 1e-9)), "{at}");
assert!(s.model.state().bodies.is_empty(), "{at}");
assert!(s.model.results.iter().all(|r| r.error.is_none()), "{at}");
assert_eq!(r["features_added"], json!([f.id]), "{at}");
}
}
let mut s = Session::default();
let e = s.execute("file.insert_step", &json!({"path": path, "history": "solids"})).expect_err("history: solids");
assert!(e.to_string().contains("FreeCAD file has no solids, only sketches"), "{e}");
assert!(s.doc.features.is_empty() && s.doc.components.len() == Session::default().doc.components.len(), "nothing is left behind");
let (empty_dir, empty) = file("emptybody", "empty_body.FCStd", EMPTY_BODY_FCSTD);
for cmd in ["file.insert_step", "doc.open"] {
let mut s = Session::default();
let e = s.execute(cmd, &json!({"path": empty})).expect_err(cmd);
assert!(e.to_string().contains("FreeCAD file has no solid and no sketch that can be read"), "{cmd}: {e}");
assert!(s.doc.features.is_empty(), "{cmd}");
}
let _ = std::fs::remove_dir_all(&dir);
let _ = std::fs::remove_dir_all(&empty_dir);
}

/// A rebuilt history that cannot be inserted (here the design is at its feature limit) falls
/// back to the file's solids with a warning, and leaves the design as it was: no features,
/// parameters or component of the attempt stay behind.
Expand Down
1 change: 1 addition & 0 deletions crates/io/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ pub use native_cad::is_native_cad_path;
pub use native_cad::is_usd_path;
pub use native_cad::native_cad_design;
pub use native_cad::native_cad_records;
pub use native_cad::native_cad_shapeless_sketches;
pub use native_cad::native_cad_sketches;
pub use native_cad::native_cad_to_step;
pub use native_cad::read_usd;
Expand Down
16 changes: 16 additions & 0 deletions crates/io/src/native_cad.rs
Original file line number Diff line number Diff line change
Expand Up @@ -562,6 +562,15 @@ pub fn native_cad_sketches(bytes: &[u8], file: &str) -> Result<NativeDesign, Str
})
}

/// The sketches of a FreeCAD file that holds no solid or surface, only sketches or other edges
/// (#26882), as [`native_cad_sketches`] makes them, for a file whose solids import finds nothing
/// to build: `None` when the file holds a face, or when its design cannot be read (the import's
/// own error then stands); else the sketches, or why none can be read.
pub fn native_cad_shapeless_sketches(bytes: &[u8], file: &str) -> Option<Result<NativeDesign, String>> {
let name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string());
solidcraft_kernel::guard("cadmpeg sketches", || Ok(convert::shapeless_sketches(&name, bytes))).ok().flatten()
}

mod design;
pub use design::NativeDesign;

Expand Down Expand Up @@ -702,6 +711,13 @@ mod convert {
pub(super) fn sketches(name: &str, bytes: &[u8]) -> Result<super::NativeDesign, String> {
super::design::sketches(&history(name, bytes)?)
}

/// The sketches of a FreeCAD file (`name`) that holds no face; `None` when it holds one, or
/// when its design cannot be read.
pub(super) fn shapeless_sketches(name: &str, bytes: &[u8]) -> Option<Result<super::NativeDesign, String>> {
let arenas = history(name, bytes).ok()?;
(arenas.faces == 0).then(|| super::design::sketches(&arenas))
}
}

#[cfg(test)]
Expand Down
Binary file not shown.
52 changes: 52 additions & 0 deletions crates/io/src/native_cad/fixtures/make_sketch_only_fcstd.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Writes sketch_only.FCStd and empty_body.FCStd, two FreeCAD files with no solid (#26882).
# sketch_only.FCStd: a PartDesign body called "Plate" that holds one sketch, "Outline", and no
# Pad: a fully constrained 30 x 20 mm rectangle on the XY plane with a 4 mm radius circle
# centred at (15, 10). The sketch's internal faces are turned off (MakeInternals), so the file
# holds the sketch's edges and no face at all.
# empty_body.FCStd: a PartDesign body called "Empty" with nothing in it: no solid and no sketch.
# Run inside FreeCAD as an external program, from this directory:
# `freecadcmd make_sketch_only_fcstd.py` (made with FreeCAD 26.3).
import os

import FreeCAD
import Part
import Sketcher

V = FreeCAD.Vector


def rect(sk, w, h):
pts = [V(0, 0, 0), V(w, 0, 0), V(w, h, 0), V(0, h, 0)]
g = [sk.addGeometry(Part.LineSegment(pts[i], pts[(i + 1) % 4]), False) for i in range(4)]
for i in range(4):
sk.addConstraint(Sketcher.Constraint("Coincident", g[i], 2, g[(i + 1) % 4], 1))
sk.addConstraint(Sketcher.Constraint("Horizontal", g[0]))
sk.addConstraint(Sketcher.Constraint("Horizontal", g[2]))
sk.addConstraint(Sketcher.Constraint("Vertical", g[1]))
sk.addConstraint(Sketcher.Constraint("Vertical", g[3]))
sk.addConstraint(Sketcher.Constraint("DistanceX", g[0], 1, g[0], 2, w))
sk.addConstraint(Sketcher.Constraint("DistanceY", g[1], 1, g[1], 2, h))
sk.addConstraint(Sketcher.Constraint("Coincident", -1, 1, g[0], 1))


doc = FreeCAD.newDocument("SketchOnly")
body = doc.addObject("PartDesign::Body", "Body")
body.Label = "Plate"
sk = body.newObject("Sketcher::SketchObject", "Outline")
sk.AttachmentSupport = (next(f for f in body.Origin.OriginFeatures if f.Role == "XY_Plane"), [""])
sk.MapMode = "FlatFace"
if hasattr(sk, "MakeInternals"):
sk.MakeInternals = False
rect(sk, 30, 20)
c = sk.addGeometry(Part.Circle(V(15, 10, 0), V(0, 0, 1), 4), False)
sk.addConstraint(Sketcher.Constraint("Radius", c, 4))
sk.addConstraint(Sketcher.Constraint("DistanceX", -1, 1, c, 3, 15))
sk.addConstraint(Sketcher.Constraint("DistanceY", -1, 1, c, 3, 10))
doc.recompute()
doc.saveAs(os.path.join(os.getcwd(), "sketch_only.FCStd"))

empty = FreeCAD.newDocument("EmptyBody")
body = empty.addObject("PartDesign::Body", "Body")
body.Label = "Empty"
empty.recompute()
empty.saveAs(os.path.join(os.getcwd(), "empty_body.FCStd"))
Binary file not shown.
Loading
Loading