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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions assets/locales/pending/frame-member-groups.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
{
"ar": {
"ui.frame_member.group": "المجموعة {number}",
"ui.frame_member.groups": "المجموعات",
"ui.frame_member.new_group": "مجموعة جديدة",
"ui.frame_member.remove_group": "إزالة المجموعة"
},
"de": {
"ui.frame_member.group": "Gruppe {number}",
"ui.frame_member.groups": "Gruppen",
"ui.frame_member.new_group": "Neue Gruppe",
"ui.frame_member.remove_group": "Gruppe entfernen"
},
"en": {
"ui.frame_member.group": "Group {number}",
"ui.frame_member.groups": "Groups",
"ui.frame_member.new_group": "New Group",
"ui.frame_member.remove_group": "Remove Group"
},
"he": {
"ui.frame_member.group": "קבוצה {number}",
"ui.frame_member.groups": "קבוצות",
"ui.frame_member.new_group": "קבוצה חדשה",
"ui.frame_member.remove_group": "הסרת קבוצה"
},
"ja": {
"ui.frame_member.group": "グループ {number}",
"ui.frame_member.groups": "グループ",
"ui.frame_member.new_group": "新しいグループ",
"ui.frame_member.remove_group": "グループを削除"
},
"ko": {
"ui.frame_member.group": "그룹 {number}",
"ui.frame_member.groups": "그룹",
"ui.frame_member.new_group": "새 그룹",
"ui.frame_member.remove_group": "그룹 제거"
},
"vi": {
"ui.frame_member.group": "Nhóm {number}",
"ui.frame_member.groups": "Nhóm",
"ui.frame_member.new_group": "Tạo nhóm mới",
"ui.frame_member.remove_group": "Xóa nhóm"
},
"zh": {
"ui.frame_member.group": "组 {number}",
"ui.frame_member.groups": "组",
"ui.frame_member.new_group": "新建组",
"ui.frame_member.remove_group": "删除组"
}
}
5 changes: 5 additions & 0 deletions crates/doc/src/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1017,6 +1017,11 @@ pub enum FeatureKind {
/// come and go (`frame::member_names`).
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
names: std::collections::BTreeMap<String, String>,
/// Two or more groups of lines, each placed its own way (`frame::MemberGroup`); then they
/// stand in for `lines`, `anchor`, `angle`, `mirror` and `body_name`, which stay unset.
/// None: those fields are the feature's one group (`frame::member_groups`).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
groups: Vec<crate::frame::MemberGroup>,
},
/// Raise or sink profiles on a planar face, or wrap them on a selected cylindrical wall.
Emboss {
Expand Down
109 changes: 73 additions & 36 deletions crates/doc/src/eval_frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
//! profile laid square to the line (`frame::member_axes`) and run from one end to the other.

use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, HashMap, HashSet};

use solidcraft_geom::{Aabb2, Plane, Region2, Ring, Vec2, Vec3};
use solidcraft_kernel as kernel;
use solidcraft_sketch::CurveKind;

use super::{ModelBody, ModelState, SolvedSketch, new_name, path_in_frame, select_profiles, sketch_in_feature_frame, val};
use crate::expr::{Kind, Value};
use crate::frame::{self, MAX_MEMBERS, MemberProfile};
use crate::frame::{self, MAX_MEMBERS, MemberGroup, MemberProfile};
use crate::{DocError, Document, Feature, FeatureKind, ProfileSel, Result};

/// Most profiles a profile sketch may have for its material to be worked out.
Expand All @@ -20,36 +20,42 @@ const MIN_LENGTH: f64 = 1e-6;
/// How far (mm) a 3D sketch curve may stray from the line between its ends and still be a line.
const STRAIGHT_TOL: f64 = 1e-3;

