diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index efcbde96e34..47d4b5e8ae0 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -1055,8 +1055,8 @@ into THIRD-PARTY-LICENSES.txt when `main` regenerates it. ## FreeCAD, Rhino and OpenUSD library -FreeCAD `.FCStd` and Rhino `.3dm` files are read, OpenUSD files read and written, and STEP and IGES -files read when "Import with cadmpeg" is chosen, with +FreeCAD `.FCStd` files are read, Rhino `.3dm` files are read and written, OpenUSD files read and written, and STEP and IGES +files read and written when that is asked for, with [cadmpeg](https://github.com/cadmpeg/cadmpeg) 0.6.12 (Apache-2.0), linked as the crates `cadmpeg-core`, `cadmpeg-ir`, `cadmpeg-registry`, `cadmpeg-container`, `cadmpeg-codec-freecad`, `cadmpeg-codec-iges`, `cadmpeg-codec-rhino`, `cadmpeg-codec-step`, `cadmpeg-codec-usd` and `cadmpeg-tessellate` diff --git a/Cargo.toml b/Cargo.toml index 13bdd769490..768fb365165 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -126,7 +126,8 @@ gethostname = "1" # FreeCAD and Rhino import (Apache-2.0, pure Rust; native and browser builds). # Pinned: its IR and codec APIs change between minor versions. Open formats only: no default # features, so cadmpeg's codecs for commercial formats (f3d, sldprt, inventor, catia, creo, nx) -# and its ShapeManager/ACIS `sat` codec are not compiled in. `step` is the writer we restate through. +# and its ShapeManager/ACIS `sat` codec are not compiled in. `step` is the writer we restate through; +# `iges` writes IGES when "Export STEP and IGES with cadmpeg" is on (no IGES import route). cadmpeg-core = "=0.6.12" cadmpeg-ir = "=0.6.12" cadmpeg-registry = { version = "=0.6.12", default-features = false, features = ["fcstd", "iges", "rhino", "step", "usd"] } diff --git a/assets/locales/pending/cadmpeg-step-iges-export.json b/assets/locales/pending/cadmpeg-step-iges-export.json new file mode 100644 index 00000000000..6201ed13474 --- /dev/null +++ b/assets/locales/pending/cadmpeg-step-iges-export.json @@ -0,0 +1,42 @@ +{ + "en": { + "settings.cadmpeg_export": "Write STEP and IGES files with cadmpeg, from the design, instead of with SolidCraft's own writers", + "prefs.cadmpeg_export": "Export STEP and IGES with cadmpeg" + }, + "es": { + "settings.cadmpeg_export": "Escribir los archivos STEP e IGES con cadmpeg, a partir del diseño, en lugar de con los escritores propios de SolidCraft", + "prefs.cadmpeg_export": "Exportar STEP e IGES con cadmpeg" + }, + "de": { + "settings.cadmpeg_export": "STEP- und IGES-Dateien mit cadmpeg aus der Konstruktion schreiben statt mit den eigenen Schreibern von SolidCraft", + "prefs.cadmpeg_export": "STEP und IGES mit cadmpeg exportieren" + }, + "fr": { + "settings.cadmpeg_export": "Écrire les fichiers STEP et IGES avec cadmpeg, à partir de la conception, plutôt qu'avec les écrivains de SolidCraft", + "prefs.cadmpeg_export": "Exporter STEP et IGES avec cadmpeg" + }, + "ar": { + "settings.cadmpeg_export": "كتابة ملفات STEP وIGES باستخدام cadmpeg من التصميم، بدلاً من كاتبات SolidCraft الخاصة", + "prefs.cadmpeg_export": "تصدير STEP وIGES باستخدام cadmpeg" + }, + "he": { + "settings.cadmpeg_export": "כתיבת קובצי STEP ו-IGES בעזרת cadmpeg מתוך התכן, במקום בכותבים של SolidCraft עצמה", + "prefs.cadmpeg_export": "ייצוא STEP ו-IGES בעזרת cadmpeg" + }, + "ja": { + "settings.cadmpeg_export": "STEP と IGES ファイルを SolidCraft 独自のライターではなく、cadmpeg で設計から書き出す", + "prefs.cadmpeg_export": "cadmpeg で STEP と IGES をエクスポート" + }, + "vi": { + "settings.cadmpeg_export": "Ghi tệp STEP và IGES bằng cadmpeg từ thiết kế, thay vì bằng bộ ghi riêng của SolidCraft", + "prefs.cadmpeg_export": "Xuất STEP và IGES bằng cadmpeg" + }, + "zh": { + "settings.cadmpeg_export": "使用 cadmpeg 从设计写出 STEP 和 IGES 文件,而不是使用 SolidCraft 自己的写入器", + "prefs.cadmpeg_export": "使用 cadmpeg 导出 STEP 和 IGES" + }, + "ko": { + "settings.cadmpeg_export": "SolidCraft 자체 작성기 대신 cadmpeg로 설계에서 STEP 및 IGES 파일 쓰기", + "prefs.cadmpeg_export": "cadmpeg로 STEP 및 IGES 내보내기" + } +} diff --git a/attribution/pending/cadmpeg-step-iges-export.md b/attribution/pending/cadmpeg-step-iges-export.md new file mode 100644 index 00000000000..b328bcd5766 --- /dev/null +++ b/attribution/pending/cadmpeg-step-iges-export.md @@ -0,0 +1,3 @@ +| File | Author | Source | Licence | +|---|---|---|---| +| assets/locales/pending/cadmpeg-step-iges-export.json | SolidCraft contributors | Original cadmpeg STEP/IGES export setting label and translations | MIT OR Apache-2.0 | diff --git a/attribution/pending/rhino-export.md b/attribution/pending/rhino-export.md new file mode 100644 index 00000000000..7e7de981b62 --- /dev/null +++ b/attribution/pending/rhino-export.md @@ -0,0 +1,3 @@ +| File | Author | Source | Licence | +|---|---|---|---| +| assets/locales/pending/rhino-export.json | SolidCraft contributors | Original Rhino export label and translations | MIT OR Apache-2.0 | diff --git a/crates/doc/src/joints_cam.rs b/crates/doc/src/joints_cam.rs index 4cf60ce898d..5e3dec42c79 100644 --- a/crates/doc/src/joints_cam.rs +++ b/crates/doc/src/joints_cam.rs @@ -324,8 +324,10 @@ fn cam_turned_occurrence(doc: &Document, cam: &super::Joint) -> u64 { } } -/// The occurrence that slides along a slider joint (the moving side of the joint). -fn slider_moving_occurrence(doc: &Document, j: &super::Joint) -> u64 { +/// The occurrence that moves on joint `j` (slides along a slider, turns on a hinge): the side +/// that is not grounded (the design itself is), else the side farther from the design through +/// the other joints, else B. +pub fn moving_occurrence(doc: &Document, j: &super::Joint) -> u64 { let a_grounded = j.a.occurrence == 0 || doc.occurrences.iter().any(|o| o.id == j.a.occurrence && o.grounded); let b_grounded = j.b.occurrence == 0 || doc.occurrences.iter().any(|o| o.id == j.b.occurrence && o.grounded); if a_grounded && !b_grounded { @@ -356,7 +358,7 @@ fn part_slides(doc: &Document, occ: Option, comp: Option) -> bool { if j.suppressed || j.kind != JointKind::Slider { return false; } - let moving = slider_moving_occurrence(doc, j); + let moving = moving_occurrence(doc, j); if occ.is_some_and(|o| moving == o) { return true; } @@ -374,7 +376,7 @@ fn part_slides(doc: &Document, occ: Option, comp: Option) -> bool { if cost == 0 && other_occ != o && other_occ != u64::MAX - && doc.assembly.joints.iter().any(|j| !j.suppressed && j.kind == JointKind::Slider && slider_moving_occurrence(doc, j) == other_occ) + && doc.assembly.joints.iter().any(|j| !j.suppressed && j.kind == JointKind::Slider && moving_occurrence(doc, j) == other_occ) { return true; } diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e1a1a39322d..66d6789948c 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -174,16 +174,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .noundo() .contract(&EXPORT_CONTRACT) .output(crate::schema::output_schema_for::) - .params(concat!( - "path; ", - "format?: stl|stla|obj|step|3mf|3mf-tagged|glb|urdf|sdf|json, or plugin_id.entry for an installed exporter plugin (plugin.list exporters), which writes the whole design with options?: the slot's declared options (default from extension; an extension SolidCraft doesn't write goes to the exporter plugin that claims it; sdf: a Gazebo model folder, as file.export_sdf (the path is the folder, a `.sdf` ending dropped; name?, static?, model_uris?, quality?); docs/sdf.md; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; glb: binary glTF in metres with Y up, each body placed and named, its colours, metallic, roughness and opacity as materials (a look that is not opaque is alpha blended), and the Glass a render setup gives a body as glTF transmission; Glass with subsurface scattering, Glass two setups give a body differently, or a body a render setup gives an image texture, is refused; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md); ", - "bodies?: [names] (JSON and URDF export the complete design); ", - "urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10), images?: bool (default false; true: each shown canvas and decal is written as a textured quad, its image next to the URDF); ", - "quality?: standard|fine|finest (STL, OBJ, 3MF and GLB: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); ", - "objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts); ", - "lay_on_print_faces?: bool (STL and 3MF only, default false: each body with a print face (body.print_face) is written laid on it, as a slicer export lays it → print_faces: the bodies laid, warnings: each body that has a print face but was written as it lies); ", - "solids?: body|face (ASCII STL, format stla only, default body: face writes one `solid ` block per B-rep face, named by the face's persistent name, for CFD meshers; docs/formats/stl-face-solids.md)", - )), + .params("path; format?: stl|stla|obj|step|3mf|3mf-tagged|glb|usd|3dm|urdf|sdf|json, or plugin_id.entry for an installed exporter plugin (plugin.list exporters), which writes the whole design with options?: the slot's declared options (default from extension; an extension SolidCraft doesn't write goes to the exporter plugin that claims it; sdf: a Gazebo model folder, as file.export_sdf (the path is the folder, a `.sdf` ending dropped; name?, static?, model_uris?, quality?); docs/sdf.md; 3mf-tagged: 3MF whose triangles carry their B-rep face, at full precision, for meshing and analysis tools; docs/formats/3mf-face-tags.md; obj: the colours of the bodies go in a material library (`.mtl`) written next to the mesh file; glb: binary glTF in metres with Y up, each body placed and named, its colours, metallic, roughness and opacity as materials (a look that is not opaque is alpha blended), and the Glass a render setup gives a body as glTF transmission; Glass with subsurface scattering, Glass two setups give a body differently, or a body a render setup gives an image texture, is refused; urdf: the whole assembly as a robot, with STL meshes written next to it; docs/urdf.md; 3dm: Rhino 8, written by cadmpeg: each body where the design shows it (no components), named and in its colour, as its exact shape when every face is planar and every edge straight, else as its mesh, with warnings for what the file leaves out; fcstd is refused, as cadmpeg cannot write a new FreeCAD file yet); bodies?: [names] (JSON and URDF export the complete design); writer?: solidcraft|cadmpeg (STEP and IGES only, refused for the other formats; default solidcraft: SolidCraft's own writers; cadmpeg: written from the design by cadmpeg, STEP AP242 with the components and colours but no solid names, IGES 5.3 with each body where the design shows it, named and coloured; warnings say what the file leaves out); urdf only: mesh_prefix? (before each mesh file name, e.g. package://robot/meshes/), effort? (default 1000), velocity? (default 10), images?: bool (URDF and OpenUSD, default false, true for OpenUSD with purpose: distribution; true: each shown canvas and decal is written as a textured quad, its image next to the URDF or, for OpenUSD, in the .usdz package, a .usda or .usdc file leaving them out with a warning; an OpenUSD export of chosen bodies writes none, with a warning); quality?: standard|fine|finest (STL, OBJ, 3MF, GLB, OpenUSD and Rhino: how closely the mesh follows curved faces, a chord tolerance of 2e-4, 5e-5 or 1e-5 of each body's size; default standard); objects?: body|component (3MF only: one object per body, the default, or one object for each placed component with two or more bodies, with those bodies as its parts, so a slicer loads them as one object with parts); lay_on_print_faces?: bool (STL and 3MF only, default false: each body with a print face (body.print_face) is written laid on it, as a slicer export lays it → print_faces: the bodies laid, warnings: each body that has a print face but was written as it lies); solids?: body|face (ASCII STL, format stla only, default body: face writes one `solid ` block per B-rep face, named by the face's persistent name, for CFD meshers; docs/formats/stl-face-solids.md); physics?: bool (OpenUSD only, default false: true also writes the joints, gears and racks as PhysX couplings of their joints, the grounded placements, each placement as a rigid body and each component's mass as OpenUSD physics, for a simulator, for the whole design with its components only, else none with a warning; a jointed placement moved without capturing the move is written where its joints place it, with a warning); render_setup?: name (OpenUSD only, default none: the saved render setup whose image textures (base colour, roughness, metallic, and a normal map the file can show as the renderer does) a .usdz package holds on each body's mesh; a .usda or .usdc file is written without them, with a warning; and the optics it gives bodies, written as glass in every encoding: the index of refraction, and full transmission on the MaterialX OpenPBR shader); purpose?: interchange|distribution (OpenUSD only, default interchange: each body's exact shape beside its mesh, for another CAD program; distribution: meshes only, with the pictures shown on the model, for a viewer or a game engine); exact_brep?: bool (OpenUSD only, default true for interchange, false for distribution: each body's exact shape beside its mesh); a given images or exact_brep overrides the purpose's default"), // One command per format, so each File › Export item can have a key of its own; started // from a key or command search, the app opens the save picker (the mesh dialog for STL and // 3MF). Each takes `file.export`'s parameters for its format, without `format`. @@ -2703,8 +2694,8 @@ fn export_to( if format == Format::Glb { return export_glb(s, cmd, path, bodies, quality, hierarchy); } - if format == Format::Usd { - return export_usd(s, path, bodies); + if written_by_cadmpeg(format) { + return export_cadmpeg(s, cmd, path, bodies, quality, format, CadmpegChoices::default()); } let name = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| s.doc.name.clone()); // What meshing the bodies reported (STL and 3MF): each face the mesh path left short of the @@ -2750,6 +2741,31 @@ fn export_thumbnail(s: &Session, format: Format, bodies: &[String]) -> Option Result { + match p.get("physics") { + None | Some(Value::Null) | Some(Value::Bool(false)) => Ok(false), + Some(Value::Bool(true)) if format == Format::Usd => Ok(true), + Some(Value::Bool(true)) => { + Err(bad(cmd, "`physics` is for OpenUSD: URDF and SDF always write their joints and masses, and the other formats hold none")) + } + Some(_) => Err(bad(cmd, "`physics` must be true or false")), + } +} + +/// `render_setup` as `file.export` reads it: the saved render setup whose image textures an +/// OpenUSD package holds. Only OpenUSD takes it. +fn render_setup_arg<'a>(p: &'a Value, cmd: &str, format: Format) -> Result> { + match p.get("render_setup") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(name)) if format == Format::Usd && !name.trim().is_empty() => Ok(Some(name.as_str())), + Some(Value::String(_)) if format == Format::Usd => Err(bad(cmd, "`render_setup` must name a render setup")), + Some(Value::String(_)) => Err(bad(cmd, "`render_setup` is for OpenUSD: other formats written here hold no image textures")), + Some(_) => Err(bad(cmd, "`render_setup` must be the name of a render setup")), + } +} + /// `lay_on_print_faces` as the mesh exports read it: true writes each body with a print face laid /// on it, as a slicer export does. Only STL and 3MF take it; `false` is accepted for any format. fn lay_on_print_faces(p: &Value, cmd: &str, format: Format) -> Result { @@ -2861,6 +2877,41 @@ fn export(s: &mut Session, p: &Value) -> Result { } // Checked first so URDF and SDF refuse `solids: face` too, rather than ignoring it. let face_solids = stl_solids(p, cmd, format)?; + // A format asked for by name is written whatever the path's extension, as it always was + // (`format: stl` writes STL to `part.usda`), but for one cadmpeg writes: a Rhino or OpenUSD + // file asked for under another format's extension is refused, rather than written under + // the wrong one (OpenUSD's own target check refused that before; Rhino and FreeCAD are new). + if let Some(f) = str_(p, "format") + && let Ok(by_path) = Format::from_name(path) + && by_path != format + && written_by_cadmpeg(format) + && std::path::Path::new(path).extension().is_some() + { + return Err(bad("file.export", format!("`format: {f}` disagrees with the path's extension, which names {by_path:?}"))); + } + // Read before URDF, SDF and laid-out prints go their own way, so none takes them silently. + let physics = physics_flag(p, cmd, format)?; + let setup = render_setup_arg(p, cmd, format)?; + // OpenUSD's purpose sets the defaults of its exact shapes and pictures; each given option + // overrides it. + let purpose = crate::schema::file::usd_purpose(p.get("purpose"), format).map_err(|e| bad(cmd, e))?.unwrap_or_default(); + let usd_flag = |key: &str| -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(Value::Bool(b)) if format == Format::Usd => Ok(Some(*b)), + Some(Value::Bool(_)) if key == "exact_brep" => Err(bad(cmd, "`exact_brep` is for OpenUSD: other formats written here choose their own")), + Some(Value::Bool(_)) => Ok(None), + Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))), + } + }; + let exact_brep = usd_flag("exact_brep")?; + // STEP and IGES: SolidCraft's own writer unless `writer: cadmpeg` asks for cadmpeg's. + let writer = crate::schema::file::export_writer(p.get("writer"), format).map_err(|e| bad(cmd, e))?; + if writer == Some(crate::schema::file::ExportWriter::Cadmpeg) { + lay_on_print_faces(p, cmd, format)?; + mesh_parts(s, p, cmd, format)?; + return export_cadmpeg(s, cmd, path, &string_list(cmd, p, "bodies")?, mesh_quality(p, cmd)?, format, CadmpegChoices::default()); + } if format == Format::Urdf { if !string_list(cmd, p, "bodies")?.is_empty() { return Err(bad(cmd, "urdf exports the whole assembly; omit bodies")); @@ -2880,6 +2931,13 @@ fn export(s: &mut Session, p: &Value) -> Result { if lay { return export_laid(s, path, format, &bodies, &parts, quality); } + // Pictures are written only when asked (or for distribution), as URDF's are. + let distribution = purpose == crate::schema::file::UsdPurpose::Distribution; + let images = format == Format::Usd && usd_flag("images")?.unwrap_or(distribution); + let meshes_only = format == Format::Usd && !exact_brep.unwrap_or(!distribution); + if written_by_cadmpeg(format) { + return export_cadmpeg(s, cmd, path, &bodies, quality, format, CadmpegChoices { physics, setup, images, meshes_only }); + } export_to(s, cmd, path, format, &bodies, &parts, quality, hierarchy(p, cmd, format)?) } @@ -3113,6 +3171,33 @@ fn shown_decals(doc: &solidcraft_doc::Document, st: &solidcraft_doc::ModelState, decals } +/// What an export through cadmpeg writes beyond the bodies: OpenUSD's physics, a render setup's +/// images and the pictures shown on the model. +#[derive(Clone, Copy, Default)] +struct CadmpegChoices<'a> { + physics: bool, + setup: Option<&'a str>, + images: bool, + meshes_only: bool, +} + +/// The design's shown decals for an OpenUSD export, each in its component's frame and the world. +fn usd_decals(doc: &solidcraft_doc::Document, st: &solidcraft_doc::ModelState, warnings: &mut Vec) -> Vec { + let mut decals = Vec::new(); + for d in shown_decals(doc, st, warnings) { + let Ok(to_component) = solidcore_ops::affine::inverse(&doc.component_transform(d.component)) else { + warnings.push(format!("decal `{}`: its component's placement is degenerate: left out", d.name)); + continue; + }; + let world = d.corners.map(|p| [p.x, p.y, p.z]); + let local = world.map(|p| solidcore_ops::affine::apply_point(&to_component, p)); + let sha256 = solidcraft_doc::render_resources::HdrId::of(&d.image).to_string(); + let image = solidcraft_io::SurfaceMap { sha256, bytes: std::sync::Arc::from(d.image) }; + decals.push(solidcraft_io::DecalPlan { name: d.name, component: d.component, local, world, image }); + } + decals +} + /// The design's shown decals for a URDF export, each in its component's frame. fn urdf_decals(doc: &solidcraft_doc::Document, st: &solidcraft_doc::ModelState, warnings: &mut Vec) -> Vec { let mut decals = Vec::new(); @@ -3221,28 +3306,116 @@ fn usd_encoding(name: &str) -> &'static str { } } -/// The OpenUSD export: the bodies written as STEP, as `file.export` writes STEP (a design with -/// components, when no bodies are chosen, as a STEP assembly), then restated as OpenUSD by -/// cadmpeg; the path's extension picks text (`.usda`), binary (`.usdc`, `.usd`) or a package -/// (`.usdz`). Written atomically, so a refusal or a failed write leaves a file already there as it -/// was. What the file could not carry is in the reply's warnings. -fn export_usd(s: &Session, path: &str, bodies: &[String]) -> Result { +/// Whether cadmpeg writes `format` from the design ([`export_cadmpeg`]). +fn written_by_cadmpeg(format: Format) -> bool { + matches!(format, Format::Usd | Format::Rhino | Format::FreeCad) +} + +/// An export through cadmpeg (OpenUSD, Rhino): the design written into cadmpeg's neutral model +/// (its components and placements when no bodies are chosen and the format holds them, each +/// body's exact B-rep and, where the format takes it, its mesh at `quality`, and the looks the +/// design shows), then written by cadmpeg's writer for `format`; for OpenUSD the path's extension +/// picks text (`.usda`), binary (`.usdc`, `.usd`) or a package (`.usdz`). FreeCAD is refused: +/// cadmpeg cannot write a new FreeCAD file yet. What the view hides is written hidden. Written +/// atomically, so a refusal or a failed write leaves a file already there as it was. What the +/// file could not carry is in the reply's warnings, among them each body a render setup gives an +/// image texture or optics, written with its look alone. With `physics`, OpenUSD also holds the +/// joints, grounding and each component's mass, with `setup` the image textures that render +/// setup gives bodies, and with `images` the pictures shown on the model (both in a `.usdz` +/// package). +fn export_cadmpeg( + s: &Session, + cmd: &str, + path: &str, + bodies: &[String], + quality: solidcraft_io::MeshQuality, + format: Format, + choices: CadmpegChoices<'_>, +) -> Result { + let CadmpegChoices { physics, setup, images, meshes_only } = choices; solidcraft_io::vfs::check(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - let name = std::path::Path::new(path).file_stem().map(|x| x.to_string_lossy().to_string()).unwrap_or_else(|| s.doc.name.clone()); - let step = if bodies.is_empty() && !s.doc.occurrences.is_empty() { - solidcraft_io::step_assembly(&s.doc, &s.doc.painted(&s.model.state()), &name)? - } else { - let quality = solidcraft_io::MeshQuality::default(); - solidcraft_io::export_with_parts_noted(&s.doc.painted(&*s.world_state()?), bodies, &[], Format::Step, &name, &s.doc.metadata, quality, None)? - .0 + let world = s.world_state()?; + // The placements the world has, uncaptured moves included, so the assembly is written where + // the design shows it, as chosen bodies are; with physics written, as URDF has them, a + // placement the joints place is where they place it, so its joints' frames meet as the + // simulator starts. An export that writes no physics (chosen bodies, a placement that is not + // rigid) is written where the design shows it, and says nothing of joints. + let jointed = if physics { Some(jointed_document(s)) } else { None }; + let (doc, held) = match jointed { + Some((doc, held)) if solidcraft_io::CadmpegOptions::physics_fits(&doc, bodies) => (doc, held), + _ => (s.placed_document(), Vec::new()), + }; + let hidden = solidcraft_io::Hidden { + bodies: world.bodies.iter().filter(|b| !s.body_visible(&b.name)).map(|b| b.name.clone()).collect(), + placements: s.visibility.hidden_occurrences.clone(), }; - let (bytes, warnings) = solidcraft_io::usd_from_step(&step, path).map_err(EngineError::Other)?; + let mut warnings = Vec::new(); + let (surfaces, optics) = match setup { + Some(name) => ( + super::render::surface_bindings::export_plans(s, name, cmd, &mut warnings)?, + super::render::surface_bindings::optics_plans(s, name, cmd, &mut warnings)?, + ), + None => (Vec::new(), Vec::new()), + }; + let decals = if images { usd_decals(&doc, &s.model.state(), &mut warnings) } else { Vec::new() }; + let options = solidcraft_io::CadmpegOptions { hidden, physics, surfaces, decals, optics, meshes_only }; + let (bytes, written) = + solidcraft_io::cadmpeg_export(&doc, &s.model.state(), &world, bodies, &options, path, quality, format).map_err(EngineError::Other)?; + warnings.extend(written); + warnings.extend(held.iter().map(|name| held_warning(name))); + let label = match format { + Format::Usd => "OpenUSD", + Format::Rhino => "Rhino", + Format::Step => "STEP", + Format::Iges => "IGES", + Format::FreeCad => "FreeCAD", + _ => "this", + }; + let chosen = |b: &str| bodies.is_empty() || bodies.iter().any(|x| x == b); + // The chosen setup's images and optics are written (or what is not is a warning already). + if setup.is_none() { + let bound = super::render::bound_bodies(s, cmd)?; + for b in world.bodies.iter().filter(|b| chosen(&b.name)) { + if let Some((setup, what)) = bound.get(&b.name) { + warnings.push(format!( + "{}: render setup `{setup}` gives it {what}, which {label} export does not write yet: written with its look", + b.name + )); + } + } + } solidcraft_io::write_atomic(std::path::Path::new(path), &bytes, false).map_err(|e| EngineError::Other(format!("{path}: {e}")))?; - let reply = - ExportResult { path: path.to_string(), bytes: bytes.len(), format: format!("{:?}", Format::Usd), warnings, ..ExportResult::default() }; + let reply = ExportResult { path: path.to_string(), bytes: bytes.len(), format: format!("{format:?}"), warnings, ..ExportResult::default() }; serde_json::to_value(reply).map_err(|e| EngineError::Other(e.to_string())) } +/// The design with its uncaptured moves (not the exploded view, which is shown only), except +/// for the occurrences the joint solver places: it puts them back as soon as a joint moves, so +/// they stay where their joints place them. With the names of those left so. +fn jointed_document(s: &Session) -> (std::borrow::Cow<'_, solidcraft_doc::Document>, Vec) { + let moves = s.uncaptured_moves(); + if moves.is_empty() { + return (std::borrow::Cow::Borrowed(&*s.doc), Vec::new()); + } + let placed = solidcraft_doc::joints::solve(&s.doc, &s.model.state()).world; + let mut held = Vec::new(); + let mut doc = (*s.doc).clone(); + for o in &mut doc.occurrences { + match moves.get(&o.id) { + Some(_) if placed.contains_key(&o.id) => held.push(o.name.clone()), + Some(t) => o.transform = *t, + None => {} + } + } + (std::borrow::Cow::Owned(doc), held) +} + +/// The warning for occurrence `name`, moved without the move captured, written where its joints +/// place it ([`jointed_document`]). +fn held_warning(name: &str) -> String { + format!("`{name}` was moved but the move is not captured: exported where its joints place it") +} + /// The assembly as a URDF and its meshes next to it (docs/urdf.md). Every path is checked before /// anything is written; the meshes go first and the `.urdf` last. fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result { @@ -3265,32 +3438,14 @@ fn export_urdf(s: &Session, cmd: &str, path: &str, p: &Value) -> Result { // places: it puts them back as soon as a joint moves, so the move must not become part of // their links. let st = s.model.state(); - let mut held = Vec::new(); - // The exploded view is shown only: the links are where the design places them. - let moves = s.uncaptured_moves(); - let doc = if moves.is_empty() { - std::borrow::Cow::Borrowed(&*s.doc) - } else { - let placed = solidcraft_doc::joints::solve(&s.doc, &st).world; - let mut doc = (*s.doc).clone(); - for o in &mut doc.occurrences { - match moves.get(&o.id) { - Some(_) if placed.contains_key(&o.id) => held.push(o.name.clone()), - Some(t) => o.transform = *t, - None => {} - } - } - std::borrow::Cow::Owned(doc) - }; + let (doc, held) = jointed_document(s); let mut decal_warnings = Vec::new(); if images { options.decals = urdf_decals(&doc, &st, &mut decal_warnings); } let mut pkg = solidcraft_io::urdf(&doc, &doc.painted(&st), &stem, &options)?; pkg.warnings.extend(decal_warnings); - for name in held { - pkg.warnings.push(format!("`{name}` was moved but the move is not captured: exported where its joints place it")); - } + pkg.warnings.extend(held.iter().map(|name| held_warning(name))); let dir = file.parent().unwrap_or(std::path::Path::new("")); let mut targets: Vec<(String, &[u8])> = pkg.meshes.iter().map(|(n, b)| (dir.join(n).to_string_lossy().to_string(), b.as_slice())).collect(); targets.push((path.to_string(), pkg.xml.as_bytes())); diff --git a/crates/engine/src/cmd/render.rs b/crates/engine/src/cmd/render.rs index 9bd711286e2..63376577a83 100644 --- a/crates/engine/src/cmd/render.rs +++ b/crates/engine/src/cmd/render.rs @@ -38,11 +38,32 @@ mod resources; mod shots; mod staging; mod studio_presets; -mod surface_bindings; +pub(super) mod surface_bindings; mod surface_resources; mod textures; mod transmission; +/// The placed bodies (by world name) that a saved render setup gives an image texture or optics, +/// each with the first such setup's name and what it gives: what a file without render setups +/// cannot hold (GLB export, #1553). A binding whose body is gone binds nothing. +pub(super) fn bound_bodies(s: &Session, cmd: &str) -> Result> { + let mut out = std::collections::BTreeMap::new(); + let setups = &s.doc.render.setups; + if setups.values().all(|x| x.surfaces.is_empty() && x.optics.is_empty()) { + return Ok(out); + } + let names = surface_bindings::targets(s, cmd)?; + for (setup, x) in setups { + let bound = x.surfaces.iter().map(|b| (&b.target, "an image texture")).chain(x.optics.iter().map(|b| (&b.target, "optics"))); + for (target, what) in bound { + if let Some(name) = names.get(target) { + out.entry(name.clone()).or_insert_with(|| (setup.clone(), what)); + } + } + } + Ok(out) +} + pub static COMMANDS: &[CommandSpec] = &[ CommandSpec::new("render.surface.import", "Import Surface Maps", crate::checked!("render.surface.import", surface_resources::import)) .icon("appearance") diff --git a/crates/engine/src/cmd/render/surface_bindings.rs b/crates/engine/src/cmd/render/surface_bindings.rs index 11403b5a934..5e57c1c1e81 100644 --- a/crates/engine/src/cmd/render/surface_bindings.rs +++ b/crates/engine/src/cmd/render/surface_bindings.rs @@ -209,3 +209,140 @@ pub(super) fn unbind(s: &mut Session, params: &Value) -> Result { setup.surfaces.remove(&input.target); publish(s, input.name, setup, command) } + +/// The image textures render setup `name` gives the design's bodies, for an export: one plan per +/// binding, with its maps' bytes. A binding that cannot be read (its target gone, a built-in +/// surface this build lacks or that changed, an image missing) is left out with a warning. +pub(in crate::cmd) fn export_plans(s: &Session, name: &str, command: &str, warnings: &mut Vec) -> Result> { + use solidcraft_render::texture_input::MapRole; + let setup = s.doc.render.setups.get(name).ok_or_else(|| bad(command, format!("there is no render setup named `{name}`")))?; + if setup.surfaces.is_empty() { + return Ok(Vec::new()); + } + // A design whose bodies cannot be named for the setup (too many placed bodies for the + // renderer, say) is still exported: its images are left out, with why. + let identities = match targets(s, command) { + Ok(identities) => identities, + Err(e) => { + warnings.push(format!("render setup `{name}`: its images are left out: {e}")); + return Ok(Vec::new()); + } + }; + let maximum = solidcraft_doc::render_texture_resources::MAX_TEXTURE_BYTES as u64; + // Each image read once and shared by every binding that uses it. + let mut read: BTreeMap> = BTreeMap::new(); + let mut map = |sha: String, bytes: &dyn Fn() -> std::result::Result, String>| -> std::result::Result { + let bytes = match read.get(&sha) { + Some(b) => b.clone(), + None => { + let b: Arc<[u8]> = Arc::from(bytes()?); + read.insert(sha.clone(), b.clone()); + b + } + }; + Ok(solidcraft_io::SurfaceMap { sha256: sha, bytes }) + }; + let mut plans = Vec::new(); + for binding in setup.surfaces.iter() { + let Some(world) = identities.get(&binding.target) else { + warnings.push(format!("render setup `{name}`: a surface's body is gone or changed: left out")); + continue; + }; + let mut plan = solidcraft_io::SurfacePlan { + setup: name.to_string(), + definition: binding.target.definition.clone(), + component: binding.target.component, + path: binding.target.occurrence_path.clone(), + world: world.clone(), + origin: binding.local_frame.origin, + u: binding.local_frame.u, + v: binding.local_frame.v, + flip_v: true, + normal_strength: binding.normal_strength, + base_color: None, + normal: None, + roughness: None, + metallic: None, + }; + let outcome = match &binding.source { + SurfaceSource::Builtin(builtin) => (|| { + if !cfg!(feature = "bundled-render-library") { + return Err(format!("this build has no built-in surface images, so `{}` is written without them", builtin.id)); + } + if source(&builtin.id, command).ok().as_ref() != Some(builtin) { + return Err(format!("built-in surface `{}` differs from the installed one: written without its images", builtin.id)); + } + let bytes = |role: MapRole, file: &str| { + super::library::texture_bytes(&format!("{}/{file}", builtin.id), role, maximum, command).map_err(|e| e.to_string()) + }; + plan.base_color = Some(map(builtin.base_color_sha256.to_string(), &|| bytes(MapRole::BaseColor, "base_color"))?); + plan.normal = Some(map(builtin.normal_sha256.to_string(), &|| bytes(MapRole::NormalOpenGl, "normal_open_gl"))?); + plan.roughness = Some(map(builtin.roughness_sha256.to_string(), &|| bytes(MapRole::Roughness, "roughness"))?); + plan.metallic = Some(map(builtin.metallic_sha256.to_string(), &|| bytes(MapRole::Metallic, "metallic"))?); + Ok(()) + })(), + SurfaceSource::Embedded(embedded) => (|| { + plan.flip_v = embedded.flip_v; + let resources = &s.doc.render.texture_resources; + let mut bytes = |id: Option| -> std::result::Result, String> { + id.map(|id| map(id.to_string(), &|| resources.required(&id).map(|r| r.bytes().to_vec()).map_err(|e| e.to_string()))).transpose() + }; + plan.base_color = bytes(embedded.base_color)?; + plan.normal = bytes(embedded.normal_open_gl)?; + plan.roughness = bytes(embedded.roughness)?; + plan.metallic = bytes(embedded.metallic)?; + Ok(()) + })(), + }; + match outcome { + Ok(()) => plans.push(plan), + Err(e) => warnings.push(format!("{world}: render setup `{name}`: {e}")), + } + } + Ok(plans) +} + +/// The optics render setup `name` gives the design's bodies, for an export: one plan per binding. +/// What the export cannot write (a glass model, subsurface scattering, transmissive shadows) is a +/// warning naming the body; a binding whose body is gone is left out with a warning. +pub(in crate::cmd) fn optics_plans(s: &Session, name: &str, command: &str, warnings: &mut Vec) -> Result> { + let Some(setup) = s.doc.render.setups.get(name) else { return Ok(Vec::new()) }; + if setup.optics.is_empty() { + return Ok(Vec::new()); + } + let identities = match targets(s, command) { + Ok(identities) => identities, + Err(e) => { + warnings.push(format!("render setup `{name}`: its optics are not written: {e}")); + return Ok(Vec::new()); + } + }; + let mut plans = Vec::new(); + for binding in setup.optics.iter() { + let Some(world) = identities.get(&binding.target) else { + warnings.push(format!("render setup `{name}`: a body given optics is gone or changed: left out")); + continue; + }; + let optics = &binding.optics; + for (unwritten, what) in [ + (optics.model.is_some(), "its glass model"), + (optics.subsurface.is_some(), "its subsurface scattering"), + (optics.shadow_transmission, "its transmissive shadows"), + ] { + if unwritten { + warnings.push(format!("{world}: render setup `{name}`: {what} has no OpenUSD form here: left out")); + } + } + plans.push(solidcraft_io::OpticsPlan { + setup: name.to_string(), + definition: binding.target.definition.clone(), + component: binding.target.component, + path: binding.target.occurrence_path.clone(), + world: world.clone(), + ior: optics.ior, + absorption_per_mm: optics.absorption_per_mm, + thin_sheet: optics.boundary == solidcraft_doc::render_optics::OpticalBoundary::ThinSheet, + }); + } + Ok(plans) +} diff --git a/crates/engine/src/schema/file.rs b/crates/engine/src/schema/file.rs index 9761c1fccdb..ce34c93079d 100644 --- a/crates/engine/src/schema/file.rs +++ b/crates/engine/src/schema/file.rs @@ -40,6 +40,60 @@ pub enum ObjectsParam { Component, } +/// Which program writes a STEP or IGES file. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum ExportWriter { + /// SolidCraft's own STEP and IGES writers (the default). + Solidcraft, + /// cadmpeg's, from the design written into its neutral model. + Cadmpeg, +} + +/// What an OpenUSD file is for: the defaults of what it holds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, JsonSchema)] +#[serde(rename_all = "lowercase")] +pub enum UsdPurpose { + /// For another CAD program: each body's exact shape beside its mesh (the default). + #[default] + Interchange, + /// For a viewer, a game engine or a store: meshes only, with the pictures shown on the model. + Distribution, +} + +/// `purpose` as `file.export` reads it: `None` when left out (interchange); refused for a format +/// other than OpenUSD, and for any other word. +pub(crate) fn usd_purpose(value: Option<&Value>, format: Format) -> Result, String> { + let purpose = match value { + None | Some(Value::Null) => return Ok(None), + Some(_) if format != Format::Usd => { + return Err("`purpose` is for OpenUSD: other formats written here have one form".into()); + } + Some(Value::String(s)) if s == "interchange" => UsdPurpose::Interchange, + Some(Value::String(s)) if s == "distribution" => UsdPurpose::Distribution, + Some(_) => return Err("`purpose` must be interchange or distribution".into()), + }; + Ok(Some(purpose)) +} + +/// `writer` as `file.export` reads it for `format`: `None` when left out (SolidCraft's own writer); +/// refused for a format other than STEP and IGES, and for any other word. +pub(crate) fn export_writer(value: Option<&Value>, format: Format) -> Result, String> { + let writer = match value { + None | Some(Value::Null) => return Ok(None), + Some(Value::String(w)) => match w.trim().to_ascii_lowercase().as_str() { + "solidcraft" => ExportWriter::Solidcraft, + "cadmpeg" => ExportWriter::Cadmpeg, + _ => return Err(format!("`writer` must be solidcraft or cadmpeg, not {w}")), + }, + Some(v) => return Err(format!("`writer` must be solidcraft or cadmpeg, not {v}")), + }; + if !matches!(format, Format::Step | Format::Iges) { + return Err(format!("`writer` is for STEP and IGES only: {format:?} has one writer")); + } + Ok(Some(writer)) +} + /// Export bodies as a STEP file. With no `bodies`, a design with components exports as a STEP /// assembly, otherwise its bodies as placed. The file is STEP whatever the path's extension. #[derive(Debug, Deserialize, JsonSchema)] @@ -190,10 +244,10 @@ pub struct ExportParams { /// The file to write. #[serde(default)] pub path: Option, - /// The format: stl, stla, obj, step, 3mf, 3mf-tagged, glb, urdf, sdf or json, or a file name - /// whose extension names it, or an installed exporter plugin as `plugin_id.entry` (`plugin.list`'s - /// `exporters`). Default: from the path's extension; an extension SolidCraft does not write - /// goes to the exporter plugin that claims it. + /// The format: stl, stla, obj, step, 3mf, 3mf-tagged, glb, usd, 3dm, urdf, sdf or json, or a + /// file name whose extension names it, or an installed exporter plugin as `plugin_id.entry` + /// (`plugin.list`'s `exporters`). Default: from the path's extension; an extension SolidCraft + /// does not write goes to the exporter plugin that claims it. #[serde(default)] pub format: Option, /// An exporter plugin's options, as its slot declares them. Refused for SolidCraft's own @@ -204,7 +258,7 @@ pub struct ExportParams { /// complete design, so they refuse a list. #[serde(default)] pub bodies: Option, - /// How closely the mesh follows curved faces (STL, OBJ, 3MF and GLB). Default: standard. Not read + /// How closely the mesh follows curved faces (STL, OBJ, 3MF, GLB, OpenUSD and Rhino). Default: standard. Not read /// for URDF. #[serde(default)] pub quality: Option, @@ -221,7 +275,8 @@ pub struct ExportParams { /// URDF only: each joint's velocity limit, a positive number. Default: 10. #[serde(default)] pub velocity: Option, - /// URDF only: also write each picture shown on the model as a textured visual. Default: false. + /// URDF and OpenUSD only: also write each picture shown on the model as a textured visual + /// (OpenUSD: in a `.usdz` package). Default: false. #[serde(default)] pub images: Option, /// STL and 3MF only: true writes each body with a print face laid on it, as @@ -238,6 +293,30 @@ pub struct ExportParams { /// `file.export_stl` has it; refused for the other formats. Default: body. #[serde(default)] pub solids: Option, + /// OpenUSD only: also write the joints, the grounded placements and each component's mass as + /// OpenUSD physics, for a simulator. Default: false. + #[serde(default)] + pub physics: Option, + /// OpenUSD only: what the file is for. `interchange` (for another CAD program: each body's + /// exact shape beside its mesh) or `distribution` (for a viewer or a game engine: meshes only, + /// with the pictures shown on the model). `exact_brep` and `images` override it. Default: + /// interchange. + #[serde(default)] + pub purpose: Option, + /// OpenUSD only: write each body's exact shape (B-rep) beside its mesh. Default: from + /// `purpose` (true for interchange, false for distribution). + #[serde(default)] + pub exact_brep: Option, + /// OpenUSD only: the saved render setup whose image textures a `.usdz` package holds. + /// Default: none, each body written with its look. + #[serde(default)] + pub render_setup: Option, + /// STEP and IGES only: which program writes the file. Default: solidcraft, SolidCraft's own + /// writers; cadmpeg writes it from the design through cadmpeg's neutral model (STEP AP242 with + /// the components, IGES 5.3 with each body where the design shows it), with warnings for what + /// it leaves out. Refused for the other formats. + #[serde(default)] + pub writer: Option, /// SDF only: the model's name. Default: the folder's name. #[serde(default)] pub name: Option, @@ -322,6 +401,11 @@ impl<'de> Deserialize<'de> for ExportParams { lay_on_print_faces: None, hierarchy: None, solids: None, + physics: None, + render_setup: None, + purpose: None, + exact_brep: None, + writer: None, name: None, is_static: None, model_uris: None, @@ -356,6 +440,32 @@ impl<'de> Deserialize<'de> for ExportParams { } Some(v) => return Err(refuse(format!("`solids` must be body or face, not {v}"))), }; + // Read before URDF and SDF read their own keys, as the handler reads it. + out.physics = match m.get("physics") { + None | Some(Value::Null) => None, + Some(Value::Bool(false)) => Some(false), + Some(Value::Bool(true)) if format == Format::Usd => Some(true), + Some(Value::Bool(true)) => { + return Err(refuse("`physics` is for OpenUSD: URDF and SDF always write their joints and masses, and the other formats hold none")); + } + Some(_) => return Err(refuse("`physics` must be true or false")), + }; + out.render_setup = match m.get("render_setup") { + None | Some(Value::Null) => None, + Some(Value::String(n)) if format == Format::Usd && !n.trim().is_empty() => Some(n.clone()), + Some(Value::String(_)) if format == Format::Usd => return Err(refuse("`render_setup` must name a render setup")), + Some(Value::String(_)) => return Err(refuse("`render_setup` is for OpenUSD: other formats written here hold no image textures")), + Some(_) => return Err(refuse("`render_setup` must be the name of a render setup")), + }; + // Read before URDF and SDF return, so neither takes an OpenUSD option silently. + out.purpose = usd_purpose(m.get("purpose"), format).map_err(refuse::)?; + out.exact_brep = match m.get("exact_brep") { + None | Some(Value::Null) => None, + Some(Value::Bool(b)) if format == Format::Usd => Some(*b), + Some(Value::Bool(_)) => return Err(refuse("`exact_brep` is for OpenUSD: other formats written here choose their own")), + Some(_) => return Err(refuse("`exact_brep` must be true or false")), + }; + out.writer = export_writer(m.get("writer"), format).map_err(refuse::)?; if format == Format::Urdf { // URDF reads its own keys; `quality` and `objects` are not read. out.mesh_prefix = text::(&m, "mesh_prefix")?; @@ -395,6 +505,12 @@ impl<'de> Deserialize<'de> for ExportParams { _ => return Err(refuse(format!("`objects` must be body or component, not {v}"))), }, }; + if format == Format::Usd { + out.images = match m.get("images") { + None | Some(Value::Null) => None, + Some(v) => Some(v.as_bool().ok_or_else(|| refuse::("`images` must be true or false"))?), + }; + } out.lay_on_print_faces = match m.get("lay_on_print_faces") { None | Some(Value::Null) => None, Some(Value::Bool(false)) => Some(false), @@ -420,7 +536,8 @@ pub struct ExportResult { /// Its size in bytes. pub bytes: usize, /// The format written: Step, StlBinary, ThreeMf or Obj (and for `file.export` and - /// `file.save_mesh` also StlAscii or ThreeMfTagged, and for `file.export` also Design and Glb). + /// `file.save_mesh` also StlAscii or ThreeMfTagged, and for `file.export` also Design, Glb, Usd + /// and Rhino). pub format: String, /// OBJ only: every file written, the material library first and the mesh file last. #[serde(default, skip_serializing_if = "Vec::is_empty")] diff --git a/crates/engine/src/schema/file_tests.rs b/crates/engine/src/schema/file_tests.rs index fc03f4f720b..dcc49df32d5 100644 --- a/crates/engine/src/schema/file_tests.rs +++ b/crates/engine/src/schema/file_tests.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use super::{ Export3mfParams, ExportMeshParams, ExportParams, ExportSdfParams, ExportStepParams, ExportStlParams, ExportUrdfParams, FileExportResult, NewerFileReport, OpenElsewhere, OpenParams, OpenResult, OpenedDesign, RecoverParams, RecoverResult, RecoveryDiscardParams, RecoveryDiscardResult, - RecoveryListParams, RecoveryListResult, + RecoveryListParams, RecoveryListResult, UsdPurpose, }; use crate::Session; use crate::recovery::Autosaver; @@ -25,6 +25,7 @@ fn schemas_and_the_key_check_agree() { &[ "bodies", "effort", + "exact_brep", "format", "hierarchy", "images", @@ -35,10 +36,14 @@ fn schemas_and_the_key_check_agree() { "objects", "options", "path", + "physics", + "purpose", "quality", + "render_setup", "solids", "static", "velocity", + "writer", ], ); assert_keys( @@ -347,6 +352,11 @@ fn strict_keeps_todays_errors() { ("file.export", json!({"path": at("a.obj"), "lay_on_print_faces": true})), ("file.export", json!({"path": at("a.stl"), "lay_on_print_faces": "yes"})), ("file.export", json!({"path": at("a.3mf"), "lay_on_print_faces": 1})), + ("file.export", json!({"path": at("a.urdf"), "physics": true})), + ("file.export", json!({"path": at("a.sdf"), "physics": "yes"})), + ("file.export", json!({"path": at("a.step"), "physics": true})), + ("file.export", json!({"path": at("a.urdf"), "render_setup": "Studio"})), + ("file.export", json!({"path": at("a.sdf"), "render_setup": 5})), ("file.export_stl", json!({"path": at("a.stl"), "lay_on_print_faces": "yes"})), ("file.export_3mf", json!({"path": at("a.3mf"), "lay_on_print_faces": [true]})), ("doc.open", json!({"path": ""})), @@ -399,6 +409,33 @@ fn the_export_type_reads_each_key_only_for_its_format() { } let e = read(json!({"path": "a.stl", "lay_on_print_faces": "yes"})).expect_err("a string"); assert!(e.contains("must be true or false"), "{e}"); + // `purpose` is one of OpenUSD's two forms, as the type, the schema and the handler read it. + assert_eq!(ok(json!({"path": "a.usda", "purpose": "distribution"})).purpose, Some(UsdPurpose::Distribution)); + let e = read(json!({"path": "a.usda", "purpose": "viewer"})).expect_err("a purpose OpenUSD does not have"); + assert!(e.contains("`purpose` must be interchange or distribution"), "{e}"); +} + +/// OpenUSD's `purpose` and `exact_brep` are refused for every other format, URDF, SDF and laid-out +/// prints included, by the type and by the handler alike. +#[test] +fn openusd_only_options_are_refused_for_every_other_format() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10})); + let calls = [ + (json!({"path": "robot.urdf", "purpose": "distribution"}), "`purpose` is for OpenUSD"), + (json!({"path": "world.sdf", "purpose": "interchange"}), "`purpose` is for OpenUSD"), + (json!({"path": "robot.urdf", "exact_brep": true}), "`exact_brep` is for OpenUSD"), + (json!({"path": "part.step", "exact_brep": false}), "`exact_brep` is for OpenUSD"), + (json!({"path": "part.stl", "lay_on_print_faces": true, "exact_brep": false}), "`exact_brep` is for OpenUSD"), + ]; + for (p, says) in calls { + let typed = serde_json::from_value::(p.clone()).expect_err("the type refuses").to_string(); + assert!(typed.contains(says), "{p}: {typed}"); + let handled = s.execute("file.export", &p).expect_err("the handler refuses").to_string(); + assert!(handled.contains(says), "{p}: {handled}"); + } + // Absent or null, they are the defaults for any format. + assert!(serde_json::from_value::(json!({"path": "robot.urdf", "purpose": null, "exact_brep": null})).is_ok()); } /// (`conforms` does not read `oneOf`, so `quality` and `objects` values are checked by the type, @@ -413,6 +450,9 @@ fn the_export_schema_takes_what_the_handler_reads() { (json!({"path": "robot.urdf", "mesh_prefix": "package://robot/meshes/", "effort": 50, "velocity": 2.5}), true), (json!({"path": "a.step", "bodies": "Body1"}), true), (json!({"path": "a.stl", "lay_on_print_faces": true}), true), + (json!({"path": "a.step", "writer": "cadmpeg"}), true), + (json!({"path": "a.igs", "writer": "solidcraft"}), true), + (json!({"path": "a.usda", "purpose": "distribution"}), true), (json!({}), false), (json!({"path": "a.stl", "lay_on_print_faces": "yes"}), false), (json!({"path": "a.stl", "bodies": [1]}), false), @@ -420,6 +460,29 @@ fn the_export_schema_takes_what_the_handler_reads() { ] { assert_eq!(conforms(schema, schema, &p), takes, "{p}"); } + // OpenUSD's `purpose` offers its two forms in the schema, not any string. + let mut allowed = allows(schema, &schema["properties"]["purpose"]); + allowed.sort(); + assert_eq!(allowed, ["distribution", "interchange"], "{:?}", schema["properties"]["purpose"]); +} + +/// The string values a property's schema allows, through a `$ref` and an `Option`'s, an `enum`'s +/// and a closed list's branches. +fn allows(root: &Value, node: &Value) -> Vec { + let node = + node.get("$ref").and_then(Value::as_str).and_then(|r| r.strip_prefix("#/$defs/")).and_then(|name| root["$defs"].get(name)).unwrap_or(node); + if let Some(list) = node.get("enum").and_then(Value::as_array) { + return list.iter().filter_map(Value::as_str).map(str::to_string).collect(); + } + if let Some(only) = node.get("const").and_then(Value::as_str) { + return vec![only.to_string()]; + } + ["anyOf", "oneOf"] + .into_iter() + .filter_map(|key| node.get(key).and_then(Value::as_array)) + .flatten() + .flat_map(|branch| allows(root, branch)) + .collect() } /// Real exports of every format in warn: no `param_warnings`, and each reply matches the output @@ -443,6 +506,9 @@ fn export_replies_match_the_output_schema() { // body is a part of a component's object, so it stays as it lies). json!({"path": at("i.stl"), "lay_on_print_faces": true}), json!({"path": at("j.3mf"), "objects": "component", "lay_on_print_faces": true}), + json!({"path": at("k.step"), "writer": "cadmpeg"}), + json!({"path": at("l.igs"), "writer": "cadmpeg"}), + json!({"path": at("m.3dm")}), ]; for level in [ParamCheck::Warn, ParamCheck::Strict] { let mut s = two_cubes(); diff --git a/crates/engine/src/tests/native_cad_import.rs b/crates/engine/src/tests/native_cad_import.rs index 249b2c2e91a..7c44547697c 100644 --- a/crates/engine/src/tests/native_cad_import.rs +++ b/crates/engine/src/tests/native_cad_import.rs @@ -325,3 +325,253 @@ fn either_reader_names_the_program_and_its_up_axis() { } let _ = std::fs::remove_dir_all(&dir); } + +// Rhino export through cadmpeg (`file.export` to `.3dm`), read back through the Rhino import +// above. Expected volumes and boxes come from the designs' dimensions. + +/// The world box of every shown body, rounded to a micrometre, sorted. +fn shown_boxes(s: &Session) -> Vec<[i64; 6]> { + let mut out: Vec<[i64; 6]> = s + .world_state() + .unwrap() + .bodies + .iter() + .map(|b| { + let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox; + [bb.min.x, bb.min.y, bb.min.z, bb.max.x, bb.max.y, bb.max.z].map(|v| (v * 1e3).round() as i64) + }) + .collect(); + out.sort(); + out +} + +fn um(b: [f64; 6]) -> [i64; 6] { + b.map(|v| (v * 1e3).round() as i64) +} + +/// The cylinder's exact volume, π · 6² · 15 = 540π mm³. +const CYLINDER_VOLUME_MM3: f64 = 1_696.460_032_938_488; + +/// A loose 10 mm cube, a coloured cylinder (radius 6 mm, 15 mm high, at x = 80 mm), and a +/// `Bracket` component (a 20 × 20 × 10 mm base and a 10 × 10 × 10 mm block on it) placed twice, +/// the second copy 40 mm along Y. +fn parts() -> Session { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [-30, 0, 0], "body_name": "Loose"})); + run(&mut s, "solid.cylinder", json!({"radius": 6, "height": 15, "base": [80, 0, 0], "body_name": "Pin"})); + run(&mut s, "appearance.assign", json!({"bodies": ["Pin"], "color": "#0040ff"})); + run(&mut s, "appearance.assign", json!({"bodies": ["Loose"], "color": "#ff8000"})); + run(&mut s, "component.create", json!({"name": "Bracket"})); + run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "body_name": "Base"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [5, 5, 10], "operation": "new", "body_name": "Block"})); + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "occurrence.copy", json!({"component": "Bracket", "translate": [0, 40, 0]})); + s +} + +/// The design's solids that Rhino holds exactly: the cube and the bracket's boxes, twice. +fn exact_boxes() -> Vec<[i64; 6]> { + let mut want = vec![ + um([-30.0, 0.0, 0.0, -20.0, 10.0, 10.0]), + um([0.0, 0.0, 0.0, 20.0, 20.0, 10.0]), + um([0.0, 40.0, 0.0, 20.0, 60.0, 10.0]), + um([5.0, 5.0, 10.0, 15.0, 15.0, 20.0]), + um([5.0, 45.0, 10.0, 15.0, 55.0, 20.0]), + ]; + want.sort(); + want +} + +/// `file.export` writes a `.3dm` file (any case) from the design: every box where the design shows +/// it, as an exact solid that both Rhino readers bring back with its volume, and the cylinder, +/// which cadmpeg's Rhino writer cannot hold exactly yet, as its mesh with a warning naming it. +/// The components are not kept, and a warning says so. +#[test] +fn file_export_writes_rhino_and_it_reads_back() { + let (dir, _) = file("rhino-out", "unused", b""); + let mut s = parts(); + let cylinder = s.world_state().unwrap().bodies.iter().find(|b| b.name.starts_with("Pin")).map(|b| b.name.clone()).unwrap(); + for name in ["parts.3dm", "PARTS.3DM"] { + let path = dir.join(name).to_string_lossy().to_string(); + let out = run(&mut s, "file.export", json!({"path": path})); + assert_eq!(out["format"], "Rhino", "{out}"); + let warnings = out["warnings"].to_string(); + assert!(warnings.contains(&format!("{cylinder}: written as its mesh only")), "{out}"); + assert!(warnings.contains("components and placements are not written"), "{out}"); + for reader in ["solidcraft", "cadmpeg"] { + let mut back = Session::default(); + run(&mut back, "file.insert_step", json!({"path": path, "reader": reader})); + // SolidCraft's own Rhino reader leaves the cylinder's mesh out; cadmpeg's brings it in + // as a mesh body spanning the cylinder (radius 6 mm, 15 mm high, at x = 80 mm). + let mut want = exact_boxes(); + let mut mesh_volume = 0.0; + if reader == "cadmpeg" { + let world = back.world_state().unwrap(); + let meshes: Vec<_> = world.bodies.iter().filter(|b| b.body.is_mesh()).collect(); + let [mesh] = meshes.as_slice() else { panic!("{name}: one mesh body, got {}", meshes.len()) }; + let m = solidcraft_kernel::measure(&mesh.body).unwrap(); + let bb = [m.bbox.min.x, m.bbox.min.y, m.bbox.min.z, m.bbox.max.x, m.bbox.max.y, m.bbox.max.z]; + for (got, want) in bb.iter().zip([74.0, -6.0, 0.0, 86.0, 6.0, 15.0]) { + assert!((got - want).abs() < 0.01, "{name}: {bb:?}"); + } + want.push(bb.map(|v| (v * 1e3).round() as i64)); + want.sort(); + // The cylinder's volume is π r² h = 540π mm³. Its mesh is a prism on a + // polygon inscribed in the circle, at a chord tolerance of at most 2e-4 of the + // body's size (its 22.6 mm diagonal: a sagitta s ≤ 0.0046 mm), so short of it by + // less than (4/3) s / r ≈ 0.1%; 1% allows that, and the file's single-precision + // points (≈1e-6 relative) cannot take it past π r² h by 1e-4. + let exact = CYLINDER_VOLUME_MM3; + assert!( + m.volume > 0.99 * exact && m.volume < exact * (1.0 + 1e-4), + "{name}: the cylinder's mesh holds {} mm³, not {exact}", + m.volume + ); + mesh_volume = m.volume; + } + assert_eq!(shown_boxes(&back), want, "{name} {reader}"); + let v = volume(&mut back); + assert!((v - (1000.0 + 2.0 * (4000.0 + 1000.0)) - mesh_volume).abs() < 1e-6, "{name} {reader}: {v}"); + } + } + // Chosen bodies only. + let path = dir.join("loose.3dm").to_string_lossy().to_string(); + let out = run(&mut s, "file.export", json!({"path": path, "bodies": ["Loose"]})); + assert!(out.get("warnings").is_none_or(|w| w.as_array().is_some_and(Vec::is_empty)), "{out}"); + let mut back = Session::default(); + run(&mut back, "file.insert_step", json!({"path": path})); + assert_eq!(shown_boxes(&back), vec![um([-30.0, 0.0, 0.0, -20.0, 10.0, 10.0])]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// `format: 3dm` names Rhino; `format: 3dm` under another format's extension is refused, while +/// another format named under a Rhino extension is written as asked; FreeCAD is refused with +/// why, leaving no file behind. +#[test] +fn rhino_and_freecad_export_check_their_format() { + let (dir, _) = file("rhino-format", "unused", b""); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30})); + let path = dir.join("block.3dm").to_string_lossy().to_string(); + assert_eq!(run(&mut s, "file.export", json!({"path": path, "format": "3dm"}))["format"], "Rhino"); + let step = dir.join("block.step").to_string_lossy().to_string(); + let e = s.execute("file.export", &json!({"path": step, "format": "3dm"})).unwrap_err().to_string(); + assert!(e.contains("disagrees with the path's extension"), "{e}"); + assert!(!std::path::Path::new(&step).exists()); + // The other way round, a format SolidCraft writes itself, named, is written whatever the + // extension, as an explicit format always was: STEP under a Rhino name. + let rhino = dir.join("part.3dm").to_string_lossy().to_string(); + assert_eq!(run(&mut s, "file.export", json!({"path": rhino, "format": "step"}))["format"], "Step"); + assert!(std::fs::read(&rhino).unwrap().starts_with(b"ISO-10303-21;")); + let fcstd = dir.join("block.FCStd").to_string_lossy().to_string(); + let e = s.execute("file.export", &json!({"path": fcstd})).unwrap_err().to_string(); + assert!(e.contains("FreeCAD files cannot be exported yet"), "{e}"); + assert!(!std::path::Path::new(&fcstd).exists()); + // A file already there is left as it was by a refused export. + std::fs::write(&fcstd, b"kept").unwrap(); + assert!(s.execute("file.export", &json!({"path": fcstd})).is_err()); + assert_eq!(std::fs::read(&fcstd).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A body's colour: its own, else the one colour every face of it has. +fn colour_of(b: &solidcraft_kernel::Body) -> Option<[f32; 3]> { + b.color().or_else(|| { + let faces = &b.paint()?.faces; + let first = faces.first()?.color; + (faces.len() == b.face_count() && faces.iter().all(|f| f.color == first)).then_some(first) + }) +} + +/// [`exact_boxes`] and the cylinder: radius 6 mm, 15 mm high at x = 80 mm. +fn all_boxes() -> Vec<[i64; 6]> { + let mut want = exact_boxes(); + want.push(um([74.0, -6.0, 0.0, 86.0, 6.0, 15.0])); + want.sort(); + want +} + +/// `file.export` writes STEP and IGES with SolidCraft's own writers unless `writer: cadmpeg` +/// asks for cadmpeg's. Each file, by either writer, reads back through SolidCraft's reader (and a +/// STEP file through cadmpeg's too) with every body where the design shows it, the volume the +/// design's dimensions give and the cylinder in its colour. The default writes the same file as +/// `writer: solidcraft`, which is not cadmpeg's. +#[test] +fn file_export_writes_step_and_iges_with_either_writer() { + let (dir, _) = file("step-writer", "unused", b""); + let mut s = parts(); + let volume_want = 1000.0 + 2.0 * (4000.0 + 1000.0) + CYLINDER_VOLUME_MM3; + let blue = [0.0, 64.0 / 255.0, 1.0]; + for ext in ["step", "igs"] { + let mut texts = Vec::new(); + for writer in [None, Some("solidcraft"), Some(" CadMpeg ")] { + let path = dir.join(format!("parts-{}.{ext}", writer.map_or("default", str::trim))).to_string_lossy().to_string(); + let mut p = json!({"path": path}); + if let Some(w) = writer { + p["writer"] = json!(w); + } + let out = run(&mut s, "file.export", p); + assert_eq!(out["format"], if ext == "step" { "Step" } else { "Iges" }, "{out}"); + let text = std::fs::read_to_string(&path).unwrap(); + // cadmpeg's writers name themselves in the file's header; SolidCraft's do not. + assert_eq!(text.contains("cadmpeg"), writer.is_some_and(|w| w.trim().eq_ignore_ascii_case("cadmpeg")), "{ext} {writer:?}"); + texts.push(text); + let readers: &[&str] = if ext == "step" { &["solidcraft", "cadmpeg"] } else { &["solidcraft"] }; + for reader in readers { + let mut back = Session::default(); + run(&mut back, "file.insert_step", json!({"path": path, "reader": reader})); + assert_eq!(shown_boxes(&back), all_boxes(), "{ext} {writer:?} {reader}"); + assert!((volume(&mut back) - volume_want).abs() < 1e-3, "{ext} {writer:?} {reader}"); + let world = back.world_state().unwrap(); + // Names need not survive every writer: the cylinder is the body with its box. + let cylinder = world + .bodies + .iter() + .find(|b| { + let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox; + [bb.min.x, bb.min.y, bb.min.z, bb.max.x, bb.max.y, bb.max.z].map(|v| (v * 1e3).round() as i64) + == um([74.0, -6.0, 0.0, 86.0, 6.0, 15.0]) + }) + .unwrap_or_else(|| panic!("{ext} {writer:?} {reader}: no cylinder body")); + let colour = colour_of(&cylinder.body).unwrap_or_else(|| panic!("{ext} {writer:?} {reader}: the cylinder is not coloured")); + for (got, want) in colour.iter().zip(blue) { + assert!((f64::from(*got) - want).abs() < 1e-3, "{ext} {writer:?} {reader}: the cylinder's colour: {colour:?}"); + } + assert_eq!( + world + .bodies + .iter() + .filter(|b| colour_of(&b.body).is_some_and(|c| c.iter().zip(blue).all(|(g, w)| (f64::from(*g) - w).abs() < 1e-3))) + .count(), + 1, + "{ext} {writer:?} {reader}: only the cylinder is blue" + ); + } + } + // The default and `solidcraft` write the same file but for the header's time stamp. + let body = |t: &str| t.split_once("DATA;").or_else(|| t.split_once("S 1")).map(|(_, b)| b.to_string()).unwrap_or_default(); + assert_eq!(body(&texts[0]).lines().count(), body(&texts[1]).lines().count(), "{ext}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// `writer` is for STEP and IGES only, and takes solidcraft or cadmpeg; anything else is refused +/// before a file is written. +#[test] +fn the_writer_option_is_refused_where_it_does_not_apply() { + let (dir, _) = file("step-writer-refused", "unused", b""); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30})); + for (name, writer) in + [("a.stl", "cadmpeg"), ("a.3mf", "solidcraft"), ("a.usda", "cadmpeg"), ("a.3dm", "cadmpeg"), ("a.step", "other"), ("a.igs", "")] + { + let path = dir.join(name).to_string_lossy().to_string(); + let e = s.execute("file.export", &json!({"path": path, "writer": writer})).expect_err(name).to_string(); + assert!(e.contains("`writer`"), "{name}: {e}"); + assert!(!std::path::Path::new(&path).exists(), "{name}"); + } + let path = dir.join("a.step").to_string_lossy().to_string(); + let e = s.execute("file.export", &json!({"path": path, "writer": 1})).expect_err("a number").to_string(); + assert!(e.contains("`writer`"), "{e}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/src/tests/openusd.rs b/crates/engine/src/tests/openusd.rs index 6a85ce2de40..0e5cbb00856 100644 --- a/crates/engine/src/tests/openusd.rs +++ b/crates/engine/src/tests/openusd.rs @@ -8,11 +8,57 @@ use serde_json::json; use super::run; use crate::*; -fn temp_dir(tag: &str) -> std::path::PathBuf { +/// A test's temporary directory, removed when dropped, so a failed assertion cleans up too. +struct TempDir(std::path::PathBuf); + +impl AsRef for TempDir { + fn as_ref(&self) -> &std::path::Path { + &self.0 + } +} + +impl std::ops::Deref for TempDir { + type Target = std::path::Path; + + fn deref(&self) -> &std::path::Path { + &self.0 + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn temp_dir(tag: &str) -> TempDir { let dir = std::env::temp_dir().join(format!("solidcraft-usd-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); - dir + TempDir(dir) +} + +/// The members of a `.usdz` package, by name. +fn usdz_members(bytes: &[u8]) -> std::collections::BTreeMap> { + use std::io::Read as _; + let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).expect("a .usdz package is a ZIP archive"); + let mut members = std::collections::BTreeMap::new(); + for i in 0..archive.len() { + let mut entry = archive.by_index(i).unwrap(); + let name = entry.name().unwrap().into_owned(); + let mut data = Vec::new(); + entry.read_to_end(&mut data).unwrap(); + members.insert(name, data); + } + members +} + +/// Image `bytes` in a file of their own in the caller's directory, as `canvas.decal` and +/// `canvas.insert` take an image. +fn picture_file(dir: &std::path::Path, bytes: &[u8]) -> String { + let path = dir.join("picture.png"); + std::fs::write(&path, bytes).unwrap(); + path.to_string_lossy().into_owned() } /// World bounding boxes of every shown body, rounded to 0.01 mm (USD mesh points are single @@ -100,6 +146,15 @@ fn an_assembly_exports_to_openusd_and_reads_back_in_place() { } let e = s.execute("file.export", &json!({"path": path, "format": "usda"})).unwrap_err().to_string(); assert!(e.contains("disagrees with the path's extension"), "{e}"); + // A format SolidCraft writes itself, named, is written whatever the extension, as it always + // was; another format cadmpeg writes is not written under an OpenUSD name. + let stl = dir.join("named-stl.usda").to_string_lossy().to_string(); + assert_eq!(run(&mut s, "file.export", json!({"path": stl, "format": "stl"}))["format"], "StlBinary"); + assert!(!std::fs::read(&stl).unwrap().starts_with(b"#usda")); + let rhino = dir.join("named-rhino.usda").to_string_lossy().to_string(); + let e = s.execute("file.export", &json!({"path": rhino, "format": "3dm"})).unwrap_err().to_string(); + assert!(e.contains("disagrees with the path's extension"), "{e}"); + assert!(!std::path::Path::new(&rhino).exists()); // Chosen bodies only. let path = dir.join("loose.usda").to_string_lossy().to_string(); run(&mut s, "file.export", json!({"path": path, "bodies": ["Loose"]})); @@ -240,3 +295,643 @@ fn exact_geometry_stands_a_y_up_stage_up() { } let _ = std::fs::remove_dir_all(&dir); } + +/// The points of every `Mesh` prim of a text layer. +fn mesh_points(text: &str) -> usize { + // A long array goes on over several lines, up to its closing bracket. + text.split("point3f[] points = [").skip(1).map(|rest| rest.split(']').next().unwrap_or("").matches('(').count()).sum() +} + +/// `quality` is the export's Mesh quality, as for STL: a finer one writes more points for a +/// cylinder, whose round faces are what it refines. +#[test] +fn mesh_quality_changes_the_points_written() { + let dir = temp_dir("quality"); + let mut s = Session::default(); + run(&mut s, "solid.cylinder", json!({"radius": 20, "height": 10, "body_name": "Disc"})); + let mut points = Vec::new(); + for quality in ["standard", "fine"] { + let path = dir.join(format!("{quality}.usda")).to_string_lossy().to_string(); + let out = run(&mut s, "file.export", json!({"path": path, "quality": quality})); + assert_eq!(out["format"], "Usd", "{out}"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("def BrepArray"), "the exact shape goes with the mesh:\n{text}"); + points.push(mesh_points(&text)); + } + assert!(points[0] > 0 && points[1] > points[0], "fine writes more points than standard: {points:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A mesh body (an inserted STL) has no exact shape: it is written as its mesh alone, and reads +/// back as the same box. +#[test] +fn a_mesh_body_exports_as_a_mesh() { + let dir = temp_dir("meshbody"); + let stl = dir.join("cube.stl").to_string_lossy().to_string(); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 20, "height": 30})); + run(&mut s, "file.save_mesh", json!({"path": stl})); + let mut s = Session::default(); + run(&mut s, "file.insert_mesh", json!({"path": stl})); + assert!(s.world_state().unwrap().bodies.iter().all(|b| b.body.is_mesh())); + let path = dir.join("cube.usda").to_string_lossy().to_string(); + let out = run(&mut s, "file.export", json!({"path": path})); + assert!(out.get("warnings").is_none_or(|w| w.as_array().is_some_and(Vec::is_empty)), "{out}"); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("def Mesh") && !text.contains("def BrepArray"), "{text}"); + let mut back = Session::default(); + run(&mut back, "file.insert_mesh", json!({"path": path})); + assert_eq!(shown_boxes(&back), vec![mm([0.0, 0.0, 0.0, 10.0, 20.0, 30.0])]); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A placement that mirrors (not a rigid one) is not written as one: every body is written where +/// the design shows it, with a warning naming the occurrence, and reads back there. +#[test] +fn a_mirroring_placement_writes_the_bodies_where_they_are_shown() { + let dir = temp_dir("mirror"); + let mut s = bracket(); + let o = s.doc_mut().occurrences.iter_mut().find(|o| o.name.starts_with("Bracket")).unwrap(); + o.transform[0][0] = -1.0; + let name = o.name.clone(); + let shown = shown_boxes(&s); + assert_ne!(shown, bracket_boxes(), "the mirror moves the first bracket"); + let path = dir.join("mirror.usda").to_string_lossy().to_string(); + let out = run(&mut s, "file.export", json!({"path": path})); + assert!(out["warnings"].to_string().contains(&name), "{out}"); + let mut back = Session::default(); + run(&mut back, "file.insert_mesh", json!({"path": path})); + assert_eq!(shown_boxes(&back), shown); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A component moved and not captured yet is written where the design shows it, in the +/// assembly as when the bodies are chosen by name. +#[test] +fn an_uncaptured_move_is_written_where_it_is_shown() { + let dir = temp_dir("moved"); + let mut s = bracket(); + let o = s.doc.occurrences.iter().find(|o| o.name.starts_with("Bracket")).unwrap(); + let mut moved = o.transform; + moved[3][0] += 25.0; + s.pending_moves.insert(o.id, moved); + let shown = shown_boxes(&s); + assert_ne!(shown, bracket_boxes(), "the move shows"); + let path = dir.join("moved.usda").to_string_lossy().to_string(); + let out = run(&mut s, "file.export", json!({"path": path})); + assert!(out.get("warnings").is_none_or(|w| w.as_array().is_some_and(Vec::is_empty)), "{out}"); + let mut back = Session::default(); + run(&mut back, "file.insert_mesh", json!({"path": path})); + assert_eq!(shown_boxes(&back), shown); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The text of the `Xform` prim named `name` in `text`: from its `def` to its closing brace. +fn prim<'a>(text: &'a str, name: &str) -> &'a str { + let start = text.find(&format!("def Xform \"{name}\"")).unwrap_or_else(|| panic!("no {name} prim:\n{text}")); + let mut depth = 0usize; + for (i, c) in text[start..].char_indices() { + match c { + '{' => depth += 1, + '}' if depth == 1 => return &text[start..=start + i], + '}' => depth = depth.saturating_sub(1), + _ => {} + } + } + panic!("{name}'s prim does not close:\n{text}") +} + +/// A body the view hides is written invisible. A body a render setup gives optics is written, +/// with a warning naming the body, the setup and what the file leaves out. +#[test] +fn hidden_bodies_are_invisible_and_render_setup_optics_warn() { + let dir = temp_dir("view"); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 3, "body_name": "Glass"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 3, "corner": [20, 0, 0], "operation": "new", "body_name": "Shelf"})); + run( + &mut s, + "render.settings.set", + json!({"name": "Studio", "set": {"width": 4, "height": 4, "job": {"method": "cpu_raytrace", "options": {"lights": [], + "environment": {"color": [1, 1, 1], "intensity": 1}, "progressive": {"samples_per_pixel": 1, "seed": 1}}}}}), + ); + let revision = s.revision; + run( + &mut s, + "render.optics.bind", + json!({"name": "Studio", "body_index": 0, "body_name": "Glass", "expected_revision": revision, + "optics": {"ior": 1.5, "absorption_per_mm": [0.0, 0.0, 0.0], "boundary": "closed_mesh"}}), + ); + run(&mut s, "browser.visibility", json!({"items": ["Shelf"], "visible": false})); + let path = dir.join("view.usda"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy()})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap(); + assert!( + warnings.iter().any(|w| w.starts_with("Glass: render setup `Studio` gives it optics, which OpenUSD export does not write yet")), + "{warnings:?}" + ); + let text = std::fs::read_to_string(&path).unwrap(); + let invisible = "token visibility = \"invisible\""; + assert_eq!(text.matches(invisible).count(), 1, "{text}"); + assert!(prim(&text, "Shelf").contains(invisible), "the Shelf prim holds it:\n{text}"); + assert!(!prim(&text, "Glass").contains(invisible), "Glass stays shown:\n{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The value of the attribute that `line` (such as `float physics:mass =`) starts, in `text` +/// after `from`. +fn value_after(text: &str, from: usize, line: &str) -> Vec { + let rest = &text[from..]; + let at = rest.find(line).unwrap_or_else(|| panic!("no `{line}` after {from}:\n{text}")); + let value = rest[at + line.len()..].lines().next().unwrap_or_default(); + value.split(['(', ')', ',']).filter_map(|v| v.trim().parse().ok()).collect() +} + +/// With `physics`, a jointed placement moved without capturing the move is written where its +/// joints place it, as URDF export writes it, with URDF's warning, so its joint's frames meet as a +/// simulator starts: the file is the one written before the move. +#[test] +fn a_physics_export_writes_jointed_parts_where_their_joints_place_them() { + let dir = temp_dir("physics-moved"); + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + let a = s.doc.occurrence_of(s.doc.find_component("A").unwrap()).unwrap().id; + run(&mut s, "occurrence.ground", json!({"occurrence": a, "grounded": true})); + run(&mut s, "joint.create", json!({"type": "revolute", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "name": "Hinge"})); + let before = dir.join("before.usda"); + run(&mut s, "file.export", json!({"path": before.to_string_lossy(), "physics": true})); + let b = s.doc.occurrence_of(s.doc.find_component("B").unwrap()).unwrap(); + let (id, name) = (b.id, b.name.clone()); + let mut moved = b.transform; + moved[3][0] += 20.0; + s.pending_moves.insert(id, moved); + let after = dir.join("after.usda"); + let reply = run(&mut s, "file.export", json!({"path": after.to_string_lossy(), "physics": true})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap_or_default(); + assert!( + warnings.iter().any(|w| w == &format!("`{name}` was moved but the move is not captured: exported where its joints place it")), + "{warnings:?}" + ); + assert_eq!(std::fs::read_to_string(&after).unwrap(), std::fs::read_to_string(&before).unwrap()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With `physics`, an export of chosen bodies writes no physics, so a jointed placement moved +/// without capturing the move is written where the design shows it, as without `physics`, and +/// nothing says it was exported where its joints place it. +#[test] +fn a_physics_export_of_chosen_bodies_writes_them_where_they_are_shown() { + let dir = temp_dir("physics-chosen"); + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + let a = s.doc.occurrence_of(s.doc.find_component("A").unwrap()).unwrap().id; + run(&mut s, "occurrence.ground", json!({"occurrence": a, "grounded": true})); + run(&mut s, "joint.create", json!({"type": "revolute", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "name": "Hinge"})); + let b = s.doc.occurrence_of(s.doc.find_component("B").unwrap()).unwrap(); + let id = b.id; + let mut moved = b.transform; + moved[3][0] += 20.0; + s.pending_moves.insert(id, moved); + let world = s.world_state().unwrap(); + let body = world.bodies.iter().find(|b| solidcraft_kernel::measure(&b.body).unwrap().bbox.min.x > 15.0).expect("the moved body").name.clone(); + let export = |s: &mut Session, name: &str, physics: bool| { + let path = dir.join(name); + let reply = run(s, "file.export", json!({"path": path.to_string_lossy(), "bodies": [body.clone()], "physics": physics})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap_or_default(); + (std::fs::read_to_string(&path).unwrap(), warnings) + }; + let (with, warnings) = export(&mut s, "with.usda", true); + assert!(!warnings.iter().any(|w| w.contains("exported where its joints place it")), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.contains("no physics is written")), "{warnings:?}"); + let (without, _) = export(&mut s, "without.usda", false); + assert_eq!(with, without); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With `physics`, the joints, the grounded placement and each component's mass are written as +/// OpenUSD physics: a revolute joint with its limits in degrees, the grounded placement fixed to +/// the world, and a 10 mm cube's mass, centre and inertia from its density. A joint with no +/// OpenUSD form is left out with a warning. Without `physics`, none of it is written. +#[test] +fn physics_writes_joints_grounding_and_mass() { + let dir = temp_dir("physics"); + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20), ("C", 40)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + let a = s.doc.occurrence_of(s.doc.find_component("A").unwrap()).unwrap().id; + run(&mut s, "occurrence.ground", json!({"occurrence": a, "grounded": true})); + run( + &mut s, + "joint.create", + json!({"type": "revolute", "a": {"face": [5, 5, 10]}, "b": {"face": [25, 5, 0]}, "limits": [[-0.5, 1.0]], "name": "Hinge"}), + ); + run(&mut s, "joint.create", json!({"type": "pin_slot", "a": {"face": [25, 5, 10]}, "b": {"face": [45, 5, 0]}, "name": "Slot"})); + let path = dir.join("physics.usda"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy(), "physics": true})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap(); + assert!(warnings.iter().any(|w| w.starts_with("joint `Slot`: a PinSlot joint has no OpenUSD physics form")), "{warnings:?}"); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text.matches("def PhysicsRevoluteJoint").count(), 1, "{text}"); + assert_eq!(text.matches("def PhysicsFixedJoint").count(), 1, "the grounded A:\n{text}"); + // The grounded A roots the articulation of A and B, jointed by the hinge; C's joint has no + // OpenUSD form, so C is in none. + let a_prim = text.find("\"A_1\"").unwrap_or_else(|| panic!("no A_1 prim:\n{text}")); + let a_head = &text[a_prim..a_prim + text[a_prim..].find('{').unwrap_or(0)]; + assert!(a_head.contains("PhysicsArticulationRootAPI"), "{text}"); + assert_eq!(text.matches("PhysicsArticulationRootAPI").count(), 1, "{text}"); + let hinge = text.find("def PhysicsRevoluteJoint").unwrap(); + let lower = value_after(&text, hinge, "float physics:lowerLimit = "); + let upper = value_after(&text, hinge, "float physics:upperLimit = "); + // `joint.create` takes the limits in degrees, as written. + let saved = s.doc.assembly.joints.iter().find(|j| j.name == "Hinge").unwrap().limits[0].unwrap(); + assert!((saved.0.to_degrees() + 0.5).abs() < 1e-9 && (saved.1.to_degrees() - 1.0).abs() < 1e-9, "{saved:?}"); + assert!((lower[0] + 0.5).abs() < 1e-4 && (upper[0] - 1.0).abs() < 1e-4, "{lower:?} {upper:?}"); + // B: a 10 mm cube (1 cm³) of its material's density (g/cm³), centred at (25, 5, 5) mm in its + // frame; about its centre each moment is m a² / 6. The stage is in kg and metres. + let body = s.model.state().bodies.iter().find(|b| s.doc.model_body_component(b) == s.doc.find_component("B").unwrap()).unwrap().name.clone(); + let mass = s.doc.density(&body) * 1e-3; + let b = text.find("\"B").unwrap_or_else(|| panic!("no B prim:\n{text}")); + let got = value_after(&text, b, "float physics:mass = "); + assert!((got[0] - mass).abs() < 1e-6 * mass.max(1.0), "{got:?} is not {mass}"); + let com = value_after(&text, b, "point3f physics:centerOfMass = "); + assert_eq!(com.len(), 3, "{com:?}"); + for (g, w) in com.iter().zip([0.025, 0.005, 0.005]) { + assert!((g - w).abs() < 1e-6, "{com:?}"); + } + let inertia = value_after(&text, b, "float3 physics:diagonalInertia = "); + assert_eq!(inertia.len(), 3, "{inertia:?}"); + let moment = mass * 0.01 * 0.01 / 6.0; + for g in &inertia { + assert!((g - moment).abs() < 1e-3 * moment, "{inertia:?} is not {moment} each"); + } + + let plain = dir.join("plain.usda"); + run(&mut s, "file.export", json!({"path": plain.to_string_lossy()})); + let text = std::fs::read_to_string(&plain).unwrap(); + assert!(!text.contains("Physics"), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With `physics`, gears and a rack couple their joints as PhysX does: G1 (radius 10) meshing G2 +/// (radius 20) turns it half as far the other way, a PhysX gear joint of ratio 0.5 from G1's +/// hinge to G2's; a 10 mm pinion moves its rack 10 mm per radian, 0.1 rad/mm, which the stage +/// writes in degrees per metre. An internal gear turns its mate the same way, which PhysX's gear +/// joint does not: it is left out with a warning. +#[test] +fn physics_writes_gears_and_racks_as_couplings() { + let dir = temp_dir("gears"); + let mut s = Session::default(); + let part = |s: &mut Session, name: &str, solid: &str, p: Value| { + run(s, "component.activate", json!({"component": "root"})); + run(s, "component.create", json!({"name": name, "grounded": false})); + run(s, solid, p); + }; + part(&mut s, "Base", "solid.box", json!({"length": 120, "width": 60, "height": 10, "corner": [-30, -30, -20]})); + for (name, x, r) in [("G1", 0, 10), ("G2", 30, 20), ("G3", 65, 15)] { + part(&mut s, name, "solid.cylinder", json!({"base": [x, 0, 0], "axis": [0, 0, 1], "radius": r, "height": 5})); + } + part(&mut s, "Rack", "solid.box", json!({"length": 40, "width": 4, "height": 4, "corner": [-20, -14, 0]})); + run(&mut s, "component.activate", json!({"component": "root"})); + let base = s.doc.occurrence_of(s.doc.find_component("Base").unwrap()).unwrap().id; + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + let pin = |s: &mut Session, kind: &str, name: &str, b: &str, p: [f64; 3], z: [f64; 3]| { + let at = |o: &str| json!({"occurrence": o, "point": p, "z": z}); + run(s, "joint.create", json!({"type": kind, "a": at("Base"), "b": at(b), "flip": true, "name": name})); + }; + pin(&mut s, "revolute", "H1", "G1", [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]); + pin(&mut s, "revolute", "H2", "G2", [30.0, 0.0, 0.0], [0.0, 0.0, 1.0]); + pin(&mut s, "revolute", "H3", "G3", [65.0, 0.0, 0.0], [0.0, 0.0, 1.0]); + pin(&mut s, "slider", "Rail", "Rack", [0.0, -10.0, 0.0], [1.0, 0.0, 0.0]); + run(&mut s, "joint.gear", json!({"a": "H1", "b": "H2", "ra": 10, "rb": 20})); + run(&mut s, "joint.rack_pinion", json!({"a": "H1", "b": "Rail", "radius": 10})); + run(&mut s, "joint.gear", json!({"a": "H2", "b": "H3", "ra": 20, "rb": 15, "internal": true})); + let path = dir.join("gears.usda"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy(), "physics": true})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap(); + assert!(warnings.iter().any(|w| w.starts_with("motion link 3 between `H2` and `H3`: its gears turn the same way")), "{warnings:?}"); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text.matches("def PhysxPhysicsGearJoint").count(), 1, "{text}"); + assert_eq!(text.matches("def PhysxPhysicsRackAndPinionJoint").count(), 1, "{text}"); + // Each coupled joint: the revolute or prismatic joint whose prim the relationship names, + // found by the part its B side moves. + let target = |at: usize, rel: &str| -> String { + let rest = &text[at..]; + let line = rest[rest.find(rel).unwrap_or_else(|| panic!("no {rel}:\n{text}"))..].lines().next().unwrap(); + line[line.find('<').unwrap() + 1..line.find('>').unwrap()].to_string() + }; + let moves = |joint: &str| -> String { + let name = joint.rsplit('/').next().unwrap(); + let at = text.find(&format!("\"{name}\"")).unwrap_or_else(|| panic!("no {joint}:\n{text}")); + target(at, "rel physics:body1 = ") + }; + // Each coupling is named after the joints it couples. + assert!(text.contains("def PhysxPhysicsGearJoint \"H1_H2\""), "{text}"); + assert!(text.contains("def PhysxPhysicsRackAndPinionJoint \"H1_Rail\""), "{text}"); + let gear = text.find("def PhysxPhysicsGearJoint").unwrap(); + assert!((value_after(&text, gear, "float physics:gearRatio = ")[0] - 0.5).abs() < 1e-6, "{text}"); + assert!(moves(&target(gear, "rel physics:hinge0 = ")).ends_with("/G1_1"), "{text}"); + assert!(moves(&target(gear, "rel physics:hinge1 = ")).ends_with("/G2_1"), "{text}"); + let rack = text.find("def PhysxPhysicsRackAndPinionJoint").unwrap(); + let ratio = 0.1 * 1000.0 * 180.0 / std::f64::consts::PI; + assert!((value_after(&text, rack, "float physics:ratio = ")[0] - ratio).abs() < 1e-3, "{text}"); + assert!(moves(&target(rack, "rel physics:hinge = ")).ends_with("/G1_1"), "{text}"); + assert!(moves(&target(rack, "rel physics:prismatic = ")).ends_with("/Rack_1"), "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A gear coupling joins the two gears, the parts its hinges turn, whichever side of each hinge +/// the grounded base is on: here B of one hinge and A of the other. +#[test] +fn a_gear_coupling_joins_the_gears_whichever_side_the_base_is_on() { + let dir = temp_dir("gears-sides"); + let mut s = Session::default(); + let part = |s: &mut Session, name: &str, solid: &str, p: Value| { + run(s, "component.activate", json!({"component": "root"})); + run(s, "component.create", json!({"name": name, "grounded": false})); + run(s, solid, p); + }; + part(&mut s, "Base", "solid.box", json!({"length": 120, "width": 60, "height": 10, "corner": [-30, -30, -20]})); + for (name, x, r) in [("G1", 0, 10), ("G2", 30, 20)] { + part(&mut s, name, "solid.cylinder", json!({"base": [x, 0, 0], "axis": [0, 0, 1], "radius": r, "height": 5})); + } + run(&mut s, "component.activate", json!({"component": "root"})); + let base = s.doc.occurrence_of(s.doc.find_component("Base").unwrap()).unwrap().id; + run(&mut s, "occurrence.ground", json!({"occurrence": base, "grounded": true})); + let at = |o: &str, p: [f64; 3]| json!({"occurrence": o, "point": p, "z": [0.0, 0.0, 1.0]}); + run(&mut s, "joint.create", json!({"type": "revolute", "a": at("Base", [0.0; 3]), "b": at("G1", [0.0; 3]), "flip": true, "name": "H1"})); + let p2 = [30.0, 0.0, 0.0]; + run(&mut s, "joint.create", json!({"type": "revolute", "a": at("G2", p2), "b": at("Base", p2), "flip": true, "name": "H2"})); + run(&mut s, "joint.gear", json!({"a": "H1", "b": "H2", "ra": 10, "rb": 20})); + let path = dir.join("gears.usda"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy(), "physics": true})); + let text = std::fs::read_to_string(&path).unwrap(); + let at = text.find("def PhysxPhysicsGearJoint").unwrap_or_else(|| panic!("no gear joint: {reply}\n{text}")); + let rest = &text[at + 1..]; + let gear = &rest[..rest.find("\n def ").unwrap_or(rest.len())]; + let body = |rel: &str| -> String { + let line = gear[gear.find(rel).unwrap_or_else(|| panic!("no {rel}:\n{gear}"))..].lines().next().unwrap(); + line[line.find('<').unwrap() + 1..line.find('>').unwrap()].to_string() + }; + let bodies = [body("rel physics:body0 = "), body("rel physics:body1 = ")]; + assert!(bodies.iter().any(|b| b.ends_with("/G1_1")) && bodies.iter().any(|b| b.ends_with("/G2_1")), "{bodies:?}\n{gear}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A built-in surface bound in a render setup is written into an OpenUSD package with +/// `render_setup`: its four images are members and the body's mesh has coordinates. +#[cfg(feature = "bundled-render-library")] +#[test] +fn a_render_setups_builtin_surface_is_packaged() { + let dir = temp_dir("surface"); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 2, "body_name": "Coupon"})); + run( + &mut s, + "render.library.surface.bind", + json!({"name": "Maps", "set": {"job": {"method": "gpu_path", "options": {}}}, "surface": {"id": "SURF-001", "body_index": 0, "body_name": "Coupon"}}), + ); + let path = dir.join("coupon.usdz"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy(), "render_setup": "Maps"})); + // The reply leaves out an empty list of warnings. + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap_or_default(); + assert!(warnings.is_empty(), "{warnings:?}"); + // A package is a ZIP archive: its texture members are entries with image bytes. + let bytes = std::fs::read(&path).unwrap(); + let members = usdz_members(&bytes); + let textures: Vec<&String> = members.keys().filter(|name| name.starts_with("textures/")).collect(); + assert_eq!(textures.len(), 4, "{textures:?}"); + for name in textures { + let image = &members[name]; + assert!(image.starts_with(b"\x89PNG") || image.starts_with(&[0xFF, 0xD8]), "{name}: no image bytes"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// Without the built-in surfaces' images in the build, the body is written with its look, and a +/// warning says so; a setup that does not exist is refused. +#[test] +fn a_render_setup_without_its_images_warns_and_a_missing_setup_is_refused() { + let dir = temp_dir("nosurface"); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 2, "body_name": "Coupon"})); + let path = dir.join("coupon.usdz"); + let refused = s.execute("file.export", &json!({"path": path.to_string_lossy(), "render_setup": "Nowhere"})); + assert!(refused.unwrap_err().to_string().contains("no render setup named `Nowhere`")); + let refused = s.execute("file.export", &json!({"path": dir.join("c.stl").to_string_lossy(), "render_setup": "Maps"})); + assert!(refused.unwrap_err().to_string().contains("`render_setup` is for OpenUSD")); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The `points` of mesh prim `prim` in `text`, in millimetres. +fn decal_points(text: &str, prim: &str) -> Vec<[f64; 3]> { + // The decal's material has its name too: the mesh prim is the one to read. + let at = text.find(&format!("def Mesh \"{prim}\"")).unwrap_or_else(|| panic!("no {prim} mesh:\n{text}")); + let rest = &text[at..]; + let start = rest.find("point3f[] points = [").unwrap() + "point3f[] points = [".len(); + let body = &rest[start..start + rest[start..].find(']').unwrap()]; + let values: Vec = body.split(['(', ')', ',']).filter_map(|v| v.trim().parse().ok()).collect(); + values.chunks(3).map(|p| [p[0] * 1e3, p[1] * 1e3, p[2] * 1e3]).collect() +} + +/// With `images`, an OpenUSD package holds each shown picture as a two-sided quad with its image, +/// in its component, 0.2 mm off the face on each side; the image is a member of the package. A +/// hidden picture is not written, nor any picture without `images`, and a text layer warns. +#[test] +fn images_write_the_shown_pictures_into_a_package() { + use image::ImageEncoder; + let dir = temp_dir("decals"); + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20)] { + run(&mut s, "component.activate", json!({"component": "root"})); + run(&mut s, "component.create", json!({"name": name})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0]})); + } + run(&mut s, "component.activate", json!({"component": "B"})); + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png).write_image(&[200u8; 4 * 8], 4, 2, image::ExtendedColorType::Rgba8).unwrap(); + let file = picture_file(&dir, &png); + run(&mut s, "canvas.decal", json!({"path": file, "face": [25, 5, 10], "width": 8, "name": "Logo"})); + run(&mut s, "canvas.insert", json!({"path": file, "plane": "XY", "width": 8, "name": "Hidden"})); + run(&mut s, "canvas.edit", json!({"canvas": "Hidden", "visible": false})); + + let path = dir.join("decals.usdz"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy(), "images": true})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap_or_default(); + assert!(warnings.is_empty(), "{warnings:?}"); + // A package is a ZIP archive: the layer is an entry, and the picture is a member with bytes. + let bytes = std::fs::read(&path).unwrap(); + let members = usdz_members(&bytes); + let text = String::from_utf8(members["root.usda"].clone()).unwrap(); + let image = format!("textures/{}.png", solidcraft_doc::render_resources::HdrId::of(&png)); + assert!(members.get(&image).is_some_and(|data| !data.is_empty()), "no {image} member"); + assert!(!text.contains("\"Hidden\""), "the hidden picture is written"); + // Worked out by hand: B is placed where it was built. The decal is 8 x 4 mm (the image is 2:1) + // about (25, 5) on B's top face at z = 10, along the face's axes either way round; the front + // quad 0.2 mm above the face, the back quad 0.2 mm below. + let corners = decal_points(&text, "Logo"); + assert_eq!(corners.len(), 8, "{corners:?}"); + let plan = |c: &[[f64; 3]]| { + let mut xy: Vec<(i64, i64)> = c.iter().map(|p| ((p[0] * 1e3).round() as i64, (p[1] * 1e3).round() as i64)).collect(); + xy.sort(); + xy + }; + let along_x = [(21000, 3000), (21000, 7000), (29000, 3000), (29000, 7000)]; + let along_y = [(23000, 1000), (23000, 9000), (27000, 1000), (27000, 9000)]; + let front = plan(&corners[..4]); + assert!(front == along_x || front == along_y, "{corners:?}"); + assert_eq!(plan(&corners[4..]), front); + assert!(corners[..4].iter().all(|p| (p[2] - 10.2).abs() < 1e-3) && corners[4..].iter().all(|p| (p[2] - 9.8).abs() < 1e-3), "{corners:?}"); + + let plain = dir.join("plain.usdz"); + run(&mut s, "file.export", json!({"path": plain.to_string_lossy()})); + assert!(!String::from_utf8_lossy(&std::fs::read(&plain).unwrap()).contains("\"Logo\"")); + let layer = dir.join("decals.usda"); + let reply = run(&mut s, "file.export", json!({"path": layer.to_string_lossy(), "images": true})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap_or_default(); + assert!(warnings.iter().any(|w| w.contains("written only in a .usdz package")), "{warnings:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// With `render_setup`, a body the setup gives optics is written as glass: the preview surface's +/// index of refraction, and the MaterialX shader's full transmission, with the colour 1 mm of the +/// absorption leaves (e^(−a)) at a depth of 1 mm; a warning says a reader of the preview surface +/// alone shows it opaque. +#[test] +fn render_setup_optics_are_written_as_transmission() { + let dir = temp_dir("optics"); + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 3, "body_name": "Pane"})); + run( + &mut s, + "render.settings.set", + json!({"name": "Glass", "set": {"width": 4, "height": 4, "job": {"method": "cpu_raytrace", "options": {"lights": [], + "environment": {"color": [1, 1, 1], "intensity": 1}, "progressive": {"samples_per_pixel": 1, "seed": 1}}}}}), + ); + let revision = s.revision; + run( + &mut s, + "render.optics.bind", + json!({"name": "Glass", "body_index": 0, "body_name": "Pane", "expected_revision": revision, + "optics": {"ior": 1.52, "absorption_per_mm": [0.1, 0.0, 2.0], "boundary": "closed_mesh"}}), + ); + let path = dir.join("glass.usda"); + let reply = run(&mut s, "file.export", json!({"path": path.to_string_lossy(), "render_setup": "Glass"})); + let warnings: Vec = serde_json::from_value(reply["warnings"].clone()).unwrap_or_default(); + assert!( + warnings.iter().any(|w| w.starts_with("Pane: the optics of render setup `Glass` are written as the MaterialX shader's transmission")), + "{warnings:?}" + ); + let text = std::fs::read_to_string(&path).unwrap(); + let preview = text.find("info:id = \"UsdPreviewSurface\"").unwrap_or_else(|| panic!("no preview surface:\n{text}")); + assert!((value_after(&text, preview, "float inputs:ior = ")[0] - 1.52).abs() < 1e-6, "{text}"); + let pbr = text.find("info:id = \"ND_open_pbr_surface_surfaceshader\"").unwrap_or_else(|| panic!("no OpenPBR shader:\n{text}")); + assert_eq!(value_after(&text, pbr, "float inputs:transmission_weight = "), [1.0]); + let colour = value_after(&text, pbr, "color3f inputs:transmission_color = "); + assert_eq!(colour.len(), 3, "{colour:?}"); + for (got, want) in colour.iter().zip([(-0.1f64).exp(), 1.0, (-2.0f64).exp()]) { + assert!((got - want).abs() < 1e-6, "{colour:?}"); + } + assert!((value_after(&text, pbr, "float inputs:transmission_depth = ")[0] - 0.001).abs() < 1e-9, "{text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A design with a picture on a 10 mm cube in component B, and a loose cube at the root. +fn pictured(dir: &std::path::Path) -> Session { + use image::ImageEncoder; + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [-30, 0, 0], "body_name": "Loose"})); + run(&mut s, "component.create", json!({"name": "B"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [20, 0, 0]})); + let mut png = Vec::new(); + image::codecs::png::PngEncoder::new(&mut png).write_image(&[200u8; 4 * 8], 4, 2, image::ExtendedColorType::Rgba8).unwrap(); + run(&mut s, "canvas.decal", json!({"path": picture_file(dir, &png), "face": [25, 5, 10], "width": 8, "name": "Logo"})); + run(&mut s, "component.activate", json!({"component": "root"})); + s +} + +/// `purpose: distribution` writes meshes only, with the pictures shown on the model; +/// `interchange` (the default) writes the exact shapes and no pictures; `exact_brep` and +/// `images` override the purpose; `purpose` is for OpenUSD only. +#[test] +fn a_distribution_export_is_meshes_with_pictures() { + let dir = temp_dir("purpose"); + let mut s = pictured(&dir); + let export = |s: &mut Session, name: &str, extra: Value| { + let path = dir.join(name); + let mut p = json!({"path": path.to_string_lossy()}); + for (k, v) in extra.as_object().unwrap() { + p[k] = v.clone(); + } + run(s, "file.export", p); + String::from_utf8_lossy(&std::fs::read(&path).unwrap()).to_string() + }; + let interchange = export(&mut s, "interchange.usdz", json!({})); + assert!(interchange.contains("def BrepArray") && !interchange.contains("\"Logo\""), "{interchange}"); + let distribution = export(&mut s, "distribution.usdz", json!({"purpose": "distribution"})); + assert!(!distribution.contains("BrepArray"), "{distribution}"); + assert_eq!(distribution.matches("def Mesh").count(), 3, "two cubes and the picture:\n{distribution}"); + assert!(distribution.contains("def Mesh \"Logo\""), "{distribution}"); + let exact = export(&mut s, "exact.usdz", json!({"purpose": "distribution", "exact_brep": true, "images": false})); + assert!(exact.contains("def BrepArray") && !exact.contains("\"Logo\""), "{exact}"); + let stl = dir.join("x.stl"); + let refused = s.execute("file.export", &json!({"path": stl.to_string_lossy(), "purpose": "distribution"})); + assert!(refused.unwrap_err().to_string().contains("`purpose` is for OpenUSD")); + let refused = s.execute("file.export", &json!({"path": dir.join("y.usda").to_string_lossy(), "purpose": "print"})); + assert!(refused.unwrap_err().to_string().contains("`purpose` must be interchange or distribution")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn openusd_exports_pass_openusd_validators() { + let dir = temp_dir("validate"); + let mut s = pictured(&dir); + let b = s.doc.occurrence_of(s.doc.find_component("B").unwrap()).unwrap().id; + run(&mut s, "occurrence.ground", json!({"occurrence": b, "grounded": true})); + run(&mut s, "browser.visibility", json!({"items": ["Loose"], "visible": false})); + let mut files = Vec::new(); + for (name, options) in [ + ("interchange.usda", json!({})), + ("interchange.usdc", json!({})), + ("distribution.usdz", json!({"purpose": "distribution"})), + ("physics.usda", json!({"physics": true})), + ] { + let path = dir.join(name); + let mut p = options; + p["path"] = json!(path.to_string_lossy()); + run(&mut s, "file.export", p); + files.push(path); + } + // `SOLIDCRAFT_USD_PYTHON` names a Python that has the bindings: then nothing may skip. + let required = std::env::var("SOLIDCRAFT_USD_PYTHON").ok(); + let python = required.clone().unwrap_or_else(|| "python3".into()); + let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/usd-validate.py"); + let out = std::process::Command::new(&python).arg(&script).args(["--ignore", "MissingShaderIdInRegistry"]).args(&files).output(); + match out { + // Exit 3 is the script's "no bindings, nothing checked"; any other failure, a signal + // included (no exit code), or a file that does not open (2) fails. + Ok(out) if required.is_none() && out.status.code() == Some(3) => { + eprintln!("skipped: {python} has no OpenUSD bindings: {}", String::from_utf8_lossy(&out.stderr)); + } + Ok(out) => assert!(out.status.success(), "{}: {}{}", out.status, String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)), + Err(e) => { + assert!(required.is_none(), "{python} does not run: {e}"); + eprintln!("skipped: {python} does not run: {e}"); + } + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/io/src/formats.rs b/crates/io/src/formats.rs index 569a1efbf55..a55658058c0 100644 --- a/crates/io/src/formats.rs +++ b/crates/io/src/formats.rs @@ -254,7 +254,9 @@ pub static FORMATS: &[FormatSpec] = &[ extensions: &["3dm"], role: Role::Artifact, import: Some(ImportSpec { target: ImportTarget::Brep, options: BREP_IMPORT, native_only: true }), - export: None, + // Written by cadmpeg from the design (`file.export`); FreeCAD is not, as cadmpeg cannot + // write a new FreeCAD file yet. + export: Some(ExportSpec { command: "file.export", format: None, options: &[], scope: ExportScope::Bodies, lossless: false }), }, FormatSpec { id: "kicad", @@ -627,6 +629,9 @@ mod tests { assert_eq!(writes(e), vec!["usd"]); } assert!(writes("gltf").is_empty(), "a .gltf file is never written"); + assert_eq!(writes("3dm"), vec!["3dm"]); + assert_eq!(for_path("a.3DM").map(|f| f.id), Some("3dm")); + assert!(writes("fcstd").is_empty(), "cadmpeg cannot write a new FreeCAD file yet"); assert!(for_path("a.png").is_none()); assert!(for_path("nodot").is_none()); } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index d43c0958b00..3fc3417351d 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -82,10 +82,17 @@ pub mod limits; #[cfg(test)] mod mutate; mod native_cad; +pub use native_cad::CadmpegOptions; +pub use native_cad::DecalPlan; +pub use native_cad::Hidden; pub use native_cad::NATIVE_CAD_EXTS; pub use native_cad::NativeDesign; +pub use native_cad::OpticsPlan; pub use native_cad::RecordsRead; +pub use native_cad::SurfaceMap; +pub use native_cad::SurfacePlan; pub use native_cad::USD_EXTS; +pub use native_cad::cadmpeg_export; pub use native_cad::cadmpeg_iges_records; pub use native_cad::cadmpeg_step_records; pub use native_cad::detects_freecad; @@ -96,7 +103,7 @@ pub use native_cad::native_cad_design; pub use native_cad::native_cad_records; pub use native_cad::native_cad_to_step; pub use native_cad::read_usd; -pub use native_cad::usd_from_step; +pub use native_cad::usd_from_design; pub use native_cad::usd_records; pub mod paper; mod pat; @@ -891,8 +898,15 @@ pub enum Format { /// and decal images; written by the engine, since it is several files. Sdf, /// OpenUSD: `.usda` text, `.usdc` (or `.usd`) binary, or a `.usdz` package, chosen by the - /// file's extension ([`usd_from_step`]); written by the engine from the STEP it writes. + /// file's extension ([`usd_from_design`]); written from the design, which holds the + /// components and looks. Usd, + /// Rhino `.3dm`, written by cadmpeg from the design ([`cadmpeg_export`]): each body's exact + /// shape where cadmpeg's Rhino writer can write it, else its mesh. + Rhino, + /// FreeCAD `.FCStd`: named so that `file.export` can say why it is not written yet (cadmpeg + /// cannot write a new FreeCAD file; [`cadmpeg_export`] refuses it). + FreeCad, } impl Format { @@ -911,6 +925,8 @@ impl Format { "glb" => Format::Glb, "sdf" => Format::Sdf, "usd" | "usda" | "usdc" | "usdz" => Format::Usd, + "3dm" => Format::Rhino, + "fcstd" => Format::FreeCad, e if e == "json" || is_design_ext(e) => Format::Design, _ => return Err(IoError::Format(ext)), }) @@ -1790,6 +1806,8 @@ pub fn export_with_parts_noted( Format::Glb => return Err(IoError::Format("glb (its looks come from the design; use file.export)".into())), Format::Sdf => return Err(IoError::Format("sdf (a model folder; use file.export)".into())), Format::Usd => return Err(IoError::Format("usd (the file's extension picks its encoding; use file.export)".into())), + Format::Rhino => return Err(IoError::Format("3dm (written from the design by cadmpeg; use file.export)".into())), + Format::FreeCad => return Err(IoError::Invalid(native_cad::FREECAD_REFUSED.into())), }; Ok((bytes, notes)) } diff --git a/crates/io/src/native_cad.rs b/crates/io/src/native_cad.rs index c121d26dc9c..666c6c6f977 100644 --- a/crates/io/src/native_cad.rs +++ b/crates/io/src/native_cad.rs @@ -1,6 +1,7 @@ //! Other CAD formats read through [cadmpeg](https://github.com/cadmpeg/cadmpeg): FreeCAD -//! `.FCStd` and Rhino `.3dm`, and OpenUSD both ways ([`usd`]); and STEP and IGES when the -//! cadmpeg reader is chosen ([`cadmpeg_step_records`], [`cadmpeg_iges_records`]). cadmpeg decodes the file into its neutral model (CADIR). By default +//! `.FCStd` files are read, and Rhino `.3dm` and OpenUSD files read and written +//! ([`usd`], [`cadmpeg_export`]); STEP and IGES files are read when the cadmpeg reader is +//! chosen ([`cadmpeg_step_records`], [`cadmpeg_iges_records`]) and written through it. cadmpeg decodes the file into its neutral model (CADIR). By default //! cadmpeg's STEP writer restates that as STEP, which the Import feature then reads and keeps like //! any STEP file ([`native_cad_to_step`]); with [`crate::StepReader::Cadmpeg`] (the Preferences //! switch "Import with cadmpeg", off by default) the model is read straight into B-rep records @@ -11,7 +12,8 @@ //! `sat` codec (a ShapeManager stream decoder that reads ACIS as one dialect), are not built. //! //! This module is the cadmpeg seam: the one place cadmpeg is called, returning the STEP text, the -//! records or the OpenUSD bytes plus warnings. A cadmpeg-based STEP reader could be added here later and chosen by a setting, to +//! records or the exported bytes plus warnings; an export writes the design into cadmpeg's model +//! directly (`cadir_out`) and cadmpeg's writer writes the file (`export`). A cadmpeg-based STEP reader could be added here later and chosen by a setting, to //! compare with our own STEP reader, without changing that reader. /// File extensions read through cadmpeg (lower case). @@ -492,16 +494,163 @@ pub use design::NativeDesign; mod usd; pub use usd::{USD_EXTS, is_usd_path}; -/// `step` (STEP text SolidCraft wrote for the bodies to export) as an OpenUSD file called `file`: -/// `.usda` text, `.usdc` or `.usd` binary, or a `.usdz` package. Returns the file's bytes and what -/// it could not carry. Panics inside cadmpeg become errors. -pub fn usd_from_step(step: &[u8], file: &str) -> Result<(Vec, Vec), String> { - solidcraft_kernel::guard("cadmpeg USD export", || usd::from_step(step, file).map_err(solidcraft_kernel::KernelError::Invalid)).map_err( - |e| match e { - solidcraft_kernel::KernelError::Invalid(m) => m, - e => e.to_string(), - }, - ) +mod cadir_out; +mod cadir_physics; +mod cadir_textures; +mod export; + +/// What the design's view hides, for an export that writes it: bodies by their world name +/// (hidden themselves, by a folder or by a placement above them) and placements by their path +/// (hidden themselves). +#[derive(Clone, Debug, Default)] +pub struct Hidden { + pub bodies: std::collections::BTreeSet, + pub placements: Vec>, +} + +/// The choices of an export through cadmpeg beyond its bodies, file and quality. +#[derive(Clone, Debug, Default)] +pub struct CadmpegOptions { + /// What the design's view hides, written hidden. + pub hidden: Hidden, + /// OpenUSD: the joints, grounding and each component's mass written as physics. + pub physics: bool, + /// OpenUSD: the image textures a render setup gives bodies, written into a `.usdz` package. + pub surfaces: Vec, + /// OpenUSD: the pictures shown on the model (decals), written into a `.usdz` package. + pub decals: Vec, + /// OpenUSD: the optics a render setup gives bodies (glass). + pub optics: Vec, + /// OpenUSD: each body as its mesh alone, without its exact shape (B-rep), for a file a + /// viewer or a game engine shows rather than a CAD program edits. + pub meshes_only: bool, +} + +/// The optics a render setup gives one placement of a body: a dielectric (glass) of index `ior` +/// absorbing `absorption_per_mm` (red, green, blue, per mm) inside, its surface a thin sheet or +/// the boundary of a closed volume. +#[derive(Clone, Debug, PartialEq)] +pub struct OpticsPlan { + /// The render setup's name. + pub setup: String, + /// The body as the design holds it: its definition name and the component holding it (0: + /// the design itself). An export with the design's components matches these and `path`. + pub definition: String, + pub component: u64, + /// The placement bound: its occurrence path from the design (empty for a body of the design + /// itself). + pub path: Vec, + /// The body's world name, which an export of bodies where the design shows them (no + /// components) matches. + pub world: String, + /// The index of refraction. + pub ior: f64, + /// How much of red, green and blue the inside absorbs, per mm. + pub absorption_per_mm: [f64; 3], + /// The surface is a thin sheet, not the boundary of a closed volume. + pub thin_sheet: bool, +} + +/// A picture shown on the model: its image on a quad. +#[derive(Clone, Debug)] +pub struct DecalPlan { + pub name: String, + /// The component it belongs to (0: the design itself). + pub component: u64, + /// Its corners (bottom-left, bottom-right, top-right, top-left) in its component's frame and + /// in the world, mm. + pub local: [[f64; 3]; 4], + pub world: [[f64; 3]; 4], + /// Its PNG or JPEG image, and the image's SHA-256 (hex), naming the file it is written as. + pub image: SurfaceMap, +} + +/// One image map of a [`SurfacePlan`]: its SHA-256 (hex), naming the file it is written as, and its +/// PNG or JPEG bytes. +#[derive(Clone, Debug)] +pub struct SurfaceMap { + pub sha256: String, + pub bytes: std::sync::Arc<[u8]>, +} + +/// The image maps a render setup gives one placement of a body: the textures of the body's look +/// for an OpenUSD export. +#[derive(Clone, Debug)] +pub struct SurfacePlan { + /// The render setup's name. + pub setup: String, + /// The body as the design holds it: its definition name and component. + pub definition: String, + pub component: u64, + /// The placement bound (empty for a body of the design itself) and the body's world name. + pub path: Vec, + pub world: String, + /// The projection, in the body's definition frame (mm): a point `p` is at + /// `((p − origin)·u / |u|², (p − origin)·v / |v|²)` in the images, repeating. + pub origin: [f64; 3], + pub u: [f64; 3], + pub v: [f64; 3], + /// The image's v runs the other way (the built-in surfaces' images are stored so). + pub flip_v: bool, + /// How strongly the normal map tilts the surface, 0 to 1. + pub normal_strength: f64, + pub base_color: Option, + pub normal: Option, + pub roughness: Option, + pub metallic: Option, +} + +impl CadmpegOptions { + /// Whether an export of `bodies` (all when empty) of `doc` writes the physics + /// [`Self::physics`] asks for: only the whole design, with its components, each placed + /// rigidly. Otherwise each body is written where the world shows it, without physics. + pub fn physics_fits(doc: &solidcraft_doc::Document, bodies: &[String]) -> bool { + bodies.is_empty() && !doc.occurrences.is_empty() && doc.occurrences.iter().all(|o| solidcraft_doc::is_placement(&o.transform)) + } +} +pub(crate) use export::FREECAD_REFUSED; + +/// The bodies of `world` (the design's model placed in the world; all of them when `bodies` is +/// empty) as a `format` file called `file`, written by cadmpeg: OpenUSD ([`crate::Format::Usd`], +/// the extension picking the encoding), Rhino ([`crate::Format::Rhino`]), or STEP and IGES +/// ([`crate::Format::Step`], [`crate::Format::Iges`]: SolidCraft's own writers are the default; this is +/// the choice of writing them with cadmpeg); FreeCAD is refused, +/// as cadmpeg cannot write a new FreeCAD file yet. With no bodies chosen, a design with components +/// keeps them where the format holds them: `model`, the model before placing, holds each +/// component's bodies. `options` says what else is written. Meshes are made at `quality`. Returns +/// the file's bytes and what it could not carry (`export` says what each format leaves out). +/// Panics inside cadmpeg become errors. +#[allow(clippy::too_many_arguments)] +pub fn cadmpeg_export( + doc: &solidcraft_doc::Document, + model: &solidcraft_doc::ModelState, + world: &solidcraft_doc::ModelState, + bodies: &[String], + options: &CadmpegOptions, + file: &str, + quality: crate::MeshQuality, + format: crate::Format, +) -> Result<(Vec, Vec), String> { + solidcraft_kernel::guard("cadmpeg export", || { + export::from_design(doc, model, world, bodies, options, file, quality, format).map_err(solidcraft_kernel::KernelError::Invalid) + }) + .map_err(|e| match e { + solidcraft_kernel::KernelError::Invalid(m) => m, + e => e.to_string(), + }) +} + +/// [`cadmpeg_export`] as OpenUSD: `.usda` text, `.usdc` or `.usd` binary, or a `.usdz` package. +pub fn usd_from_design( + doc: &solidcraft_doc::Document, + model: &solidcraft_doc::ModelState, + world: &solidcraft_doc::ModelState, + bodies: &[String], + options: &CadmpegOptions, + file: &str, + quality: crate::MeshQuality, +) -> Result<(Vec, Vec), String> { + cadmpeg_export(doc, model, world, bodies, options, file, quality, crate::Format::Usd) } /// An OpenUSD file (`file` is its name) read for an import of its exact geometry, kept as records diff --git a/crates/io/src/native_cad/cadir_out.rs b/crates/io/src/native_cad/cadir_out.rs new file mode 100644 index 00000000000..57a580296f6 --- /dev/null +++ b/crates/io/src/native_cad/cadir_out.rs @@ -0,0 +1,1354 @@ +//! A design written as cadmpeg's neutral model (CADIR), for the writers cadmpeg has (OpenUSD and +//! Rhino): nothing passes through STEP text on the way. What each writer can hold differs, and +//! [`Writes`] says what the model is built with for it: the product structure or the bodies where +//! the design shows them, a mesh beside each exact shape or only for mesh bodies, looks as +//! appearances or as each body's colour, and colours linear or as SolidCraft keeps them (sRGB). +//! +//! Product structure: each component is a product definition named after it, holding its bodies +//! in its own frame, and each placement of it an occurrence named after the occurrence, placed in +//! its parent's frame (millimetres). CADIR's occurrences are the placed instances, so a component +//! inside a sub-assembly placed twice has an occurrence under each; the definition is still one, +//! and a writer writes a definition placed more than once once. The design itself is the root +//! definition, placed once at the root and named after the design. With bodies chosen, or a +//! placement that is not a rigid one (a mirror, or a number that is not finite), the bodies are +//! written where the design shows them, all in that root definition. +//! +//! Each body: its exact B-rep ([`solidcore_cadir::write_body`], from the body's record), and the +//! mesh the design is drawn with at the export's quality ([`crate::display_mesh_at`]) as a +//! tessellation of it, so the writer writes SolidCraft's mesh rather than meshing again. A mesh +//! body has the mesh alone, as is every body of an export asked for meshes only +//! ([`crate::CadmpegOptions::meshes_only`]). A B-rep CADIR cannot hold yet is written as its mesh, +//! with a warning naming the body. +//! +//! Looks: one appearance per distinct look, named after it, its colour linear (SolidCraft's are +//! sRGB, CADIR's as USD's linear) with the look's opacity as alpha, and the PBR parameters +//! (`metallic`, `roughness`, `ior`, the names `UsdPreviewSurface` gives its inputs) when the look +//! has them. A body's look is bound to the body; a face with a look of its own is bound to a +//! triangle group of the tessellation (the triangles meshed from it). It is not bound to the +//! B-rep face as well: cadmpeg 0.6.12 writes such a binding as a `GeomSubset` under the +//! `BrepArray` prim, which OpenUSD's validation refuses (no family name, and a parent that is not +//! imageable). A writer that takes no mesh beside the exact shape (STEP) has the face's look +//! bound to its B-rep face instead. A body with no look but a colour (an imported one) carries +//! that colour. +//! +//! What the view hides is written hidden: a placement hidden itself as a hidden occurrence, and +//! a body as a hidden body when it is hidden in every shown placement of its component. A body +//! hidden in some of those placements and shown in others is written shown, with a warning: the +//! file gives a component's body one visibility. +//! +//! Body names, for OpenUSD ([`Writes::named_bodies`]): cadmpeg 0.6.12 names the prim of a +//! component's only body after the placement when the component is placed once (the design's own +//! included), so a body named otherwise lost its name. Such a body is put in a definition of its +//! own, named after the component and placed once in the placement, with no offset and the +//! body's name: the file then holds a prim named after the placement and one named after the +//! body. A component placed more than once keeps cadmpeg's form, its only body's prim named after +//! the component: moving the body out would make each placement a component of its own when the +//! file is read back. +//! +//! The design is untrusted: every placement is checked, the placements walked are capped as the +//! design's own walk caps them, and the meshes' size is capped ([`MAX_BYTES`]). + +use std::collections::{BTreeMap, HashMap, HashSet}; + +use cadmpeg_core::text::NonBlankString; +use cadmpeg_ir::appearance::{Appearance, AppearanceBinding, AppearanceTarget}; +use cadmpeg_ir::document::CadIr; +use cadmpeg_ir::ids::{AppearanceId, BodyId, ProductDefinitionId}; +use cadmpeg_ir::math::{Point3, Vector3}; +use cadmpeg_ir::products::{Occurrence, OccurrenceParent, ProductDefinition, ProductDefinitionKind, PrototypeReference}; +use cadmpeg_ir::scalar::{FiniteReal, PositiveLength}; +use cadmpeg_ir::tessellation::{Tessellation, TessellationMesh, TessellationTriangleGroup}; +use cadmpeg_ir::topology::{Body, BodyKind, Color}; +use cadmpeg_ir::transform::Transform; +use solidcraft_doc::appearance::Look; +use solidcraft_doc::{Document, Mat, ModelBody, ModelState}; + +use super::CadmpegOptions; +use crate::MeshQuality; + +/// Largest total size of the meshes written, estimated as the text layer holds them (about 40 +/// bytes a point and 30 a triangle): a model meshed far too finely is refused at the first mesh +/// that passes it, before that mesh goes into the model, as a GLB is +/// ([`crate::glb::MAX_GLB_BYTES`]). Each mesh's own size is bounded by its quality's chord +/// tolerance, which is a fraction of the body's size. +pub(crate) const MAX_BYTES: usize = 1 << 30; +const BYTES_PER_POINT: usize = 40; +const BYTES_PER_TRIANGLE: usize = 30; + +/// Longest name written (prims are named after them). +const MAX_NAME: usize = 128; + +/// What the model is built with for one of cadmpeg's writers. +#[derive(Clone, Copy)] +pub(crate) struct Writes { + /// The format's name, for warnings. + pub label: &'static str, + /// Components as product definitions and placements as occurrences. Without them every body + /// is written where the design shows it, with no product records at all. + pub products: bool, + /// A body with an exact shape carries its mesh too (else only mesh bodies have a mesh). + pub brep_meshes: bool, + /// Meshes are bound to their body; else each is a mesh of its own, with no body record (and + /// no face groups, so a face's own look is not written). + pub bound_meshes: bool, + /// Looks as appearances bound to bodies and faces; else each body's colour alone. + pub appearances: bool, + /// Colours linear (OpenUSD's); else as SolidCraft keeps them, sRGB. + pub linear: bool, + /// Pcurves on planes kept; `false` leaves them out, for a writer that makes them from the + /// edges itself and takes no other. + pub planar_pcurves: bool, + /// A component's only body named other than the prim the writer names after its one + /// placement is put in a definition of its own, so its name reaches the file. + pub named_bodies: bool, + /// Each pcurve states its own parameter range (its coedge's), and each use whether it is + /// declared isoparametric (never, as that is only a hint), for a writer that must have both. + pub stated_pcurves: bool, + /// The writer names each solid after its body; else a warning says the names are not written. + pub solid_names: bool, + /// Whether the writer takes a body's exact shape (the body alone in a model, planned by the + /// writer); a body it refuses is written as its mesh, with a warning naming it and why. + pub admit: Option Result<(), String>>, +} + +impl Writes { + /// OpenUSD: the product structure, each body's exact shape and mesh, looks as materials with + /// linear colours. + pub const USD: Writes = Writes { + label: "OpenUSD", + products: true, + brep_meshes: true, + bound_meshes: true, + appearances: true, + linear: true, + planar_pcurves: true, + named_bodies: true, + stated_pcurves: false, + solid_names: true, + admit: None, + }; +} + +/// A design (or the chosen bodies of it) as CADIR, with what could not be carried. +pub(crate) struct Built { + pub ir: CadIr, + pub warnings: Vec, +} + +/// [`design_for`] for OpenUSD ([`Writes::USD`]). +#[cfg(test)] +pub(crate) fn design( + doc: &Document, + model: &ModelState, + world: &ModelState, + bodies: &[String], + options: &CadmpegOptions, + name: &str, + quality: MeshQuality, +) -> Result { + design_for(doc, model, world, bodies, options, name, quality, Writes::USD) +} + +/// The bodies of `world` (the design's model placed in the world) as CADIR: all of them as the +/// design's product structure when `bodies` is empty and the design has placements (`model`, the +/// model before placing, holds each component's bodies), else the chosen bodies (all when +/// `bodies` is empty) where the world has them, with what `options` asks for. `name` names +/// the root when the design's own name is blank. Each mesh at `quality`. Built for the writer +/// `writes` describes. +#[allow(clippy::too_many_arguments)] +pub(crate) fn design_for( + doc: &Document, + model: &ModelState, + world: &ModelState, + bodies: &[String], + options: &CadmpegOptions, + name: &str, + quality: MeshQuality, + writes: Writes, +) -> Result { + let _span = solidcraft_profile::span("io", "cadir_out.design"); + let root = clean(&doc.name).or_else(|| clean(name)).unwrap_or_else(|| "Design".into()); + let mut b = Builder::new(doc, quality, writes, &options.hidden); + let assembly = bodies.is_empty() && !doc.occurrences.is_empty(); + if assembly && !writes.products { + b.warnings.push(format!( + "the components and placements are not written: cadmpeg's {} writer writes no assemblies, so each body is written where the design shows it", + writes.label + )); + } + let structured = assembly && writes.products; + let unplaced = doc.occurrences.iter().find(|o| !solidcraft_doc::is_placement(&o.transform)); + b.physics = options.physics && writes.products && CadmpegOptions::physics_fits(doc, bodies); + b.surfaces = &options.surfaces; + // A picture is not attached to a body, so a part of the design cannot say which pictures are + // its own: they are written with the whole design only. + if bodies.is_empty() { + b.decals = &options.decals; + } else if !options.decals.is_empty() { + b.warnings.push(format!( + "the {} pictures shown on the model are not written: they are written only with the whole design, as a picture belongs to no body", + options.decals.len() + )); + } + b.optics = &options.optics; + b.meshes_only = options.meshes_only; + if options.physics && !b.physics { + b.warnings + .push("joints and mass are written only for the whole design with its components and rigid placements: no physics is written".into()); + } + match (structured, unplaced) { + (true, None) => b.assembly(model, &root)?, + (true, Some(o)) => { + b.warnings.push(format!( + "{}: its placement is not a rigid one, so every body is written where the design shows it, without the components", + o.name + )); + b.flat(world, bodies, &root)?; + } + (false, _) => b.flat(world, bodies, &root)?, + } + b.finish() +} + +/// A name as written: trimmed, without control characters, at most [`MAX_NAME`] characters; +/// `None` when nothing is left. +fn clean(s: &str) -> Option { + let s: String = s.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME).collect(); + (!s.trim().is_empty()).then(|| s.trim().to_string()) +} + +/// An id of this design's model: `solidcraft:design:#`, the key padded so the model's +/// arenas, sorted by id, keep the order they were made in. +fn id>(kind: &str, key: usize) -> Result { + let s = format!("solidcraft:design:{kind}#{key:09}"); + T::try_from(s.clone()).map_err(|_| format!("{s} is not a CADIR identity")) +} + +/// `m` (column-major, mm) as a CADIR transform, when finite. +fn transform(m: &Mat) -> Option { + let row = |r: usize| [m[0][r], m[1][r], m[2][r], m[3][r]]; + Transform::affine([row(0), row(1), row(2)]) +} + +/// SolidCraft's sRGB colour (bytes) and an opacity as a CADIR colour: linear when `linear` (as +/// OpenUSD's are), else the sRGB values themselves. +fn colour(rgb: [u8; 3], opacity: f64, linear: bool) -> Option { + let channel = |v: u8| if linear { solidcraft_color::srgb::decode8(v) } else { f64::from(v) / 255.0 }; + let [r, g, b] = rgb.map(|v| channel(v).clamp(0.0, 1.0) as f32); + let a = if opacity.is_finite() { opacity.clamp(0.0, 1.0) as f32 } else { 1.0 }; + Color::new(r, g, b, a) +} + +/// What makes two looks one appearance: every value written. +type LookKey = (String, [u8; 3], u64, Option<[u64; 3]>); + +fn look_key(look: &Look) -> LookKey { + let pbr = look.pbr.map(|p| [p.metallic().to_bits(), p.roughness().to_bits(), p.dielectric_ior().to_bits()]); + (look.name.clone(), look.color, look.opacity.to_bits(), pbr) +} + +struct Builder<'a> { + doc: &'a Document, + quality: MeshQuality, + writes: Writes, + hidden: &'a super::Hidden, + /// Joints, grounding and mass written ([`super::cadir_physics`]). + physics: bool, + /// Each component's bodies' masses in its frame, when [`Self::physics`]. + masses: HashMap>, + /// The image textures a render setup gives bodies ([`super::cadir_textures`]). + surfaces: &'a [crate::SurfacePlan], + /// The pictures shown on the model, each written as a body of its own. + decals: &'a [crate::DecalPlan], + /// The optics a render setup gives bodies. + optics: &'a [crate::OpticsPlan], + /// Each body as its mesh alone ([`crate::CadmpegOptions::meshes_only`]). + meshes_only: bool, + /// The appearances with optics made, by plain appearance (`None`: a body's colour) and + /// optics. + optical: HashMap<(Option, String), AppearanceId>, + /// The decal bodies written so far. + decal_count: usize, + /// The texture images written. + texture_assets: super::cadir_textures::Assets, + /// The textured appearances made, by plain appearance (`None`: a body's colour, which the + /// key then holds) and projection. + textured: HashMap<(Option, String), AppearanceId>, + ir: CadIr, + warnings: Vec, + looks: HashMap, + bodies: usize, + bindings: usize, + /// The loosest tolerance of the records written. + tolerance: Option, + /// The estimated size of the meshes so far. + bytes: usize, +} + +impl<'a> Builder<'a> { + fn new(doc: &'a Document, quality: MeshQuality, writes: Writes, hidden: &'a super::Hidden) -> Self { + Builder { + doc, + quality, + writes, + hidden, + physics: false, + masses: HashMap::new(), + surfaces: &[], + decals: &[], + decal_count: 0, + optics: &[], + meshes_only: false, + optical: HashMap::new(), + texture_assets: super::cadir_textures::Assets::default(), + textured: HashMap::new(), + ir: CadIr::empty(), + warnings: Vec::new(), + looks: HashMap::new(), + bodies: 0, + bindings: 0, + tolerance: None, + bytes: 0, + } + } + + fn finish(mut self) -> Result { + if self.ir.model.bodies.is_empty() && self.ir.model.tessellations.is_empty() { + return Err("there is no geometry to write".into()); + } + if let Some(t) = self.tolerance.and_then(PositiveLength::new) { + self.ir.tolerances.linear = t; + } + if !self.writes.planar_pcurves { + without_planar_pcurves(&mut self.ir); + } + if self.writes.named_bodies { + self.keep_body_names()?; + } + if self.writes.stated_pcurves { + with_stated_pcurves(&mut self.ir); + } + if !self.writes.solid_names && self.ir.model.bodies.iter().any(|b| b.name.is_some()) { + self.warnings.push(format!( + "the bodies' names are not written: cadmpeg's {} writer writes each solid without a name (the components keep theirs)", + self.writes.label + )); + } + self.ir.finalize(); + Ok(Built { ir: self.ir, warnings: self.warnings }) + } + + /// Each definition placed once, holding one body and placing nothing, whose body is named + /// other than the placement: the body moves to a definition of its own named as this one, + /// placed in that placement with no offset and named after the body. + fn keep_body_names(&mut self) -> Result<(), String> { + let model = &self.ir.model; + // Indexed once, so the pass stays linear in the definitions and placements. + let names: HashMap<&BodyId, &str> = model.bodies.iter().filter_map(|b| b.name.as_deref().map(|n| (&b.id, n))).collect(); + let mut placing: HashMap<&ProductDefinitionId, Vec<(cadmpeg_ir::ids::OccurrenceId, Option)>> = HashMap::new(); + for o in &model.occurrences { + if let PrototypeReference::Local { definition } = &o.prototype { + placing.entry(definition).or_default().push((o.id.clone(), o.name.clone())); + } + } + let parents: std::collections::HashSet<&cadmpeg_ir::ids::OccurrenceId> = model + .occurrences + .iter() + .filter_map(|o| match &o.parent { + OccurrenceParent::Occurrence { occurrence } => Some(occurrence), + _ => None, + }) + .collect(); + let mut moves = Vec::new(); + for (index, d) in model.product_definitions.iter().enumerate() { + let [body] = d.bodies.as_slice() else { continue }; + let Some(&name) = names.get(body) else { continue }; + let Some(placements) = placing.get(&d.id) else { continue }; + let [(placement, placed_as)] = placements.as_slice() else { continue }; + if !parents.contains(placement) && placed_as.as_deref() != Some(name) { + moves.push((index, name.to_string(), placements.clone())); + } + } + for (index, name, placements) in moves { + let key = self.ir.model.product_definitions.len(); + let id: ProductDefinitionId = id("product", key)?; + let Some(outer) = self.ir.model.product_definitions.get_mut(index) else { continue }; + let bodies = std::mem::take(&mut outer.bodies); + let source_name = outer.source_name.clone(); + self.ir.model.product_definitions.push(ProductDefinition { + id: id.clone(), + kind: ProductDefinitionKind::Object, + source_name, + label: None, + description: None, + part_number: None, + bom_properties: BTreeMap::new(), + bodies, + sketches: Vec::new(), + native_ref: None, + }); + for (parent, _) in placements { + let key = self.ir.model.occurrences.len(); + self.occurrence(key, &id, OccurrenceParent::Occurrence { occurrence: parent }, 0, Transform::identity(), Some(name.clone()))?; + } + } + Ok(()) + } + + /// The mass of body `b` (its geometry `geometry` in its component's frame) for component + /// `component`, from its material's density and its closed mesh; a body that does not close + /// adds none, with a warning. + fn add_mass(&mut self, b: &ModelBody, geometry: &solidcraft_kernel::Body, component: u64) { + match crate::mass_properties(geometry) { + Ok(Some(mp)) => { + // g/cm³ to kg/mm³. + let rho = self.doc.density(&b.name) * 1e-6; + self.masses.entry(component).or_default().push((rho * mp.volume, mp.centroid, mp.inertia.map(|r| r.map(|x| x * rho)))); + } + Ok(None) => self.warnings.push(format!("{}: not a closed solid: it adds no mass", clean(&b.name).unwrap_or_else(|| "a body".into()))), + Err(e) => self.warnings.push(format!("{}: its mass could not be measured: {e}", clean(&b.name).unwrap_or_else(|| "a body".into()))), + } + } + + /// The render setup's textures of model body `b` of component `component`, with the matrix + /// from its definition frame to its mesh's, when every shown placement (`shown`) has them + /// alike; else none, with a warning when some placement has them. `glass` leaves the metallic + /// map out of the comparison, as it is left out of the file. + fn surface(&mut self, b: &ModelBody, component: u64, shown: &[Vec], glass: bool) -> Option<(&'a crate::SurfacePlan, Mat)> { + let surfaces = self.surfaces; + let bound: Vec<&crate::SurfacePlan> = surfaces.iter().filter(|p| p.definition == b.definition_name() && p.component == component).collect(); + // The reference is a shown placement's: a hidden one's images do not count. + let first = *bound.iter().find(|p| shown.contains(&p.path)).or(bound.first())?; + let covered = + !shown.is_empty() && shown.iter().all(|path| bound.iter().any(|p| &p.path == path && super::cadir_textures::same(p, first, glass))); + if !covered { + self.warnings.push(format!( + "{}: render setup `{}` gives its placements different images (or some none): written with its look, as the file gives a component's body one mesh", + clean(&b.name).unwrap_or_else(|| "a body".into()), + first.setup + )); + return None; + } + let to_mesh = match self.doc.model_body_offset(b) { + Some(offset) => solidcraft_doc::mat_mul(offset, &b.source_transform), + None => b.source_transform, + }; + Some((first, to_mesh)) + } + + /// Decal `d` with its corners at `corners` (in the frame of the definition that holds it): a + /// body of its own named after it, its two-sided quad as its mesh and its image as its look. + /// `None`, with a warning, when it cannot be written. + fn decal(&mut self, d: &crate::DecalPlan, corners: [[f64; 3]; 4]) -> Result, String> { + let shown = clean(&d.name).unwrap_or_else(|| "a decal".into()); + let Some((points, normals, triangles, coordinates)) = super::cadir_textures::decal_quad(corners) else { + self.warnings.push(format!("decal `{shown}`: its corners give no plane: left out")); + return Ok(None); + }; + let Some(textures) = super::cadir_textures::decal_references(&d.image, &mut self.texture_assets, &mut self.ir.model.assets) else { + self.warnings.push(format!("decal `{shown}`: its image is neither PNG nor JPEG: left out")); + return Ok(None); + }; + // Its quad counts towards the file's size, as a body's mesh does. + if self.charge(points.len(), triangles.len()).is_none() { + return Err(format!( + "decal `{shown}`: the meshes are too large for the file (at most {} MiB); export fewer bodies or pictures, or use standard quality", + MAX_BYTES >> 20 + )); + } + let n = self.decal_count; + self.decal_count += 1; + let prefix = format!("solidcraft:decal-{n:09}"); + let body: BodyId = BodyId::try_from(format!("{prefix}:body#0")).map_err(|_| format!("{prefix}: not a CADIR identity"))?; + let tessellation = cadmpeg_ir::tessellation::TessellationId::try_from(format!("{prefix}:tessellation#0")) + .map_err(|_| format!("{prefix}: not a CADIR identity"))?; + let positions = points.iter().map(|p| Point3::new(p[0], p[1], p[2])).collect(); + let normals = normals.iter().map(|v| Vector3::new(v[0], v[1], v[2])).collect(); + let lanes = TessellationMesh::from_list_lanes(positions, triangles, Some(normals)).map_err(|e| e.to_string())?; + let mesh = Tessellation::new(tessellation.clone(), lanes, Vec::new()) + .map_err(|e| e.to_string())? + .with_body(Some(body.clone())) + .with_texture_coordinates(vec![coordinates]) + .map_err(|e| e.to_string())?; + self.ir.model.bodies.push(Body { + id: body.clone(), + kind: BodyKind::General, + regions: Vec::new(), + transform: None, + name: Some(shown.clone()), + color: None, + visible: None, + }); + self.ir.model.tessellations.push(mesh); + let appearance: AppearanceId = id("decal-appearance", n)?; + self.ir.model.appearances.push(Appearance { + id: appearance.clone(), + name: Some(shown), + asset_guid: None, + library_id: None, + visual_guid: None, + physical_token: None, + schema: None, + category: None, + base_color: Color::new(1.0, 1.0, 1.0, 1.0), + properties: BTreeMap::new(), + textures, + }); + self.bind(AppearanceTarget::Tessellation(tessellation.to_string()), appearance)?; + Ok(Some(body)) + } + + /// The render setup's optics of model body `b` of component `component`, when every shown + /// placement (`shown`) has them alike; else none, with a warning when some placement has them. + fn optics_of(&mut self, b: &ModelBody, component: u64, shown: &[Vec]) -> Option<&'a crate::OpticsPlan> { + let all = self.optics; + let bound: Vec<&crate::OpticsPlan> = all.iter().filter(|p| p.definition == b.definition_name() && p.component == component).collect(); + // The reference is a shown placement's: a hidden one's optics do not count. + let first = *bound.iter().find(|p| shown.contains(&p.path)).or(bound.first())?; + let alike = |p: &crate::OpticsPlan| (p.ior, p.absorption_per_mm, p.thin_sheet) == (first.ior, first.absorption_per_mm, first.thin_sheet); + let covered = !shown.is_empty() && shown.iter().all(|path| bound.iter().any(|p| &p.path == path && alike(p))); + if !covered { + self.warnings.push(format!( + "{}: render setup `{}` gives its placements different optics (or some none): written without them, as the file gives a component's body one look", + clean(&b.name).unwrap_or_else(|| "a body".into()), + first.setup + )); + return None; + } + Some(first) + } + + /// The appearance `plain` (else one of colour `colour`) with `optics`' properties, made once. + fn with_optics(&mut self, plain: Option, colour: Option, optics: &crate::OpticsPlan) -> Result { + let properties = super::cadir_textures::optics_properties(optics); + // With no appearance of its own, the colour it falls back to tells two apart too. + let fallback = if plain.is_none() { colour.map(|c| [c.r(), c.g(), c.b(), c.a()].map(f32::to_bits)) } else { None }; + let key = (plain.clone(), format!("{:?}", (properties.as_slice(), fallback))); + if let Some(id) = self.optical.get(&key) { + return Ok(id.clone()); + } + let id: AppearanceId = id("optics-appearance", self.optical.len())?; + let base = plain.as_ref().and_then(|p| self.ir.model.appearances.iter().find(|a| a.id == *p)).cloned(); + let mut appearance = base.unwrap_or_else(|| Appearance { + id: id.clone(), + name: None, + asset_guid: None, + library_id: None, + visual_guid: None, + physical_token: None, + schema: None, + category: None, + base_color: colour, + properties: BTreeMap::new(), + textures: Vec::new(), + }); + appearance.id = id.clone(); + appearance.name = Some(match &appearance.name { + Some(n) => format!("{n} {}", optics.setup), + None => optics.setup.clone(), + }); + for (name, value) in properties { + if let (Some(name), Some(value)) = (NonBlankString::new(name), FiniteReal::new(value)) { + appearance.properties.insert(name, value); + } + } + self.ir.model.appearances.push(appearance); + self.optical.insert(key, id.clone()); + Ok(id) + } + + /// The appearance `plain` (else one of colour `colour`) with `plan`'s images, made once. + fn textured( + &mut self, + plain: Option, + colour: Option, + plan: &crate::SurfacePlan, + refs: &[cadmpeg_ir::appearance::TextureRef], + ) -> Result { + // With no appearance of its own, the colour it falls back to tells two apart too. + let fallback = if plain.is_none() { colour.map(|c| [c.r(), c.g(), c.b(), c.a()].map(f32::to_bits)) } else { None }; + let projection = + format!("{:?}", (plan.origin, plan.u, plan.v, plan.flip_v, fallback, refs.iter().map(|r| (&r.slot, &r.asset_guid)).collect::>())); + let key = (plain.clone(), projection); + if let Some(id) = self.textured.get(&key) { + return Ok(id.clone()); + } + let id: AppearanceId = id("textured-appearance", self.textured.len())?; + let base = plain.as_ref().and_then(|p| self.ir.model.appearances.iter().find(|a| a.id == *p)).cloned(); + let mut appearance = base.unwrap_or_else(|| Appearance { + id: id.clone(), + name: None, + asset_guid: None, + library_id: None, + visual_guid: None, + physical_token: None, + schema: None, + category: None, + base_color: colour, + properties: BTreeMap::new(), + textures: Vec::new(), + }); + appearance.id = id.clone(); + appearance.name = Some(match &appearance.name { + Some(n) => format!("{n} {}", plan.setup), + None => plan.setup.clone(), + }); + appearance.textures = refs.to_vec(); + self.ir.model.appearances.push(appearance); + self.textured.insert(key, id.clone()); + Ok(id) + } + + /// Body `id` written hidden. + fn hide(&mut self, id: &BodyId) { + if let Some(body) = self.ir.model.bodies.iter_mut().find(|x| x.id == *id) { + body.visible = Some(false); + } + } + + /// A product definition named `name` holding `bodies`, with its id. + fn definition(&mut self, key: usize, name: &str, bodies: Vec) -> Result { + let id: ProductDefinitionId = id("product", key)?; + self.ir.model.product_definitions.push(ProductDefinition { + id: id.clone(), + kind: ProductDefinitionKind::Part, + source_name: Some(name.to_string()), + label: None, + description: None, + part_number: None, + bom_properties: BTreeMap::new(), + bodies, + sketches: Vec::new(), + native_ref: None, + }); + Ok(id) + } + + /// Occurrence number `key` of `definition` in `parent`, placed there by `placement`. + fn occurrence( + &mut self, + key: usize, + definition: &ProductDefinitionId, + parent: OccurrenceParent, + ordinal: u32, + placement: Transform, + name: Option, + ) -> Result { + let id: cadmpeg_ir::ids::OccurrenceId = id("occurrence", key)?; + self.ir.model.occurrences.push(Occurrence { + id: id.clone(), + prototype: PrototypeReference::Local { definition: definition.clone() }, + parent, + ordinal, + transform: placement, + linked_prototype: None, + scale: [FiniteReal::ONE; 3], + name, + visible: None, + link: None, + native_ref: None, + }); + Ok(id) + } + + /// The chosen bodies of `world` (all when `bodies` is empty), where it has them, in one root + /// definition named `root`. + fn flat(&mut self, world: &ModelState, bodies: &[String], root: &str) -> Result<(), String> { + let sel = crate::selected(world, bodies).map_err(|e| e.to_string())?; + let mut ids = Vec::with_capacity(sel.len()); + for b in sel { + let meshes = self.ir.model.tessellations.len(); + let surface = self.surfaces.iter().find(|p| p.world == b.name).map(|p| (p, b.source_transform)); + let optics = self.optics.iter().find(|p| p.world == b.name); + match self.body(b, &b.body, &b.name, surface, optics)? { + Some(id) => { + if self.hidden.bodies.contains(&b.name) { + self.hide(&id); + } + ids.push(id); + } + // Written as a mesh of its own, which the writer gives no visibility. + None if self.hidden.bodies.contains(&b.name) && self.ir.model.tessellations.len() > meshes => { + self.warnings.push(format!( + "{}: hidden, but written shown: cadmpeg's {} writer gives a mesh no visibility", + clean(&b.name).unwrap_or_else(|| "a body".into()), + self.writes.label + )); + } + None => {} + } + } + for d in self.decals { + if let Some(id) = self.decal(d, d.world)? { + ids.push(id); + } + } + if self.writes.products { + let definition = self.definition(0, root, ids)?; + self.occurrence(0, &definition, OccurrenceParent::Root {}, 0, Transform::identity(), Some(root.to_string()))?; + } + Ok(()) + } + + /// The design's components as definitions and its placements as occurrences, the design + /// itself the root definition named `root`. `model` is the model before placing: each body + /// in its component's frame (taken there by its offset, as the world placement takes it). + fn assembly(&mut self, model: &ModelState, root: &str) -> Result<(), String> { + let doc = self.doc; + // Definition keys: 0 the design, then each component in order. + let mut keys: HashMap = HashMap::new(); + keys.insert(0, 0); + let mut names = vec![root.to_string()]; + for c in &doc.components { + if keys.contains_key(&c.id) { + continue; + } + keys.insert(c.id, names.len()); + names.push(clean(&c.name).unwrap_or_else(|| format!("Component {}", c.id))); + } + let mut owned: Vec> = vec![Vec::new(); names.len()]; + let owners = doc.model_body_components(model); + // The paths of each component's shown placements: a hidden placement hides what it + // places, so a body's own state counts in the others only. + let mut shown: HashMap>> = HashMap::new(); + for (component, path, _) in doc.placements() { + if !self.hidden.placements.iter().any(|h| !h.is_empty() && path.starts_with(h)) { + shown.entry(component).or_default().push(path); + } + } + let world_names = solidcraft_doc::WorldNames::new(doc, model); + for (b, owner) in model.bodies.iter().zip(owners) { + let Some(&key) = keys.get(&owner) else { continue }; + let framed = match doc.model_body_offset(b) { + Some(offset) if !solidcraft_doc::is_identity(offset) => match solidcraft_kernel::transform_matrix(&b.body, *offset) { + Ok(f) => Some(f), + Err(e) => { + self.warnings.push(format!("{}: not written: it could not be taken into its component's frame: {e}", b.name)); + continue; + } + }, + _ => None, + }; + let placements = shown.get(&owner).map(Vec::as_slice).unwrap_or_default(); + let optics = self.optics_of(b, owner, placements); + let surface = self.surface(b, owner, placements, optics.is_some()); + if let Some(id) = self.body(b, framed.as_ref().unwrap_or(&b.body), b.definition_name(), surface, optics)? + && let Some(list) = owned.get_mut(key) + { + let paths = shown.get(&owner).map(Vec::as_slice).unwrap_or_default(); + let hidden_in = paths.iter().filter(|p| self.hidden.bodies.contains(&world_names.name(&b.name, owner, p))).count(); + if hidden_in > 0 && hidden_in == paths.len() { + self.hide(&id); + } else if hidden_in > 0 { + self.warnings.push(format!( + "{}: hidden in {hidden_in} of the {} shown placements of its component: written shown, as the file gives a component's body one visibility", + clean(&b.name).unwrap_or_else(|| "a body".into()), + paths.len() + )); + } + list.push(id); + if self.physics { + self.add_mass(b, framed.as_ref().unwrap_or(&b.body), owner); + } + } + } + for d in self.decals { + let Some(&key) = keys.get(&d.component) else { continue }; + if let Some(id) = self.decal(d, d.local)? + && let Some(list) = owned.get_mut(key) + { + list.push(id); + } + } + let mut definitions = Vec::with_capacity(names.len()); + for (key, (name, bodies)) in names.iter().zip(owned).enumerate() { + definitions.push(self.definition(key, name, bodies)?); + } + let Some(design) = definitions.first().cloned() else { return Err("the design has no root".into()) }; + // The placed instances, walked from the root, as the design's own walk caps them. Each + // parent's children keep their ordinal among all its children; one whose component has + // no definition is left out here, once, not on every instance of its parent. + let mut children: HashMap> = HashMap::new(); + let mut counts: HashMap = HashMap::new(); + for o in &doc.occurrences { + let count = counts.entry(o.parent).or_default(); + let ordinal = *count; + *count = count.saturating_add(1); + if let Some(definition) = keys.get(&o.component).and_then(|k| definitions.get(*k)) { + children.entry(o.parent).or_default().push((ordinal, o, definition.clone())); + } + } + // The placements written are exactly those the design's own walk reaches + // (`Document::placements`, which the display and the world model take), capped where it + // caps them: a placement the design shows is written, and none it leaves out. + let walked: HashSet> = doc.placements().into_iter().map(|(_, path, _)| path).collect(); + let mut cut = !doc.placements_complete(); + let first = self.occurrence(0, &design, OccurrenceParent::Root {}, 0, Transform::identity(), Some(root.to_string()))?; + let mut stack = vec![(0u64, first, Vec::new())]; + let mut placed_ids: HashMap, cadmpeg_ir::ids::OccurrenceId> = HashMap::new(); + let mut made = 1usize; + while let Some((component, parent, path)) = stack.pop() { + for (ordinal, o, definition) in children.get(&component).into_iter().flatten() { + let mut placed: Vec = path.clone(); + placed.push(o.id); + if !walked.contains(&placed) { + cut = true; + continue; + } + let Some(placement) = transform(&o.transform) else { + return Err(format!("{}: its placement is not a finite number", o.name)); + }; + let parent = OccurrenceParent::Occurrence { occurrence: parent.clone() }; + let id = self.occurrence(made, definition, parent, *ordinal, placement, clean(&o.name))?; + made += 1; + if self.hidden.placements.contains(&placed) + && let Some(occurrence) = self.ir.model.occurrences.last_mut() + { + occurrence.visible = Some(false); + } + placed_ids.insert(placed.clone(), id.clone()); + stack.push((o.component, id, placed)); + } + } + if cut { + self.warnings.push(format!( + "the assembly is too large or too deep: placements past {} levels or {} in all were left out", + solidcraft_doc::MAX_PLACEMENT_DEPTH, + solidcraft_doc::MAX_PLACEMENTS + )); + } + if self.physics { + let components: HashMap = + keys.iter().filter_map(|(component, key)| definitions.get(*key).map(|d| (*component, d.clone()))).collect(); + let physics = super::cadir_physics::build(doc, model, &placed_ids, &components, &self.masses)?; + self.warnings.extend(physics.warnings); + self.ir.model.assembly_joints.extend(physics.joints); + self.ir.model.mass_properties.extend(physics.masses); + self.ir.model.rigid_bodies.extend(physics.rigid_bodies); + self.ir.model.articulations.extend(physics.articulations); + self.ir.model.physics_scenes.extend(physics.scenes); + } + Ok(()) + } + + /// The appearance of `look`, made the first time it is asked for. + fn appearance(&mut self, look: &Look) -> Result { + let key = look_key(look); + if let Some(id) = self.looks.get(&key) { + return Ok(id.clone()); + } + let id: AppearanceId = id("appearance", self.looks.len())?; + let mut properties = BTreeMap::new(); + if let Some(p) = look.pbr { + for (k, v) in [("metallic", p.metallic()), ("roughness", p.roughness()), ("ior", p.dielectric_ior())] { + if let (Some(k), Some(v)) = (NonBlankString::new(k), FiniteReal::new(v)) { + properties.insert(k, v); + } + } + } + self.ir.model.appearances.push(Appearance { + id: id.clone(), + name: clean(&look.name), + asset_guid: None, + library_id: None, + visual_guid: None, + physical_token: None, + schema: None, + category: None, + base_color: colour(look.color, look.opacity, self.writes.linear), + properties, + textures: Vec::new(), + }); + self.looks.insert(key, id.clone()); + Ok(id) + } + + fn bind(&mut self, target: AppearanceTarget, appearance: AppearanceId) -> Result<(), String> { + let id = id("binding", self.bindings)?; + self.bindings += 1; + self.ir.model.appearance_bindings.push(AppearanceBinding { + id, + target, + appearance, + source_entity_id: None, + object_type: None, + visible: None, + channels: BTreeMap::new(), + }); + Ok(()) + } + + /// Body `b` (its looks), its geometry `geometry` (the body itself, or taken into its + /// component's frame), named `name`: its B-rep and, where the writer takes one, its mesh. + /// `None` when nothing of it could be written, with a warning naming it, or when it is + /// written as a mesh of its own, with no body record ([`Writes::bound_meshes`]). + fn body( + &mut self, + b: &ModelBody, + geometry: &solidcraft_kernel::Body, + name: &str, + surface: Option<(&'a crate::SurfacePlan, Mat)>, + optics: Option<&'a crate::OpticsPlan>, + ) -> Result, String> { + let shown = clean(&b.name).unwrap_or_else(|| "a body".into()); + let n = self.bodies; + self.bodies += 1; + let prefix = format!("solidcraft:body-{n:09}"); + let name = clean(name).unwrap_or_else(|| shown.clone()); + let label = self.writes.label; + // Each record face's CADIR face, when the exact shape is written. + let mut brep_faces = Vec::new(); + let mut brep = if geometry.is_mesh() || self.meshes_only { + None + } else { + match self.brep(geometry, &prefix, &name) { + Ok(written) => { + brep_faces = written.faces; + Some(written.body) + } + Err(e) => { + self.warnings.push(format!("{shown}: written as its mesh only: its exact shape could not be: {e}")); + None + } + } + }; + let mesh = if brep.is_some() && !self.writes.brep_meshes { + None + } else { + let made = self.mesh(geometry, &shown); + // Asked for meshes only, but the mesh cannot be made: the exact shape is what is left. + let instead = shape_instead(&made, self.meshes_only, geometry.is_mesh()).then(|| self.brep(geometry, &prefix, &name).ok()).flatten(); + match (instead, made) { + (Some(written), Err(Unmeshed::Failed(e))) => { + self.warnings + .push(format!("{shown}: its mesh could not be made ({e}): written as its exact shape, although the file is meshes only")); + brep_faces = written.faces; + brep = Some(written.body); + None + } + (_, made) => kept_without_mesh(made, brep.is_some(), &shown, &mut self.warnings)?, + } + }; + let has_brep = brep.is_some(); + // The body record just appended, so a look does not scan the list for its id. + let (id, pushed) = match brep { + Some(id) => (Some(id), None), + None if self.writes.bound_meshes => { + let id: BodyId = BodyId::try_from(format!("{prefix}:body#0")).map_err(|_| format!("{prefix}: not a CADIR identity"))?; + let index = self.ir.model.bodies.len(); + self.ir.model.bodies.push(Body { + id: id.clone(), + kind: BodyKind::General, + regions: Vec::new(), + transform: None, + name: Some(name.clone()), + color: None, + visible: None, + }); + (Some(id), Some(index)) + } + None => (None, None), + }; + // Looks: the body's, else its colour; and each face's own. + let doc = self.doc; + let look = doc.model_body_look(b); + let mut face_looks: BTreeMap = BTreeMap::new(); + let faces = doc.face_colors(b); + // The body's own appearance, for its textured variant. + let mut own: Option = None; + match &id { + Some(id) if self.writes.appearances => { + match &look { + Some(look) => { + let mut a = self.appearance(look)?; + if let Some(o) = optics { + a = self.with_optics(Some(a), None, o)?; + } + own = Some(a.clone()); + self.bind(AppearanceTarget::Body(id.clone()), a)?; + } + None => { + self.set_colour(id, b, pushed); + if let Some(o) = optics { + let colour = pushed + .and_then(|i| self.ir.model.bodies.get(i)) + .filter(|x| x.id == *id) + .or_else(|| self.ir.model.bodies.iter().find(|x| x.id == *id)) + .and_then(|x| x.color); + let a = self.with_optics(None, colour, o)?; + own = Some(a.clone()); + self.bind(AppearanceTarget::Body(id.clone()), a)?; + } + } + } + if let Some(o) = optics { + self.warnings.push(format!( + "{shown}: the optics of render setup `{}` are written as the MaterialX shader's transmission: a reader of the preview surface alone shows it opaque", + o.setup + )); + } + if self.writes.bound_meshes { + for (face, look) in &faces { + let mut a = self.appearance(look)?; + if let Some(o) = optics { + a = self.with_optics(Some(a), None, o)?; + } + if let Ok(face) = u32::try_from(*face) { + face_looks.insert(face, a); + } + } + } + } + Some(id) => { + let linear = self.writes.linear; + match &look { + Some(look) => { + let color = colour(look.color, look.opacity, linear); + match pushed.and_then(|i| self.ir.model.bodies.get_mut(i)) { + Some(body) => body.color = color, + None => { + if let Some(body) = self.ir.model.bodies.iter_mut().find(|x| x.id == *id) { + body.color = color; + } + } + } + } + None => self.set_colour(id, b, pushed), + } + if !faces.is_empty() { + self.warnings + .push(format!("{shown}: the colours of its own faces are not written: cadmpeg's {label} writer writes one colour a body")); + } + } + None => { + if look.is_some() || doc.body_color(b).is_some() || !faces.is_empty() { + self.warnings + .push(format!("{shown}: written as a mesh without its name or colour: cadmpeg's {label} writer writes a mesh without them")); + } else { + self.warnings.push(format!("{shown}: written as a mesh without its name: cadmpeg's {label} writer writes a mesh without one")); + } + } + } + let Some(mesh) = mesh else { + // No mesh beside the exact shape (STEP): each face's own look is bound to its B-rep + // face, as there are no triangles to bind it to. + for (face, a) in face_looks { + match brep_faces.get(face as usize).cloned().flatten() { + Some(f) => self.bind(AppearanceTarget::Face(f), a)?, + None => self.warnings.push(format!("{shown}: the colour of its face {face} is not written: the face is not in its exact shape")), + } + } + return Ok(id); + }; + // A render setup's textures: the mesh's coordinates in its images, and the body's and its + // faces' appearances with the images, bound to the mesh (the exact shape keeps the plain + // look). + let mut textures = None; + if let (Some((plan, to_mesh)), Some(id), true) = (surface, &id, self.writes.appearances) { + match super::cadir_textures::coordinates(&mesh.positions, plan, &to_mesh) { + Some(coordinates) => { + let mut refs = + super::cadir_textures::references(plan, &mut self.texture_assets, &mut self.ir.model.assets, &shown, &mut self.warnings); + // Glass transmits: a metallic map would drive OpenPBR's metalness, which takes + // the transmission away, so a body given optics is written without it. + if let Some(o) = optics + && refs.iter().any(|r| r.slot.starts_with("metallic")) + { + refs.retain(|r| !r.slot.starts_with("metallic")); + self.warnings.push(format!( + "{shown}: the metallic image of render setup `{}` is not written, as its optics make it glass, which a metal does not transmit", + o.setup + )); + } + if !refs.is_empty() { + let colour = self.ir.model.bodies.iter().find(|x| x.id == *id).and_then(|x| x.color); + let body_look = self.textured(own.clone(), colour, plan, &refs)?; + for a in face_looks.values_mut() { + *a = self.textured(Some(a.clone()), None, plan, &refs)?; + } + textures = Some((coordinates, body_look)); + } + } + None => { + self.warnings.push(format!("{shown}: the projection of render setup `{}` is not finite: written without its images", plan.setup)) + } + } + } + let (coordinates, textured_look) = textures.unzip(); + let written = self.tessellation(&prefix, id.as_ref(), &mesh, &face_looks, coordinates); + if written.is_err() { + // Not written, so its size is not the file's. + let solidcraft_geom::Mesh { triangles, .. } = mesh; + self.refund(mesh.positions.len(), triangles.len()); + } + match written { + Ok(()) => { + if let Some(a) = textured_look { + self.bind(AppearanceTarget::Tessellation(format!("{prefix}:tessellation#0")), a)?; + } + } + Err(e) if has_brep => self.warnings.push(format!("{shown}: its mesh was not written ({e}), so the file's writer meshes it")), + Err(e) => { + self.warnings.push(format!("{shown}: not written: {e}")); + if let Some(id) = &id { + self.ir.model.bodies.retain(|x| x.id != *id); + self.ir.model.appearance_bindings.retain(|x| x.target != AppearanceTarget::Body(id.clone())); + } + return Ok(None); + } + } + Ok(id) + } + + /// A body with no look but a colour (an imported one) carries that colour. `pushed` is its + /// record's index when this call appended it. + fn set_colour(&mut self, id: &BodyId, b: &ModelBody, pushed: Option) { + let doc = self.doc; + if let Some(c) = doc.body_color(b) { + let to8 = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + let color = colour(c.map(to8), doc.model_body_opacity(b), self.writes.linear); + let body = match pushed { + Some(i) => self.ir.model.bodies.get_mut(i).filter(|x| x.id == *id), + None => self.ir.model.bodies.iter_mut().find(|x| x.id == *id), + }; + if let Some(body) = body { + body.color = color; + } + } + } + + /// `geometry`'s exact shape written as body `name` under `prefix`, once the writer takes it + /// ([`Writes::admit`]). + fn brep(&mut self, geometry: &solidcraft_kernel::Body, prefix: &str, name: &str) -> Result { + let record = solidcraft_kernel::brep_record(geometry).map_err(|e| e.to_string())?; + let tolerance = record.tolerance; + if let Some(admit) = self.writes.admit { + let mut alone = CadIr::empty(); + solidcore_cadir::write_body(&mut alone.model, &record, prefix, Some(name)).map_err(|e| e.to_string())?; + if let Some(t) = PositiveLength::new(tolerance) { + alone.tolerances.linear = t; + } + if !self.writes.planar_pcurves { + without_planar_pcurves(&mut alone); + } + alone.finalize(); + admit(&alone).map_err(|e| format!("cadmpeg's {} writer cannot write it yet ({e})", self.writes.label))?; + } + let w = solidcore_cadir::write_body(&mut self.ir.model, &record, prefix, Some(name)).map_err(|e| e.to_string())?; + if tolerance.is_finite() && tolerance > 0.0 { + self.tolerance = Some(self.tolerance.map_or(tolerance, |t| t.max(tolerance))); + } + Ok(w) + } + + /// `geometry`'s mesh at the export's quality, within the file's size cap. + fn mesh(&mut self, geometry: &solidcraft_kernel::Body, shown: &str) -> Result { + let mesh = crate::display_mesh_at(geometry, self.quality).map_err(|e| Unmeshed::Failed(format!("could not be meshed: {e}")))?; + let solidcraft_geom::Mesh { triangles, .. } = &mesh; + if triangles.is_empty() { + return Err(Unmeshed::Failed("could not be meshed: no face gave triangles".into())); + } + self.charge(mesh.positions.len(), triangles.len()).ok_or_else(|| { + Unmeshed::TooLarge(format!( + "{shown}: the meshes are too large for the file (at most {} MiB); export fewer bodies or use standard quality", + MAX_BYTES >> 20 + )) + })?; + Ok(mesh) + } + + /// `points` points and `triangles` triangles added to the meshes written; `None`, adding + /// nothing, when they would take the meshes past [`MAX_BYTES`]. + fn charge(&mut self, points: usize, triangles: usize) -> Option<()> { + let size = points + .checked_mul(BYTES_PER_POINT) + .zip(triangles.checked_mul(BYTES_PER_TRIANGLE)) + .and_then(|(p, t)| p.checked_add(t)) + .and_then(|n| n.checked_add(self.bytes)) + .filter(|n| *n <= MAX_BYTES)?; + self.bytes = size; + Some(()) + } + + /// Take back what [`Self::charge`] added for `points` points and `triangles` triangles, for + /// a mesh it charged that is not written after all. + fn refund(&mut self, points: usize, triangles: usize) { + let size = points.saturating_mul(BYTES_PER_POINT).saturating_add(triangles.saturating_mul(BYTES_PER_TRIANGLE)); + self.bytes = self.bytes.saturating_sub(size); + } + + /// `mesh` as the tessellation of body `body` (a mesh of its own when `None`), the triangles of + /// each face in `face_looks` a triangle group bound to that face's appearance. + fn tessellation( + &mut self, + prefix: &str, + body: Option<&BodyId>, + mesh: &solidcraft_geom::Mesh, + face_looks: &BTreeMap, + coordinates: Option, + ) -> Result<(), String> { + let solidcraft_geom::Mesh { triangles, tri_face, .. } = mesh; + if triangles.is_empty() { + return Err("its mesh has no triangles".into()); + } + let id = cadmpeg_ir::tessellation::TessellationId::try_from(format!("{prefix}:tessellation#0")) + .map_err(|_| format!("{prefix}: not a CADIR identity"))?; + let positions: Vec = mesh.positions.iter().map(|p| Point3::new(p.x, p.y, p.z)).collect(); + let normals: Option> = (mesh.normals.len() == mesh.positions.len() + && mesh.normals.iter().all(|n| n.x.is_finite() && n.y.is_finite() && n.z.is_finite())) + .then(|| mesh.normals.iter().map(|n| Vector3::new(n.x, n.y, n.z)).collect()); + let lanes = TessellationMesh::from_list_lanes(positions, triangles.clone(), normals).map_err(|e| e.to_string())?; + let mut t = Tessellation::new(id.clone(), lanes, Vec::new()).map_err(|e| e.to_string())?.with_body(body.cloned()); + if let Some(coordinates) = coordinates { + t = t.with_texture_coordinates(vec![coordinates]).map_err(|e| e.to_string())?; + } + if !face_looks.is_empty() && tri_face.len() == triangles.len() { + let mut groups: BTreeMap, Vec> = BTreeMap::new(); + for (i, f) in tri_face.iter().enumerate() { + let Ok(i) = u32::try_from(i) else { return Err("its mesh has too many triangles".into()) }; + let group = face_looks.contains_key(f).then_some(*f); + groups.entry(group).or_default().push(i); + } + let partition: Vec = groups + .iter() + .map(|(f, triangles)| TessellationTriangleGroup { source_id: f.map(|f| format!("face{f}")), triangles: triangles.clone() }) + .collect(); + t = t.with_triangle_groups(partition).map_err(|e| e.to_string())?; + for f in groups.keys().flatten() { + if let Some(a) = face_looks.get(f).cloned() { + self.bind(AppearanceTarget::TriangleGroup { tessellation: id.to_string(), group: format!("face{f}") }, a)?; + } + } + } + self.ir.model.tessellations.push(t); + Ok(()) + } +} + +/// `ir` without the pcurves of faces on planes: a writer that makes them from the edges takes no +/// other ([`Writes::planar_pcurves`]). +fn without_planar_pcurves(ir: &mut CadIr) { + use cadmpeg_ir::geometry::{SolvedSurfaceGeometry, SurfaceGeometry}; + use std::collections::HashSet; + let planes: HashSet<&str> = ir + .model + .surfaces + .iter() + .filter(|s| matches!(s.geometry, SurfaceGeometry::Solved(SolvedSurfaceGeometry::Plane(_)))) + .map(|s| s.id.as_str()) + .collect(); + let planar_faces: HashSet<&str> = ir.model.faces.iter().filter(|f| planes.contains(f.surface.as_str())).map(|f| f.id.as_str()).collect(); + let planar_loops: HashSet = + ir.model.loops.iter().filter(|l| planar_faces.contains(l.face.as_str())).map(|l| l.id.as_str().to_string()).collect(); + let mut dropped: HashSet = HashSet::new(); + for c in ir.model.coedges.iter_mut().filter(|c| planar_loops.contains(c.owner_loop.as_str())) { + dropped.extend(c.pcurves.drain(..).map(|u| u.pcurve.as_str().to_string())); + } + ir.model.pcurves.retain(|p| !dropped.contains(p.id.as_str())); +} + +/// Why a body's mesh was not made ([`Builder::mesh`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Unmeshed { + /// Its display mesh could not be made, with why. + Failed(String), + /// The export's meshes would pass the file's size cap ([`MAX_BYTES`]), said in full. + TooLarge(String), +} + +/// Whether a body of a meshes-only export (`meshes_only`) whose mesh failed (`made`) is written +/// as its exact shape: only when it has one (it is not a mesh body, `is_mesh`), and only when the +/// mesh failed, not when it passed the size cap. +pub(crate) fn shape_instead(made: &Result, meshes_only: bool, is_mesh: bool) -> bool { + meshes_only && !is_mesh && matches!(made, Err(Unmeshed::Failed(_))) +} + +/// The mesh `made` for body `shown`, or none: a body with an exact B-rep whose display mesh could +/// not be made is written as its B-rep alone, with a warning, as one whose mesh the file cannot +/// take is (the file's writer meshes it). The size cap stays fatal, and so does a failed mesh of a +/// body with no exact shape, which has nothing else to be written as. +pub(crate) fn kept_without_mesh( + made: Result, + has_brep: bool, + shown: &str, + warnings: &mut Vec, +) -> Result, String> { + match made { + Ok(mesh) => Ok(Some(mesh)), + Err(Unmeshed::Failed(e)) if has_brep => { + warnings.push(format!("{shown}: its mesh was not written ({e}), so the file's writer meshes it")); + Ok(None) + } + Err(Unmeshed::Failed(e)) => Err(format!("{shown}: {e}")), + Err(Unmeshed::TooLarge(e)) => Err(e), + } +} + +/// Each pcurve of `ir` states the parameter range its one use runs over, and each use that says +/// nothing states it is not declared isoparametric (the flag is only a hint to a reader) +/// ([`Writes::stated_pcurves`]). A pcurve used by more than one coedge, or with no range on its +/// use, is left as it is. +fn with_stated_pcurves(ir: &mut CadIr) { + use cadmpeg_ir::geometry::pcurve::PcurveMetadata; + use cadmpeg_ir::units::FiniteVector; + let mut ranges: HashMap> = HashMap::new(); + for u in ir.model.coedges.iter_mut().flat_map(|c| c.pcurves.iter_mut()) { + if u.isoparametric.is_none() { + u.isoparametric = Some(false); + } + let range = u.parameter_range.map(|r| { + let [a, b] = r.endpoints(); + [a.min(b), a.max(b)] + }); + // A second use makes the pcurve's own range ambiguous. + ranges.entry(u.pcurve.as_str().to_string()).and_modify(|r| *r = None).or_insert(range); + } + for p in &mut ir.model.pcurves { + if p.metadata != PcurveMetadata::default() { + continue; + } + if let Some(range) = ranges.get(p.id.as_str()).copied().flatten().and_then(FiniteVector::new) { + p.metadata = PcurveMetadata::general(None, Some(range), None); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A decal's quad (eight points, four triangles) counts towards the file's size: near the cap + /// it is refused, adding nothing; with room it is written and charged. + #[test] + fn a_decal_is_charged_to_the_size_cap() { + let doc = Document::new("Decal"); + let hidden = crate::Hidden::default(); + let corners = [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 5.0, 0.0], [0.0, 5.0, 0.0]]; + let image = crate::SurfaceMap { sha256: "f00d".into(), bytes: std::sync::Arc::from(&b"\x89PNG\r\n\x1a\n"[..]) }; + let plan = crate::DecalPlan { name: "Logo".into(), component: 0, local: corners, world: corners, image }; + let quad = 8 * BYTES_PER_POINT + 4 * BYTES_PER_TRIANGLE; + let mut b = Builder::new(&doc, MeshQuality::Standard, Writes::USD, &hidden); + b.bytes = MAX_BYTES - quad + 1; + assert!(b.decal(&plan, corners).is_err()); + assert_eq!(b.bytes, MAX_BYTES - quad + 1); + assert!(b.ir.model.tessellations.is_empty()); + b.bytes = MAX_BYTES - quad; + assert!(b.decal(&plan, corners).unwrap().is_some()); + assert_eq!(b.bytes, MAX_BYTES); + } + + /// A body whose mesh is charged but not written (its mesh has no triangles, which its + /// tessellation refuses) takes its charge back: the cap counts only the meshes written. + #[test] + fn a_mesh_not_written_is_not_charged() { + let doc = Document::new("Unwritten"); + let hidden = crate::Hidden::default(); + let mut b = Builder::new(&doc, MeshQuality::Standard, Writes::USD, &hidden); + let mesh = solidcraft_geom::Mesh { positions: vec![solidcore_record::Vec3::new(0.0, 0.0, 0.0); 3], ..Default::default() }; + assert!(b.charge(mesh.positions.len(), mesh.triangles.len()).is_some()); + assert_eq!(b.bytes, 3 * BYTES_PER_POINT); + assert!(b.tessellation("solidcraft:body-000000000", None, &mesh, &BTreeMap::new(), None).is_err()); + b.refund(mesh.positions.len(), mesh.triangles.len()); + assert_eq!(b.bytes, 0); + } +} diff --git a/crates/io/src/native_cad/cadir_physics.rs b/crates/io/src/native_cad/cadir_physics.rs new file mode 100644 index 00000000000..2f9cfff982e --- /dev/null +++ b/crates/io/src/native_cad/cadir_physics.rs @@ -0,0 +1,595 @@ +//! The design's joints, grounding and masses as CADIR physics records, for an OpenUSD export +//! that asks for them ([`crate::CadmpegOptions::physics`]); cadmpeg's writer writes them as +//! `UsdPhysics` joints, rigid bodies and mass. +//! +//! Joints: each joint is written between the two placements it joins, at the first placement of +//! each (the one the design's own joint solver moves). Its two frames are those the solver +//! mates: A's frame with its lateral offset, and B's frame with the mate (turn, offset and flip) +//! taken off, so at the joint's zero the two frames coincide and its values and limits mean what +//! they mean in SolidCraft. A side on the design itself is the world. Rigid, revolute, slider, +//! cylindrical, planar and ball joints have an OpenUSD form; the writer keeps the limits of +//! revolute and slider joints only. A joint of another kind and a suppressed joint are left out, +//! each with a warning. A grounded placement is fixed to the world, in every placement written. +//! +//! Motion links: a gear link between two revolute joints and a rack-and-pinion link between a +//! revolute joint and a slider become PhysX gear and rack-and-pinion joints that couple the two +//! written joints ([`coupling`]). Another link (a screw, a cam, a link with no coupling) is left +//! out with a warning. +//! +//! Mass: each component placed in the design gets its bodies' mass, centre of mass and principal +//! inertia, from each body's density (its material's) and its closed mesh at standard quality, as +//! URDF export's links, and each placement of such a component is a rigid body, joined or not. +//! The design's own bodies get none: they never move. + +use std::collections::HashMap; + +use cadmpeg_ir::features::FinitePoint3; +use cadmpeg_ir::ids::{ArticulationId, MassPropertiesId, OccurrenceId, PhysicsSceneId, ProductDefinitionId, RigidBodyId}; +use cadmpeg_ir::math::Point3; +use cadmpeg_ir::physics::{Articulation, MassProperties, PhysicsScene, PhysicsTarget, PrincipalInertia, RigidBody}; +use cadmpeg_ir::products::{AssemblyJoint, JointConnector, JointId, JointLimits, JointOperand, PairedJointKind, PlaneSense}; +use cadmpeg_ir::scalar::{NonNegativeReal, PositiveReal}; +use cadmpeg_ir::transform::Transform; +use solidcraft_doc::joints::{self, Coupling, Joint, JointKind, MotionLink}; +use solidcraft_doc::{Document, IDENTITY, Mat, ModelState, mat_inverse, mat_mul}; + +use crate::urdf::BodyMass; + +/// The physics records of a design, and what they leave out. +#[derive(Default)] +pub(super) struct Physics { + pub joints: Vec, + pub masses: Vec, + pub rigid_bodies: Vec, + pub articulations: Vec, + pub scenes: Vec, + pub warnings: Vec, +} + +/// An id of this design's model, as [`super::cadir_out`] makes them. +fn id>(kind: &str, key: usize) -> Result { + let s = format!("solidcraft:design:{kind}#{key:09}"); + T::try_from(s.clone()).map_err(|_| format!("{s} is not a CADIR identity")) +} + +/// `m` (column-major, mm) as a CADIR transform, when finite. +fn transform(m: &Mat) -> Option { + let row = |r: usize| [m[0][r], m[1][r], m[2][r], m[3][r]]; + Transform::affine([row(0), row(1), row(2)]) +} + +/// The joints, grounding and masses of `doc` (`model`, the model before placing, holds each +/// component's bodies in its frame). `placed` gives the CADIR occurrence of each placement path, +/// `definitions` the CADIR definition of each component, `masses` each component's bodies' +/// masses in its frame. +pub(super) fn build( + doc: &Document, + model: &ModelState, + placed: &HashMap, OccurrenceId>, + definitions: &HashMap, + masses: &HashMap>, +) -> Result { + let mut out = Physics::default(); + // A side's written placement: `Some(None)` for the design itself (the world). + let end = |occurrence: u64| -> Option> { + if occurrence == 0 { + return Some(None); + } + placed.get(&crate::urdf::canonical(doc, occurrence)).map(|id| Some(id.clone())) + }; + let operand = |occurrence: u64| -> Option { + end(occurrence).map(|id| match id { + None => JointOperand::root("design", Vec::new()), + Some(id) => JointOperand::occurrence(id, "placement", Vec::new()), + }) + }; + // The written joints' ends, for the articulations. + let mut edges: Vec<(Option, Option, String)> = Vec::new(); + // Each written joint's id and kind, by the design's joint, for the motion links. + let mut written: HashMap = HashMap::new(); + let all = doc.joints_with_rigid_groups(); + for j in all.iter() { + if j.suppressed { + out.warnings.push(format!("joint `{}`: suppressed: left out of the physics", j.name)); + continue; + } + let Some(kind) = paired_kind(j, &mut out.warnings) else { continue }; + let connectors = match (connectors(doc, model, j), operand(j.a.occurrence), operand(j.b.occurrence)) { + (Some([fa, fb]), Some(a), Some(b)) if j.a.occurrence != j.b.occurrence => { + [JointConnector { operand: a, frame: fa, detached: false }, JointConnector { operand: b, frame: fb, detached: false }] + } + _ => { + out.warnings.push(format!( + "joint `{}`: its origins don't resolve, its placements are not written, or it joins a placement to itself: left out of the physics", + j.name + )); + continue; + } + }; + let mut joint = AssemblyJoint::paired(id::("joint", out.joints.len())?, kind, connectors, None); + joint.native_ref = Some(format!("solidcraft:design:joint/{}", j.name.replace('/', "_"))); + written.insert(j.id, (joint.id.clone(), j.kind)); + out.joints.push(joint); + if let (Some(a), Some(b)) = (end(j.a.occurrence), end(j.b.occurrence)) { + edges.push((a, b, j.name.clone())); + } + } + // Each coupling joins the parts its two joints turn or slide: each joint's moving side (the + // side not grounded, as the assembly solver moves it). It runs outside the articulations, so + // it adds no edge. + for (n, link) in doc.assembly.links.iter().enumerate() { + let name = |id: u64| all.iter().find(|j| j.id == id).map_or_else(|| format!("#{id}"), |j| j.name.replace('/', "_")); + let what = format!("motion link {} between `{}` and `{}`", n + 1, name(link.a), name(link.b)); + let (kind, coupled) = match coupling(link, &written) { + Ok(found) => found, + Err(reason) => { + out.warnings.push(format!("{what}: {reason}: left out of the physics")); + continue; + } + }; + // The part each joint moves, as the assembly solver takes it: not the grounded side. + let moving = |id: u64| all.iter().find(|j| j.id == id).and_then(|j| operand(joints::cam::moving_occurrence(doc, j))); + let (Some(a), Some(b)) = (moving(coupled[0]), moving(coupled[1])) else { + out.warnings.push(format!("{what}: its parts are not written: left out of the physics")); + continue; + }; + let connector = |operand| JointConnector { operand, frame: Transform::identity(), detached: false }; + let mut joint = AssemblyJoint::paired(id::("joint", out.joints.len())?, kind, [connector(a), connector(b)], None); + joint.native_ref = Some(format!("solidcraft:design:link/{}_{}", name(link.a), name(link.b))); + out.joints.push(joint); + } + // Every written placement of a grounded occurrence is fixed: a subassembly placed twice + // grounds its grounded part in both, as the design does. + let grounded: HashMap = doc.occurrences.iter().filter(|o| o.grounded).map(|o| (o.id, o.name.as_str())).collect(); + let mut paths: Vec<(&Vec, &OccurrenceId)> = placed.iter().collect(); + paths.sort(); + let mut anchored: Vec = Vec::new(); + for (path, occurrence) in &paths { + let Some(name) = path.last().and_then(|o| grounded.get(o)) else { continue }; + anchored.push((*occurrence).clone()); + let operand = JointOperand::occurrence((*occurrence).clone(), "placement", Vec::new()); + let connector = JointConnector { operand, frame: Transform::identity(), detached: false }; + let mut joint = AssemblyJoint::grounded(id::("joint", out.joints.len())?, connector, None); + joint.native_ref = Some(format!("solidcraft:design:joint/{} grounded", name.replace('/', "_"))); + out.joints.push(joint); + } + // Every written placement of a component with mass moves as a rigid body, joined or not + // (the writer makes rigid bodies of joined placements alone); the design itself stays put. + let component_of: HashMap = doc.occurrences.iter().map(|o| (o.id, o.component)).collect(); + for (path, occurrence) in &paths { + let Some(component) = path.last().and_then(|o| component_of.get(o)) else { continue }; + if masses.get(component).is_none_or(Vec::is_empty) { + continue; + } + out.rigid_bodies.push(RigidBody { + id: id::("rigid-body", out.rigid_bodies.len())?, + target: PhysicsTarget::Occurrence { occurrence: (*occurrence).clone() }, + kinematic: false, + enabled: true, + linear_velocity: None, + angular_velocity: None, + starts_asleep: false, + native_ref: None, + }); + } + out.articulations = articulations(&edges, &anchored, &mut out.warnings)?; + let mut components: Vec<(&u64, &Vec)> = masses.iter().filter(|(c, _)| **c != 0).collect(); + components.sort_by_key(|(c, _)| **c); + for (component, bodies) in components { + let Some(definition) = definitions.get(component) else { continue }; + let Some(inertial) = crate::urdf::inertial(bodies, &IDENTITY) else { continue }; + // kg m² back to kg mm². + let tensor = inertial.inertia.map(|row| row.map(|x| x * 1e6)); + let inertia = principal(tensor).and_then(|(moments, axes)| match moments.map(|m| NonNegativeReal::new(m.max(0.0))) { + [Some(a), Some(b), Some(c)] => Some(PrincipalInertia { moments: [a, b, c], axes }), + _ => None, + }); + out.masses.push(MassProperties { + id: id::("mass", out.masses.len())?, + target: PhysicsTarget::Definition { definition: definition.clone() }, + mass: PositiveReal::new(inertial.mass), + density: None, + center_of_mass: FinitePoint3::new(Point3::new(inertial.com.x, inertial.com.y, inertial.com.z)), + inertia, + material: None, + native_ref: None, + }); + } + out.scenes.push(PhysicsScene { + id: id::("scene", 0)?, + name: Some("PhysicsScene".into()), + gravity_direction: None, + gravity_magnitude: None, + native_ref: None, + }); + Ok(out) +} + +/// The articulations of the joints `edges` (each joint's two ends: a placement, or `None` for the +/// world) with the placements `anchored` fixed to the world: one for each group of placements the +/// joints connect that forms a tree. Its root is the group's anchor (a placement fixed to the world +/// or jointed to it), else the first joint's A side, as URDF export anchors a floating group. A +/// group with a closed loop, through two anchors and the world included, has no articulation, with +/// a warning: PhysX would solve its joints apart. +pub(super) fn articulations( + edges: &[(Option, Option, String)], + anchored: &[OccurrenceId], + warnings: &mut Vec, +) -> Result, String> { + // Union-find over the placements the joints touch, in the order the joints first touch them, + // halving each path it walks, so a long chain of unions is walked once. + let mut order: Vec = Vec::new(); + let mut parent: HashMap = HashMap::new(); + fn find(parent: &mut HashMap, mut x: OccurrenceId) -> OccurrenceId { + while let Some(p) = parent.get(&x).filter(|p| **p != x).cloned() { + let up = parent.get(&p).cloned().unwrap_or_else(|| p.clone()); + parent.insert(x, up.clone()); + x = up; + } + x + } + for (a, b, _) in edges { + for id in [a, b].into_iter().flatten() { + if !parent.contains_key(id) { + parent.insert(id.clone(), id.clone()); + order.push(id.clone()); + } + } + if let (Some(a), Some(b)) = (a, b) { + let (ra, rb) = (find(&mut parent, a.clone()), find(&mut parent, b.clone())); + if ra != rb { + parent.insert(rb, ra); + } + } + } + // Each group's members, joints and world joints, gathered in one pass over the placements + // and one over the joints, the groups in the order of their first placements. + struct Group<'e> { + first: OccurrenceId, + members: Vec, + joints: Vec<&'e str>, + internal: usize, + to_world: Vec, + } + let mut groups: Vec = Vec::new(); + let mut group_of: HashMap = HashMap::new(); + for o in &order { + let root = find(&mut parent, o.clone()); + let k = *group_of.entry(root).or_insert_with(|| { + groups.push(Group { first: o.clone(), members: Vec::new(), joints: Vec::new(), internal: 0, to_world: Vec::new() }); + groups.len() - 1 + }); + if let Some(g) = groups.get_mut(k) { + g.members.push(o.clone()); + } + } + for (a, b, name) in edges { + let Some(side) = a.as_ref().or(b.as_ref()) else { continue }; + let root = find(&mut parent, side.clone()); + let Some(g) = group_of.get(&root).and_then(|k| groups.get_mut(*k)) else { continue }; + g.joints.push(name.as_str()); + match (a, b) { + (Some(_), Some(_)) => g.internal += 1, + (Some(o), None) | (None, Some(o)) => g.to_world.push(o.clone()), + (None, None) => {} + } + } + let anchored: std::collections::HashSet<&OccurrenceId> = anchored.iter().collect(); + let mut out = Vec::new(); + for g in groups { + let fixed: Vec<&OccurrenceId> = g.members.iter().filter(|m| anchored.contains(m)).collect(); + if g.internal + 1 != g.members.len() || g.to_world.len() + fixed.len() > 1 { + warnings.push(format!( + "joints `{}` close a loop (two fixed or world-jointed parts close one through the world): written without an articulation, so PhysX solves them as separate joints", + g.joints.join("`, `") + )); + continue; + } + let root = fixed.first().map(|m| (*m).clone()).or_else(|| g.to_world.first().cloned()).unwrap_or(g.first); + out.push(Articulation { + id: id::("articulation", out.len())?, + root: PhysicsTarget::Occurrence { occurrence: root }, + native_ref: None, + }); + } + Ok(out) +} + +/// The PhysX coupling of motion link `link` between the written joints `written` (each design +/// joint's written id and kind), with the design joints it couples in CADIR's order (the gears' a +/// and b; the pinion's, then the rack's), or why it has none. PhysX's gear joint turns its second +/// hinge `ratio` times its first's angle the other way round, and its rack-and-pinion joint moves +/// the rack along its slider's axis as the pinion turns positively about its hinge's. CADIR states +/// each ratio as a magnitude, so gears that turn the same way (an internal gear, or a reversed +/// link) and a rack that moves the other way have no form. +pub(super) fn coupling(link: &MotionLink, written: &HashMap) -> Result<(PairedJointKind, [u64; 2]), String> { + let joint = |id: u64| written.get(&id).ok_or("its joints are not written"); + let ((ja, ka), (jb, kb)) = (joint(link.a)?, joint(link.b)?); + let ratio = |r: f64| PositiveReal::new(r).ok_or_else(|| format!("its ratio {} has no PhysX form", link.ratio)); + match &link.coupling { + Some(Coupling::Gear { .. }) => { + if (*ka, *kb) != (JointKind::Revolute, JointKind::Revolute) { + return Err("PhysX gears couple two revolute joints".into()); + } + if link.ratio > 0.0 { + return Err("its gears turn the same way, and PhysX's gear joint turns them opposite ways".into()); + } + let kind = PairedJointKind::Gears { + distance: None, + distance2: None, + ratio: Some(ratio(-link.ratio)?), + coupled_joints: vec![ja.clone(), jb.clone()], + }; + Ok((kind, [link.a, link.b])) + } + Some(Coupling::RackPinion { .. }) => { + // The rack's travel (mm) per radian of the pinion, and the two joints in that order. + let (travel, pinion, rack) = match (ka, kb) { + (JointKind::Revolute, JointKind::Slider) if link.ia == 0 && link.ib == 0 => (link.ratio, (link.a, ja), (link.b, jb)), + (JointKind::Slider, JointKind::Revolute) if link.ia == 0 && link.ib == 0 => (1.0 / link.ratio, (link.b, jb), (link.a, ja)), + _ => return Err("a PhysX rack and pinion couples a revolute joint and a slider".into()), + }; + if travel < 0.0 { + return Err("its rack moves against the pinion's turn, and PhysX's rack and pinion moves it with the turn".into()); + } + let kind = PairedJointKind::RackPinion { + distance: None, + distance2: None, + ratio: Some(ratio(1.0 / travel)?), + coupled_joints: vec![pinion.1.clone(), rack.1.clone()], + }; + Ok((kind, [pinion.0, rack.0])) + } + Some(Coupling::Screw { .. }) => Err("a screw has no OpenUSD physics form".into()), + Some(Coupling::Cam(_)) => Err("a cam has no OpenUSD physics form".into()), + None => Err("a link with no gear or rack has no OpenUSD physics form".into()), + } +} + +/// The two connector frames of `j`, each in its placement's component frame: A's frame with its +/// lateral offset, and B's frame with the mate taken off, so the two coincide at the joint's zero. +fn connectors(doc: &Document, model: &ModelState, j: &Joint) -> Option<[Transform; 2]> { + let a = j.offset_frame_a(joints::resolve_origin(doc, model, &j.a).ok()?); + let b = mat_mul(&joints::resolve_origin(doc, model, &j.b).ok()?, &mat_inverse(&joints::flip_of(j))?); + Some([transform(&a)?, transform(&b)?]) +} + +/// The CADIR form of `j`'s kind, or `None` with a warning when it has none the writer writes. +fn paired_kind(j: &Joint, warnings: &mut Vec) -> Option { + let limit = |i: usize| j.limits.get(i).copied().flatten().and_then(|(min, max)| JointLimits::new(Some(min), Some(max))); + let limited = j.limits.iter().any(Option::is_some); + let mut unlimited = |kind: &str| { + if limited { + warnings.push(format!("joint `{}`: OpenUSD writes a {kind} joint without limits: its limits are left out", j.name)); + } + }; + Some(match j.kind { + JointKind::Rigid => PairedJointKind::Fixed { angle: None, translation_offset: None, angular_limits: None, linear_limits: None }, + JointKind::Revolute => PairedJointKind::Revolute { angle: None, angular_limits: limit(0) }, + JointKind::Slider => PairedJointKind::Slider { distance: None, translation_offset: None, linear_limits: limit(0) }, + JointKind::Cylindrical => { + unlimited("cylindrical"); + PairedJointKind::Cylindrical { angle: None, distance: None, angular_limits: limit(0), linear_limits: limit(1) } + } + JointKind::Planar => { + unlimited("planar"); + PairedJointKind::PlaneCoincidence { sense: PlaneSense::Aligned, offset: None } + } + JointKind::Ball => { + unlimited("ball"); + PairedJointKind::Ball {} + } + other => { + warnings.push(format!("joint `{}`: a {other:?} joint has no OpenUSD physics form: left out", j.name)); + return None; + } + }) +} + +/// How close two principal moments are (a share of the largest) to count as equal: round-off +/// only, so the axes written are the tensor's own. +const EQUAL_MOMENTS: f64 = 1e-9; + +/// The principal moments of the symmetric tensor `t` and the rotation whose columns are its +/// principal axes (`t = R · diag(moments) · Rᵀ`), `None` when they are the tensor's own axes; +/// [`solidcraft_geom::inertia::principal`] finds them. `None` for a tensor with non-finite entries. +pub(super) fn principal(t: [[f64; 3]; 3]) -> Option<([f64; 3], Option)> { + let (moments, [a, b, c]) = solidcraft_geom::inertia::principal(&t, EQUAL_MOMENTS)?; + let own = [a, b, c] == [solidcore_record::Vec3::X, solidcore_record::Vec3::Y, solidcore_record::Vec3::Z]; + let axes = if own { None } else { Transform::affine([[a.x, b.x, c.x, 0.0], [a.y, b.y, c.y, 0.0], [a.z, b.z, c.z, 0.0]]) }; + Some((moments, axes)) +} + +#[cfg(test)] +mod tests { + use super::articulations; + use cadmpeg_ir::ids::OccurrenceId; + use cadmpeg_ir::physics::PhysicsTarget; + + fn occ(name: &str) -> OccurrenceId { + OccurrenceId::try_from(format!("test:physics:occurrence#{name}")).unwrap() + } + + fn edge(a: Option<&str>, b: Option<&str>, name: &str) -> (Option, Option, String) { + (a.map(occ), b.map(occ), name.to_string()) + } + + fn roots(edges: &[(Option, Option, String)], anchored: &[&str]) -> (Vec, Vec) { + let anchored: Vec = anchored.iter().map(|a| occ(a)).collect(); + let mut warnings = Vec::new(); + let found = articulations(edges, &anchored, &mut warnings).unwrap(); + let roots = found + .into_iter() + .map(|a| match a.root { + PhysicsTarget::Occurrence { occurrence } => occurrence, + other => panic!("{other:?}"), + }) + .collect(); + (roots, warnings) + } + + /// A chain fixed at one end is one articulation rooted there; a floating chain is rooted at + /// its first joint's A side; a part jointed to the world anchors its group. + #[test] + fn a_tree_is_one_articulation_rooted_at_its_anchor() { + let chain = [edge(Some("b"), Some("a"), "j1"), edge(Some("b"), Some("c"), "j2")]; + assert_eq!(roots(&chain, &["a"]), (vec![occ("a")], vec![])); + assert_eq!(roots(&chain, &[]), (vec![occ("b")], vec![])); + let to_world = [edge(Some("a"), Some("b"), "j1"), edge(None, Some("b"), "j0")]; + assert_eq!(roots(&to_world, &[]), (vec![occ("b")], vec![])); + } + + /// Two groups are two articulations. + #[test] + fn separate_groups_are_separate_articulations() { + let edges = [edge(Some("a"), Some("b"), "j1"), edge(Some("c"), Some("d"), "j2")]; + assert_eq!(roots(&edges, &["d"]), (vec![occ("a"), occ("d")], vec![])); + } + + /// Many groups, and a long chain, take one pass each: 50,000 separate pairs are 50,000 + /// articulations in their order, and a chain of 50,000 joints one, rooted at its anchor. + #[test] + fn many_groups_and_a_long_chain_are_grouped_in_one_pass() { + let pairs: Vec<_> = (0..50_000).map(|k| edge(Some(&format!("a{k}")), Some(&format!("b{k}")), &format!("j{k}"))).collect(); + let (found, warnings) = roots(&pairs, &[]); + assert_eq!(found.len(), 50_000); + assert!(warnings.is_empty() && found[0] == occ("a0") && found[49_999] == occ("a49999")); + let chain: Vec<_> = (0..50_000).map(|k| edge(Some(&format!("c{}", k + 1)), Some(&format!("c{k}")), &format!("j{k}"))).collect(); + assert_eq!(roots(&chain, &["c0"]), (vec![occ("c0")], vec![])); + } + + /// A closed loop has no articulation, with a warning naming its joints; two anchors close one + /// through the world. + #[test] + fn a_loop_has_no_articulation() { + let triangle = [edge(Some("a"), Some("b"), "j1"), edge(Some("b"), Some("c"), "j2"), edge(Some("c"), Some("a"), "j3")]; + let (found, warnings) = roots(&triangle, &[]); + assert!(found.is_empty()); + assert!(warnings[0].contains("`j1`, `j2`, `j3`"), "{warnings:?}"); + let (found, warnings) = roots(&[edge(Some("a"), Some("b"), "j1")], &["a", "b"]); + assert!(found.is_empty() && warnings.len() == 1, "{warnings:?}"); + let (found, _) = roots(&[edge(Some("a"), Some("b"), "j1"), edge(None, Some("b"), "j0")], &["a"]); + assert!(found.is_empty()); + } + + use super::principal; + + /// `R · diag(moments) · Rᵀ` from the rotation's rows. + fn rebuilt(moments: [f64; 3], rows: [[f64; 4]; 3]) -> [[f64; 3]; 3] { + let mut t = [[0.0; 3]; 3]; + for (i, row) in t.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| rows[i][k] * moments[k] * rows[j][k]).sum(); + } + } + t + } + + #[test] + fn a_diagonal_tensor_keeps_its_axes() { + let (moments, axes) = principal([[2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 4.0]]).unwrap(); + assert_eq!(moments, [2.0, 3.0, 4.0]); + assert!(axes.is_none()); + } + + /// A box's tensor turned 30° about z: `R diag(Ixx, Iyy, Izz) Rᵀ` with R the turn. The moments + /// come back, and the axes rebuild the tensor. + #[test] + fn a_turned_tensor_gives_its_moments_and_axes() { + let (ixx, iyy, izz) = (5.0, 13.0, 10.0); + let (s, c) = 30f64.to_radians().sin_cos(); + let t = [[c * c * ixx + s * s * iyy, c * s * (ixx - iyy), 0.0], [c * s * (ixx - iyy), s * s * ixx + c * c * iyy, 0.0], [0.0, 0.0, izz]]; + let (moments, axes) = principal(t).unwrap(); + let mut sorted = moments; + sorted.sort_by(f64::total_cmp); + for (got, want) in sorted.iter().zip([ixx, izz, iyy]) { + assert!((got - want).abs() < 1e-12, "{moments:?}"); + } + let rows = axes.expect("turned axes").affine_rows(); + let back = rebuilt(moments, rows); + for (g, w) in back.iter().flatten().zip(t.iter().flatten()) { + assert!((g - w).abs() < 1e-12, "{back:?} is not {t:?}"); + } + } + + mod couplings { + use super::super::coupling; + use cadmpeg_ir::products::{JointId, PairedJointKind}; + use solidcraft_doc::joints::{Coupling, JointKind, MotionLink, Size}; + use std::collections::HashMap; + + fn joint(n: u64) -> JointId { + JointId::try_from(format!("test:physics:joint#{n}")).unwrap() + } + + /// Joints 1 and 2 are revolute, joint 3 a slider; joint 4 is not written. + fn written() -> HashMap { + [(1, JointKind::Revolute), (2, JointKind::Revolute), (3, JointKind::Slider)].into_iter().map(|(n, k)| (n, (joint(n), k))).collect() + } + + fn link(a: u64, b: u64, ratio: f64, coupling: Coupling) -> MotionLink { + MotionLink { a, ia: 0, b, ib: 0, ratio, offset: 0.0, coupling: Some(coupling), lift: Vec::new() } + } + + fn gear() -> Coupling { + Coupling::Gear { ra: Size::Length(20.0), rb: Size::Length(10.0), internal: false, reverse: false } + } + + fn rack() -> Coupling { + Coupling::RackPinion { radius: Size::Length(5.0), reverse: false } + } + + fn ratio_of(kind: &PairedJointKind) -> (f64, Vec) { + match kind { + PairedJointKind::Gears { ratio, coupled_joints, .. } | PairedJointKind::RackPinion { ratio, coupled_joints, .. } => { + (ratio.unwrap().get(), coupled_joints.clone()) + } + other => panic!("{other:?} is no coupling"), + } + } + + #[test] + fn opposite_gears_are_a_gear_joint_of_the_ratio() { + // b turns twice a's angle the other way: gearRatio 2, hinge0 a's joint. + let (kind, coupled) = coupling(&link(1, 2, -2.0, gear()), &written()).unwrap(); + assert!(matches!(kind, PairedJointKind::Gears { .. })); + assert_eq!(ratio_of(&kind), (2.0, vec![joint(1), joint(2)])); + assert_eq!(coupled, [1, 2]); + } + + #[test] + fn gears_turning_the_same_way_have_no_form() { + let err = coupling(&link(1, 2, 0.5, gear()), &written()).unwrap_err(); + assert!(err.contains("same way"), "{err}"); + } + + #[test] + fn a_rack_is_coupled_pinion_first_in_radians_per_millimetre() { + // 5 mm of rack per radian is 0.2 rad/mm, whichever joint drives. + for (l, want) in [(link(1, 3, 5.0, rack()), 0.2), (link(3, 1, 0.2, rack()), 0.2)] { + let (kind, coupled) = coupling(&l, &written()).unwrap(); + assert!(matches!(kind, PairedJointKind::RackPinion { .. })); + let (ratio, joints) = ratio_of(&kind); + assert!((ratio - want).abs() < 1e-12, "{ratio}"); + assert_eq!(joints, vec![joint(1), joint(3)]); + assert_eq!(coupled, [1, 3]); + } + } + + #[test] + fn a_rack_moving_against_the_turn_has_no_form() { + assert!(coupling(&link(1, 3, -5.0, rack()), &written()).is_err()); + assert!(coupling(&link(3, 1, -0.2, rack()), &written()).is_err()); + } + + #[test] + fn other_links_have_no_form() { + let screw = Coupling::Screw { pitch: Size::Length(2.0), reverse: false }; + assert!(coupling(&link(1, 3, 1.0, screw), &written()).is_err()); + assert!(coupling(&link(1, 3, -2.0, gear()), &written()).is_err(), "a gear on a slider"); + assert!(coupling(&link(1, 4, -2.0, gear()), &written()).is_err(), "an unwritten joint"); + let plain = MotionLink { coupling: None, ..link(1, 2, -1.0, gear()) }; + assert!(coupling(&plain, &written()).is_err()); + } + } +} diff --git a/crates/io/src/native_cad/cadir_textures.rs b/crates/io/src/native_cad/cadir_textures.rs new file mode 100644 index 00000000000..43d412219bb --- /dev/null +++ b/crates/io/src/native_cad/cadir_textures.rs @@ -0,0 +1,401 @@ +//! The image textures a render setup gives a body, as CADIR texture coordinates, assets and +//! texture references, for an OpenUSD package ([`crate::CadmpegOptions::surfaces`]). +//! +//! Coordinates: the setup projects its images onto the body along a plane, so a point's place in +//! the images is a linear function of the point, and the coordinates of the mesh's vertices +//! reproduce the projection exactly. The renderer reads an image from its top-left corner with v +//! downwards; a `UsdUVTexture` reads it from its bottom-left with t upwards, so t is the +//! renderer's v negated (the images repeat, so no offset is needed). +//! +//! Maps: base colour drives the diffuse colour, roughness and metallic their inputs (from the +//! red channel, as the renderer reads them), and the normal map the normal. A normal map is +//! written only where the file shows it as the renderer does: at full strength, with the image's +//! v flipped as the built-in surfaces have it (then the map's green points along the +//! projection's v in both). Any other normal map is left out, with a warning. + +use std::collections::HashMap; + +use cadmpeg_core::text::NonBlankString; +use cadmpeg_ir::appearance::{TextureMap2d, TextureRef}; +use cadmpeg_ir::assets::{Asset, AssetContent, AssetData, AssetId}; +use cadmpeg_ir::scalar::{Angle, FiniteReal, Length}; +use cadmpeg_ir::tessellation::{TextureCoordinateAddressing, TextureCoordinates}; +use cadmpeg_ir::units::FinitePoint2; +use solidcraft_doc::{Mat, apply_point, apply_vector}; + +use crate::SurfacePlan; + +/// The name of the texture-coordinate set written. +const COORDINATES: &str = "st"; + +/// The texture coordinates of `positions` (in the frame `to_mesh` takes the body's definition +/// frame to) under `plan`'s projection; `None` when the projection or a point is not finite. +pub(super) fn coordinates(positions: &[solidcore_record::Vec3], plan: &SurfacePlan, to_mesh: &Mat) -> Option { + let v3 = |a: [f64; 3]| solidcore_record::Vec3::new(a[0], a[1], a[2]); + let origin = apply_point(to_mesh, v3(plan.origin)); + let (u, v) = (apply_vector(to_mesh, v3(plan.u)), apply_vector(to_mesh, v3(plan.v))); + // The projection's own layout maths, written out: no model decision is made here. + let dot = |a: solidcore_record::Vec3, b: solidcore_record::Vec3| a.x * b.x + a.y * b.y + a.z * b.z; + let (uu, vv) = (dot(u, u), dot(v, v)); + if !(uu > 0.0 && vv > 0.0 && uu.is_finite() && vv.is_finite()) { + return None; + } + let mut values = Vec::new(); + values.try_reserve_exact(positions.len()).ok()?; + for p in positions { + let d = *p - origin; + let s = dot(d, u) / uu; + let along_v = dot(d, v) / vv; + let t = if plan.flip_v { along_v } else { -along_v }; + values.push(FinitePoint2::new(cadmpeg_ir::math::Point2::new(s, t))?); + } + Some(TextureCoordinates { name: NonBlankString::new(COORDINATES)?, addressing: TextureCoordinateAddressing::Vertex, values }) +} + +/// The assets written, by the SHA-256 of their bytes. +#[derive(Default)] +pub(super) struct Assets { + by_sha: HashMap, +} + +impl Assets { + /// The asset holding `map`, added to `assets` the first time. + fn asset(&mut self, assets: &mut Vec, map: &crate::SurfaceMap) -> Option { + if let Some(id) = self.by_sha.get(&map.sha256) { + return Some(id.clone()); + } + let (extension, media) = if map.bytes.starts_with(b"\x89PNG") { + ("png", "image/png") + } else if map.bytes.starts_with(&[0xFF, 0xD8]) { + ("jpg", "image/jpeg") + } else { + return None; + }; + let id = AssetId::try_from(format!("solidcraft:design:texture#{}", map.sha256)).ok()?; + let content = AssetContent::Embedded { data: AssetData::new(map.bytes.to_vec())? }; + let asset = Asset::try_new(id.clone(), Some(format!("{}.{extension}", map.sha256)), Some(media.into()), content, None).ok()?; + assets.push(asset); + self.by_sha.insert(map.sha256.clone(), id.clone()); + Some(id) + } +} + +/// A texture reading the `COORDINATES` set as they are: no offset, scale or turn, repeating. +fn mapping() -> TextureMap2d { + TextureMap2d { + map_channel: 0, + uvw_source: 0, + u_offset: FiniteReal::ZERO, + v_offset: FiniteReal::ZERO, + u_scale: FiniteReal::ONE, + v_scale: FiniteReal::ONE, + rotation: Angle::ZERO, + repeat_u: true, + repeat_v: true, + real_world_offset_x: Length::ZERO, + real_world_offset_y: Length::ZERO, + real_world_scale_x: Length::ZERO, + real_world_scale_y: Length::ZERO, + coordinates: NonBlankString::new(COORDINATES), + } +} + +/// The texture references of `plan`'s maps, their assets added to `assets`; what is left out is +/// a warning naming `shown`. +pub(super) fn references( + plan: &SurfacePlan, + registry: &mut Assets, + assets: &mut Vec, + shown: &str, + warnings: &mut Vec, +) -> Vec { + if plan.normal.is_some() && written_normal(plan).is_none() { + warnings.push(format!( + "{shown}: the normal map of render setup `{}` is left out: OpenUSD shows only a full-strength map whose image's v is flipped as the renderer reads it", + plan.setup + )); + } + let maps = [ + ("diffuseColor", plan.base_color.as_ref()), + ("normal", written_normal(plan)), + ("roughness.r", plan.roughness.as_ref()), + ("metallic.r", plan.metallic.as_ref()), + ]; + let mut out = Vec::new(); + for (slot, map) in maps { + let Some(map) = map else { continue }; + let Some(asset) = registry.asset(assets, map) else { + warnings.push(format!("{shown}: an image of render setup `{}` is neither PNG nor JPEG: left out", plan.setup)); + continue; + }; + out.push(TextureRef { + asset_guid: asset.to_string(), + slot: slot.to_string(), + schema: "UsdPreviewSurface".into(), + paths: Vec::new(), + urn: None, + mapping: mapping(), + bump: None, + }); + } + out +} + +/// How far a decal's quad is lifted off the face it lies on, each side, mm: as URDF export's. +const DECAL_LIFT_MM: f64 = 0.2; + +/// A decal's quad lifted clear of its face on both sides: its points (the front four, then the +/// back four), their normals, its triangles (the back wound the other way, so one side faces out +/// whichever way the face does) and its texture coordinates (the image's bottom-left at (0, 0), +/// its top-right at (1, 1)). `None` when the corners give no plane. +pub(super) fn decal_quad(corners: [[f64; 3]; 4]) -> Option<(Vec<[f64; 3]>, Vec<[f64; 3]>, Vec<[u32; 3]>, TextureCoordinates)> { + let (normal, front, back) = solidcore_ops::affine::lifted_quad(corners, DECAL_LIFT_MM)?; + let points: Vec<[f64; 3]> = front.into_iter().chain(back).collect(); + let flipped = normal.map(|x| -x); + let normals: Vec<[f64; 3]> = std::iter::repeat_n(normal, 4).chain(std::iter::repeat_n(flipped, 4)).collect(); + let triangles = vec![[0, 1, 2], [0, 2, 3], [4, 6, 5], [4, 7, 6]]; + let corner_uv = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]; + let values = corner_uv + .iter() + .chain(corner_uv.iter()) + .map(|[u, v]| FinitePoint2::new(cadmpeg_ir::math::Point2::new(*u, *v))) + .collect::>>()?; + let coordinates = TextureCoordinates { name: NonBlankString::new(COORDINATES)?, addressing: TextureCoordinateAddressing::Vertex, values }; + Some((points, normals, triangles, coordinates)) +} + +/// The texture references of a decal's image: its colour, and its alpha as the opacity when the +/// image has one (a PNG of an alpha colour type, or with a transparency chunk). +pub(super) fn decal_references(image: &crate::SurfaceMap, registry: &mut Assets, assets: &mut Vec) -> Option> { + let asset = registry.asset(assets, image)?; + let reference = |slot: &str| TextureRef { + asset_guid: asset.to_string(), + slot: slot.to_string(), + schema: "UsdPreviewSurface".into(), + paths: Vec::new(), + urn: None, + mapping: mapping(), + bump: None, + }; + let mut out = vec![reference("diffuseColor")]; + if png_has_alpha(&image.bytes) { + out.push(reference("opacity.a")); + } + Some(out) +} + +/// Whether `bytes` are a PNG with an alpha channel: a colour type with alpha (grey or RGB with +/// alpha, IHDR's) or a transparency chunk (`tRNS`, which comes before the image data). Only the +/// chunks before the first `IDAT` are walked, by their lengths, so the work is bounded by the +/// header chunks and not the image; anything else (a JPEG, a damaged PNG) has none. +fn png_has_alpha(bytes: &[u8]) -> bool { + const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; + let Some(mut rest) = bytes.strip_prefix(SIGNATURE) else { return false }; + // Each chunk: its data's length (4 bytes, big-endian), its type (4), the data, a CRC (4). + // IHDR's data: width and height (8), bit depth (1), colour type (1). + while let Some((head, after)) = rest.split_first_chunk::<8>() { + let length = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize; + let Some(data) = after.get(..length) else { return false }; + match &head[4..] { + b"IHDR" if matches!(data.get(9), Some(4 | 6)) => return true, + b"tRNS" => return true, + b"IDAT" | b"IEND" => return false, + _ => {} + } + let Some(next) = length.checked_add(4).and_then(|n| after.get(n..)) else { return false }; + rest = next; + } + false +} + +/// The `MaterialX` OpenPBR shader cadmpeg writes beside the preview surface: an appearance +/// property `/` is that shader's input. +const OPEN_PBR: &str = "ND_open_pbr_surface_surfaceshader"; +/// The depth at which a transmission colour is reached, in the layer's units (metres): 1 mm. +const TRANSMISSION_DEPTH_M: f64 = 1e-3; + +/// The appearance properties of `optics`: its index of refraction (the preview surface's `ior`, +/// which cadmpeg also gives OpenPBR as `specular_ior`), and OpenPBR's transmission: full, with the +/// colour the absorption leaves after 1 mm (Beer–Lambert, e^(−absorption · 1 mm)) at a depth of +/// 1 mm, thin-walled for a thin sheet. OpenPBR's metalness is 0, as a metal does not transmit: +/// cadmpeg would otherwise give it the look's `metallic`, and base metalness takes the +/// transmission away (the preview surface, which has no transmission, keeps the look's). +pub(super) fn optics_properties(optics: &crate::OpticsPlan) -> Vec<(String, f64)> { + let mut out = + vec![("ior".to_string(), optics.ior), (format!("{OPEN_PBR}/transmission_weight"), 1.0), (format!("{OPEN_PBR}/base_metalness"), 0.0)]; + for (channel, a) in ["r", "g", "b"].iter().zip(optics.absorption_per_mm) { + out.push((format!("{OPEN_PBR}/transmission_color.{channel}"), (-a).exp())); + } + out.push((format!("{OPEN_PBR}/transmission_depth"), TRANSMISSION_DEPTH_M)); + if optics.thin_sheet { + out.push((format!("{OPEN_PBR}/geometry_thin_walled"), 1.0)); + } + out +} + +/// The normal map `plan` writes: only one the file shows as the renderer does (full strength, +/// the image's v flipped as the built-in surfaces have it). +fn written_normal(plan: &SurfacePlan) -> Option<&crate::SurfaceMap> { + plan.normal.as_ref().filter(|_| plan.flip_v && plan.normal_strength == 1.0) +} + +/// Whether `a` and `b` texture a body alike: the same projection and the same images written (a +/// normal map left out of both does not tell them apart). A glass body's metallic map is not +/// written either (`glass`), so it does not tell two placements apart. +pub(super) fn same(a: &SurfacePlan, b: &SurfacePlan, glass: bool) -> bool { + let sha = |m: Option<&crate::SurfaceMap>| m.map(|m| m.sha256.clone()); + let metallic = |p: &SurfacePlan| if glass { None } else { sha(p.metallic.as_ref()) }; + (a.origin, a.u, a.v, a.flip_v) == (b.origin, b.u, b.v, b.flip_v) + && [sha(a.base_color.as_ref()), sha(written_normal(a)), sha(a.roughness.as_ref()), metallic(a)] + == [sha(b.base_color.as_ref()), sha(written_normal(b)), sha(b.roughness.as_ref()), metallic(b)] +} + +#[cfg(test)] +mod tests { + use super::*; + use solidcore_record::Vec3; + + fn plan(flip_v: bool) -> SurfacePlan { + SurfacePlan { + setup: "Studio".into(), + definition: "Body1".into(), + component: 0, + path: Vec::new(), + world: "Body1".into(), + origin: [10.0, 0.0, 0.0], + u: [20.0, 0.0, 0.0], + v: [0.0, 0.0, 5.0], + flip_v, + normal_strength: 1.0, + base_color: None, + normal: None, + roughness: None, + metallic: None, + } + } + + /// A point's coordinates are its offsets from the origin along u and v in repeats of their + /// lengths: (30, 7, 2.5) is one repeat of u (20 mm) and half a repeat of v (5 mm) from + /// (10, 0, 0); t is v negated unless the image's v is flipped. A point off the plane (y = 7) + /// projects along its normal. + #[test] + fn coordinates_follow_the_projection() { + let points = [Vec3::new(10.0, 0.0, 0.0), Vec3::new(30.0, 7.0, 2.5)]; + let st = |flip: bool| -> Vec<[f64; 2]> { + coordinates(&points, &plan(flip), &solidcraft_doc::IDENTITY).unwrap().values.iter().map(|p| [p.get().u, p.get().v]).collect() + }; + assert_eq!(st(true), [[0.0, 0.0], [1.0, 0.5]]); + assert_eq!(st(false), [[0.0, 0.0], [1.0, -0.5]]); + } + + /// Moving the body moves the projection with it: the definition frame taken 100 mm along x. + #[test] + fn coordinates_follow_the_body_frame() { + let mut moved = solidcraft_doc::IDENTITY; + moved[3][0] = 100.0; + let points = [Vec3::new(130.0, 0.0, 2.5)]; + let got = coordinates(&points, &plan(true), &moved).unwrap(); + let p = got.values[0].get(); + assert_eq!([p.u, p.v], [1.0, 0.5]); + } + + /// Optics as properties: the index, full transmission, the colour 1 mm of absorption leaves + /// (e^(−a)), and thin walls for a thin sheet only. + #[test] + fn optics_become_ior_and_openpbr_transmission() { + let mut optics = crate::OpticsPlan { + setup: "Glass".into(), + definition: "Body1".into(), + component: 0, + path: Vec::new(), + world: "Body1".into(), + ior: 1.52, + absorption_per_mm: [0.0, 0.1, 2.0], + thin_sheet: false, + }; + let get = |p: &[(String, f64)], k: &str| p.iter().find(|(n, _)| n.ends_with(k)).map(|(_, v)| *v); + let p = optics_properties(&optics); + assert_eq!(get(&p, "ior"), Some(1.52)); + assert_eq!(get(&p, "transmission_weight"), Some(1.0)); + assert_eq!(get(&p, "base_metalness"), Some(0.0)); + assert_eq!(get(&p, "transmission_color.r"), Some(1.0)); + assert!((get(&p, "transmission_color.g").unwrap() - (-0.1f64).exp()).abs() < 1e-15); + assert!((get(&p, "transmission_color.b").unwrap() - (-2.0f64).exp()).abs() < 1e-15); + assert_eq!(get(&p, "transmission_depth"), Some(1e-3)); + assert_eq!(get(&p, "geometry_thin_walled"), None); + optics.thin_sheet = true; + assert_eq!(get(&optics_properties(&optics), "geometry_thin_walled"), Some(1.0)); + } + + /// A decal's quad: eight points, two lifted 0.2 mm each side of the corners' plane, with the + /// image's corners at its corners. + #[test] + fn a_decal_is_a_two_sided_quad_with_its_image_corners() { + let corners = [[0.0, 0.0, 0.0], [10.0, 0.0, 0.0], [10.0, 5.0, 0.0], [0.0, 5.0, 0.0]]; + let (points, normals, triangles, st) = decal_quad(corners).unwrap(); + assert_eq!(points.len(), 8); + assert!(points[..4].iter().all(|p| (p[2] - 0.2).abs() < 1e-12) && points[4..].iter().all(|p| (p[2] + 0.2).abs() < 1e-12), "{points:?}"); + assert_eq!(normals[0], [0.0, 0.0, 1.0]); + assert_eq!(triangles.len(), 4); + let uv: Vec<[f64; 2]> = st.values.iter().map(|p| [p.get().u, p.get().v]).collect(); + assert_eq!(uv[2], [1.0, 1.0]); + assert_eq!(uv[6], [1.0, 1.0]); + assert!(decal_quad([[0.0; 3]; 4]).is_none()); + } + + /// A PNG of `colour` type, with a transparency chunk for RGB when `trns`. + fn png(colour: png::ColorType, trns: bool) -> Vec { + let mut out = Vec::new(); + { + let mut encoder = png::Encoder::new(&mut out, 1, 1); + encoder.set_color(colour); + encoder.set_depth(png::BitDepth::Eight); + if trns { + // One transparent colour as PNG writes it for RGB: two bytes for each channel, + // whatever the bit depth. + encoder.set_trns(vec![0u8; 6]); + } + let mut writer = encoder.write_header().unwrap(); + let size = match colour { + png::ColorType::Rgba => 4, + png::ColorType::Rgb => 3, + png::ColorType::GrayscaleAlpha => 2, + _ => 1, + }; + writer.write_image_data(&vec![255u8; size]).unwrap(); + } + out + } + + /// Alpha is read from the PNG's header chunks: an RGBA or grey-and-alpha PNG has it, and an + /// RGB one has it only with a transparency chunk. A JPEG whose 26th byte (a quantization value) + /// reads as an alpha colour type, and a PNG cut off in its header, have none. + #[test] + fn png_alpha_is_read_from_its_header_chunks() { + assert!(png_has_alpha(&png(png::ColorType::Rgba, false))); + assert!(png_has_alpha(&png(png::ColorType::GrayscaleAlpha, false))); + assert!(!png_has_alpha(&png(png::ColorType::Rgb, false))); + assert!(png_has_alpha(&png(png::ColorType::Rgb, true))); + let mut jpeg = vec![0u8; 64]; + jpeg[..4].copy_from_slice(&[0xFF, 0xD8, 0xFF, 0xDB]); + jpeg[25] = 6; + assert!(!png_has_alpha(&jpeg)); + let rgba = png(png::ColorType::Rgba, false); + assert!(!png_has_alpha(&rgba[..20])); + } + + /// A normal map at less than full strength, or with v as stored, is left out with a warning. + #[test] + fn only_a_faithful_normal_map_is_written() { + let map = crate::SurfaceMap { sha256: "ab".into(), bytes: std::sync::Arc::from(&b"\x89PNG\r\n\x1a\n"[..]) }; + for (flip, strength, written) in [(true, 1.0, true), (false, 1.0, false), (true, 0.5, false)] { + let mut p = plan(flip); + p.normal_strength = strength; + p.normal = Some(map.clone()); + let (mut registry, mut assets, mut warnings) = (Assets::default(), Vec::new(), Vec::new()); + let refs = references(&p, &mut registry, &mut assets, "Body1", &mut warnings); + assert_eq!(refs.iter().any(|r| r.slot == "normal"), written, "{flip} {strength}"); + assert_eq!(warnings.is_empty(), written, "{warnings:?}"); + } + } +} diff --git a/crates/io/src/native_cad/export.rs b/crates/io/src/native_cad/export.rs new file mode 100644 index 00000000000..54fe490ceb7 --- /dev/null +++ b/crates/io/src/native_cad/export.rs @@ -0,0 +1,202 @@ +//! Export through cadmpeg: the design is written into cadmpeg's neutral model +//! ([`super::cadir_out`], built for what each writer holds) and cadmpeg's writer for the format +//! writes the file. What the writer reports it could not carry, and what the model could not hold +//! for it, are the export's warnings; nothing is left out without one. +//! +//! - OpenUSD: the extension picks text, binary or a package ([`super::usd`]). +//! - Rhino `.3dm`: archive version 8 (Rhino 8's), cadmpeg's default. cadmpeg 0.6.12's Rhino +//! writer writes a body's exact shape only when every face is a plane and every edge a straight +//! line; any other body is written as its mesh, with a warning naming it. It writes no +//! assemblies, no looks (one colour a body), and meshes without a name or colour, so each body +//! is written where the design shows it, and each of those is a warning too. +//! - STEP and IGES, when asked for (`file.export`'s `writer: cadmpeg`; SolidCraft's own writers +//! are the default): STEP AP242 edition 1, as SolidCraft's own writer declares, with the product +//! structure and the looks as each face's colour (a face's own look on that face), but no solid +//! names (a warning says so); IGES 5.3 with each body's name and colour where the design shows +//! it, as cadmpeg's IGES writer writes no assemblies (a warning says so). +//! - FreeCAD `.FCStd`: refused. cadmpeg 0.6.12's FreeCAD writer only writes back a FreeCAD file it +//! read (it patches the file's own `Document.xml` and makes none), so it cannot write a design. + +use cadmpeg_ir::codec::write::{EncodeInput, target::TargetRequest}; +use cadmpeg_ir::document::CadIr; +use cadmpeg_registry::{Format as Codec, build_encoder}; + +use super::cadir_out::{self, Writes}; +use crate::Format; + +/// Why a FreeCAD file is not written. +pub(crate) const FREECAD_REFUSED: &str = "FreeCAD files cannot be exported yet: cadmpeg's FreeCAD writer only writes back a FreeCAD file it read, \ + and makes no new one from a design"; + +/// Why a Rhino file is not written in the browser. +pub(crate) const RHINO_IN_BROWSER: &str = "Rhino files cannot be exported in the browser yet: cadmpeg's Rhino writer needs a temporary file"; + +/// Rhino: no product records, a mesh only where the exact shape cannot be written, each mesh a +/// mesh of its own, one sRGB colour a body, and the pcurves of planar faces left to the writer, +/// which makes them from the edges and takes no other. +const RHINO: Writes = Writes { + label: "Rhino", + products: false, + brep_meshes: false, + bound_meshes: false, + appearances: false, + linear: false, + planar_pcurves: false, + named_bodies: false, + stated_pcurves: false, + solid_names: true, + admit: Some(rhino_admits), +}; + +/// The Rhino archive version written: Rhino 8's, cadmpeg's default. +const RHINO_TARGET: &str = "8"; + +/// Whether cadmpeg's Rhino writer writes `ir` (one body alone). +fn rhino_admits(ir: &CadIr) -> Result<(), String> { + build_encoder(Codec::Rhino).plan(EncodeInput::new(ir, None), TargetRequest::Explicit(RHINO_TARGET)).map(|_| ()).map_err(|e| e.to_string()) +} + +/// STEP: the product structure, each body's exact shape (a mesh only for mesh bodies, as AP242 +/// tessellated geometry), looks as styled colours in sRGB, as SolidCraft's own STEP writer gives +/// them, a face's own look on its B-rep face. +const STEP: Writes = Writes { + label: "STEP", + products: true, + brep_meshes: false, + bound_meshes: true, + appearances: true, + linear: false, + planar_pcurves: true, + named_bodies: false, + stated_pcurves: false, + solid_names: false, + admit: None, +}; + +/// The STEP schema written: AP242 edition 1, the one SolidCraft's own STEP writer declares. +const STEP_TARGET: &str = "ap242e1"; + +/// IGES: no product records (cadmpeg's IGES writer drops them), each body's exact shape, one +/// sRGB colour a body. +const IGES: Writes = Writes { + label: "IGES", + products: false, + brep_meshes: false, + bound_meshes: true, + appearances: false, + linear: false, + planar_pcurves: true, + named_bodies: false, + stated_pcurves: true, + solid_names: true, + admit: None, +}; + +/// The IGES version written: 5.3, as SolidCraft's own IGES writer writes. +const IGES_TARGET: &str = "5.3"; + +/// Losses cadmpeg reports that say nothing to the person exporting: a USD mesh's points are +/// single precision, which every USD mesh is (the exact B-rep beside it keeps double precision; +/// a mesh that is a body's only geometry is said when the rounding can matter, +/// [`mesh_only_rounds`]); a Rhino mesh's normals are single precision, as every 3DM mesh's are; and +/// STEP has no place for a pcurve's own parameter range or an edge's and a vertex's tolerance +/// (micrometres or less from SolidCraft's records), which SolidCraft's own STEP writer does not +/// write either. +const QUIET_LOSSES: [&str; 4] = + [VERTEX_PRECISION, "rhino/mesh.normal-precision-reduced", "step/pcurve.use-native-metadata", "step/topology.metadata-not-represented"]; + +/// cadmpeg's USD loss for points written in single precision. +const VERTEX_PRECISION: &str = "usd/export.vertex-precision"; + +/// Whether a mesh of `ir` that is its body's only geometry (no body, or a body with no exact +/// regions) lies so far from the origin for its size that single precision can move its points +/// past the export's weld distance: a coordinate `x` rounds to within `|x| 2⁻²⁴` (relative, in +/// any unit), and the weld distance is the distance within which a mesh's points are one +/// (`crate::weld_distance`, of the mesh's diagonal). +pub(super) fn mesh_only_rounds(ir: &CadIr) -> bool { + ir.model.tessellations.iter().any(|t| { + let exact = t.body.as_ref().is_some_and(|b| ir.model.bodies.iter().any(|x| x.id == *b && !x.regions.is_empty())); + if exact { + return false; + } + let (mut lo, mut hi, mut far) = ([f64::INFINITY; 3], [f64::NEG_INFINITY; 3], 0.0_f64); + for p in t.vertices() { + let p = p.get(); + for (k, v) in [p.x, p.y, p.z].into_iter().enumerate() { + lo[k] = lo[k].min(v); + hi[k] = hi[k].max(v); + far = far.max(v.abs()); + } + } + let size = (0..3).map(|k| (hi[k] - lo[k]).powi(2)).sum::().sqrt(); + size.is_finite() && far * f64::from(f32::EPSILON) * 0.5 > crate::weld_distance(size) + }) +} + +/// The bodies of `world` (all when `bodies` is empty) as a `format` file called `file`, written by +/// cadmpeg, with what the file could not carry: the design's components and placements when no +/// bodies are chosen and the format holds them ([`cadir_out::design_for`] says how), each mesh at +/// `quality`, and what `options` asks for. +#[allow(clippy::too_many_arguments)] +pub(super) fn from_design( + doc: &solidcraft_doc::Document, + model: &solidcraft_doc::ModelState, + world: &solidcraft_doc::ModelState, + bodies: &[String], + options: &super::CadmpegOptions, + file: &str, + quality: crate::MeshQuality, + format: Format, +) -> Result<(Vec, Vec), String> { + let name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); + let (codec, target, writes) = match format { + Format::Usd => { + let target = super::usd::target(&name).ok_or_else(|| format!("{name}: not an OpenUSD file name (.usda, .usdc, .usd or .usdz)"))?; + (Codec::Usd, target, Writes::USD) + } + // cadmpeg's Rhino writer stages the objects in a temporary file, and the browser has no + // file system: asking it for one there would end the page, so it is refused first. + Format::Rhino if cfg!(target_arch = "wasm32") => return Err(format!("{name}: {RHINO_IN_BROWSER}")), + Format::Rhino => (Codec::Rhino, RHINO_TARGET, RHINO), + Format::FreeCad => return Err(format!("{name}: {FREECAD_REFUSED}")), + Format::Step => (Codec::Step, STEP_TARGET, STEP), + Format::Iges => (Codec::Iges, IGES_TARGET, IGES), + other => return Err(format!("{name}: {other:?} is not written through cadmpeg")), + }; + let stem = std::path::Path::new(&name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); + // Images go inside a package; a layer alone would name files the export does not write. + let mut early = Vec::new(); + let unpackaged; + let options = if (!options.surfaces.is_empty() || !options.decals.is_empty()) && target != "usdz" { + if let Some(plan) = options.surfaces.first() { + early.push(format!( + "the images of render setup `{}` are written only in a .usdz package: the bodies are written with their looks", + plan.setup + )); + } + if !options.decals.is_empty() { + early.push("the pictures shown on the model are written only in a .usdz package: they are left out".into()); + } + unpackaged = super::CadmpegOptions { surfaces: Vec::new(), decals: Vec::new(), ..options.clone() }; + &unpackaged + } else { + options + }; + let built = cadir_out::design_for(doc, model, world, bodies, options, &stem, quality, writes).map_err(|e| format!("{name}: {e}"))?; + let label = writes.label; + let plan = build_encoder(codec) + .plan(EncodeInput::new(&built.ir, None), TargetRequest::Explicit(target)) + .map_err(|e| format!("{name}: could not write {label}: {e}"))?; + let mut warnings = early; + warnings.extend(built.warnings); + let rounds = mesh_only_rounds(&built.ir); + for l in &plan.report().losses { + let code = l.code.to_string(); + if !QUIET_LOSSES.contains(&code.as_str()) || (code == VERTEX_PRECISION && rounds) { + warnings.push(format!("{code}: {}", l.message)); + } + } + let mut out = Vec::new(); + plan.write_to(&mut out).map_err(|e| format!("{name}: could not write {label}: {e}"))?; + Ok((out, warnings)) +} diff --git a/crates/io/src/native_cad/tests.rs b/crates/io/src/native_cad/tests.rs index b39c6cac967..94fbdb3d710 100644 --- a/crates/io/src/native_cad/tests.rs +++ b/crates/io/src/native_cad/tests.rs @@ -1264,6 +1264,390 @@ fn a_placed_parts_centre_is_checked_in_its_own_coordinates() { assert!(!records.warnings.iter().chain(&warnings).any(|w| w.contains("the file states")), "{warnings:?}"); } +// Export through cadmpeg. Expected boxes, volumes, names and colours come from the designs' +// own dimensions and looks; nothing is taken from SolidCraft's output. + +/// A box `size` with its corner at `at`, as a new body in component `component`. +fn add_box(doc: &mut solidcraft_doc::Document, at: solidcore_record::Vec3, size: [f64; 3], component: u64) { + let id = doc + .add_feature( + solidcraft_doc::FeatureKind::Box { + corner: solidcraft_doc::point_expr(at), + length: size[0].to_string().into(), + width: size[1].to_string().into(), + height: size[2].to_string().into(), + operation: solidcraft_doc::Operation::NewBody, + centred: false, + }, + None, + ) + .unwrap(); + doc.feature_mut(id).unwrap().component = component; +} + +/// A 6 mm cylinder 15 mm high standing at x = 80 mm, as a new body. +fn add_cylinder(doc: &mut solidcraft_doc::Document) { + doc.add_feature( + solidcraft_doc::FeatureKind::Cylinder { + base: solidcraft_doc::point_expr(solidcore_record::Vec3::new(80.0, 0.0, 0.0)), + axis: solidcraft_doc::dir_expr(solidcore_record::Vec3::Z), + radius: "6".into(), + height: "15".into(), + operation: solidcraft_doc::Operation::NewBody, + references: Vec::new(), + }, + None, + ) + .unwrap(); +} + +fn evaluated(doc: &solidcraft_doc::Document) -> solidcraft_doc::Model { + let mut model = solidcraft_doc::Model::new(); + model.evaluate(doc); + model +} + +/// `doc` exported through cadmpeg as `file` in `format`, every body, at standard quality. +fn exported(doc: &solidcraft_doc::Document, file: &str, format: crate::Format) -> Result<(Vec, Vec), String> { + let model = evaluated(doc); + let world = solidcraft_doc::world_state(doc, &model.state()).unwrap(); + cadmpeg_export(doc, &model.state(), &world, &[], &crate::CadmpegOptions::default(), file, crate::MeshQuality::Standard, format) +} + +/// Each imported body's volume and box (`[min, max]`), sorted, rounded to a micrometre. +fn solids(sf: &crate::StepFeature) -> Vec<(i64, [i64; 6])> { + let mut out: Vec<(i64, [i64; 6])> = sf + .import + .bodies + .iter() + .map(|b| { + let m = solidcraft_kernel::measure(&b.body).unwrap(); + let bb = [m.bbox.min.x, m.bbox.min.y, m.bbox.min.z, m.bbox.max.x, m.bbox.max.y, m.bbox.max.z]; + ((m.volume * 1e3).round() as i64, bb.map(|v| (v * 1e3).round() as i64)) + }) + .collect(); + out.sort(); + out +} + +fn solid(volume: f64, bb: [f64; 6]) -> (i64, [i64; 6]) { + ((volume * 1e3).round() as i64, bb.map(|v| (v * 1e3).round() as i64)) +} + +/// An imported body's box, in micrometres. +fn body_box(b: &solidcraft_kernel::ImportedBody) -> [i64; 6] { + let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox; + [bb.min.x, bb.min.y, bb.min.z, bb.max.x, bb.max.y, bb.max.z].map(|v| (v * 1e3).round() as i64) +} + +/// A Rhino file as cadmpeg reads it back. +fn rhino_model(bytes: &[u8]) -> cadmpeg_ir::document::CadIr { + let (format, decoded) = convert::decode_at("x.3dm", "3dm", bytes, &["rhino"], cadmpeg_core::decode::DecodeDepth::Full).unwrap(); + assert_eq!(format, "rhino"); + decoded.into_parts().0 +} + +/// A frame holding a needle placed twice: the first needle turned a quarter about Z and moved +/// 100 mm along X, the second moved 50 mm along Y. Each box is 10 × 20 × 30 mm; the needle's +/// corner is at x = 5 mm in its component. +fn galvanometer() -> solidcraft_doc::Document { + use solidcore_record::Vec3; + let mut doc = solidcraft_doc::Document::new("Galvanometer"); + let frame = doc.add_component(Some("Frame"), 0).unwrap(); + let needle = doc.add_component(Some("Needle"), frame).unwrap(); + add_box(&mut doc, Vec3::ZERO, [10.0, 20.0, 30.0], frame); + add_box(&mut doc, Vec3::new(5.0, 0.0, 0.0), [10.0, 20.0, 30.0], needle); + let turned = solidcraft_doc::rigid(Vec3::new(100.0, 0.0, 0.0), Vec3::ZERO, Vec3::Z, std::f64::consts::FRAC_PI_2); + doc.occurrences.iter_mut().find(|o| o.component == needle).unwrap().transform = turned; + doc.add_occurrence(needle, frame, solidcraft_doc::rigid(Vec3::new(0.0, 50.0, 0.0), Vec3::ZERO, Vec3::Z, 0.0)).unwrap(); + doc +} + +/// Where the galvanometer's three boxes are: a quarter turn about Z takes the needle's x 5..15, +/// y 0..20 to x -20..-0, y 5..15, then 100 mm along X. +fn galvanometer_solids() -> Vec<(i64, [i64; 6])> { + let mut want = vec![ + solid(6000.0, [0.0, 0.0, 0.0, 10.0, 20.0, 30.0]), + solid(6000.0, [80.0, 5.0, 0.0, 100.0, 15.0, 30.0]), + solid(6000.0, [5.0, 50.0, 0.0, 15.0, 70.0, 30.0]), + ]; + want.sort(); + want +} + +/// A 10 × 20 × 30 mm box exports to Rhino as an exact solid, named after the body, and reads back +/// through both of SolidCraft's Rhino readers as that box, with nothing reported lost. +#[test] +fn a_box_exports_to_rhino_and_reads_back() { + let mut doc = solidcraft_doc::Document::new("Block"); + add_box(&mut doc, solidcore_record::Vec3::ZERO, [10.0, 20.0, 30.0], 0); + let (bytes, warnings) = exported(&doc, "block.3dm", crate::Format::Rhino).unwrap(); + assert!(bytes.starts_with(b"3D Geometry File Format "), "{:?}", bytes.get(..32)); + assert!(warnings.is_empty(), "{warnings:?}"); + let name = evaluated(&doc).state().bodies[0].name.clone(); + for reader in READERS { + let sf = read(&bytes, "block.3dm", reader); + assert_eq!(solids(&sf), vec![solid(6000.0, [0.0, 0.0, 0.0, 10.0, 20.0, 30.0])], "{reader:?}"); + // `Body1` reads as a placeholder, so by default the body is named after the file; the + // records keep the object's own name. + assert_eq!(sf.body_names, vec!["block".to_string()], "{reader:?}"); + if reader == crate::StepReader::Cadmpeg { + let own = crate::step_import_feature_read(&bytes, "block.3dm", crate::StepNames::Solid, reader).unwrap(); + assert_eq!(own.body_names, vec![name.clone()]); + } + } + let ir = rhino_model(&bytes); + let names: Vec<_> = ir.model.bodies.iter().filter_map(|b| b.name.clone()).collect(); + assert_eq!(names, vec![name]); +} + +/// A body's look is its colour in the Rhino file, sRGB as SolidCraft keeps it (a Rhino colour is +/// the bytes themselves); a cylinder, whose round faces cadmpeg's Rhino writer cannot write +/// exactly yet, is written as its mesh, with warnings naming it, and that mesh spans the +/// cylinder: radius 6 mm, 15 mm high, at x = 80 mm. +#[test] +fn rhino_export_keeps_colours_and_writes_a_cylinder_as_its_mesh() { + let mut doc = solidcraft_doc::Document::new("Parts"); + add_box(&mut doc, solidcore_record::Vec3::ZERO, [10.0, 20.0, 30.0], 0); + add_cylinder(&mut doc); + let names: Vec = evaluated(&doc).state().bodies.iter().map(|b| b.name.clone()).collect(); + doc.appearances.bodies.insert(names[0].clone(), solidcraft_doc::appearance::Look::custom([255, 128, 0], 1.0)); + doc.appearances.bodies.insert(names[1].clone(), solidcraft_doc::appearance::Look::custom([0, 64, 255], 1.0)); + let (bytes, warnings) = exported(&doc, "parts.3dm", crate::Format::Rhino).unwrap(); + let cylinder = &names[1]; + assert!(warnings.iter().any(|w| w.starts_with(&format!("{cylinder}: written as its mesh only"))), "{warnings:?}"); + assert!(warnings.iter().any(|w| w.starts_with(&format!("{cylinder}: written as a mesh without its name or colour"))), "{warnings:?}"); + let ir = rhino_model(&bytes); + let block = ir.model.bodies.iter().find(|b| b.name.as_deref() == Some(names[0].as_str())).unwrap(); + let c = block.color.unwrap(); + assert_eq!([c.r(), c.g(), c.b(), c.a()], [1.0, 128.0 / 255.0, 0.0, 1.0]); + let [mesh] = ir.model.tessellations.as_slice() else { panic!("one mesh: {}", ir.model.tessellations.len()) }; + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for p in mesh.vertices() { + let p = p.get(); + for (k, v) in [p.x, p.y, p.z].into_iter().enumerate() { + lo[k] = lo[k].min(v); + hi[k] = hi[k].max(v); + } + } + for (got, want) in lo.iter().chain(&hi).zip([74.0, -6.0, 0.0, 86.0, 6.0, 15.0]) { + // Within the mesh's chord tolerance (2e-4 of the cylinder's 22.6 mm diagonal). + assert!((got - want).abs() < 0.01, "{lo:?} {hi:?}"); + } + // The box reads back through SolidCraft's readers. The mesh is not a solid: SolidCraft's own + // Rhino reader leaves it out, and cadmpeg's brings it in as a mesh body spanning the cylinder. + for reader in READERS { + let sf = read(&bytes, "parts.3dm", reader); + let mut got = solids(&sf); + if reader == crate::StepReader::Cadmpeg { + let mesh = sf.import.bodies.iter().position(|b| b.body.is_mesh()).unwrap_or_else(|| panic!("no mesh body: {got:?}")); + let m = solidcraft_kernel::measure(&sf.import.bodies[mesh].body).unwrap(); + let bb = [m.bbox.min.x, m.bbox.min.y, m.bbox.min.z, m.bbox.max.x, m.bbox.max.y, m.bbox.max.z]; + for (got, want) in bb.iter().zip([74.0, -6.0, 0.0, 86.0, 6.0, 15.0]) { + assert!((got - want).abs() < 0.01, "{bb:?}"); + } + got.retain(|s| s.1 != bb.map(|v| (v * 1e3).round() as i64)); + } + assert_eq!(got, vec![solid(6000.0, [0.0, 0.0, 0.0, 10.0, 20.0, 30.0])], "{reader:?}"); + } +} + +/// A hidden body Rhino writes as its exact shape is hidden in the file; a hidden cylinder, which +/// cadmpeg's Rhino writer writes as a mesh with no visibility, is said to be written shown. +#[test] +fn a_hidden_body_rhino_writes_as_a_mesh_is_said_to_be_shown() { + let mut doc = solidcraft_doc::Document::new("Parts"); + add_box(&mut doc, solidcore_record::Vec3::ZERO, [10.0, 20.0, 30.0], 0); + add_cylinder(&mut doc); + let model = evaluated(&doc); + let names: Vec = model.state().bodies.iter().map(|b| b.name.clone()).collect(); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = + crate::CadmpegOptions { hidden: crate::Hidden { bodies: names.iter().cloned().collect(), ..Default::default() }, ..Default::default() }; + let (bytes, warnings) = + cadmpeg_export(&doc, &model.state(), &world, &[], &options, "parts.3dm", crate::MeshQuality::Standard, crate::Format::Rhino).unwrap(); + let shown = |name: &str| warnings.iter().any(|w| w.starts_with(&format!("{name}: hidden, but written shown"))); + assert!(shown(&names[1]), "{warnings:?}"); + assert!(!shown(&names[0]), "{warnings:?}"); + let ir = rhino_model(&bytes); + let block = ir.model.bodies.iter().find(|b| b.name.as_deref() == Some(names[0].as_str())).unwrap(); + assert_eq!(block.visible, Some(false)); +} + +/// Rhino has no assemblies here, so every body of the galvanometer is written where the design +/// shows it, with a warning, and reads back there. +#[test] +fn an_assembly_exports_to_rhino_where_the_design_shows_it() { + let (bytes, warnings) = exported(&galvanometer(), "galvanometer.3dm", crate::Format::Rhino).unwrap(); + assert!(warnings.iter().any(|w| w.contains("components and placements are not written")), "{warnings:?}"); + for reader in READERS { + let sf = read(&bytes, "galvanometer.3dm", reader); + assert_eq!(solids(&sf), galvanometer_solids(), "{reader:?}"); + } +} + +/// FreeCAD is refused with why: cadmpeg 0.6.12 only writes back a FreeCAD file it read. A design +/// with nothing to write, an unknown body and a format cadmpeg does not write here are refused; +/// odd names and placements never panic. +#[test] +fn cadmpeg_export_refuses_what_it_cannot_write() { + let mut doc = solidcraft_doc::Document::new("Block"); + add_box(&mut doc, solidcore_record::Vec3::ZERO, [10.0, 20.0, 30.0], 0); + let e = exported(&doc, "block.FCStd", crate::Format::FreeCad).unwrap_err(); + assert!(e.contains("FreeCAD files cannot be exported yet"), "{e}"); + let e = exported(&doc, "block.obj", crate::Format::Obj).unwrap_err(); + assert!(e.contains("not written through cadmpeg"), "{e}"); + // The plain export says the same of FreeCAD, and sends Rhino to `file.export`. + let state = evaluated(&doc).state(); + let painted = doc.painted(&state); + let e = crate::export(&painted, &[], crate::Format::FreeCad, "Block").unwrap_err().to_string(); + assert!(e.contains("FreeCAD files cannot be exported yet"), "{e}"); + let e = crate::export(&painted, &[], crate::Format::Rhino, "Block").unwrap_err().to_string(); + assert!(e.contains("use file.export"), "{e}"); + assert!(exported(&solidcraft_doc::Document::new("Empty"), "empty.3dm", crate::Format::Rhino).is_err()); + let model = evaluated(&doc); + let st = model.state(); + assert!( + cadmpeg_export( + &doc, + &st, + &st, + &["Nothing".into()], + &crate::CadmpegOptions::default(), + "x.3dm", + crate::MeshQuality::Standard, + crate::Format::Rhino + ) + .is_err() + ); + let mut odd = solidcraft_doc::Document::new("\0\u{7} "); + add_box(&mut odd, solidcore_record::Vec3::new(1e9, -1e9, 0.0), [1e-3, 1e6, 1.0], 0); + let r = std::panic::catch_unwind(|| exported(&odd, "\0.3dm", crate::Format::Rhino)); + assert!(r.is_ok(), "an odd design panicked"); +} + +/// `bytes`, an IGES file, read by cadmpeg's IGES decoder into records and an Import feature, as +/// a STEP file is with the cadmpeg reader (there is no cadmpeg IGES import route yet). +fn iges_by_cadmpeg(bytes: &[u8]) -> crate::StepFeature { + let (format, decoded) = convert::decode_at("x.igs", "igs", bytes, &["iges"], cadmpeg_core::decode::DecodeDepth::Full).unwrap(); + assert_eq!(format, "iges"); + let records = cadir_records(&decoded.into_parts().0, "x", "", true); + let read = crate::RecordsRead { records, warnings: Vec::new(), freecad: false, preprocessor: String::new(), description: String::new() }; + crate::records_import_feature(read, "x.igs", crate::StepNames::default()).unwrap() +} + +/// An imported body's colour: its own, else the one colour every face of it has (cadmpeg's STEP +/// writer styles a body's faces, each with the body's colour). +fn colour_of(b: &solidcraft_kernel::ImportedBody) -> Option<[f32; 3]> { + b.color.or_else(|| { + let faces = &b.body.paint()?.faces; + let first = faces.first()?.color; + (faces.len() == b.body.face_count() && faces.iter().all(|f| f.color == first)).then_some(first) + }) +} + +/// A 10 × 20 × 30 mm box and a cylinder of radius 6 mm, 15 mm high at x = 80 mm (volume +/// π·36·15), coloured #0040FF. +fn box_and_cylinder() -> (solidcraft_doc::Document, Vec<(i64, [i64; 6])>) { + let mut doc = solidcraft_doc::Document::new("Parts"); + add_box(&mut doc, solidcore_record::Vec3::ZERO, [10.0, 20.0, 30.0], 0); + add_cylinder(&mut doc); + let names: Vec = evaluated(&doc).state().bodies.iter().map(|b| b.name.clone()).collect(); + doc.appearances.bodies.insert(names[1].clone(), solidcraft_doc::appearance::Look::custom([0, 64, 255], 1.0)); + let mut want = + vec![solid(6000.0, [0.0, 0.0, 0.0, 10.0, 20.0, 30.0]), solid(std::f64::consts::PI * 36.0 * 15.0, [74.0, -6.0, 0.0, 86.0, 6.0, 15.0])]; + want.sort(); + (doc, want) +} + +/// cadmpeg writes STEP (AP242 edition 1, as SolidCraft's own writer declares) and IGES 5.3 from +/// the design: a box with a coloured cylinder, and the galvanometer (a part placed twice). Each +/// file reads back through SolidCraft's own reader and through cadmpeg's, every solid with the +/// volume and box the design's dimensions give, the cylinder in its colour. STEP keeps the +/// assembly: each needle under Galvanometer › Frame › Needle; IGES has none here, so its bodies +/// are where the design shows them, with a warning. +#[test] +fn cadmpeg_writes_step_and_iges_that_both_readers_read_back() { + let (parts, parts_want) = box_and_cylinder(); + let blue = [0.0, 64.0 / 255.0, 1.0]; + for (label, doc, want) in [("parts", parts, parts_want), ("galvanometer", galvanometer(), galvanometer_solids())] { + for (file, format) in [("x.step", crate::Format::Step), ("x.igs", crate::Format::Iges)] { + let (bytes, warnings) = exported(&doc, file, format).unwrap_or_else(|e| panic!("{label} {file}: {e}")); + let assembly = label == "galvanometer"; + let flattened = warnings.iter().any(|w| w.contains("components and placements are not written")); + assert_eq!(flattened, assembly && format == crate::Format::Iges, "{label} {file}: {warnings:?}"); + // STEP names the components but not the solids; nothing else is reported lost. + let unnamed = warnings.iter().any(|w| w.contains("the bodies' names are not written")); + assert_eq!(unnamed, format == crate::Format::Step, "{label} {file}: {warnings:?}"); + assert_eq!(warnings.len(), usize::from(flattened) + usize::from(unnamed), "{label} {file}: {warnings:?}"); + let ours = crate::step_import_feature_read(&bytes, file, crate::StepNames::default(), crate::StepReader::SolidCraft).unwrap(); + assert_eq!(solids(&ours), want, "{label} {file}: SolidCraft's reader"); + let theirs = match format { + crate::Format::Step => { + crate::step_import_feature_read(&bytes, file, crate::StepNames::default(), crate::StepReader::Cadmpeg).unwrap() + } + _ => iges_by_cadmpeg(&bytes), + }; + assert_eq!(solids(&theirs), want, "{label} {file}: cadmpeg's reader"); + let theirs: Vec<_> = theirs.import.bodies.iter().map(|b| (colour_of(b), b.path.clone(), body_box(b))).collect(); + if format == crate::Format::Step { + assert!(ours.import.schema.contains("AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF"), "{}", ours.import.schema); + } + let ours: Vec<_> = ours.import.bodies.iter().map(|b| (colour_of(b), b.path.clone(), body_box(b))).collect(); + for (reader, bodies) in [("SolidCraft", ours), ("cadmpeg", theirs)] { + if !assembly { + // Names need not survive a writer: the cylinder is the body with its box. + let cylinder = bodies + .iter() + .find(|(_, _, bb)| *bb == [74_000, -6_000, 0, 86_000, 6_000, 15_000]) + .unwrap_or_else(|| panic!("{label} {file} {reader}: no cylinder body: {bodies:?}")); + let colour = cylinder.0.unwrap_or_else(|| panic!("{label} {file} {reader}: the cylinder is not coloured")); + for (got, want) in colour.iter().zip(blue) { + assert!((f64::from(*got) - want).abs() < 1e-3, "{label} {file} {reader}: the cylinder's colour: {colour:?}"); + } + assert_eq!( + bodies.iter().filter(|(c, _, _)| c.is_some()).count(), + 1, + "{label} {file} {reader}: only the cylinder is coloured: {bodies:?}" + ); + } else if format == crate::Format::Step { + let needles = bodies.iter().filter(|(_, p, _)| p.iter().map(String::as_str).eq(["Galvanometer", "Frame", "Needle"])).count(); + assert_eq!(needles, 2, "{label} {file} {reader}: {bodies:?}"); + } + } + } + } +} + +/// STEP written by cadmpeg has no mesh beside the exact shape, so a face's own look is bound to +/// its B-rep face: a grey box with a red top face reads back, through both readers, with one red +/// face and the others grey. +#[test] +fn cadmpeg_step_keeps_a_faces_own_colour() { + let mut doc = solidcraft_doc::Document::new("Block"); + add_box(&mut doc, solidcore_record::Vec3::ZERO, [10.0, 20.0, 30.0], 0); + let body = evaluated(&doc).state().bodies[0].name.clone(); + doc.appearances.bodies.insert(body.clone(), solidcraft_doc::appearance::Look::custom([128, 128, 128], 1.0)); + doc.appearances.faces.push(solidcraft_doc::appearance::FaceLook { + body, + point: solidcore_record::Vec3::new(5.0, 10.0, 30.0), + look: solidcraft_doc::appearance::Look::custom([255, 0, 0], 1.0), + name: None, + strict_name: false, + certificate: None, + }); + let (bytes, warnings) = exported(&doc, "x.step", crate::Format::Step).unwrap(); + assert!(warnings.iter().all(|w| w.contains("the bodies' names are not written")), "{warnings:?}"); + for reader in [crate::StepReader::SolidCraft, crate::StepReader::Cadmpeg] { + let read = crate::step_import_feature_read(&bytes, "x.step", crate::StepNames::default(), reader).unwrap(); + let [b] = read.import.bodies.as_slice() else { panic!("{reader:?}: one body") }; + let faces = &b.body.paint().unwrap_or_else(|| panic!("{reader:?}: no paint")).faces; + let red = faces.iter().filter(|f| f.color[0] > 0.99 && f.color[1] < 0.01 && f.color[2] < 0.01).count(); + assert_eq!(red, 1, "{reader:?}: {faces:?}"); + } +} + /// A part an AP242 file gives as triangles alone: a 1 cm tetrahedron, as a TRIANGULATED_SURFACE_SET /// in a TESSELLATED_SHAPE_REPRESENTATION, in centimetres. const TETRAHEDRON_PART: &str = "ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION((''),'2;1');\nFILE_NAME('tetrahedron','',(''),(''),'','','');\n\ @@ -1394,3 +1778,78 @@ fn product_names_come_in_trimmed() { let tree = tree_of(&theirs); assert!(tree.get(1).is_some_and(|l| l.starts_with("1 cylinder_placed [") && l.contains("/cylinder_placed|")), "{tree:?}"); } + +/// A body with an exact B-rep whose display mesh cannot be made is written as its B-rep alone, +/// with a warning naming it; the meshes' size cap stays fatal, and so does a failed mesh of a body +/// with no exact shape, which has nothing else to be written as. +#[test] +fn a_failed_display_mesh_keeps_the_exact_body() { + use cadir_out::{Unmeshed, kept_without_mesh}; + let mut warnings = Vec::new(); + let failed = || Err(Unmeshed::Failed("could not be meshed: no face meshed".into())); + assert!(matches!(kept_without_mesh(failed(), true, "Body1", &mut warnings), Ok(None))); + assert_eq!(warnings, vec!["Body1: its mesh was not written (could not be meshed: no face meshed), so the file's writer meshes it".to_string()]); + let e = kept_without_mesh(failed(), false, "Body1", &mut warnings).err(); + assert_eq!(e.as_deref(), Some("Body1: could not be meshed: no face meshed")); + let large = Err(Unmeshed::TooLarge("Body1: the meshes are too large for the file".into())); + let e = kept_without_mesh(large, true, "Body1", &mut warnings).err(); + assert_eq!(e.as_deref(), Some("Body1: the meshes are too large for the file")); + assert_eq!(warnings.len(), 1); + assert!(kept_without_mesh(Ok(solidcraft_geom::Mesh::default()), false, "Body1", &mut warnings).unwrap().is_some()); +} + +/// In a meshes-only export, a body whose mesh fails is written as its exact shape, when it has +/// one; a mesh body has none, a mesh that passes the size cap stays fatal, and an export with exact +/// shapes keeps its own rule. +#[test] +fn a_meshes_only_export_falls_back_to_the_exact_shape() { + use cadir_out::{Unmeshed, shape_instead}; + let failed = Err(Unmeshed::Failed("no face meshed".into())); + let large = Err(Unmeshed::TooLarge("too large".into())); + assert!(shape_instead(&failed, true, false)); + assert!(!shape_instead(&failed, true, true)); + assert!(!shape_instead(&failed, false, false)); + assert!(!shape_instead(&large, true, false)); + assert!(!shape_instead(&Ok(solidcraft_geom::Mesh::default()), true, false)); +} + +/// cadmpeg's single-precision loss is kept quiet for a mesh beside an exact B-rep, and for a mesh +/// alone whose rounding is within the weld distance; it is said for a mesh alone so far from the +/// origin for its size that its points round past it. A 1 mm triangle at x = 1e9 mm: single +/// precision rounds there to within 1e9 · 2⁻²⁴ ≈ 60 mm, past its weld distance of 1e-6 mm. +#[test] +fn single_precision_is_said_for_a_mesh_alone_that_it_moves() { + use cadmpeg_ir::ids::BodyId; + use cadmpeg_ir::math::Point3; + use cadmpeg_ir::tessellation::{Tessellation, TessellationId, TessellationMesh}; + use cadmpeg_ir::topology::{Body, BodyKind}; + let triangle = |at: f64, body: Option<&str>| { + let positions = vec![Point3::new(at, 0.0, 0.0), Point3::new(at + 1.0, 0.0, 0.0), Point3::new(at, 1.0, 0.0)]; + let lanes = TessellationMesh::from_list_lanes(positions, vec![[0, 1, 2]], None).unwrap(); + let id = TessellationId::try_from("test:model:tessellation#0".to_string()).unwrap(); + Tessellation::new(id, lanes, Vec::new()).unwrap().with_body(body.map(|b| BodyId::try_from(b.to_string()).unwrap())) + }; + let body = |id: &str, regions: Vec| Body { + id: BodyId::try_from(id.to_string()).unwrap(), + kind: BodyKind::General, + regions, + transform: None, + name: None, + color: None, + visible: None, + }; + let with = |t: Tessellation, b: Option| { + let mut ir = cadmpeg_ir::document::CadIr::empty(); + ir.model.tessellations.push(t); + ir.model.bodies.extend(b); + ir + }; + let region = cadmpeg_ir::ids::RegionId::try_from("test:model:region#0".to_string()).unwrap(); + // Alone, near the origin and far from it. + assert!(!export::mesh_only_rounds(&with(triangle(10.0, None), None))); + assert!(export::mesh_only_rounds(&with(triangle(1e9, None), None))); + // A bound mesh of a body with no regions is the body's only geometry too. + assert!(export::mesh_only_rounds(&with(triangle(1e9, Some("test:model:body#0")), Some(body("test:model:body#0", Vec::new()))))); + // Beside an exact B-rep, the B-rep keeps double precision. + assert!(!export::mesh_only_rounds(&with(triangle(1e9, Some("test:model:body#0")), Some(body("test:model:body#0", vec![region]))))); +} diff --git a/crates/io/src/native_cad/usd.rs b/crates/io/src/native_cad/usd.rs index 6adb95a565c..0874db35db1 100644 --- a/crates/io/src/native_cad/usd.rs +++ b/crates/io/src/native_cad/usd.rs @@ -1,12 +1,18 @@ //! OpenUSD (`.usd`, `.usda`, `.usdc`, `.usdz`) through cadmpeg's USD codec, both ways. //! -//! Export: the bodies are written as STEP by SolidCraft's own writer (an assembly as a STEP -//! assembly, as `file.export` writes it), cadmpeg reads that STEP into its neutral model, and -//! cadmpeg's USD writer writes the model: each part as an `Xform` prim holding its exact B-rep (a -//! `BrepArray` prim) and a `Mesh` of it, a part placed more than once written once under the -//! abstract `Prototypes` prim and referenced at each placement, and colours as `UsdPreviewSurface` -//! materials. The layer is in metres with Z up and says so. SolidCraft's colours are sRGB, and -//! USD's are linear, so the colours are converted on the way. +//! Export ([`super::export`]): the design is written straight into cadmpeg's neutral model +//! ([`super::cadir_out::design_for`]: components, placements, bodies with their exact B-rep and the +//! mesh SolidCraft draws them with, and their looks), and cadmpeg's USD writer writes the model: +//! each component an `Xform` prim named after its occurrence, holding its bodies, each named after +//! it, as the exact B-rep (a `BrepArray` prim) and SolidCraft's `Mesh` of it; a part placed more +//! than once written once under the abstract `Prototypes` prim and referenced at each placement +//! (a part of one body placed so has its body's prim named after the part, as cadmpeg 0.6.12 +//! names it). A mesh body, a body whose exact shape cadmpeg's model cannot hold yet, and every +//! body of a meshes-only export (`exact_brep: false`) have their `Mesh` alone, no `BrepArray`; +//! and looks as `UsdPreviewSurface` materials with their colour, opacity, metallic, roughness and +//! index of refraction, a face with a look of its own bound through a `GeomSubset`. The layer is +//! in metres with Z up and says so. SolidCraft's colours are sRGB, and USD's are linear, so the +//! colours are converted on the way. //! //! Import: cadmpeg reads the layer (text, binary, or the root layer of a package) and composes it //! within itself. Each mesh becomes a mesh body, and the prim tree becomes components, as a glTF @@ -23,12 +29,10 @@ use std::hash::{Hash, Hasher}; use cadmpeg_core::decode::DecodeDepth; use cadmpeg_ir::appearance::AppearanceTarget; -use cadmpeg_ir::codec::write::{EncodeInput, target::TargetRequest}; use cadmpeg_ir::document::CadIr; use cadmpeg_ir::products::{Occurrence, OccurrenceParent, ProductDefinition, PrototypeReference}; use cadmpeg_ir::tessellation::Tessellation; use cadmpeg_ir::topology::Color; -use cadmpeg_registry::{Format, build_encoder}; use solidcore_record::Vec3; use solidcraft_doc::MeshData; use solidcraft_doc::appearance::Look; @@ -54,12 +58,6 @@ const MAX_COMPONENT_DEPTH: usize = 32; /// Most components one file makes. const MAX_COMPONENTS: usize = 5_000; -/// Losses cadmpeg reports that say nothing to the person exporting: how SolidCraft's own STEP -/// text was read on the way, and that mesh points are single precision, which every USD mesh is -/// (the exact B-rep beside it keeps double precision). -const QUIET_LOSSES: [&str; 4] = - ["step/decode.opaque-record-preserved", "step/topology.pcurve-global-fidelity-unproved", "step/decode.warning", "usd/export.vertex-precision"]; - /// Is this an OpenUSD file name (any case)? pub fn is_usd_path(path: &str) -> bool { std::path::Path::new(path).extension().and_then(|e| e.to_str()).is_some_and(|e| USD_EXTS.iter().any(|x| e.eq_ignore_ascii_case(x))) @@ -67,7 +65,7 @@ pub fn is_usd_path(path: &str) -> bool { /// The cadmpeg write target a file name asks for: `.usda` text, `.usdz` a package, and `.usdc` or /// `.usd` binary (a `.usd` layer is binary unless it says otherwise, as OpenUSD writes it). -fn target(file: &str) -> Option<&'static str> { +pub(super) fn target(file: &str) -> Option<&'static str> { let ext = std::path::Path::new(file).extension().and_then(|e| e.to_str())?.to_ascii_lowercase(); match ext.as_str() { "usda" => Some("usda"), @@ -77,70 +75,7 @@ fn target(file: &str) -> Option<&'static str> { } } -/// `step` (STEP text SolidCraft wrote) as an OpenUSD file called `file`, whose extension picks the -/// encoding, with what the file could not carry. -pub(super) fn from_step(step: &[u8], file: &str) -> Result<(Vec, Vec), String> { - let name = std::path::Path::new(file).file_name().map(|s| s.to_string_lossy().to_string()).unwrap_or_else(|| file.to_string()); - let target = target(&name).ok_or_else(|| format!("{name}: not an OpenUSD file name (.usda, .usdc, .usd or .usdz)"))?; - let (_, decoded) = decode_at(&name, "step", step, &["step"], DecodeDepth::Full)?; - let (mut ir, report, fidelity) = decoded.into_parts(); - if !report.geometry_transferred() { - return Err(format!("{name}: there is no geometry to write")); - } - let stem = std::path::Path::new(&name).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default(); - name_roots(&mut ir, &stem); - colours_to_linear(&mut ir); - let plan = build_encoder(Format::Usd) - .plan(EncodeInput::new(&ir, Some(&fidelity)), TargetRequest::Explicit(target)) - .map_err(|e| format!("{name}: could not write OpenUSD: {e}"))?; - let mut warnings: Vec = Vec::new(); - for l in report.losses.iter().chain(&plan.report().losses) { - let code = l.code.to_string(); - if !QUIET_LOSSES.contains(&code.as_str()) { - warnings.push(format!("{code}: {}", l.message)); - } - } - let mut out = Vec::new(); - plan.write_to(&mut out).map_err(|e| format!("{name}: could not write OpenUSD: {e}"))?; - Ok((out, warnings)) -} - -/// Name each root occurrence with no name after its part, else after the file, so the layer's -/// root prim is not called `Occurrence`. -fn name_roots(ir: &mut CadIr, stem: &str) { - let labels: HashMap = - ir.model.product_definitions.iter().filter_map(|d| Some((d.id.as_str().to_string(), product_name(d)?))).collect(); - for o in ir.model.occurrences.iter_mut().filter(|o| matches!(o.parent, OccurrenceParent::Root {})) { - if o.name.as_deref().is_some_and(|n| !n.trim().is_empty()) { - continue; - } - let part = match &o.prototype { - PrototypeReference::Local { definition } => labels.get(definition.as_str()).cloned(), - _ => None, - }; - o.name = part.or_else(|| (!stem.trim().is_empty()).then(|| stem.to_string())); - } -} - -/// SolidCraft's (and STEP's) colours are sRGB; USD's `displayColor` and `diffuseColor` are linear. -fn colours_to_linear(ir: &mut CadIr) { - let linear = |c: Color| { - let f = |v: f32| solidcraft_color::srgb::decode(f64::from(v)).clamp(0.0, 1.0) as f32; - Color::new(f(c.r()), f(c.g()), f(c.b()), c.a()).unwrap_or(c) - }; - for b in &mut ir.model.bodies { - b.color = b.color.map(linear); - } - for f in &mut ir.model.faces { - f.color = f.color.map(linear); - } - for a in &mut ir.model.appearances { - a.base_color = a.base_color.map(linear); - } -} - -/// USD's colours are linear; SolidCraft's are sRGB. The inverse of [`colours_to_linear`], for a -/// file read into records. +/// USD's colours are linear; SolidCraft's are sRGB. For a file read into records. pub(super) fn colours_to_srgb(ir: &mut CadIr) { let srgb = |c: Color| { let f = |v: f32| solidcraft_color::srgb::encode(f64::from(v).clamp(0.0, 1.0)).clamp(0.0, 1.0) as f32; diff --git a/crates/io/src/native_cad/usd_tests.rs b/crates/io/src/native_cad/usd_tests.rs index 6ec559c9a59..7eb0a65a9e5 100644 --- a/crates/io/src/native_cad/usd_tests.rs +++ b/crates/io/src/native_cad/usd_tests.rs @@ -33,9 +33,36 @@ fn one_box() -> (Document, Model) { (doc, model) } -/// The bodies of `state` as STEP, as `file.export` writes them. -fn step_of(doc: &Document, state: &ModelState) -> Vec { - crate::export(&doc.painted(state), &[], crate::Format::Step, "Box").unwrap() +/// The design as an OpenUSD file called `file`, as `file.export` writes it: `bodies` chosen (all +/// when empty), at `quality`. +fn usd_at(doc: &Document, model: &Model, bodies: &[String], file: &str, quality: crate::MeshQuality) -> (Vec, Vec) { + let world = solidcraft_doc::world_state(doc, &model.state()).unwrap(); + crate::usd_from_design(doc, &model.state(), &world, bodies, &crate::CadmpegOptions::default(), file, quality).unwrap() +} + +/// The whole design as an OpenUSD file called `file`, at standard quality. +fn usd_of(doc: &Document, model: &Model, file: &str) -> (Vec, Vec) { + usd_at(doc, model, &[], file, crate::MeshQuality::Standard) +} + +/// [`usd_of`] as text. +fn usda(doc: &Document, model: &Model) -> String { + String::from_utf8(usd_of(doc, model, "design.usda").0).unwrap() +} + +/// The design's model as CADIR, as an OpenUSD export builds it. +fn cadir(doc: &Document, model: &Model) -> super::super::cadir_out::Built { + let world = solidcraft_doc::world_state(doc, &model.state()).unwrap(); + super::super::cadir_out::design(doc, &model.state(), &world, &[], &crate::CadmpegOptions::default(), "design", crate::MeshQuality::Standard) + .unwrap() +} + +/// The values of input `input` of every shader in `text`. +fn inputs(text: &str, input: &str) -> Vec { + text.lines() + .filter_map(|l| l.trim().strip_prefix(&format!("float inputs:{input} = "))) + .map(|v| v.trim().parse().unwrap_or_else(|_| panic!("{input} = {v}"))) + .collect() } /// A frame part holding a needle part placed twice: the first needle turned a quarter about Z and @@ -54,6 +81,27 @@ fn galvanometer() -> (Document, Model) { (doc, model) } +/// A chain of components nested two levels past [`solidcraft_doc::MAX_PLACEMENT_DEPTH`] is +/// written as far as the design's own walk (the display's) reaches it: one occurrence for each +/// placement that walk holds, its deepest one level past the depth, and a warning for the rest. +#[test] +fn placements_are_written_as_deep_as_the_design_walks_them() { + let mut doc = Document::new("Chain"); + add_box(&mut doc, Vec3::ZERO, 0); + let mut parent = 0; + for k in 0..solidcraft_doc::MAX_PLACEMENT_DEPTH + 2 { + parent = doc.add_component(Some(&format!("Level {k}")), parent).unwrap(); + } + let mut model = Model::new(); + model.evaluate(&doc); + let walked = doc.placements(); + assert_eq!(walked.iter().map(|(_, path, _)| path.len()).max(), Some(solidcraft_doc::MAX_PLACEMENT_DEPTH + 1)); + let built = cadir(&doc, &model); + // The design's walk holds the root too, as the written root occurrence. + assert_eq!(built.ir.model.occurrences.len(), walked.len(), "{:?}", built.warnings); + assert!(built.warnings.iter().any(|w| w.contains("too large or too deep")), "{:?}", built.warnings); +} + /// Each mesh body's box, `[min, max]` in millimetres, sorted, with the import flattened so every /// mesh is where the file places it. fn boxes(mut g: GltfImport) -> Vec<[[f64; 3]; 2]> { @@ -100,9 +148,8 @@ fn extensions() { #[test] fn a_box_exports_as_each_encoding_and_reads_back() { let (doc, model) = one_box(); - let step = step_of(&doc, &model.state()); for (file, magic) in [("box.usda", &b"#usda 1.0"[..]), ("box.usdc", b"PXR-USDC"), ("box.usd", b"PXR-USDC"), ("box.usdz", b"PK\x03\x04")] { - let (bytes, warnings) = crate::usd_from_step(&step, file).unwrap(); + let (bytes, warnings) = usd_of(&doc, &model, file); assert!(bytes.starts_with(magic), "{file}: {:?}", bytes.get(..16)); assert!(warnings.is_empty(), "{file}: {warnings:?}"); let (g, y_up) = crate::read_usd(&bytes, file).unwrap(); @@ -111,12 +158,11 @@ fn a_box_exports_as_each_encoding_and_reads_back() { assert_eq!(got.len(), 1, "{file}"); assert_box(&got[0], [[0.0, 0.0, 0.0], [10.0, 20.0, 30.0]]); } - let (text, _) = crate::usd_from_step(&step, "box.usda").unwrap(); - let text = String::from_utf8(text).unwrap(); + let text = usda(&doc, &model); assert!(text.contains("metersPerUnit = 1\n") && text.contains("upAxis = \"Z\""), "{text}"); // The exact B-rep goes with the mesh. assert!(text.contains("def BrepArray") && text.contains("def Mesh"), "{text}"); - // The root prim is named after the part, not `Occurrence`. + // The root prim is named after the design, not `Occurrence`. assert!(text.contains("defaultPrim = \"Box\""), "{}", &text[..200.min(text.len())]); } @@ -125,8 +171,8 @@ fn a_box_exports_as_each_encoding_and_reads_back() { #[test] fn an_assembly_keeps_its_components_and_placements() { let (doc, model) = galvanometer(); - let step = crate::step_assembly(&doc, &doc.painted(&model.state()), "Galvanometer").unwrap(); - let (bytes, _) = crate::usd_from_step(&step, "galvanometer.usda").unwrap(); + let (bytes, warnings) = usd_of(&doc, &model, "galvanometer.usda"); + assert!(warnings.is_empty(), "{warnings:?}"); let text = String::from_utf8(bytes.clone()).unwrap(); assert_eq!(text.matches("def Mesh").count(), 2, "the frame's mesh and the needle's, once:\n{text}"); assert_eq!(text.matches("prepend references = = model.state().bodies.iter().map(|b| b.name.clone()).collect(); + let (bytes, warnings) = usd_at(&doc, &model, &names, "pair.usda", crate::MeshQuality::Standard); + assert!(warnings.is_empty(), "{warnings:?}"); + let text = String::from_utf8(bytes).unwrap(); + assert!(text.contains("defaultPrim = \"Pair\""), "{text}"); + for n in &names { + assert!(text.contains(&format!("def Xform \"{n}\"")), "no prim named {n}:\n{text}"); + } + let (g, _) = crate::read_usd(text.as_bytes(), "pair.usda").unwrap(); + let got = boxes(g); + assert_eq!(got.len(), 2); + assert_box(&got[0], [[0.0, 0.0, 0.0], [10.0, 20.0, 30.0]]); + assert_box(&got[1], [[40.0, 0.0, 0.0], [50.0, 20.0, 30.0]]); +} + +/// A look's physical parameters are written as the `UsdPreviewSurface` inputs of the same names, +/// and a transparent look's opacity as `opacity`, with the values the looks were given. +#[test] +fn pbr_and_transparent_looks_write_their_values() { + let mut doc = Document::new("Looks"); + add_box(&mut doc, Vec3::ZERO, 0); + add_box(&mut doc, Vec3::new(40.0, 0.0, 0.0), 0); + let mut model = Model::new(); + model.evaluate(&doc); + let names: Vec = model.state().bodies.iter().map(|b| b.name.clone()).collect(); + let mut steel = Look::custom([128, 128, 128], 1.0); + steel.name = "Steel".into(); + steel.pbr = Some(solidcraft_doc::pbr_appearance::PbrParameters::new(0.75, 0.25, 1.5).unwrap()); + let mut glass = Look::custom([0, 128, 255], 0.375); + glass.name = "Glass".into(); + doc.appearances.bodies.insert(names[0].clone(), steel); + doc.appearances.bodies.insert(names[1].clone(), glass); + let (bytes, warnings) = usd_of(&doc, &model, "looks.usda"); + assert!(warnings.is_empty(), "{warnings:?}"); + let text = String::from_utf8(bytes).unwrap(); + assert!(text.contains("def Material \"Steel\"") && text.contains("def Material \"Glass\""), "{text}"); + assert_eq!(inputs(&text, "metallic"), vec![0.75], "{text}"); + assert_eq!(inputs(&text, "roughness"), vec![0.25], "{text}"); + assert_eq!(inputs(&text, "ior"), vec![1.5], "{text}"); + assert_eq!(inputs(&text, "opacity"), vec![0.375], "{text}"); + // Each body is bound to its own material. + assert!(text.contains("rel material:binding = ") || text.contains("/Looks/Steel>"), "{text}"); + assert!(text.contains("/Looks/Glass>"), "{text}"); +} + +/// A face with a look of its own: its triangles in the mesh are bound to that look's material; the +/// rest keep the body's. The top face of the 10 × 20 × 30 mm +/// box is the one at z = 30, so every triangle of its group lies there. +#[test] +fn a_face_with_its_own_look_gets_its_own_material() { + let (mut doc, model) = one_box(); + let body = model.state().bodies[0].name.clone(); + doc.appearances.bodies.insert(body.clone(), Look::custom([200, 200, 200], 1.0)); + let mut red = Look::custom([255, 0, 0], 1.0); + red.name = "Red".into(); + doc.appearances.faces.push(solidcraft_doc::appearance::FaceLook { + body, + point: Vec3::new(5.0, 10.0, 30.0), + look: red, + name: None, + strict_name: false, + certificate: None, + }); + let built = cadir(&doc, &model); + let model_ir = &built.ir.model; + let t = &model_ir.tessellations[0]; + let groups = t.triangle_groups(); + let top = groups.iter().find(|g| g.source_id.is_some()).unwrap_or_else(|| panic!("no face group: {groups:?}")); + let (points, triangles) = (t.vertices(), t.triangles()); + for &i in &top.triangles { + for &v in &triangles[i as usize] { + assert!((points[v as usize].get().z - 30.0).abs() < 1e-9, "a triangle of the face's group is off the top face"); + } + } + // The top face is two triangles at least, and the other five faces are not in its group. + assert!(top.triangles.len() >= 2 && top.triangles.len() < triangles.len()); + let red = model_ir.appearances.iter().find(|a| a.name.as_deref() == Some("Red")).unwrap(); + let bound = |pick: fn(&cadmpeg_ir::appearance::AppearanceTarget) -> bool| { + model_ir.appearance_bindings.iter().filter(|b| b.appearance == red.id && pick(&b.target)).count() + }; + use cadmpeg_ir::appearance::AppearanceTarget as T; + assert_eq!(bound(|t| matches!(t, T::TriangleGroup { .. })), 1); + assert_eq!(bound(|t| matches!(t, T::Face(_))), 0); + // In the file: a subset of the mesh bound to the face's material. + let text = usda(&doc, &model); + let red_bindings = text.lines().filter(|l| l.contains("rel material:binding") && l.contains("/Looks/Red>")).count(); + assert_eq!(red_bindings, 1, "{text}"); +} + +/// A placement that is not a rigid one is never written as one: the bodies are written where the +/// world has them, with a warning naming the occurrence. +#[test] +fn a_placement_that_is_not_rigid_is_written_where_the_world_has_it() { + let (doc, model) = galvanometer(); + let st = model.state(); + let mut doc = doc.clone(); + let o = doc.occurrences.iter_mut().find(|o| o.name.starts_with("Needle")).unwrap(); + o.transform[0][0] = -1.0; + let name = o.name.clone(); + let world = solidcraft_doc::world_state(&doc, &st).unwrap(); + let (bytes, warnings) = + crate::usd_from_design(&doc, &st, &world, &[], &crate::CadmpegOptions::default(), "mirror.usda", crate::MeshQuality::Standard).unwrap(); + assert!(warnings.iter().any(|w| w.contains(&name)), "{warnings:?}"); + let mut want: Vec<[[f64; 3]; 2]> = world + .bodies + .iter() + .map(|b| { + let bb = solidcraft_kernel::measure(&b.body).unwrap().bbox; + [[bb.min.x, bb.min.y, bb.min.z], [bb.max.x, bb.max.y, bb.max.z]] + }) + .collect(); + want.sort_by(|a, b| a.partial_cmp(b).unwrap()); + let (g, _) = crate::read_usd(&bytes, "mirror.usda").unwrap(); + let got = boxes(g); + assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}"); + for (got, want) in got.iter().zip(&want) { + for (g, w) in got.iter().flatten().zip(want.iter().flatten()) { + // USD mesh points are single precision. + assert!((g - w).abs() < 1e-3, "{got:?} is not {want:?}"); + } + } +} + +/// A placement that is not a finite number is never written as one and never panics: the bodies +/// are written where the world has them, with a warning naming the occurrence. +#[test] +fn nonfinite_placements_never_panic() { + let (doc, model) = galvanometer(); + let st = model.state(); + for bad in [f64::NAN, f64::INFINITY] { + let mut doc = doc.clone(); + let o = doc.occurrences.iter_mut().find(|o| o.name.starts_with("Needle")).unwrap(); + o.transform[0][0] = bad; + let name = o.name.clone(); + let (bytes, warnings) = + crate::usd_from_design(&doc, &st, &st, &[], &crate::CadmpegOptions::default(), "bad.usda", crate::MeshQuality::Standard).unwrap(); + assert!(warnings.iter().any(|w| w.contains(&name)), "{bad}: {warnings:?}"); + assert!(crate::read_usd(&bytes, "bad.usda").is_ok(), "{bad}"); + } +} + +/// Placements of a component the design does not have are left out once, and the rest keep their +/// place among all their parent's children: a damaged design with many of them under a part +/// placed twice still finishes, each needle at the ordinal the design gives it. +#[test] +fn placements_of_missing_components_keep_the_others_ordinals() { + let (mut doc, model) = galvanometer(); + let frame = doc.occurrences.iter().find(|o| o.name.starts_with("Frame")).unwrap().component; + let needle = doc.occurrences.iter().find(|o| o.name.starts_with("Needle")).unwrap().clone(); + let missing = |i: u64, parent: u64| solidcraft_doc::Occurrence { + id: u64::MAX - i, + component: u64::MAX - i, + parent, + name: format!("Missing {i}"), + ..needle.clone() + }; + // One before the needles in their frame, and many under the needle placed twice. + let at = doc.occurrences.iter().position(|o| o.component == needle.component).unwrap(); + doc.occurrences.insert(at, missing(0, frame)); + doc.occurrences.extend((1..5_000).map(|i| missing(i, needle.component))); + let built = cadir(&doc, &model); + let occurrences = &built.ir.model.occurrences; + assert!(occurrences.iter().all(|o| !o.name.as_deref().unwrap_or("").starts_with("Missing"))); + let mut ordinals: Vec = + occurrences.iter().filter(|o| o.name.as_deref().is_some_and(|n| n.starts_with("Needle"))).map(|o| o.ordinal).collect(); + ordinals.sort_unstable(); + assert_eq!(ordinals, [1, 2]); +} + +/// The design as an OpenUSD text file, `bodies` chosen (all when empty), with what `hidden` +/// hides written hidden. +fn usda_hidden(doc: &Document, model: &Model, bodies: &[String], hidden: &crate::Hidden) -> (String, Vec) { + let world = solidcraft_doc::world_state(doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { hidden: hidden.clone(), ..Default::default() }; + let (bytes, warnings) = + crate::usd_from_design(doc, &model.state(), &world, bodies, &options, "design.usda", crate::MeshQuality::Standard).unwrap(); + (String::from_utf8(bytes).unwrap(), warnings) +} + +const INVISIBLE: &str = "token visibility = \"invisible\""; + +/// The galvanometer's two needle placements, by path, and the needle body's name. +fn needles(doc: &Document, model: &Model) -> (Vec>, String) { + let frame = doc.components.iter().find(|c| c.name == "Frame").unwrap().id; + let needle = doc.components.iter().find(|c| c.name == "Needle").unwrap().id; + let frame_at = doc.occurrences.iter().find(|o| o.component == frame).unwrap().id; + let paths = doc.occurrences.iter().filter(|o| o.component == needle).map(|o| vec![frame_at, o.id]).collect(); + let body = model.state().bodies.iter().find(|b| doc.model_body_component(b) == needle).unwrap().name.clone(); + (paths, body) +} + +/// A chosen body the view hides is written invisible; the other is not. +#[test] +fn a_hidden_body_is_written_invisible() { + let mut doc = Document::new("Pair"); + add_box(&mut doc, Vec3::ZERO, 0); + add_box(&mut doc, Vec3::new(40.0, 0.0, 0.0), 0); + let mut model = Model::new(); + model.evaluate(&doc); + let names: Vec = model.state().bodies.iter().map(|b| b.name.clone()).collect(); + let hidden = crate::Hidden { bodies: [names[0].clone()].into(), placements: Vec::new() }; + let (text, warnings) = usda_hidden(&doc, &model, &names, &hidden); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(text.matches(INVISIBLE).count(), 1, "{text}"); + let first = text.find(&format!("def Xform \"{}\"", names[0])).unwrap(); + let second = text.find(&format!("def Xform \"{}\"", names[1])).unwrap(); + let invisible = text.find(INVISIBLE).unwrap(); + assert!(first < invisible && invisible < second, "the first body's prim holds it:\n{text}"); +} + +/// A placement the view hides is written as an invisible placement, once. +#[test] +fn a_hidden_placement_is_written_invisible() { + let (doc, model) = galvanometer(); + let (paths, _) = needles(&doc, &model); + let hidden = crate::Hidden { bodies: Default::default(), placements: vec![paths[0].clone()] }; + let (text, warnings) = usda_hidden(&doc, &model, &[], &hidden); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(text.matches(INVISIBLE).count(), 1, "{text}"); +} + +/// A component's body hidden in every placement is written hidden once, in the component; hidden +/// in one placement of two, it is written shown, with a warning. +#[test] +fn a_body_hidden_in_its_placements_is_written_hidden_and_in_some_warns() { + let (doc, model) = galvanometer(); + let (paths, body) = needles(&doc, &model); + let needle = doc.components.iter().find(|c| c.name == "Needle").unwrap().id; + let state = model.state(); + let names = solidcraft_doc::WorldNames::new(&doc, &state); + let placed: Vec = paths.iter().map(|p| names.name(&body, needle, p)).collect(); + let all = crate::Hidden { bodies: placed.iter().cloned().collect(), placements: Vec::new() }; + let (text, warnings) = usda_hidden(&doc, &model, &[], &all); + assert!(warnings.is_empty(), "{warnings:?}"); + assert_eq!(text.matches(INVISIBLE).count(), 1, "{text}"); + let one = crate::Hidden { bodies: [placed[0].clone()].into(), placements: Vec::new() }; + let (text, warnings) = usda_hidden(&doc, &model, &[], &one); + assert_eq!(text.matches(INVISIBLE).count(), 0, "{text}"); + assert!(warnings.iter().any(|w| w.contains(&body) && w.contains("hidden in 1 of the 2 shown placements")), "{warnings:?}"); +} + +/// A component's only body keeps its name when the component is placed once, and the design's +/// only body when it is exported alone: a prim named after the body inside the placement's or +/// the design's. +#[test] +fn an_only_body_keeps_its_name_when_placed_once() { + let mut doc = Document::new("Holder"); + let bracket = doc.add_component(Some("Bracket"), 0).unwrap(); + add_box(&mut doc, Vec3::ZERO, bracket); + let mut model = Model::new(); + model.evaluate(&doc); + let body = model.state().bodies[0].name.clone(); + let placement = doc.occurrences.iter().find(|o| o.component == bracket).unwrap().name.replace(':', "_"); + let text = usda(&doc, &model); + let at = text.find(&format!("\"{placement}\"")).unwrap_or_else(|| panic!("no prim {placement}:\n{text}")); + assert!(text[at..].contains(&format!("def Xform \"{body}\"")), "{text}"); + + let (doc, model) = one_box(); + let body = model.state().bodies[0].name.clone(); + let text = usda(&doc, &model); + assert!(text.contains("defaultPrim = \"Box\""), "{text}"); + let at = text.find("def Xform \"Box\"").unwrap_or_else(|| panic!("no prim Box:\n{text}")); + assert!(text[at..].contains(&format!("def Xform \"{body}\"")), "{text}"); +} + +/// With physics, a frame placed twice grounds its grounded needle in both placements, as the +/// design does, and every placement of a part with mass is a rigid body, joined or not: the two +/// frames and the four needles. +#[test] +fn physics_grounds_every_placement_and_makes_each_placement_a_rigid_body() { + let (mut doc, _) = galvanometer(); + let frame = doc.find_component("Frame").unwrap(); + doc.add_occurrence(frame, 0, solidcraft_doc::rigid(Vec3::new(0.0, 200.0, 0.0), Vec3::ZERO, Vec3::Z, 0.0)).unwrap(); + // Only the needle is grounded (the design grounds its first part, the frame, by itself). + let needle = doc.find_component("Needle").unwrap(); + doc.occurrences.iter_mut().for_each(|o| o.grounded = false); + doc.occurrences.iter_mut().find(|o| o.component == needle).unwrap().grounded = true; + let mut model = Model::new(); + model.evaluate(&doc); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { physics: true, ..Default::default() }; + let built = super::super::cadir_out::design(&doc, &model.state(), &world, &[], &options, "design", crate::MeshQuality::Standard).unwrap(); + let grounded = built.ir.model.assembly_joints.iter().filter(|j| j.native_ref.as_deref().is_some_and(|r| r.ends_with(" grounded"))).count(); + assert_eq!(grounded, 2, "{:?}", built.warnings); + assert_eq!(built.ir.model.rigid_bodies.len(), 6, "{:?}", built.warnings); +} + +/// A 2 × 2 RGBA PNG. +fn tiny_png() -> Vec { + let mut out = Vec::new(); + { + let mut encoder = png::Encoder::new(&mut out, 2, 2); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(&[255u8; 16]).unwrap(); + } + out +} + +/// One box's surface plan: a base-colour image projected along x and y, 10 mm a repeat along x +/// and 20 mm along y, the image's v as stored. +fn box_surface(body: &str) -> crate::SurfacePlan { + let bytes = tiny_png(); + crate::SurfacePlan { + setup: "Studio".into(), + definition: body.into(), + component: 0, + path: Vec::new(), + world: body.into(), + origin: [0.0; 3], + u: [10.0, 0.0, 0.0], + v: [0.0, 20.0, 0.0], + flip_v: false, + normal_strength: 1.0, + base_color: Some(crate::SurfaceMap { sha256: "f00d".into(), bytes: std::sync::Arc::from(bytes) }), + normal: None, + roughness: None, + metallic: None, + } +} + +/// The member names of the package `bytes`. +fn members(bytes: &[u8]) -> Vec { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + (0..zip.len()).map(|i| zip.by_index(i).unwrap().name().unwrap().to_string()).collect() +} + +/// The text of `name` inside the package `bytes`. +fn member(bytes: &[u8], name: &str) -> Option> { + let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut file = zip.by_name(name).ok()?; + let mut out = Vec::new(); + std::io::Read::read_to_end(&mut file, &mut out).unwrap(); + Some(out) +} + +/// The values of the array attribute `head` (such as `point3f[] points`) in `text`, flat. +fn array(text: &str, head: &str) -> Vec { + let at = text.find(head).unwrap_or_else(|| panic!("no {head}:\n{text}")); + let rest = &text[at + head.len()..]; + let body = &rest[rest.find('[').unwrap() + 1..rest.find(']').unwrap()]; + body.split(['(', ')', ',']).filter_map(|v| v.trim().parse().ok()).collect() +} + +/// A render setup's image is written into a package with the mesh's coordinates in it: each +/// point's (s, t) is its x over 10 mm and minus its y over 20 mm (the image read from its +/// bottom-left in the file, from its top-left by the renderer), and the image is a member. +#[test] +fn a_render_setup_image_is_packaged_with_the_projections_coordinates() { + let (doc, model) = one_box(); + let body = model.state().bodies[0].name.clone(); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { surfaces: vec![box_surface(&body)], ..Default::default() }; + let (bytes, warnings) = crate::usd_from_design(&doc, &model.state(), &world, &[], &options, "box.usdz", crate::MeshQuality::Standard).unwrap(); + assert!(warnings.is_empty(), "{warnings:?}"); + let root = members(&bytes).into_iter().find(|n| n.ends_with(".usda") || n.ends_with(".usdc")).unwrap(); + let text = String::from_utf8(member(&bytes, &root).unwrap()).unwrap(); + assert!(text.contains("UsdUVTexture"), "{text}"); + assert_eq!(member(&bytes, "textures/f00d.png"), Some(tiny_png())); + let points = array(&text, "point3f[] points"); + let st = array(&text, "texCoord2f[] primvars:st"); + assert_eq!(points.len() / 3, st.len() / 2, "{text}"); + for (p, c) in points.chunks(3).zip(st.chunks(2)) { + // The layer is in metres. + let (x, y) = (p[0] * 1000.0, p[1] * 1000.0); + assert!((c[0] - x / 10.0).abs() < 1e-4 && (c[1] + y / 20.0).abs() < 1e-4, "{p:?} gives {c:?}"); + } +} + +/// A render setup's images are written only in a package: a text layer warns and keeps the look. +#[test] +fn a_render_setup_image_outside_a_package_warns() { + let (doc, model) = one_box(); + let body = model.state().bodies[0].name.clone(); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { surfaces: vec![box_surface(&body)], ..Default::default() }; + let (bytes, warnings) = crate::usd_from_design(&doc, &model.state(), &world, &[], &options, "box.usda", crate::MeshQuality::Standard).unwrap(); + assert!(warnings.iter().any(|w| w.contains("written only in a .usdz package")), "{warnings:?}"); + assert!(!String::from_utf8(bytes).unwrap().contains("UsdUVTexture")); +} + +/// A component placed twice with an image on one placement only is written with its look, with a +/// warning: the file gives a component's body one mesh. +#[test] +fn an_image_on_one_placement_of_two_warns() { + let (doc, model) = galvanometer(); + let (paths, body) = needles(&doc, &model); + let needle = doc.components.iter().find(|c| c.name == "Needle").unwrap().id; + let mut plan = box_surface(&body); + plan.component = needle; + plan.path = paths[0].clone(); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { surfaces: vec![plan], ..Default::default() }; + let (bytes, warnings) = crate::usd_from_design(&doc, &model.state(), &world, &[], &options, "g.usdz", crate::MeshQuality::Standard).unwrap(); + assert!(warnings.iter().any(|w| w.contains(&body) && w.contains("different images")), "{warnings:?}"); + assert!(!members(&bytes).iter().any(|n| n.starts_with("textures/"))); +} + +/// The galvanometer built for OpenUSD with `options`. +fn built_with(doc: &Document, model: &Model, world: &ModelState, options: &crate::CadmpegOptions) -> super::super::cadir_out::Built { + super::super::cadir_out::design(doc, &model.state(), world, &[], options, "design", crate::MeshQuality::Standard).unwrap() +} + +/// `plan` with its base-colour image named `sha`. +fn with_image(mut plan: crate::SurfacePlan, sha: &str) -> crate::SurfacePlan { + plan.base_color = Some(crate::SurfaceMap { sha256: sha.into(), bytes: std::sync::Arc::from(tiny_png()) }); + plan +} + +/// A hidden placement's image does not count: the needle's shown placement has image B, its +/// hidden one image A, and B is written with no warning. +#[test] +fn the_shown_placements_image_is_written_when_a_hidden_one_differs() { + let (doc, model) = galvanometer(); + let (paths, body) = needles(&doc, &model); + let needle = doc.components.iter().find(|c| c.name == "Needle").unwrap().id; + let plan = |path: &Vec, sha: &str| { + let mut p = with_image(box_surface(&body), sha); + p.component = needle; + p.path = path.clone(); + p + }; + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { + hidden: crate::Hidden { placements: vec![paths[0].clone()], ..Default::default() }, + surfaces: vec![plan(&paths[0], "aaaa"), plan(&paths[1], "bbbb")], + ..Default::default() + }; + let built = built_with(&doc, &model, &world, &options); + assert!(!built.warnings.iter().any(|w| w.contains("different images")), "{:?}", built.warnings); + let assets: Vec<&str> = built.ir.model.assets.iter().map(|a| a.id.as_str()).collect(); + assert!(assets.iter().any(|a| a.ends_with("bbbb")) && !assets.iter().any(|a| a.ends_with("aaaa")), "{assets:?}"); +} + +/// Two placements with the same base colour and different half-strength normal maps, which are +/// left out of both, share the base colour. +#[test] +fn normal_maps_left_out_do_not_tell_placements_apart() { + let (doc, model) = galvanometer(); + let (paths, body) = needles(&doc, &model); + let needle = doc.components.iter().find(|c| c.name == "Needle").unwrap().id; + let plan = |path: &Vec, normal: &str| { + let mut p = box_surface(&body); + p.component = needle; + p.path = path.clone(); + p.normal_strength = 0.5; + p.normal = Some(crate::SurfaceMap { sha256: normal.into(), bytes: std::sync::Arc::from(tiny_png()) }); + p + }; + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { surfaces: vec![plan(&paths[0], "n1"), plan(&paths[1], "n2")], ..Default::default() }; + let built = built_with(&doc, &model, &world, &options); + assert!(!built.warnings.iter().any(|w| w.contains("different images")), "{:?}", built.warnings); + assert!(built.ir.model.assets.iter().any(|a| a.id.as_str().ends_with("f00d")), "{:?}", built.warnings); +} + +/// Two bodies with no look of their own, one imported red and one blue, given the same roughness +/// image, keep their own colours: two textured appearances, not one. +#[test] +fn bodies_of_different_colours_with_one_image_keep_their_colours() { + let mut doc = Document::new("Pair"); + add_box(&mut doc, Vec3::ZERO, 0); + add_box(&mut doc, Vec3::new(50.0, 0.0, 0.0), 0); + let mut model = Model::new(); + model.evaluate(&doc); + let mut world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + for (b, colour) in world.bodies.iter_mut().zip([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) { + b.imported = Some(std::sync::Arc::new(solidcraft_doc::appearance::ImportedLook { color: Some(colour), ..Default::default() })); + } + let surfaces = world + .bodies + .iter() + .map(|b| { + let mut p = box_surface(&b.name); + p.roughness = p.base_color.take(); + p + }) + .collect(); + let options = crate::CadmpegOptions { surfaces, ..Default::default() }; + let built = built_with(&doc, &model, &world, &options); + let textured: Vec<_> = built.ir.model.appearances.iter().filter(|a| !a.textures.is_empty()).map(|a| a.base_color).collect(); + assert_eq!(textured.len(), 2, "{textured:?}"); + assert_ne!(textured[0], textured[1], "{textured:?}"); +} + +/// The pictures shown on the model are written with the whole design only: a picture belongs to +/// no body, so an export of chosen bodies cannot tell its own from another body's, and leaves them +/// out with a warning. +#[test] +fn chosen_bodies_leave_the_pictures_out() { + let (doc, model) = one_box(); + let body = model.state().bodies[0].name.clone(); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let corners = [[0.0, 0.0, 30.0], [10.0, 0.0, 30.0], [10.0, 5.0, 30.0], [0.0, 5.0, 30.0]]; + let image = crate::SurfaceMap { sha256: "f00d".into(), bytes: std::sync::Arc::from(tiny_png()) }; + let decals = vec![crate::DecalPlan { name: "Logo".into(), component: 0, local: corners, world: corners, image }]; + let options = crate::CadmpegOptions { decals, ..Default::default() }; + let logo = |built: &super::super::cadir_out::Built| built.ir.model.bodies.iter().any(|b| b.name.as_deref() == Some("Logo")); + let all = super::super::cadir_out::design(&doc, &model.state(), &world, &[], &options, "design", crate::MeshQuality::Standard).unwrap(); + assert!(logo(&all), "{:?}", all.warnings); + let chosen = super::super::cadir_out::design(&doc, &model.state(), &world, &[body], &options, "design", crate::MeshQuality::Standard).unwrap(); + assert!(!logo(&chosen)); + assert!(chosen.warnings.iter().any(|w| w.contains("pictures shown on the model are not written")), "{:?}", chosen.warnings); +} + +/// `plan`'s optics for body `body`: glass of index `ior`, without absorption. +fn glass(body: &str, ior: f64) -> crate::OpticsPlan { + crate::OpticsPlan { + setup: "Glass".into(), + definition: body.into(), + component: 0, + path: Vec::new(), + world: body.into(), + ior, + absorption_per_mm: [0.0; 3], + thin_sheet: false, + } +} + +/// The OpenPBR transmission properties of the appearances of `built` with optics, by index. +fn optical(built: &super::super::cadir_out::Built) -> Vec<(Option, Option<[f32; 4]>)> { + built + .ir + .model + .appearances + .iter() + .filter(|a| a.properties.keys().any(|k| k.as_str().ends_with("transmission_weight"))) + .map(|a| { + let ior = a.properties.iter().find(|(k, _)| k.as_str() == "ior").map(|(_, v)| v.get()); + (ior, a.base_color.map(|c| [c.r(), c.g(), c.b(), c.a()])) + }) + .collect() +} + +/// A hidden placement's optics do not count: the needle's shown placement is glass of index +/// 1.52, its hidden one 1.33, and 1.52 is written with no warning. +#[test] +fn the_shown_placements_optics_are_written_when_a_hidden_one_differs() { + let (doc, model) = galvanometer(); + let (paths, body) = needles(&doc, &model); + let needle = doc.components.iter().find(|c| c.name == "Needle").unwrap().id; + let plan = |path: &Vec, ior: f64| { + let mut p = glass(&body, ior); + p.component = needle; + p.path = path.clone(); + p + }; + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { + hidden: crate::Hidden { placements: vec![paths[0].clone()], ..Default::default() }, + optics: vec![plan(&paths[0], 1.33), plan(&paths[1], 1.52)], + ..Default::default() + }; + let built = built_with(&doc, &model, &world, &options); + assert!(!built.warnings.iter().any(|w| w.contains("different optics")), "{:?}", built.warnings); + let iors: Vec> = optical(&built).into_iter().map(|(ior, _)| ior).collect(); + assert_eq!(iors, [Some(1.52)], "{:?}", built.warnings); +} + +/// Two bodies with no look of their own, one imported red and one blue, given the same optics, +/// keep their own colours: two glass appearances, not one. +#[test] +fn bodies_of_different_colours_with_one_glass_keep_their_colours() { + let mut doc = Document::new("Pair"); + add_box(&mut doc, Vec3::ZERO, 0); + add_box(&mut doc, Vec3::new(50.0, 0.0, 0.0), 0); + let mut model = Model::new(); + model.evaluate(&doc); + let mut world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + for (b, colour) in world.bodies.iter_mut().zip([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]) { + b.imported = Some(std::sync::Arc::new(solidcraft_doc::appearance::ImportedLook { color: Some(colour), ..Default::default() })); + } + let optics = world.bodies.iter().map(|b| glass(&b.name, 1.5)).collect(); + let options = crate::CadmpegOptions { optics, ..Default::default() }; + let built = built_with(&doc, &model, &world, &options); + let colours: Vec> = optical(&built).into_iter().map(|(_, c)| c).collect(); + assert_eq!(colours.len(), 2, "{colours:?}"); + assert_ne!(colours[0], colours[1], "{colours:?}"); +} + +/// A metallic look on a glass body is written with OpenPBR's metalness 0 beside its transmission +/// in the glass material, so the file's glass transmits; that material's preview surface keeps +/// the look's metallic 1. +#[test] +fn a_metallic_look_on_glass_is_written_transmitting() { + let (mut doc, model) = one_box(); + let body = model.state().bodies[0].name.clone(); + let mut steel = Look::custom([128, 128, 128], 1.0); + steel.name = "Steel".into(); + steel.pbr = Some(solidcraft_doc::pbr_appearance::PbrParameters::new(1.0, 0.25, 1.5).unwrap()); + doc.appearances.bodies.insert(body.clone(), steel); + let world = solidcraft_doc::world_state(&doc, &model.state()).unwrap(); + let options = crate::CadmpegOptions { optics: vec![glass(&body, 1.52)], ..Default::default() }; + let (bytes, _) = crate::usd_from_design(&doc, &model.state(), &world, &[], &options, "glass.usda", crate::MeshQuality::Standard).unwrap(); + let text = String::from_utf8(bytes).unwrap(); + // The glass material: from the `def Material` before its transmission to the next one. + let at = text.find("float inputs:transmission_weight = 1").unwrap_or_else(|| panic!("no transmission:\n{text}")); + let start = text[..at].rfind("def Material").unwrap(); + let end = text[at..].find("def Material").map_or(text.len(), |n| at + n); + let glass = &text[start..end]; + assert!(glass.contains("float inputs:base_metalness = 0") && !glass.contains("float inputs:base_metalness = 1"), "{glass}"); + assert!(glass.contains("float inputs:metallic = 1"), "{glass}"); +} diff --git a/crates/io/src/urdf.rs b/crates/io/src/urdf.rs index 9db39837388..05f0179a5a4 100644 --- a/crates/io/src/urdf.rs +++ b/crates/io/src/urdf.rs @@ -380,7 +380,7 @@ fn parts(doc: &Document, st: &ModelState, stem: &str, decals: &[UrdfDecal], name /// The placement `occurrence_world` resolves for an occurrence: through the first occurrence of /// each parent component. -fn canonical(doc: &Document, occ: u64) -> Vec { +pub(crate) fn canonical(doc: &Document, occ: u64) -> Vec { let mut path = Vec::new(); let mut cur = doc.occurrences.iter().find(|o| o.id == occ); for _ in 0..1000 { diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 750073e25de..5869f835754 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -330,7 +330,10 @@ pub fn tool_definitions_with(opts: Options) -> Vec { "Export bodies to STEP (.step/.stp), IGES (.iges/.igs), 3MF (.3mf), binary STL (.stl), ASCII STL (format stla), OBJ or GLB (.glb: binary glTF \ in metres with Y up, with each body's colours, metallic, roughness and opacity, render-setup Glass as glTF transmission, and each \ occurrence a named node holding its part's bodies) or OpenUSD (.usda text, .usdc or .usd binary, .usdz package: in metres with Z up, \ - each part's exact B-rep and a mesh of it, with colours, and the assembly as prims, a part placed twice written once). \ + each body, named, as its exact B-rep and its mesh, with its looks' colour, opacity, metallic and roughness, \ + and the assembly as prims named after the occurrences, a part placed twice written once) or Rhino (.3dm, Rhino 8: \ + each body where the design shows it, as its exact shape, named and in its colour, when every face is planar and every \ + edge straight, else as its mesh, without its name or colour; warnings say what the file left out; FreeCAD .FCStd cannot be written yet). \ The format comes from the extension unless given; for OpenUSD the path's extension picks text, binary or package, and a \ format naming another encoding is refused. URDF (.urdf) exports the whole assembly for robot simulators: a link per \ component placement with mass and inertia, joints from the assembly's joints, and STL meshes in metres written \ @@ -340,13 +343,18 @@ pub fn tool_definitions_with(opts: Options) -> Vec { object( json!({ "path": string("Output file"), - "format": {"type": "string", "enum": ["step", "stp", "iges", "igs", "3mf", "3mf-tagged", "stl", "stla", "obj", "glb", "usd", "usda", "usdc", "usdz", "urdf", "sdf"]}, + "format": {"type": "string", "enum": ["step", "stp", "iges", "igs", "3mf", "3mf-tagged", "stl", "stla", "obj", "glb", "usd", "usda", "usdc", "usdz", "3dm", "urdf", "sdf"]}, "bodies": {"type": "array", "items": {"type": "string"}, "description": "Body names (default: all; not with urdf)"}, + "writer": {"type": "string", "enum": ["solidcraft", "cadmpeg"], "description": "STEP and IGES only: SolidCraft's own writer (default), or cadmpeg's, which writes STEP AP242 with the components and colours but no solid names, and IGES 5.3 with each body where the design shows it; refused for other formats"}, "mesh_prefix": string("urdf: put before each mesh file name (default: none, so relative to the .urdf)"), "effort": {"type": "number", "description": "urdf: joint effort limit, N or N m (default 1000)"}, "velocity": {"type": "number", "description": "urdf: joint velocity limit, m/s or rad/s (default 10)"}, "hierarchy": {"type": "boolean", "description": "glb: false writes every body flat under the root in world coordinates, as SolidCraft 0.40 did (default true: a named node per occurrence)"}, - "images": {"type": "boolean", "description": "urdf: also write each picture shown on the model as a textured visual (default false)"}, + "images": {"type": "boolean", "description": "urdf and usd: also write each picture shown on the model as a textured visual; usd writes it only in a .usdz package (default false)"}, + "physics": {"type": "boolean", "description": "usd: also write the joints, grounded parts and each component's mass as OpenUSD physics, for a simulator (default false)"}, + "render_setup": string("usd: the saved render setup whose image textures a .usdz package holds (default: none)"), + "purpose": {"type": "string", "enum": ["interchange", "distribution"], "description": "usd: what the file is for: interchange (exact shapes beside meshes, for CAD) or distribution (meshes only with the pictures shown on the model, for viewers and game engines); exact_brep and images override it (default interchange)"}, + "exact_brep": {"type": "boolean", "description": "usd: write each body's exact shape beside its mesh (default: true for interchange, false for distribution)"}, "name": string("sdf: the model's name (default: the folder's name)"), "static": {"type": "boolean", "description": "sdf: scenery Gazebo never moves (default true); false gives it the bodies' mass"}, "model_uris": {"type": "boolean", "description": "sdf: name files as model:/// (default false: relative to model.sdf)"}, @@ -1079,7 +1087,27 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Map) -> Result exec( b, "file.export", - pick(a, &["path", "format", "bodies", "mesh_prefix", "effort", "velocity", "hierarchy", "images", "name", "static", "model_uris"]), + pick( + a, + &[ + "path", + "format", + "bodies", + "writer", + "mesh_prefix", + "effort", + "velocity", + "hierarchy", + "images", + "physics", + "render_setup", + "purpose", + "exact_brep", + "name", + "static", + "model_uris", + ], + ), ), "crash_reports" => match a.get("id") { Some(_) => exec(b, "diagnostics.crash_report", pick(a, &["id"])), @@ -1349,7 +1377,27 @@ fn batch_step(step: &Value) -> Result<(String, Value, Option), String> { "redo" => mapped("edit.redo", json!({})), "export" => mapped( "file.export", - pick(a, &["path", "format", "bodies", "mesh_prefix", "effort", "velocity", "hierarchy", "images", "name", "static", "model_uris"]), + pick( + a, + &[ + "path", + "format", + "bodies", + "writer", + "mesh_prefix", + "effort", + "velocity", + "hierarchy", + "images", + "physics", + "render_setup", + "purpose", + "exact_brep", + "name", + "static", + "model_uris", + ], + ), ), "save" => mapped("file.save", pick(a, &["path", "format", "overwrite"])), "open" => mapped("doc.open", pick(a, &["path", "up", "names", "geometry"])), diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index 6216a48acc4..89b9cbcc6a9 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -2023,13 +2023,20 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) { "ui.export" => { let body = bodies.first().map(String::as_str); let name = crate::export_name::offered(app, body, body.unwrap_or(&app.session.doc.name)); - app.pick_save_command( - &format!("{name}.step"), - &["step", "stp", "igs", "stl", "3mf", "obj", "glb", "usd", "usda", "usdc", "usdz"], - "file.export", - // `hierarchy` is read for GLB only. - json!({"bodies": bodies, "hierarchy": app.preferences.glb_export_hierarchy}), - ); + // cadmpeg's Rhino writer needs a temporary file, which the browser has not. + let formats: Vec<&str> = ["step", "stp", "igs", "stl", "3mf", "obj", "glb", "usd", "usda", "usdc", "usdz", "3dm"] + .into_iter() + .filter(|f| *f != "3dm" || !cfg!(target_arch = "wasm32")) + .collect(); + let bodies = bodies.clone(); + app.pick_save(&format!("{name}.step"), &formats, move |app, path| { + let Some(path) = path else { return }; + let mut params = json!({"bodies": bodies, "path": path, "hierarchy": app.preferences.glb_export_hierarchy}); + crate::toolbar::with_export_writer(app, &path, &mut params); + if let Ok(result) = app.run("file.export", params) { + crate::toolbar::exported(app, &path, &result); + } + }); } "ui.findBrowser" => { if let Some(b) = p.get("body").and_then(Value::as_str) { diff --git a/crates/ui-egui/src/file_load.rs b/crates/ui-egui/src/file_load.rs index bf67641544e..6c585c4d99c 100644 --- a/crates/ui-egui/src/file_load.rs +++ b/crates/ui-egui/src/file_load.rs @@ -2368,6 +2368,34 @@ M30 let _ = std::fs::remove_dir_all(&dir); } + /// File › Export of a STEP or IGES file asks for cadmpeg's writer only while "Export STEP and + /// IGES with cadmpeg" is on (off by default); other formats never carry a writer. The file + /// written then names cadmpeg in its header, and SolidCraft's own writer's does not. + #[test] + fn cadmpeg_export_preference_chooses_the_step_and_iges_writer() { + assert!(!crate::prefs::Prefs::default().cadmpeg_export, "off by default"); + let dir = std::env::temp_dir().join(format!("solidcraft-cadmpeg-export-pref-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for on in [false, true] { + let mut app = SolveApp::new(Session::default(), Default::default()); + app.preferences.cadmpeg_export = on; + app.run("solid.box", json!({"length": 10, "width": 20, "height": 30})).unwrap(); + for name in ["part.step", "part.STP", "part.igs", "part.iges", "part.stl", "part.3mf", "part.usda", "part.3dm"] { + let path = dir.join(name).to_string_lossy().to_string(); + let mut params = json!({"path": path}); + crate::toolbar::with_export_writer(&app, &path, &mut params); + let step_or_iges = !matches!(name.rsplit_once('.').map(|(_, e)| e), Some("stl" | "3mf" | "usda" | "3dm")); + assert_eq!(params.get("writer").and_then(Value::as_str), (on && step_or_iges).then_some("cadmpeg"), "{name} {on}"); + app.run("file.export", params).unwrap_or_else(|e| panic!("{name} {on}: {e}")); + if step_or_iges { + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text.contains("cadmpeg"), on, "{name} {on}"); + } + } + } + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn the_reuse_import_default_is_added_to_import_opens_only() { let mut app = SolveApp::new(Session::default(), Default::default()); diff --git a/crates/ui-egui/src/home.rs b/crates/ui-egui/src/home.rs index 99ac17a722b..de3902c6638 100644 --- a/crates/ui-egui/src/home.rs +++ b/crates/ui-egui/src/home.rs @@ -1188,12 +1188,15 @@ fn export_tiles(app: &SolveApp) -> start_page::Tiles<'_, FileAction> { ("obj", "OBJ", None, FileAction::Export("obj")), ("glb", "GLB", None, FileAction::Export("glb")), ("usd", "OpenUSD", None, FileAction::Export("usd")), + ("3dm", "Rhino", None, FileAction::Export("3dm")), ("urdf", "URDF", None, FileAction::Export("urdf")), ("sdf", "SDF", None, FileAction::Export("sdf")), ("json", "JSON", Some("home.export_json_hint"), FileAction::Export("json")), ]; let tiles = formats .into_iter() + // cadmpeg's Rhino writer needs a temporary file, which the browser has not. + .filter(|(id, ..)| *id != "3dm" || !cfg!(target_arch = "wasm32")) .map(|(id, format, hint, chosen)| start_page::Tile { id: format!("home:export:{id}").into(), icon: start_page::Icon::Kit("export"), diff --git a/crates/ui-egui/src/prefs/fields/general.rs b/crates/ui-egui/src/prefs/fields/general.rs index 3da5c088fa0..93f470bc2fe 100644 --- a/crates/ui-egui/src/prefs/fields/general.rs +++ b/crates/ui-egui/src/prefs/fields/general.rs @@ -13,6 +13,10 @@ macro_rules! general_preferences { /// instead of SolidCraft's own reader, and a FreeCAD or Rhino file's solids instead of /// restated as STEP by cadmpeg's STEP writer and read by SolidCraft's STEP reader. Off (the /// default) keeps SolidCraft's readers for all four, as before. + /// Export STEP and IGES with cadmpeg: File › Export of a STEP or IGES file asks `file.export` + /// for cadmpeg's writer (`writer: cadmpeg`), which writes the design through cadmpeg's model. + /// Off (the default) keeps SolidCraft's own STEP and IGES writers, as before. + cadmpeg_export: bool = false, PAGE_GENERAL => check_id("settings.cadmpeg_export"); cadmpeg_import: bool = false, PAGE_GENERAL => check_id("settings.cadmpeg_import"); /// Check for updates at start and once a day (docs/updates.md). check_updates: bool = true, 0; diff --git a/crates/ui-egui/src/prefs/general.rs b/crates/ui-egui/src/prefs/general.rs index 65e79b0973d..d9618c1d6b1 100644 --- a/crates/ui-egui/src/prefs/general.rs +++ b/crates/ui-egui/src/prefs/general.rs @@ -188,6 +188,10 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) { let cadmpeg = setting::cadmpeg_import(app, ui); crate::scenario::publish_target("prefs:cadmpeg_import", cadmpeg.rect); }); + ui_kit::settings_section(ui, "cadmpeg_export", app.tr("prefs.cadmpeg_export"), |ui| { + let cadmpeg = setting::cadmpeg_export(app, ui); + crate::scenario::publish_target("prefs:cadmpeg_export", cadmpeg.rect); + }); ui_kit::settings_section(ui, "dialogs", app.tr("prefs.dialogs"), |ui| { let right_click = setting::right_click_confirms(app, ui); crate::scenario::publish_target("prefs:right_click_confirms", right_click.rect); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 745fce9695c..1b668d5d86d 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1002,6 +1002,17 @@ pub(crate) fn start_export(app: &mut SolveApp, id: &str) -> bool { true } +/// `file.export`'s `writer` for a file `name` (a path or a format): cadmpeg's for a STEP or IGES +/// file while Preferences › General › Export STEP and IGES with cadmpeg is on; else left out, so +/// SolidCraft's own writer writes it. The command never reads the preference itself. +pub(crate) fn with_export_writer(app: &SolveApp, name: &str, params: &mut Value) { + let step_or_iges = + matches!(solidcraft_engine::io::Format::from_name(name), Ok(solidcraft_engine::io::Format::Step | solidcraft_engine::io::Format::Iges)); + if app.preferences.cadmpeg_export && step_or_iges { + params["writer"] = json!("cadmpeg"); + } +} + /// Export to a file with extension `ext`, in `format` when the extension alone doesn't name it. fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) { let body = crate::export_name::first_body(app); @@ -1013,20 +1024,41 @@ fn export_as(app: &mut SolveApp, ext: &str, format: Option<&str>) { app.pick_save(&name, exts, move |app, path| { let Some(path) = path else { return }; let mut params = json!({"path": path}); - if let Some(format) = format { + if let Some(format) = &format { params["format"] = json!(format); } + with_export_writer(app, format.as_deref().unwrap_or(&path), &mut params); // GLB only, and not read for the other formats. params["hierarchy"] = json!(app.preferences.glb_export_hierarchy); if let Ok(result) = app.run("file.export", params) { - let skipped = - result.get("skipped").and_then(Value::as_array).map_or(Vec::new(), |a| a.iter().filter_map(Value::as_str).collect::>()); - let line = if skipped.is_empty() { format!("Exported {path}") } else { format!("Exported {path} (skipped {})", skipped.join(", ")) }; - app.set_status(line, false); + exported(app, &path, &result); } }); } +/// The status line after an export: where the file went, with the bodies the exporter skipped and +/// the first warning its writer gave. Each warning is kept in Messages, so what the file leaves out +/// stays readable after the chip fades. +pub(crate) fn exported(app: &mut SolveApp, path: &str, result: &Value) { + let listed = |key: &str| -> Vec { + result.get(key).and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() + }; + let warnings = listed("warnings"); + for warning in &warnings { + let text = crate::i18n::tr_diagnostic(warning); + app.messages.push(&text, false, crate::now_ms()); + } + let mut line = format!("Exported {path}"); + if let Some(first) = warnings.first() { + line.push_str(&format!(" with {} warning(s): {first}", warnings.len())); + } + let skipped = listed("skipped"); + if !skipped.is_empty() { + line.push_str(&format!(" (skipped {})", skipped.join(", "))); + } + app.set_status(line, false); +} + /// Commands opt into persistent presentation; the engine status list remains the only truth. const PERSISTENT_COMMANDS: &[&str] = &[ "inspect.accessibility", @@ -3508,6 +3540,28 @@ mod header_report_tests { crate::dialogs::cancel(&mut h.app); } + /// What an exporter leaves out is said on the status line, and each warning stays in Messages + /// once the chip has faded; an export with nothing left out still says just where it went. + #[test] + fn an_export_with_warnings_says_so_and_keeps_them_in_messages() { + let mut h = crate::scenario::Harness::new(); + let result = json!({ + "path": "part.3dm", + "warnings": ["Pin: written as its mesh, without its name or colour", "Loose: written as its mesh"], + "skipped": ["Hidden"] + }); + exported(&mut h.app, "part.3dm", &result); + let (line, _, error) = h.app.status.clone().expect("a status line"); + assert_eq!(line, "Exported part.3dm with 2 warning(s): Pin: written as its mesh, without its name or colour (skipped Hidden)"); + assert!(!error, "a warning, not a failure"); + let messages: Vec = h.app.messages.iter().map(|m| m.text.clone()).collect(); + assert!(messages.iter().any(|m| m.contains("Pin: written as its mesh")), "{messages:?}"); + assert!(messages.iter().any(|m| m.contains("Loose: written as its mesh")), "{messages:?}"); + + exported(&mut h.app, "part.step", &json!({"path": "part.step"})); + assert_eq!(h.app.status.as_ref().map(|s| s.0.as_str()), Some("Exported part.step")); + } + /// New designs are saved as `.sc`. A design opened from a `.solidcraft` file is saved back to /// that file by Save (no rename behind the user's back); Save As offers `.sc` and leaves it. #[test] diff --git a/docs/book/src/guide/files.md b/docs/book/src/guide/files.md index 44b4ae55e84..22dc751fd8c 100644 --- a/docs/book/src/guide/files.md +++ b/docs/book/src/guide/files.md @@ -16,10 +16,10 @@ design · **3** Save · **4** Export: meshes, STEP, a DXF of the view, URDF, JSO | STEP (AP203, AP214, AP242) | solids, assemblies, units, names, colours | AP242 with names, colours and the component tree | | IGES 5.3 | manifold solids, or trimmed surfaces sewn into solids | manifold solids with names and colours | | FreeCAD `.FCStd` | sketches and features (Pad, Pocket, Revolution, Groove, Fillet, Chamfer, primitives, Mirrored, patterns), else solids, through cadmpeg | | -| Rhino `.3dm` | solids, through cadmpeg | | +| Rhino `.3dm` | solids, through cadmpeg | Rhino 8, through cadmpeg: bodies with flat faces and straight edges exact, others as meshes; names and colours (desktop only) | | 3MF, STL, OBJ | mesh bodies | yes | | glTF 2.0 (`.glb`, `.gltf` with its `.bin` files) | mesh bodies in the node tree's components, materials as appearances | `.glb`: placed bodies with their colours, metallic and roughness, in metres with Y up | -| OpenUSD (`.usd`, `.usda`, `.usdc`, `.usdz`), through cadmpeg | mesh bodies in the prim tree's components, materials as appearances; with `geometry: "exact"`, its B-reps as B-rep bodies | each part's exact B-rep and a mesh of it, colours, the component tree; in metres with Z up | +| OpenUSD (`.usd`, `.usda`, `.usdc`, `.usdz`), through cadmpeg | mesh bodies in the prim tree's components, materials as appearances; with `geometry: "exact"`, its B-reps as B-rep bodies | each body's mesh, named, with its exact B-rep where cadmpeg's model holds it; looks with metallic, roughness and opacity; the component tree; in metres with Z up | | 3MF with face tags | as 3MF | each triangle tagged with its B-rep face, exact coordinates | | URDF | | the assembly as a robot: links with meshes, mass and inertia, joints from the assembly's joints | | DXF, SVG | into a sketch | sketches and flat patterns as DXF | @@ -37,13 +37,53 @@ wrongly; leave such a body out with `bodies`. A refused export leaves a file alr **File → Export OpenUSD…** (`file.export` with a `.usd`, `.usda`, `.usdc` or `.usdz` path) writes an OpenUSD stage for NVIDIA Omniverse and Isaac Sim, Blender, Apple's tools and other USD viewers. The extension picks the encoding: `.usda` is text, `.usdc` and `.usd` are binary, and `.usdz` is a package of -one binary file. The bodies are written as `file.export` writes STEP (a design with components, when no -bodies are chosen, as its component tree), and cadmpeg restates that as USD. Each part is an `Xform` prim -holding its exact B-rep (a `BrepArray` prim) and a mesh of it for viewers; a part placed more than once is -written once, under the abstract `Prototypes` prim, and referenced at each placement. Colours become -`UsdPreviewSurface` materials. The stage is in metres with Z up and says so in its metadata. Metallic, -roughness, transparency and textures are not written yet, and neither are joints, masses or collision -shapes. +one binary file. The design is written straight into cadmpeg's model, which cadmpeg writes as USD. With +no bodies chosen, each component placement is an `Xform` prim named after the occurrence, holding its +component's bodies; a component placed more than once is written once, under the abstract `Prototypes` +prim, and referenced at each placement. Chosen bodies are written where the design shows them, under one +prim named after the design. Each body is a prim named after it, holding its exact B-rep (a `BrepArray` +prim) and the mesh SolidCraft draws it with, made at the export's Mesh quality (`quality`: standard, fine +or finest, as for STL). A mesh body has its mesh alone, and so has a body whose shape cadmpeg's model +cannot hold exactly yet, with a warning naming it. Looks become `UsdPreviewSurface` materials named after them, with their colour, +opacity (a transparent look stays transparent), metallic, roughness and index of refraction; a face with a +look of its own gets that material. The stage is in metres with Z up and says so in its metadata. +With `physics: true`, an export of the whole design also writes OpenUSD physics for a simulator: its +rigid, revolute, slider, cylindrical, planar and ball joints (revolute and slider joints keep their limits; +the others are written without them, with a warning), each grounded placement fixed to the world, each +placement of a component as a rigid body, each component's mass, centre of mass and principal inertia from +its bodies' materials, and a physics scene. Gears between two revolute joints and a rack and pinion become +PhysX gear and rack-and-pinion joints that couple the two joints. PhysX's gears turn opposite ways and its +rack moves with the pinion's turn, so gears that turn the same way (an internal gear, or reversed +gears), a rack that moves against the pinion's turn, other joint kinds, suppressed joints, screws, cams +and other motion links are left out with a warning. With bodies chosen, or a placement that is not rigid, no physics is written, and a +warning says why. With `render_setup: ` and a `.usdz` path, the images that render setup gives the +bodies (base colour, roughness, metallic, and a normal map the file can show as the renderer does) go +into the package, on each body's mesh; a `.usda` or `.usdc` file is written without them, with a warning. +With `images: true` and a `.usdz` path, each picture shown on the model (a decal or a placed image) goes +into the package as a body of its own in its component, named after it: a quad lifted 0.2 mm off each +side, its image as its colour and, for a PNG with transparency, its opacity. A hidden picture is not +written; a `.usda` or `.usdc` file, or an export of chosen bodies, leaves the pictures out with a warning. +With `render_setup`, a body the setup gives optics is written as glass, in every encoding: the setup's +index of refraction, and full transmission on the MaterialX OpenPBR shader with the colour 1 mm of the +absorption leaves (a reader of the preview surface alone shows it opaque, and a warning says so). +Collision shapes are not written yet. + +**File → Export Rhino…** (`file.export` with a `.3dm` path) writes a Rhino 8 file through cadmpeg, from +the design directly. cadmpeg's Rhino writer does not write assemblies yet, so every body is written where +the design shows it, named after it and in its colour. A body whose faces are all flat and whose edges +are all straight is written as its exact shape; cadmpeg cannot write any other exact shape to Rhino yet, +so a body with round faces is written as its mesh, at the export's Mesh quality, without its name or +colour. A face's own colour is not written. The reply's warnings name each body this applies to. +FreeCAD files cannot be exported yet: cadmpeg only writes back a FreeCAD file it read. Rhino export is +not available in the browser yet. + +STEP and IGES are written by SolidCraft's own writers. To compare them with cadmpeg's, turn on +Preferences › General › Export STEP and IGES with cadmpeg (off by default), or pass `writer: "cadmpeg"` +to `file.export` (`writer` applies to STEP and IGES only). cadmpeg then writes the file from the design: +STEP AP242 (edition 1, as SolidCraft's writer declares) with the components and placements, each +body's colour and each face's own colour, but without the bodies' names, and IGES 5.3 with each body where the design shows it, +named and in its colour, as cadmpeg's IGES writer writes no assemblies. The reply's warnings say what +the file leaves out. Opening a STEP, IGES, FreeCAD or Rhino file creates a design with the file's bodies as a base feature, and inserting one adds them to the current design. Later features build on them. A FreeCAD file's diff --git a/docs/mcp.md b/docs/mcp.md index fd58575cd98..daaf99fd605 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -406,7 +406,7 @@ builds it. | `check_parameters` | `set: {name: value}` (a number or an expression each, as `set_parameter`'s `value`), `report?` (`measure`, `cylinders`, `errors`; default all three), `bodies?` (a list of body names: only those are measured and their cylinders listed; default all), `summary?` (`measure` as the `measure` tool's `summary: true`; default false) | Try parameter values without keeping them: one `edit.checkpoint`, every value set in one `parameters.change {changes}` (one rebuild; an app without `changes` gets one change per name), the reports read, then `edit.restore_checkpoint`, so the design, its parameters and its undo history are exactly as before. The reply has `values` (each parameter's value with the tried expressions in), `recomputed`, `measure` (volume, bbox, bodies and faces per body, as the `measure` tool reports them), `errors` and `warnings` (the features that fail or warn: `{feature, name, error}`) with `parameter_errors` (the parameters that don't evaluate), `cylinders` (every cylindrical face of every body as `{body, radius, origin, axis, faces, name, area}`; the halves a kernel splits one cylinder into are one entry, `origin` is the axis point closest to the world origin and `axis` points so that its first non-zero component is positive) and `restored: true`. On a large design, `bodies` with the bodies a change touches and `summary: true` keep the reply small. A name the design has no parameter of, a value that is not a number or a string, an expression that does not evaluate, an unknown report item or a `bodies` that is not a list of names is an error, and nothing changes; a body name the design does not have after the change is an error after the design is put back. If the checkpoint cannot be restored the call is an error with `restored: false`, `restore_error` and a note that the tried values are still in the design: set them back before saving. Replaces the loop `set_parameter`, `measure`, `body_topology`, `set_parameter` back, which cost every agent session three to five calls and up to 16 s of rebuilds. Not a `batch` step. | | `screenshot` | `view?` (iso, top, front, back, bottom, left, right, home, fit, or a named view saved with `view.save`), `camera?` (`{target, yaw, pitch, distance, fov?}`, as `view.apply`), `path?`, `width?`, `height?`, `source?` (window, model), `grid?`, `axes?` | A PNG image content block. Headless: a render with the viewport's pipelines on a headless GPU device (see `solidcraft-cli gpu`; with no adapter, the CPU rasterizer, without analysis colours), fitted to the model, or from the named view or camera; the reply's `renderer` says which (`gpu`, `gpu-software`, `cpu`, with a `warning` for `cpu`). Bridged: the app window (default) or a model render with the app's camera; a named view or camera moves the app's viewport there first (`execute` `view.apply` does the same without a screenshot). `grid: false` and `axes: false` leave the ground grid (it lies on Z 0 and cuts through a part that straddles it) and the origin's axes out of a model render; axes hidden with `browser.visibility` stay out whatever `axes` says. Bridged, a screenshot that gives `grid` or `axes` is a model render, which follows the app's Grid and Origin switches for what it does not give; `source: "window"` with either is an error. A window that is minimised or on another macOS Space presents no frame: with no `source` the reply is a model render and says so (`fallback`); `source: "window"` is an error saying why, at once. Agents that don't need the app's chrome can ask for `source: "model"`. | | `compare_picture` | `reference`, `view?`, `camera?`, `bodies?`, `crop_px?`, `crop_fraction?`, `part_fills_crop?`, `fit?` (width, height, both; default width), `rows?` | Compare the model's outline with the part in a reference picture (a PNG or JPEG inside the server's folders, read through the same path rules as `screenshot`). A JPEG's EXIF orientation is applied, so a phone photo is measured as every viewer shows it (#19138). The compare is outline only: holes are not compared — both the picture's and the model's holes are filled. The model's outline is `inspect.silhouette` seen from `view` (default front) or `camera`; the picture's part is found by growing the background in from the border through small colour steps, filling holes and keeping the largest piece, so a backdrop's shading stays background and labels on a board drop out; a part touching the border, a white part on a light grey backdrop, and a part on a transparent background all separate. `crop_px` (`[x, y, w, h]` in pixels) or `crop_fraction` (the same as fractions 0..1) takes one view off a board; with `part_fills_crop: true` the crop box is the part itself and no background search runs, for a crop that tightly frames the part; `fit` names the dimension the one uniform scale comes from, never stretched per axis (`both` scales by width and reports `aspect_mismatch`). Returns an image content block (the overlay PNG: model red, picture blue) and text: `overlap` (0..1) and the model's top, bottom, left and right edges against the picture's in mm at nine stations, positive where the model reaches past the picture, null where a station misses one of the two. As a `batch` step it runs `inspect.compare_picture` without the overlay. | -| `export` | `path`, `format?` (step, stp, iges, igs, 3mf, 3mf-tagged, stl, stla, obj, glb, urdf), `bodies?`, `mesh_prefix?`, `effort?`, `velocity?`, `hierarchy?` | STEP, IGES, 3MF or mesh export; GLB writes binary glTF in metres with Y up, with each body's colours, metallic, roughness and opacity (alpha blended when not opaque) and the Glass a render setup gives it (glTF transmission, IOR and volume), and each occurrence a named node holding its part's bodies (`hierarchy: false`: every body flat in world coordinates, as 0.40 did); URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`). | +| `export` | `path`, `format?` (step, stp, iges, igs, 3mf, 3mf-tagged, stl, stla, obj, glb, usd, usda, usdc, usdz, 3dm, urdf), `bodies?`, `writer?` (STEP and IGES: solidcraft, the default, or cadmpeg), `mesh_prefix?`, `effort?`, `velocity?`, `hierarchy?`, `physics?` (OpenUSD, default false), `render_setup?` (OpenUSD, default none), `images?` (URDF and OpenUSD, default false), `purpose?` (OpenUSD: interchange, the default, or distribution), `exact_brep?` (OpenUSD, default from `purpose`) | STEP, IGES, 3MF or mesh export; GLB writes binary glTF in metres with Y up, with each body's colours, metallic, roughness and opacity (alpha blended when not opaque) and the Glass a render setup gives it (glTF transmission, IOR and volume), and each occurrence a named node holding its part's bodies (`hierarchy: false`: every body flat in world coordinates, as 0.40 did); URDF writes the whole assembly with its meshes next to it (`docs/urdf.md`); OpenUSD writes each body's exact shape beside its mesh, the assembly as prims; Rhino (`3dm`, Rhino 8) writes each body where the design shows it, as its exact shape when every face is planar and every edge straight, else as its mesh, with warnings for what the file leaves out. OpenUSD's `physics: true` also writes the joints, grounded parts and each component's mass as physics, for a simulator. `render_setup` names the saved render setup whose image textures a `.usdz` package holds. `images: true` also writes the pictures shown on the model (OpenUSD: in a `.usdz` package only). OpenUSD's `purpose: distribution` writes meshes only, with the pictures shown on the model (`images` then defaults to true and `exact_brep` to false); a given `images` or `exact_brep` overrides the purpose. `writer: cadmpeg` writes STEP and IGES through cadmpeg instead of SolidCraft's own writers. | | `undo`, `redo` | — | Undo / redo one change. | | `pending` | — | Bridged: the result of a request that was still running when its call returned (an error starting `still running:`), waiting up to 60 s for it; `done: false` while it runs (call again), `pending: null` when nothing runs. See [Long-running requests](#long-running-requests). | | `crash_reports` | `id?`, `limit?` | The crash reports on this computer, newest first; with `id`, the whole report (backtrace, command, recent commands, `design_path`/`replay_path`). See [crash-reports.md](crash-reports.md). | diff --git a/scripts/usd-validate.py b/scripts/usd-validate.py new file mode 100755 index 00000000000..11335d3abee --- /dev/null +++ b/scripts/usd-validate.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Check OpenUSD files with OpenUSD's own validators. + +Runs every validator the installed OpenUSD registers (UsdValidation) on each file and prints its +findings. Needs OpenUSD's Python bindings: `pip install usd-core`. + + python3 scripts/usd-validate.py [--ignore NAME]... FILE... + +Exit status: 0 when no file has a finding (other than the ignored ones), 1 when one has, 2 when a +file does not open, 3 when OpenUSD's Python bindings are not installed (nothing was checked). +""" + +import argparse +import sys + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--ignore", action="append", default=[], metavar="NAME", help="a finding name to leave out, such as MissingShaderIdInRegistry") + parser.add_argument("files", nargs="+", metavar="FILE") + args = parser.parse_args() + try: + from pxr import Usd, UsdValidation + except ImportError: + print("usd-validate: OpenUSD's Python bindings are not installed (pip install usd-core)", file=sys.stderr) + return 3 + context = UsdValidation.ValidationContext(UsdValidation.ValidationRegistry().GetOrLoadAllValidators()) + found = 0 + for path in args.files: + try: + stage = Usd.Stage.Open(path) + except Exception as e: # OpenUSD raises its own error type for a file it cannot read + print(f"{path}: does not open: {e}", file=sys.stderr) + return 2 + if not stage: + print(f"{path}: does not open", file=sys.stderr) + return 2 + findings = [e for e in context.Validate(stage) if e.GetName() not in args.ignore] + print(f"{path}: {len(findings)} findings") + for e in findings: + print(f" {e.GetName()}: {e.GetMessage()}") + found += len(findings) + return 1 if found else 0 + + +if __name__ == "__main__": + sys.exit(main())