* claim: #11666 * Sketch: recover legacy references on original whole faces
This commit is contained in:
@@ -769,6 +769,8 @@ impl Model {
|
||||
let mut exact = true;
|
||||
let mut prev = 0;
|
||||
let mut results = Vec::with_capacity(features.len());
|
||||
let mut construction = HashMap::new();
|
||||
let mut prepared_states = std::collections::HashSet::new();
|
||||
for (i, (f, r)) in doc.features.iter().zip(features).enumerate() {
|
||||
let saved = unhex(r.get("fingerprint").unwrap_or(&Json::Null))?;
|
||||
// A fingerprint reads the state before its feature (where the bodies it takes lie).
|
||||
@@ -780,8 +782,26 @@ impl Model {
|
||||
}
|
||||
let ms = r.get("ms").and_then(Json::as_f64).filter(|ms| ms.is_finite()).ok_or_else(|| bad("saved model: time"))?;
|
||||
// A file without room for every state keeps some features without one (#3220).
|
||||
let state =
|
||||
r.get("state").map(|s| states.get(index(Some(s), states.len())?).cloned().ok_or_else(|| bad("saved model: state"))).transpose()?;
|
||||
let state = r.get("state").map(|s| index(Some(s), states.len())).transpose()?;
|
||||
if let Some(at) = state
|
||||
&& prepared_states.insert(at)
|
||||
{
|
||||
let original = matches!(
|
||||
&f.kind,
|
||||
FeatureKind::Box { operation: Operation::NewBody, .. } | FeatureKind::Extrude { operation: Operation::NewBody, .. }
|
||||
);
|
||||
let current = states.get_mut(at).ok_or_else(|| bad("saved model: state"))?;
|
||||
// Each state is prepared before its first shared clone. Record and NameCell
|
||||
// identity prove this is still the original geometry and its exact names.
|
||||
for body in &mut Arc::make_mut(current).bodies {
|
||||
let key = (std::ptr::from_ref(body.body.record()).addr(), body.names.id());
|
||||
if original && body.feature == f.id && before.body(&body.name).is_none() {
|
||||
construction.insert(key, f.id);
|
||||
}
|
||||
body.names.cached_construction = construction.get(&key).copied();
|
||||
}
|
||||
}
|
||||
let state = state.map(|at| states.get(at).cloned().ok_or_else(|| bad("saved model: state"))).transpose()?;
|
||||
let result = FeatureResult {
|
||||
id: f.id,
|
||||
name: f.name.clone(),
|
||||
|
||||
@@ -9,15 +9,19 @@
|
||||
//! that uses it fails, asking for the reference to be picked again
|
||||
//! ([`crate::DocError::Reselect`]). A face whose name was worked out from geometry, found where
|
||||
//! the reference's point no longer lies, is reported: only geometry decided.
|
||||
//! Saved numbered Project links also have a compatibility check for a whole face that
|
||||
//! contains the saved pick and comes directly from its original construction feature.
|
||||
//! This check is local to manual sketch projection.
|
||||
|
||||
use solidcore_record::Vec3;
|
||||
use solidcraft_geom::Mesh;
|
||||
use solidcraft_geom::brep::eval::SurfaceEval;
|
||||
use solidcraft_geom::prelude::*;
|
||||
|
||||
use crate::history_names::{Match, Names};
|
||||
use crate::naming::{self, closest, edge_names, face_names, strip_piece};
|
||||
use crate::piece_names::strip_edge_number;
|
||||
use crate::{ModelBody, ModelState};
|
||||
use crate::{FeatureKind, ModelBody, ModelState, Operation};
|
||||
|
||||
/// The mark on a name saved before format 14 (`?F2:top#2`). Those names were worked out from
|
||||
/// geometry, and some of them name a face that exact history names differently (a tube's outer
|
||||
@@ -433,6 +437,84 @@ pub(crate) fn locate_on(body: &ModelBody, name: &str, p: Vec3) -> Option<FaceHit
|
||||
locate_in(std::iter::once((0, body)), name, p).ok()
|
||||
}
|
||||
|
||||
/// Find a saved manual Project face in its body. Older designs can name a numbered piece of
|
||||
/// a face that now evaluates whole. Recover it only when the original feature directly made
|
||||
/// the exact whole face and the face contains the
|
||||
/// old pick. Other face references still require the stored name as picked.
|
||||
pub(crate) fn locate_projected_face(body: &ModelBody, name: &str, p: Vec3) -> Option<(usize, Vec3)> {
|
||||
if body.body.is_mesh() {
|
||||
return None;
|
||||
}
|
||||
match locate_in(std::iter::once((0, body)), name, p) {
|
||||
Ok(hit) => Some((hit.face, hit.point)),
|
||||
Err(Miss::Gone) => recover_numbered_projected_face(body, name, p),
|
||||
Err(Miss::Several) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Bound the quadratic scan in remove_faces, which takes the list of faces to remove.
|
||||
const MAX_PROJECTION_RECOVERY_FACES: usize = 1024;
|
||||
|
||||
fn recover_numbered_projected_face(body: &ModelBody, name: &str, pick: Vec3) -> Option<(usize, Vec3)> {
|
||||
let (stem, number) = name.rsplit_once('#')?;
|
||||
let count = body.body.face_count();
|
||||
if count > MAX_PROJECTION_RECOVERY_FACES
|
||||
|| !pick.is_finite()
|
||||
|| stem.is_empty()
|
||||
|| strip_piece(stem) != stem
|
||||
|| number.is_empty()
|
||||
|| number.starts_with('0')
|
||||
|| !number.bytes().all(|digit| digit.is_ascii_digit())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// A changed body may keep the same face name while the face absorbs a smaller piece.
|
||||
// Projecting that larger face could silently grow a downstream feature's material.
|
||||
let producer = stem.strip_prefix('F')?.split_once(':')?.0.parse::<u64>().ok()?;
|
||||
let live_construction = body.names.origin.as_ref().is_some_and(|origin| {
|
||||
producer == origin.feature.id
|
||||
&& matches!(
|
||||
&origin.feature.kind,
|
||||
FeatureKind::Box { operation: Operation::NewBody, .. } | FeatureKind::Extrude { operation: Operation::NewBody, .. }
|
||||
)
|
||||
&& origin.before.body(&body.name).is_none()
|
||||
});
|
||||
if producer != body.feature || !(live_construction || body.names.cached_construction == Some(producer)) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let candidates = faces_with_stem(body, stem);
|
||||
let &[face] = candidates.as_slice() else { return None };
|
||||
let names = naming::names(body);
|
||||
let info = names.info.get(face)?;
|
||||
if names.faces.get(face)?.as_str() != stem || !info.verified || info.aliases.iter().any(|alias| strip_piece(alias) != stem) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let record = body.body.record().faces.get(face)?;
|
||||
let [[u0, u1], [v0, v1]] = record.domain;
|
||||
let surface = SurfaceEval::new(record.parameters()).ok()?;
|
||||
let tolerance = (body.body.size() * 1e-3).max(1e-3);
|
||||
if !tolerance.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let point = surface.point(surface.project(pick, Some([u0.midpoint(u1), v0.midpoint(v1)]), tolerance)?)?;
|
||||
if !point.is_finite() || !(point.dist(pick) <= tolerance) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Isolate the face so a point on another face of the same surface cannot pass the trim test.
|
||||
let others: Vec<_> = (0..count).filter(|index| *index != face).collect();
|
||||
let isolated;
|
||||
let trimmed = if others.is_empty() {
|
||||
&body.body
|
||||
} else {
|
||||
isolated = solidcraft_kernel::remove_faces(&body.body, &others).ok()?;
|
||||
&isolated
|
||||
};
|
||||
matches!(trimmed.classify_point(point), Ok(solidcraft_kernel::PointClass::OnBoundary)).then_some((face, point))
|
||||
}
|
||||
|
||||
/// The one face a name `model.faces` lists finds, on the body called `body` or, without one, on
|
||||
/// any body. `Err` says why there is no such face, or why the name does not name just one (the
|
||||
/// pieces of a split face, or the same face on several bodies): a command that takes a face by
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::{Document, ModelBody, ModelState};
|
||||
use solidcore_record::{Plane, Vec3};
|
||||
use solidcore_record::{Plane, Vec2, Vec3};
|
||||
use solidcraft_geom::prelude::*;
|
||||
use solidcraft_sketch::{LinkKind, LinkSource, Sketch};
|
||||
use std::collections::BTreeMap;
|
||||
@@ -49,3 +49,197 @@ fn named_manual_projection_keeps_its_body_and_face_at_shared_boundaries() {
|
||||
assert_eq!(sketch.links[0].id, link);
|
||||
assert!(matches!(&sketch.links[0].source,LinkSource::Face{body,..} if body=="Source"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_manual_projection_rebuilds_from_the_whole_planar_face() {
|
||||
let mut doc = Document::default();
|
||||
doc.set_param("size", "5", Some("mm"), None).unwrap();
|
||||
let kind = serde_json::from_value(serde_json::json!({
|
||||
"type": "box", "corner": [0, 0, 0], "length": "size", "width": "size", "height": "10"
|
||||
}))
|
||||
.unwrap();
|
||||
let feature = doc.add_feature(kind, None).unwrap();
|
||||
doc.feature_mut(feature).unwrap().body_names = vec!["Source".into()];
|
||||
let mut model = crate::Model::new();
|
||||
model.evaluate(&doc);
|
||||
let plane = Plane::XY.offset(20.);
|
||||
let source = LinkSource::Face { body: "Source".into(), at: Vec3::new(2., 2., 10.) };
|
||||
let resolved = crate::project::resolve(&doc, &BTreeMap::new(), &model.state(), &plane, LinkKind::Project, &source).unwrap();
|
||||
let mut sketch = Sketch::default();
|
||||
let link = sketch.add_link(LinkKind::Project, source, &resolved.geom).unwrap();
|
||||
let numbered = format!("F{feature}:+z#1");
|
||||
sketch.links[0].face_name = Some(numbered.clone());
|
||||
|
||||
doc.set_param("size", "20", Some("mm"), None).unwrap();
|
||||
model.evaluate(&doc);
|
||||
assert!(crate::project::refresh_links(&doc, &BTreeMap::new(), &model.state(), &plane, &mut sketch).unwrap().is_empty());
|
||||
assert!(!sketch.links[0].lost);
|
||||
assert_eq!(sketch.links[0].face_name.as_deref(), Some(numbered.as_str()));
|
||||
assert_eq!(sketch.link_curves(&link).len(), 4);
|
||||
assert!(sketch.points.iter().any(|point| point.pos.x > 19. && point.pos.y > 19.));
|
||||
|
||||
let saved = model.saved(&doc).unwrap();
|
||||
let reopened = crate::format::read(&doc.to_json()).unwrap();
|
||||
let cached = crate::Model::adopt(&reopened, &saved).unwrap();
|
||||
let state = cached.state();
|
||||
assert!(state.body("Source").unwrap().names.origin.is_none());
|
||||
assert_eq!(state.body("Source").unwrap().names.cached_construction, Some(feature));
|
||||
assert!(crate::project::refresh_links(&reopened, &BTreeMap::new(), &state, &plane, &mut sketch).unwrap().is_empty());
|
||||
assert!(!sketch.links[0].lost);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_round_face_projection_recovers_the_whole_face() {
|
||||
let doc = Document {
|
||||
features: serde_json::from_value(serde_json::json!([
|
||||
{
|
||||
"id": 1, "name": "Sketch1", "type": "sketch", "plane": {"name": "XY", "type": "origin"},
|
||||
"sketch": {
|
||||
"points": [{"fixed": true, "id": "origin", "pos": [0., 0.]}, {"fixed": false, "id": "c1.center", "pos": [0., 0.]}],
|
||||
"curves": [{"c": 1, "construction": false, "id": "c1", "r": 20., "type": "circle"}],
|
||||
"constraints": [{"id": "k1", "p": 0, "q": 1, "type": "coincident"}],
|
||||
"counters": {"k": 1, "l": 0, "p": 1}
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": 2, "name": "Extrude1", "type": "extrude", "body_names": ["Body1"],
|
||||
"extent": {"convention": "total_distance", "direction": "positive", "distance": "10"},
|
||||
"operation": "new_body", "profiles": {"loops": [["c1"]], "type": "curves"}, "sketch": 1
|
||||
},
|
||||
{
|
||||
"id": 3, "name": "Sketch2", "type": "sketch", "plane": {"name": "YZ", "type": "origin"},
|
||||
"sketch": {
|
||||
"points": [
|
||||
{"fixed": true, "id": "origin", "pos": [0., 0.]},
|
||||
{"fixed": false, "id": "p1", "pos": [-20., 0.]},
|
||||
{"fixed": false, "id": "p2", "pos": [20., 0.]},
|
||||
{"fixed": false, "id": "p3", "pos": [-20., 10.]},
|
||||
{"fixed": false, "id": "p4", "pos": [20., 10.]}
|
||||
],
|
||||
"curves": [
|
||||
{"a": 1, "b": 2, "construction": false, "id": "l1", "link": "j1", "type": "line"},
|
||||
{"a": 3, "b": 4, "construction": false, "id": "l2", "link": "j1", "type": "line"}
|
||||
],
|
||||
"constraints": [],
|
||||
"counters": {"k": 0, "l": 2, "p": 4},
|
||||
"links": [{
|
||||
"face_name": "F2:side:c1#1", "id": "j1", "kind": "project",
|
||||
"source": {"at": [-19.87, -2.3, 6.], "body": "Body1", "type": "face"}
|
||||
}]
|
||||
}
|
||||
}
|
||||
]))
|
||||
.unwrap(),
|
||||
..Document::default()
|
||||
};
|
||||
let doc = crate::format::read(&doc.to_json()).unwrap();
|
||||
let mut model = crate::Model::new();
|
||||
model.evaluate(&doc);
|
||||
let state = model.state();
|
||||
let body = state.body("Body1").unwrap();
|
||||
assert!(crate::naming::face_names(body).iter().any(|name| name == "F2:side:c1"));
|
||||
let result = model.result(3).unwrap();
|
||||
assert!(result.error.is_none(), "{result:?}");
|
||||
let projected = &state.sketch(3).expect("the saved projection should rebuild").sketch;
|
||||
assert_eq!(projected.links[0].face_name.as_deref(), Some("F2:side:c1#1"));
|
||||
assert_eq!(projected.link_curves("j1").len(), 2);
|
||||
|
||||
// The edge-on projection of the round wall can retain its saved geometry with a warning.
|
||||
// The numbered reference must evaluate the same way as the whole face's existing name.
|
||||
let mut exact_doc = doc.clone();
|
||||
exact_doc.sketch_mut(3).unwrap().links[0].face_name = Some("F2:side:c1".into());
|
||||
let mut exact_model = crate::Model::new();
|
||||
exact_model.evaluate(&exact_doc);
|
||||
let exact_state = exact_model.state();
|
||||
let exact = &exact_state.sketch(3).unwrap().sketch;
|
||||
assert_eq!(result.warning, exact_model.result(3).unwrap().warning);
|
||||
assert_eq!(projected.links[0].lost, exact.links[0].lost);
|
||||
assert_eq!(projected.curves, exact.curves);
|
||||
assert_eq!(projected.points, exact.points);
|
||||
|
||||
let saved = model.saved(&doc).expect("the healthy projection should save its model cache");
|
||||
let mut reopened = crate::format::read(&doc.to_json()).unwrap();
|
||||
let mut reopened_model = crate::Model::adopt(&reopened, &saved).unwrap();
|
||||
assert!(reopened_model.state().body("Body1").unwrap().names.origin.is_none());
|
||||
assert_eq!(reopened_model.state().body("Body1").unwrap().names.cached_construction, Some(2));
|
||||
let crate::FeatureKind::Sketch { plane, .. } = &mut reopened.feature_mut(3).unwrap().kind else { panic!("projection sketch") };
|
||||
*plane = crate::PlaneRef::Custom { plane: Plane::YZ.offset(0.1) };
|
||||
reopened_model.evaluate(&reopened);
|
||||
assert!(reopened_model.result(3).unwrap().error.is_none(), "{:?}", reopened_model.result(3));
|
||||
let pick = Vec3::new(-19.87, -2.3, 6.);
|
||||
assert!(crate::naming::face_on_body(body, "F2:side:c1#1", pick).is_none(), "ordinary lookup stays strict");
|
||||
let mut split = body.clone();
|
||||
let mut names = crate::naming::face_names(body).as_ref().clone();
|
||||
*names.iter_mut().find(|name| name.as_str() != "F2:side:c1").unwrap() = "F2:side:c1#2#[wall]".into();
|
||||
let origin = split.names.origin.clone();
|
||||
split.names = crate::naming::NameCell::known(Arc::new(names));
|
||||
split.names.origin = origin;
|
||||
assert!(crate::naming::face_on_body(&split, "F2:side:c1#1", pick).is_none());
|
||||
assert!(crate::name_lookup::locate_projected_face(&split, "F2:side:c1#1", pick).is_none(), "another piece still exists");
|
||||
|
||||
let mut outside = doc.sketch(3).unwrap().clone();
|
||||
outside.links[0].source = LinkSource::Face { body: "Body1".into(), at: Vec3::new(-19.87, -2.3, 12.) };
|
||||
let error = crate::project::refresh_links(&doc, &BTreeMap::new(), &state, &Plane::YZ, &mut outside).unwrap_err();
|
||||
assert!(matches!(&error, crate::DocError::Reselect { reference, .. } if reference == "F2:side:c1#1"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_projection_refuses_modified_or_moved_cached_sources() {
|
||||
for (kind, pick) in [
|
||||
(serde_json::json!({"type": "shell", "body": "Source", "faces": [[10, 10, 10]], "thickness": "1"}), Vec3::new(0., 5., 5.)),
|
||||
(serde_json::json!({"type": "move", "bodies": ["Source"], "translate": ["1", "0", "0"]}), Vec3::new(1., 5., 5.)),
|
||||
] {
|
||||
let mut doc = Document::default();
|
||||
let source = doc
|
||||
.add_feature(
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"type": "box", "corner": [0, 0, 0], "length": "20", "width": "20", "height": "10"
|
||||
}))
|
||||
.unwrap(),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
doc.feature_mut(source).unwrap().body_names = vec!["Source".into()];
|
||||
doc.add_feature(serde_json::from_value(kind).unwrap(), None).unwrap();
|
||||
let mut model = crate::Model::new();
|
||||
model.evaluate(&doc);
|
||||
assert!(model.results.iter().all(|result| result.error.is_none()));
|
||||
let saved = model.saved(&doc).unwrap();
|
||||
let reopened = crate::format::read(&doc.to_json()).unwrap();
|
||||
let cached = crate::Model::adopt(&reopened, &saved).unwrap();
|
||||
let state = cached.state();
|
||||
let body = state.body("Source").unwrap();
|
||||
let whole = format!("F{source}:-x");
|
||||
let numbered = format!("{whole}#1");
|
||||
assert!(crate::naming::face_on_body(body, &whole, pick).is_some());
|
||||
assert!(crate::naming::face_on_body(body, &numbered, pick).is_none());
|
||||
assert!(body.names.origin.is_none());
|
||||
assert_eq!(body.names.cached_construction, None);
|
||||
assert!(crate::name_lookup::locate_projected_face(body, &numbered, pick).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numbered_projection_refuses_a_pick_inside_a_hole_in_the_named_face() {
|
||||
let mut doc = Document::default();
|
||||
let mut sketch = Sketch::new();
|
||||
sketch.add_circle(Vec2::ZERO, 10., Some(0), Some("c1")).unwrap();
|
||||
sketch.add_circle(Vec2::ZERO, 2., Some(0), Some("c2")).unwrap();
|
||||
let profile = doc.add_feature(crate::FeatureKind::Sketch { plane: crate::PlaneRef::Origin { name: "XY".into() }, sketch }, None).unwrap();
|
||||
let kind = serde_json::from_value(serde_json::json!({
|
||||
"type": "extrude", "sketch": profile, "profiles": {"type": "curves", "loops": [["c1"]]}, "extent": {"distance": "5"}
|
||||
}))
|
||||
.unwrap();
|
||||
let feature = doc.add_feature(kind, None).unwrap();
|
||||
let mut model = crate::Model::new();
|
||||
model.evaluate(&doc);
|
||||
let state = model.state();
|
||||
let body = state.body("Body1").unwrap();
|
||||
let whole = format!("F{feature}:top");
|
||||
let top = crate::naming::face_names(body).iter().position(|name| name == &whole).unwrap();
|
||||
let numbered = format!("{whole}#1");
|
||||
|
||||
let pick = |x| crate::name_lookup::locate_projected_face(body, &numbered, Vec3::new(x, 0., 5.));
|
||||
assert_eq!(pick(5.).map(|(index, _)| index), Some(top));
|
||||
assert!(pick(0.).is_none(), "the pick is on the plane but inside the hole");
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ pub struct NamingOrigin {
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NameCell {
|
||||
pub origin: Option<Arc<NamingOrigin>>,
|
||||
/// Direct construction verified from identical cached body/name cells during adoption.
|
||||
/// Used only by manual Project compatibility, independently of general naming history.
|
||||
pub(crate) cached_construction: Option<u64>,
|
||||
/// What the body's faces came from, when the feature that made it reports it.
|
||||
lineage: Option<Arc<Lineage>>,
|
||||
names: Arc<OnceLock<Arc<Names>>>,
|
||||
@@ -57,7 +60,7 @@ impl NameCell {
|
||||
}
|
||||
/// Names of a body made by `origin`'s feature, following `lineage` where it is known.
|
||||
pub(crate) fn traced(origin: Option<Arc<NamingOrigin>>, lineage: Option<Arc<Lineage>>) -> Self {
|
||||
NameCell { origin, lineage, names: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None }
|
||||
NameCell { origin, cached_construction: None, lineage, names: Arc::new(OnceLock::new()), copy_of: None, saved_depth: None }
|
||||
}
|
||||
/// Names already known, taken as they are.
|
||||
pub fn known(names: Arc<Vec<String>>) -> Self {
|
||||
@@ -98,7 +101,7 @@ impl NameCell {
|
||||
fn shared(names: Arc<Names>) -> Self {
|
||||
let cell = OnceLock::new();
|
||||
let _ = cell.set(names);
|
||||
NameCell { origin: None, lineage: None, names: Arc::new(cell), copy_of: None, saved_depth: None }
|
||||
NameCell { origin: None, cached_construction: None, lineage: None, names: Arc::new(cell), copy_of: None, saved_depth: None }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1034,8 +1034,16 @@ fn refresh_links_in(
|
||||
if !l.auto_face
|
||||
&& let (Some(name), LinkSource::Face { body, at }) = (&l.face_name, &mut source)
|
||||
{
|
||||
let (index, p) =
|
||||
st.body(body).and_then(|target| crate::naming::face_on_body(target, name, *at)).ok_or_else(|| DocError::reselect(name.as_str()))?;
|
||||
let (index, p) = st
|
||||
.body(body)
|
||||
.and_then(|target| {
|
||||
if l.kind == LinkKind::Project {
|
||||
crate::name_lookup::locate_projected_face(target, name, *at)
|
||||
} else {
|
||||
crate::naming::face_on_body(target, name, *at)
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| DocError::reselect(name.as_str()))?;
|
||||
*at = p;
|
||||
named_face = Some((body.clone(), index, p));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user