/// Evaluate a `FrameMember` feature: one new body per line, each named
/// ([`member_names`], or by position for a copy whose `body_names` were set).
/// Evaluate a `FrameMember` feature: one new body per line, group by group, each placed as its
/// group says and named ([`member_names`], or by position for a copy whose `body_names` were set).
pub(super) fn evaluate(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st: &mut ModelState) -> Result<()> {
let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, body_name, names } = &f.kind else {
let FeatureKind::FrameMember { path_sketch, profile, names, .. } = &f.kind else {
return Err(DocError::Invalid("not a frame member feature".into()));
};
let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?;
// The frame sketch in this feature's component frame: its plane, and its 3D lines.
let mapped =
if ps.sketch.wires.is_empty() { Cow::Owned(sketch_in_feature_frame(doc, ps, f.component)?) } else { path_in_frame(doc, ps, f.component)? };
let segments = member_lines(mapped.as_ref(), lines)?;
let (mut regions, description) = profile_regions(vals, st, profile)?;
if *mirror {
regions = regions.iter().map(frame::mirrored).collect();
}
let at = frame::anchor_point(&regions, *anchor);
let turn = match angle {
Some(e) => val(vals, e, Kind::Angle)?,
None => 0.0,
};
let mut made = Vec::with_capacity(segments.len());
for (id, a, b) in &segments {
let (x, y) = frame::member_axes(*b - *a, turn).ok_or_else(|| DocError::Invalid(format!("line `{id}` has no length")))?;
let plane = Plane::new(*a - x * at.x - y * at.y, x, y).ok_or_else(|| DocError::Invalid(format!("line `{id}`: no plane square to it")))?;
let mut bodies = kernel::extrude(&plane, &regions, 0.0, a.dist(*b))?;
let body = match (bodies.pop(), bodies.is_empty()) {
(Some(body), true) => body,
_ => return Err(DocError::Invalid(format!("the member on line `{id}` is not one solid"))),
let groups = frame::member_groups(&f.kind);
let lines = group_lines(mapped.as_ref(), &groups)?;
let (section, description) = profile_regions(vals, st, profile)?;
let mut made = Vec::new();
let mut ids = Vec::new();
let mut bases = Vec::new();
for (group, segments) in groups.iter().zip(lines) {
let regions: Cow<[Region2]> = if group.mirror { Cow::Owned(section.iter().map(frame::mirrored).collect()) } else { Cow::Borrowed(&section) };
let at = frame::anchor_point(&regions, group.anchor);
let turn = match &group.angle {
Some(e) => val(vals, e, Kind::Angle)?,
None => 0.0,
};
made.push(crate::lineage::numbered_tool(body));
let base = group.body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).unwrap_or(&description);
for (id, a, b) in segments {
let (x, y) = frame::member_axes(b - a, turn).ok_or_else(|| DocError::Invalid(format!("line `{id}` has no length")))?;
let plane = Plane::new(a - x * at.x - y * at.y, x, y).ok_or_else(|| DocError::Invalid(format!("line `{id}`: no plane square to it")))?;
let mut bodies = kernel::extrude(&plane, &regions, 0.0, a.dist(b))?;
let body = match (bodies.pop(), bodies.is_empty()) {
(Some(body), true) => body,
_ => return Err(DocError::Invalid(format!("the member on line `{id}` is not one solid"))),
};
made.push(crate::lineage::numbered_tool(body));
ids.push(id);
bases.push(base.to_string());
}
}
if !f.body_names.is_empty() {
// A copy (pasted, or in a copied component) names its members by position, as any
Expand All @@ -60,9 +66,7 @@ pub(super) fn evaluate(doc: &Document, vals: &BTreeMap<String, Value>, f: &Featu
}
return Ok(());
}
let base = body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).map_or(description, str::to_string);
let ids: Vec<String> = segments.into_iter().map(|(id, _, _)| id).collect();
for (name, t) in member_names(st, &ids, names, &base).into_iter().zip(made) {
for (name, t) in group_member_names(st, &ids, &bases, names).into_iter().zip(made) {
st.bodies.push(ModelBody::traced_new(name, t, f.id));
}
Ok(())
Expand All @@ -72,6 +76,12 @@ pub(super) fn evaluate(doc: &Document, vals: &BTreeMap<String, Value>, f: &Featu
/// other body has it, else the first free one of `base`, `base (2)`, `base (3)`… that no line has
/// pinned. A member therefore keeps its name when other lines are added, deleted or reordered.
pub fn member_names(st: &ModelState, lines: &[String], pinned: &BTreeMap<String, String>, base: &str) -> Vec<String> {
group_member_names(st, lines, &vec![base.to_string(); lines.len()], pinned)
}

/// [`member_names`] with a base of its own for each line (its group's), the numbers counting on
/// per base across the groups.
pub fn group_member_names(st: &ModelState, lines: &[String], bases: &[String], pinned: &BTreeMap<String, String>) -> Vec<String> {
let reserved: HashSet<&str> = pinned.values().map(String::as_str).collect();
let mut used: HashSet<String> = HashSet::new();
let mut out: Vec<Option<String>> = lines
Expand All @@ -81,32 +91,59 @@ pub fn member_names(st: &ModelState, lines: &[String], pinned: &BTreeMap<String,
used.insert(n.to_string()).then(|| n.to_string())
})
.collect();
let base = if base.trim().is_empty() { "Member" } else { base.trim() };
// Each candidate is refused at most once per body, used or reserved name: past that many,
// a free one has been found for every member.
let limit = st.bodies.len() + reserved.len() + lines.len() + 2;
let mut next = 1usize;
for slot in out.iter_mut().filter(|n| n.is_none()) {
while next <= limit {
let candidate = if next == 1 { base.to_string() } else { format!("{base} ({next})") };
next += 1;
let mut next: HashMap<&str, usize> = HashMap::new();
for (slot, base) in out.iter_mut().zip(bases.iter().map(|b| if b.trim().is_empty() { "Member" } else { b.trim() })) {
if slot.is_some() {
continue;
}
let next = next.entry(base).or_insert(1);
while *next <= limit {
let candidate = if *next == 1 { base.to_string() } else { format!("{base} ({next})") };
*next += 1;
if st.body(&candidate).is_none() && !used.contains(&candidate) && !reserved.contains(candidate.as_str()) {
used.insert(candidate.clone());
*slot = Some(candidate);
break;
}
}
}
out.into_iter().map(|n| n.unwrap_or_else(|| base.to_string())).collect()
let base = |k: usize| bases.get(k).map(|b| b.trim()).filter(|b| !b.is_empty()).unwrap_or("Member").to_string();
out.into_iter().enumerate().map(|(k, n)| n.unwrap_or_else(|| base(k))).collect()
}

/// The ids of a `FrameMember` feature's lines in `st`, in the order its members are made.
pub fn member_line_ids(st: &ModelState, kind: &FeatureKind) -> Result<Vec<String>> {
let FeatureKind::FrameMember { path_sketch, lines, .. } = kind else {
let FeatureKind::FrameMember { path_sketch, .. } = kind else {
return Err(DocError::Invalid("not a frame member feature".into()));
};
let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch}")))?;
Ok(member_lines(ps, lines)?.into_iter().map(|(id, _, _)| id).collect())
Ok(group_lines(ps, &frame::member_groups(kind))?.into_iter().flatten().map(|(id, _, _)| id).collect())
}

/// Each group's member lines ([`member_lines`]). A feature's single group may leave its lines out
/// (every line); of several, each lists its own, no line in two of them.
fn group_lines(ss: &SolvedSketch, groups: &[MemberGroup]) -> Result<Vec<Vec<(String, Vec3, Vec3)>>> {
if let [only] = groups {
return Ok(vec![member_lines(ss, &only.lines)?]);
}
if groups.iter().map(|g| g.lines.len()).sum::<usize>() > MAX_MEMBERS {
return Err(DocError::Invalid(format!("at most {MAX_MEMBERS} members in one feature")));
}
let mut seen = HashSet::new();
let mut out = Vec::with_capacity(groups.len());
for (k, g) in groups.iter().enumerate() {
if g.lines.is_empty() {
return Err(DocError::Invalid(format!("group {} has no lines", k + 1)));
}
if let Some(twice) = g.lines.iter().find(|l| !seen.insert(l.as_str())) {
return Err(DocError::Invalid(format!("line `{twice}` is listed twice")));
}
out.push(member_lines(ss, &g.lines)?);
}
Ok(out)
}

/// The member lines of the frame sketch, each as (curve id, start, end) in its frame: the lines
Expand Down
6 changes: 6 additions & 0 deletions crates/doc/src/format/pending/frame-member-groups.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
//! A `frame_member` feature can hold `groups` (#4003): two or more groups of its frame sketch's
//! lines, each with its own `lines`, `anchor`, `angle`, `mirror` and `body_name`, all made of the
//! feature's one profile. Then the feature's own `lines`, `anchor`, `angle`, `mirror` and
//! `body_name` stay unset. Older designs need no transformation: without `groups` those fields
//! are the feature's one group, as before. The last release refuses a design saved with this
//! (the newer format number) rather than dropping all but one group's settings.
38 changes: 37 additions & 1 deletion crates/doc/src/frame.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ impl crate::walk::Walk for ProfileSpec {
}
}

pub use crate::eval::frame_member::{member_line_ids, member_names};
pub use crate::eval::frame_member::{group_member_names, member_line_ids, member_names};

/// Where a frame member's cross-section comes from.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
Expand All @@ -279,6 +279,42 @@ pub enum MemberProfile {
},
}

/// One group of a frame member feature: lines whose members share a placement on the profile
/// (#4003). Per-group finishing, such as how the group's corners are treated, belongs here too.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
pub struct MemberGroup {
/// The lines, by curve id; none (only in a feature's single group): every straight line drawn
/// in the frame sketch.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub lines: Vec<String>,
/// The profile point that sits on each line.
#[serde(default, skip_serializing_if = "Anchor::is_origin")]
pub anchor: Anchor,
/// How far the profile turns about each line (see [`member_axes`]).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(angle = "Rotation")]
pub angle: Option<Expr>,
/// The profile mirrored across its y axis (before it turns).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub mirror: bool,
/// What the group's members are named after when they have no name of their own; none: the
/// profile's description or the profile sketch's name.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub body_name: Option<String>,
}

/// The groups of a frame member feature, in the order their members are made: its `groups`, or,
/// without them, the one group its own `lines`, `anchor`, `angle`, `mirror` and `body_name` make.
pub fn member_groups(kind: &crate::FeatureKind) -> Vec<MemberGroup> {
match kind {
crate::FeatureKind::FrameMember { groups, .. } if !groups.is_empty() => groups.clone(),
crate::FeatureKind::FrameMember { lines, anchor, angle, mirror, body_name, .. } => {
vec![MemberGroup { lines: lines.clone(), anchor: *anchor, angle: angle.clone(), mirror: *mirror, body_name: body_name.clone() }]
}
_ => Vec::new(),
}
}

impl Anchor {
pub fn is_origin(&self) -> bool {
*self == Anchor::Origin
Expand Down
30 changes: 27 additions & 3 deletions crates/engine/src/cmd/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1520,6 +1520,26 @@ fn input_keys(kind: &FeatureKind) -> Vec<(String, solidcraft_doc::expr::Kind)> {
keys
}

/// The name a frame member feature gives the member on `line` (its group's `body_name`); none:
/// named after the profile.
fn member_group_name(kind: &FeatureKind, line: &str) -> Option<String> {
let groups = solidcraft_doc::frame::member_groups(kind);
let group = groups.iter().find(|g| g.lines.is_empty() || g.lines.iter().any(|l| l == line))?;
group.body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).map(str::to_string)
}

/// The name `frame.member` parameters give the member on `line`, as [`member_group_name`].
fn given_group_name(p: &serde_json::Map<String, Value>, line: &str) -> Option<String> {
let named = match p.get("groups").and_then(Value::as_array) {
Some(groups) => groups
.iter()
.find(|g| g.get("lines").and_then(Value::as_array).is_some_and(|ls| ls.iter().any(|l| l.as_str() == Some(line))))?
.get("body_name"),
None => p.get("body_name"),
};
named.and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty()).map(str::to_string)
}

fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "timeline.redefine";
let id = feature_id(s, p.get("feature"), cmd)?;
Expand Down Expand Up @@ -1574,12 +1594,16 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
parameters.entry("convention").or_insert_with(|| json!(convention));
}
// Members keep their names through an edit, unless it gives them another name.
if let FeatureKind::FrameMember { names, body_name, .. } = &old.kind
// With groups, a member keeps its name while its group's name stays the same.
if let FeatureKind::FrameMember { names, .. } = &old.kind
&& cid == "frame.member"
&& let Some(parameters) = params.as_object_mut()
&& parameters.get("body_name").and_then(Value::as_str) == body_name.as_deref()
{
parameters.entry("names").or_insert_with(|| json!(names));
let kept: BTreeMap<&String, &String> =
names.iter().filter(|(line, _)| member_group_name(&old.kind, line) == given_group_name(parameters, line)).collect();
if !kept.is_empty() {
parameters.entry("names").or_insert_with(|| json!(kept));
}
}
if !old.participants.is_empty()
&& let Some(parameters) = params.as_object_mut()
Expand Down
Loading