Skip to main content

kcl_lib/std/
fillet.rs

1//! Standard library fillets.
2
3use anyhow::Result;
4use indexmap::IndexMap;
5use kcmc::ModelingCmd;
6use kcmc::each_cmd as mcmd;
7use kcmc::length_unit::LengthUnit;
8use kcmc::shared::CutTypeV2;
9use kcmc::shared::EdgeCutVersion;
10use kittycad_modeling_cmds as kcmc;
11use serde::Deserialize;
12use serde::Serialize;
13
14use super::DEFAULT_TOLERANCE_MM;
15use super::args::TyF64;
16use crate::SourceRange;
17use crate::errors::KclError;
18use crate::errors::KclErrorDetails;
19use crate::execution::EdgeCut;
20use crate::execution::ExecState;
21use crate::execution::ExtrudeSurface;
22use crate::execution::FilletSurface;
23use crate::execution::GeoMeta;
24use crate::execution::KclValue;
25use crate::execution::ModelingCmdMeta;
26use crate::execution::Solid;
27use crate::execution::TagIdentifier;
28use crate::execution::types::RuntimeType;
29use crate::parsing::ast::types::TagNode;
30use crate::std::Args;
31use crate::std::csg::CsgAlgorithm;
32
33/// A tag or a uuid of an edge.
34#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq, Hash)]
35#[serde(untagged)]
36pub enum EdgeReference {
37    /// A uuid of an edge.
38    Uuid(uuid::Uuid),
39    /// A tag of an edge.
40    Tag(Box<TagIdentifier>),
41}
42
43impl EdgeReference {
44    pub fn get_engine_id(&self, exec_state: &mut ExecState, args: &Args) -> Result<uuid::Uuid, KclError> {
45        match self {
46            EdgeReference::Uuid(uuid) => Ok(*uuid),
47            EdgeReference::Tag(tag) => Ok(args.get_tag_engine_info(exec_state, tag)?.id),
48        }
49    }
50
51    /// Get all engine IDs for this edge reference.
52    /// For region-mapped tags, returns multiple IDs (one per region segment).
53    pub fn get_all_engine_ids(&self, exec_state: &mut ExecState, args: &Args) -> Result<Vec<uuid::Uuid>, KclError> {
54        match self {
55            EdgeReference::Uuid(uuid) => Ok(vec![*uuid]),
56            EdgeReference::Tag(tag) => {
57                let infos = tag.get_all_cur_info();
58                if infos.is_empty() {
59                    // Fallback to single ID lookup (checks the stack).
60                    Ok(vec![args.get_tag_engine_info(exec_state, tag)?.id])
61                } else {
62                    Ok(infos.iter().map(|i| i.id).collect())
63                }
64            }
65        }
66    }
67}
68
69pub(super) fn validate_unique<T: Eq + std::hash::Hash>(tags: &[(T, SourceRange)]) -> Result<(), KclError> {
70    // Check if tags contains any duplicate values.
71    let mut tag_counts: IndexMap<&T, Vec<SourceRange>> = Default::default();
72    for tag in tags {
73        tag_counts.entry(&tag.0).or_insert(Vec::new()).push(tag.1);
74    }
75    let mut duplicate_tags_source = Vec::new();
76    for (_tag, count) in tag_counts {
77        if count.len() > 1 {
78            duplicate_tags_source.extend(count)
79        }
80    }
81    if !duplicate_tags_source.is_empty() {
82        return Err(KclError::new_type(KclErrorDetails::new(
83            "The same edge ID is being referenced multiple times, which is not allowed. Please select a different edge"
84                .to_string(),
85            duplicate_tags_source,
86        )));
87    }
88    Ok(())
89}
90
91/// Create fillets on tagged paths.
92pub async fn fillet(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
93    let solid = args.get_unlabeled_kw_arg("solid", &RuntimeType::solid(), exec_state)?;
94    let radius: TyF64 = args.get_kw_arg("radius", &RuntimeType::length(), exec_state)?;
95    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
96    let tags = args.kw_arg_edge_array_and_source("tags")?;
97    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
98    let legacy_csg: Option<bool> = args.get_kw_arg_opt("legacyMethod", &RuntimeType::bool(), exec_state)?;
99    let csg_algorithm = CsgAlgorithm::legacy(legacy_csg.unwrap_or_default());
100    let edge_cut_number: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
101    let edge_cut_version: EdgeCutVersion = edge_cut_number
102        .map(|num| {
103            num.try_into().map_err(|()| {
104                KclError::new_semantic(KclErrorDetails::new(
105                    format!("{} is not a version of the Zoo edge cut algorithm", num),
106                    vec![args.source_range],
107                ))
108            })
109        })
110        .transpose()?
111        .unwrap_or_default();
112
113    // Run the function.
114    validate_unique(&tags)?;
115    let tags: Vec<EdgeReference> = tags.into_iter().map(|item| item.0).collect();
116    let value = inner_fillet(
117        solid,
118        radius,
119        tags,
120        tolerance,
121        csg_algorithm,
122        tag,
123        edge_cut_version,
124        exec_state,
125        args,
126    )
127    .await?;
128    Ok(KclValue::Solid { value })
129}
130
131#[allow(clippy::too_many_arguments)]
132async fn inner_fillet(
133    solid: Box<Solid>,
134    radius: TyF64,
135    tags: Vec<EdgeReference>,
136    tolerance: Option<TyF64>,
137    csg_algorithm: CsgAlgorithm,
138    tag: Option<TagNode>,
139    edge_cut_version: EdgeCutVersion,
140    exec_state: &mut ExecState,
141    args: Args,
142) -> Result<Box<Solid>, KclError> {
143    // If you try and tag multiple edges with a tagged fillet, we want to return an
144    // error to the user that they can only tag one edge at a time.
145    if tag.is_some() && tags.len() > 1 {
146        return Err(KclError::new_type(KclErrorDetails {
147            message: "You can only tag one edge at a time with a tagged fillet. Either delete the tag for the fillet fn if you don't need it OR separate into individual fillet functions for each tag.".to_string(),
148            source_ranges: vec![args.source_range],
149            backtrace: Default::default(),
150        }));
151    }
152    if tags.is_empty() {
153        return Err(KclError::new_semantic(KclErrorDetails {
154            source_ranges: vec![args.source_range],
155            message: "You must fillet at least one tag".to_owned(),
156            backtrace: Default::default(),
157        }));
158    }
159
160    let mut solid = solid.clone();
161    let edge_ids = tags
162        .into_iter()
163        .map(|edge_tag| edge_tag.get_all_engine_ids(exec_state, &args))
164        .try_fold(Vec::new(), |mut acc, item| match item {
165            Ok(ids) => {
166                acc.extend(ids);
167                Ok(acc)
168            }
169            Err(e) => Err(e),
170        })?;
171
172    let id = exec_state.next_uuid();
173    let mut extra_face_ids = Vec::new();
174    let num_extra_ids = edge_ids.len() - 1;
175    for _ in 0..num_extra_ids {
176        extra_face_ids.push(exec_state.next_uuid());
177    }
178    exec_state
179        .batch_end_cmd(
180            ModelingCmdMeta::from_args_id(exec_state, &args, id),
181            ModelingCmd::from(
182                mcmd::Solid3dCutEdges::builder()
183                    .use_legacy(csg_algorithm.is_legacy())
184                    .edge_ids(edge_ids.clone())
185                    .extra_face_ids(extra_face_ids)
186                    .strategy(Default::default())
187                    .object_id(solid.id)
188                    .version(edge_cut_version)
189                    .tolerance(LengthUnit(
190                        tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
191                    ))
192                    .cut_type(CutTypeV2::Fillet {
193                        radius: LengthUnit(radius.to_mm()),
194                        second_length: None,
195                    })
196                    .build(),
197            ),
198        )
199        .await?;
200
201    let new_edge_cuts = edge_ids.into_iter().map(|edge_id| EdgeCut::Fillet {
202        id,
203        edge_id,
204        radius: radius.clone(),
205        tag: Box::new(tag.clone()),
206    });
207    solid.edge_cuts.extend(new_edge_cuts);
208
209    if let Some(ref tag) = tag {
210        solid.value.push(ExtrudeSurface::Fillet(FilletSurface {
211            face_id: id,
212            tag: Some(tag.clone()),
213            geo_meta: GeoMeta {
214                id,
215                metadata: args.source_range.into(),
216            },
217        }));
218    }
219
220    Ok(solid)
221}
222
223#[cfg(test)]
224mod tests {
225    use super::*;
226
227    #[test]
228    fn test_validate_unique() {
229        let dup_a = SourceRange::from([1, 3, 0]);
230        let dup_b = SourceRange::from([10, 30, 0]);
231        // Two entries are duplicates (abc) with different source ranges.
232        let tags = vec![("abc", dup_a), ("abc", dup_b), ("def", SourceRange::from([2, 4, 0]))];
233        let actual = validate_unique(&tags);
234        // Both the duplicates should show up as errors, with both of the
235        // source ranges they correspond to.
236        // But the unique source range 'def' should not.
237        let expected = vec![dup_a, dup_b];
238        assert_eq!(actual.err().unwrap().source_ranges(), expected);
239    }
240}