SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
perf: placed parts draw their definition's display plan, moved (#3044) (#3127)
bherbruck0a328a3d0a0c
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex dcf95e1769..eb7a1e5c3a 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -123,16 +123,12 @@ impl ModelBody {/// The display plan at a given display quality, made once per level.pub fn display_plan_at(&self, q: crate::display_quality::DisplayQuality) -> Option<Arc<TessPlan>> {- self.plan- .get(q.index())?- .get_or_init(|| match self.body.display_plan_angular(q.chord(self.body.size()), q.angle()) {- Ok(plan) => Some(Arc::new(plan)),- Err(e) => {- log::debug!("{}: no display plan ({e})", self.name);- None- }- })- .clone()+ let cell = self.plan.get(q.index())?;+ match self.mesh_placement.as_deref() {+ // A placed part shows its definition's plan, moved (planned once for every placement).+ Some(placed) => cell.get_or_init(|| placed.plan(q, &self.name)).clone(),+ None => placed_mesh::definition_plan(&self.body, cell, q, &self.name),+ }}/// The display plan's mesh, evaluated on the CPU once per level: the same triangles a GPU@@ -147,7 +143,10 @@ impl ModelBody {pub fn plan_mesh_at(&self, q: crate::display_quality::DisplayQuality) -> Option<Arc<Mesh>> {self.plan_mesh.get(q.index())?- .get_or_init(|| self.display_plan_at(q).and_then(|plan| self.body.display_mesh_of(&plan).ok()).map(Arc::new))+ .get_or_init(|| match self.mesh_placement.as_deref() {+ Some(placed) => placed.plan_mesh(q, &self.name),+ None => self.display_plan_at(q).and_then(|plan| self.body.display_mesh_of(&plan).ok()).map(Arc::new),+ }).clone()}diff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rsindex 76c7243a41..f07d48e0c0 100644--- a/crates/doc/src/placed_mesh.rs+++ b/crates/doc/src/placed_mesh.rs@@ -2,6 +2,7 @@//! source mesh and map it into each pose; retain the exact placed B-rep separately in ModelBody.use std::sync::{Arc, OnceLock};+use solidcraft_geom::tess::TessPlan;use solidcraft_geom::{Mesh, Vec3};use solidcraft_kernel::{self as kernel, Body};@@ -11,6 +12,10 @@ use super::ModelBody;pub(super) struct PlacedMesh {body: Body,mesh: Arc<OnceLock<Arc<Mesh>>>,+ /// The definition's display plans and their meshes by display quality (its own cells):+ /// each placement draws them moved, so a part is planned once however often it is placed.+ plans: Arc<[OnceLock<Option<Arc<TessPlan>>>; 4]>,+ plan_meshes: Arc<[OnceLock<Option<Arc<Mesh>>>; 4]>,transform: crate::Mat,pub(super) tolerance: f64,}@@ -26,16 +31,47 @@ impl PlacedMesh {Some(original) => Self {body: original.body.clone(),mesh: original.mesh.clone(),+ plans: original.plans.clone(),+ plan_meshes: original.plan_meshes.clone(),transform: crate::mat_mul(transform, &original.transform),tolerance: original.tolerance,},- None => Self { body: source.body.clone(), mesh: source.mesh.clone(), transform: *transform, tolerance: source.display_tol() },+ None => Self {+ body: source.body.clone(),+ mesh: source.mesh.clone(),+ plans: source.plan.clone(),+ plan_meshes: source.plan_mesh.clone(),+ transform: *transform,+ tolerance: source.display_tol(),+ },})}pub(super) fn mesh(&self) -> Arc<Mesh> {- let source = reference_mesh(&self.body, &self.mesh, self.tolerance);- Arc::new(Mesh {+ Arc::new(self.moved(&reference_mesh(&self.body, &self.mesh, self.tolerance)))+ }++ /// The definition's display plan at quality `q` (made once, in its own cell), moved here.+ pub(super) fn plan(&self, q: crate::display_quality::DisplayQuality, name: &str) -> Option<Arc<TessPlan>> {+ let source = definition_plan(&self.body, self.plans.get(q.index())?, q, name)?;+ Some(Arc::new(source.transformed(&self.transform)))+ }++ /// The definition's display plan mesh at quality `q`, moved here.+ pub(super) fn plan_mesh(&self, q: crate::display_quality::DisplayQuality, name: &str) -> Option<Arc<Mesh>> {+ let cell = self.plan_meshes.get(q.index())?;+ let source = cell+ .get_or_init(|| {+ let plan = definition_plan(&self.body, self.plans.get(q.index())?, q, name)?;+ self.body.display_mesh_of(&plan).ok().map(Arc::new)+ })+ .clone()?;+ Some(Arc::new(self.moved(&source)))+ }++ /// `source` (in the definition's place) moved by this placement.+ fn moved(&self, source: &Mesh) -> Mesh {+ Mesh {positions: source.positions.iter().map(|p| crate::apply_point(&self.transform, *p)).collect(),normals: source.normals.iter().map(|n| crate::apply_vector(&self.transform, *n)).collect(),edges: source.edges.iter().map(|edge| edge.iter().map(|p| crate::apply_point(&self.transform, *p)).collect()).collect(),@@ -45,10 +81,27 @@ impl PlacedMesh {seams: source.seams.clone(),smooth_edges: source.smooth_edges.clone(),sharp_edges: source.sharp_edges.clone(),- })+ }}}+/// The display plan of a definition `body` at quality `q`, made once in `cell`.+pub(super) fn definition_plan(+ body: &Body,+ cell: &OnceLock<Option<Arc<TessPlan>>>,+ q: crate::display_quality::DisplayQuality,+ name: &str,+) -> Option<Arc<TessPlan>> {+ cell.get_or_init(|| match body.display_plan_angular(q.chord(body.size()), q.angle()) {+ Ok(plan) => Some(Arc::new(plan)),+ Err(e) => {+ log::debug!("{name}: no display plan ({e})");+ None+ }+ })+ .clone()+}+pub(super) fn reference_mesh(body: &Body, mesh: &OnceLock<Arc<Mesh>>, tolerance: f64) -> Arc<Mesh> {mesh.get_or_init(|| Arc::new(body.reference_display_mesh_angular(tolerance, kernel::DISPLAY_ANGLE).unwrap_or_default())).clone()}@@ -97,6 +150,57 @@ mod tests {assert!(Arc::ptr_eq(&mesh, &nested.mesh()));}+ /// Placed parts share their definition's display plan (#3044): the definition is planned+ /// once, every placement moves that plan, and a moved plan evaluates to the definition's+ /// points moved, on every kind of surface (planes, revolved and spline surfaces).+ #[test]+ fn placed_parts_are_planned_once_and_draw_the_moved_plan() {+ use crate::display_quality::DisplayQuality;+ let q = DisplayQuality::parse("normal").unwrap();+ for body in [+ kernel::box_solid(Vec3::ZERO, Vec3::new(2., 3., 4.)).unwrap(),+ kernel::cylinder(Vec3::new(1., 0., 0.), Vec3::Z, 2., 8.).unwrap(),+ kernel::torus(Vec3::ZERO, 6., 1.5).unwrap(),+ kernel::sphere(Vec3::new(0., 1., 2.), 3.).unwrap(),+ ] {+ let source = ModelBody::new("Part".into(), body, 1);+ let a = crate::rigid(Vec3::new(10., 20., 30.), Vec3::ZERO, Vec3::Z, 0.7);+ let b = crate::rigid(Vec3::new(-4., 5., 1.), Vec3::new(1., 1., 0.), Vec3::X, 1.1);+ let placed: Vec<ModelBody> = [a, b]+ .iter()+ .map(|m| {+ let mut p = ModelBody::new("Copy".into(), kernel::transform_matrix(&source.body, *m).unwrap(), 1);+ p.mesh_placement = Some(Arc::new(PlacedMesh::new(&source, m).unwrap()));+ p+ })+ .collect();+ assert!(source.plan.get(q.index()).unwrap().get().is_none());+ let plans: Vec<_> = placed.iter().map(|p| p.display_plan_at(q).unwrap()).collect();+ assert!(source.plan.get(q.index()).unwrap().get().is_some(), "placing plans the definition, in its own cell");+ let own = source.display_plan_at(q).unwrap();+ let local = own.evaluate();+ for (m, plan) in [a, b].iter().zip(&plans) {+ assert!(!Arc::ptr_eq(plan, &own));+ let moved = plan.evaluate();+ assert_eq!(moved.triangles, local.triangles);+ for (p, q) in local.positions.iter().zip(&moved.positions) {+ assert!(crate::apply_point(m, *p).dist(*q) < 1e-9, "{p:?} -> {q:?}");+ }+ for (n, k) in local.normals.iter().zip(&moved.normals) {+ assert!(crate::apply_vector(m, *n).dist(*k) < 1e-9);+ }+ }+ for (m, p) in [a, b].iter().zip(&placed) {+ let mesh = p.plan_mesh_at(q).unwrap();+ let base = source.plan_mesh_at(q).unwrap();+ assert_eq!(mesh.triangles, base.triangles);+ for (x, y) in base.positions.iter().zip(&mesh.positions) {+ assert!(crate::apply_point(m, *x).dist(*y) < 1e-9);+ }+ }+ }+ }+#[test]fn world_instances_warm_one_definition_and_an_edit_replaces_it() {let mut doc = crate::Document::new("instances");diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rsindex 94d23b9442..3bb3e47ac2 100644--- a/crates/geom/src/tess.rs+++ b/crates/geom/src/tess.rs@@ -109,6 +109,70 @@ impl TessPlan {pub fn vertex_count(&self) -> usize {self.faces.iter().map(|f| f.uv.len()).sum()}++ /// This plan for the body moved by the rotation and translation `m` (by columns, the+ /// translation in `m[3]`): the same parameters and triangles on the moved surfaces, so a+ /// part placed many times is planned once. Only for proper rigid motions (a reflection+ /// would turn the triangles inside out; the caller checks).+ pub fn transformed(&self, m: &[[f64; 4]; 4]) -> TessPlan {+ let vector = |v: Vec3| {+ Vec3::new(+ m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z,+ m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z,+ m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z,+ )+ };+ let point = |p: Vec3| vector(p) + Vec3::new(m[3][0], m[3][1], m[3][2]);+ let surfaces = self+ .surfaces+ .iter()+ .map(|s| match s {+ EvalSurface::Plane { origin, du, dv } => EvalSurface::Plane { origin: point(*origin), du: vector(*du), dv: vector(*dv) },+ EvalSurface::Nurbs { degree, knots, count, ctrl } => EvalSurface::Nurbs {+ degree: *degree,+ knots: knots.clone(),+ count: *count,+ // Homogeneous: the translation scales with the weight.+ ctrl: ctrl+ .iter()+ .map(|c| {+ let q = vector(Vec3::new(c[0], c[1], c[2])) + Vec3::new(m[3][0], m[3][1], m[3][2]) * c[3];+ [q.x, q.y, q.z, c[3]]+ })+ .collect(),+ },+ EvalSurface::Revolved { profile, origin, axis, transform, swap } => {+ // `m` (as rows) after the surface's own affine map.+ let r = |i: usize| [m[0][i], m[1][i], m[2][i], m[3][i]];+ let rows = [r(0), r(1), r(2)];+ let t = transform;+ let composed = rows.map(|row| {+ let mut out = [0.0; 4];+ for (j, slot) in out.iter_mut().enumerate() {+ *slot = (0..3).map(|k| row[k] * t[k][j]).sum::<f64>() + if j == 3 { row[3] } else { 0.0 };+ }+ out+ });+ EvalSurface::Revolved { profile: profile.clone(), origin: *origin, axis: *axis, transform: composed, swap: *swap }+ }+ })+ .collect();+ let faces = self+ .faces+ .iter()+ .map(|f| FacePlan {+ fixed: f.fixed.iter().map(|p| point(*p)).collect(),+ normals: f.normals.iter().map(|n| vector(*n)).collect(),+ ..f.clone()+ })+ .collect();+ TessPlan {+ surfaces,+ faces,+ edges: self.edges.iter().map(|e| e.iter().map(|p| point(*p)).collect()).collect(),+ edge_faces: self.edge_faces.clone(),+ }+ }}impl EvalCurve {@@ -312,6 +376,53 @@ mod tests {a.dist(b) <= tol}+ /// A moved plan evaluates to the plan's points moved, on a rational spline surface (the+ /// translation scales with each weight) and a revolved one (composed with its own map).+ #[test]+ fn a_transformed_plan_evaluates_to_the_moved_points() {+ let (c, s) = (0.6f64.cos(), 0.6f64.sin());+ // Turned about z by 0.6 rad, then moved: by columns.+ let m = [[c, s, 0.0, 0.0], [-s, c, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [5.0, -2.0, 7.0, 1.0]];+ let apply = |p: Vec3| Vec3::new(c * p.x - s * p.y + 5.0, s * p.x + c * p.y - 2.0, p.z + 7.0);+ let w = std::f64::consts::FRAC_1_SQRT_2;+ let nurbs = EvalSurface::Nurbs {+ degree: [2, 1],+ knots: [vec![0.0, 0.0, 0.0, 1.0, 1.0, 1.0], vec![0.0, 0.0, 1.0, 1.0]],+ count: [3, 2],+ ctrl: vec![[1.0, 0.0, 0.0, 1.0], [w, w, 0.0, w], [0.0, 1.0, 0.0, 1.0], [1.0, 0.0, 2.0, 1.0], [w, w, 2.0 * w, w], [0.0, 1.0, 2.0, 1.0]],+ };+ let revolved = EvalSurface::Revolved {+ profile: line(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 0.0, 1.0)),+ origin: Vec3::ZERO,+ axis: Vec3::Z,+ transform: [[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, -1.0, 2.0], [0.0, 1.0, 0.0, 3.0]],+ swap: false,+ };+ let face = |i: u32| FacePlan {+ face: i,+ surface: Some(i),+ uv: vec![[0.1, 0.2], [0.7, 0.4], [0.3, 0.9]],+ fixed: vec![Vec3::new(1.0, 2.0, 3.0)],+ triangles: vec![[0, 1, 2]],+ ..Default::default()+ };+ let plan = TessPlan {+ surfaces: vec![nurbs, revolved],+ faces: vec![face(0), face(1)],+ edges: vec![vec![Vec3::new(1.0, 1.0, 1.0)]],+ edge_faces: vec![vec![0, 1]],+ };+ let (a, b) = (plan.evaluate(), plan.transformed(&m).evaluate());+ assert_eq!(a.triangles, b.triangles);+ for (p, q) in a.positions.iter().zip(&b.positions) {+ assert!(close(apply(*p), *q, 1e-12), "{p:?} -> {q:?}");+ }+ for (n, k) in a.normals.iter().zip(&b.normals) {+ assert!(close(apply(*n) - apply(Vec3::ZERO), *k, 1e-12));+ }+ assert!(close(apply(a.edges[0][0]), b.edges[0][0], 1e-12));+ }+fn line(a: Vec3, b: Vec3) -> EvalCurve {EvalCurve { degree: 1, knots: vec![0.0, 0.0, 1.0, 1.0], ctrl: vec![[a.x, a.y, a.z, 1.0], [b.x, b.y, b.z, 1.0]] }}