Skip to main content

kcl_lib/std/
sweep.rs

1//! Standard library sweep.
2
3use anyhow::Result;
4use kcmc::ModelingCmd;
5use kcmc::each_cmd as mcmd;
6use kcmc::length_unit::LengthUnit;
7use kcmc::shared::BodyType;
8use kittycad_modeling_cmds::id::ModelingCmdId;
9use kittycad_modeling_cmds::shared::RelativeTo;
10use kittycad_modeling_cmds::websocket::ModelingCmdReq;
11use kittycad_modeling_cmds::{self as kcmc};
12use serde::Serialize;
13
14use super::DEFAULT_TOLERANCE_MM;
15use super::args::TyF64;
16use crate::KclVersion;
17use crate::errors::KclError;
18use crate::errors::KclErrorDetails;
19use crate::execution::ExecState;
20use crate::execution::Extrudable;
21use crate::execution::Helix;
22use crate::execution::KclValue;
23use crate::execution::ModelingCmdMeta;
24use crate::execution::ProfileClosed;
25use crate::execution::Segment;
26use crate::execution::Sketch;
27use crate::execution::SketchSurface;
28use crate::execution::Solid;
29use crate::execution::types::ArrayLen;
30use crate::execution::types::RuntimeType;
31use crate::parsing::ast::types::TagNode;
32use crate::std::Args;
33use crate::std::extrude::BeingExtruded;
34use crate::std::extrude::build_segment_surface_sketch;
35use crate::std::extrude::coerce_extrude_targets;
36use crate::std::extrude::do_post_extrude;
37
38/// A path to sweep along.
39#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
40#[ts(export)]
41#[serde(untagged)]
42#[allow(clippy::large_enum_variant)]
43pub enum SweepPath {
44    Sketch(Sketch),
45    Helix(Box<Helix>),
46    Segments(Vec<Segment>),
47}
48
49/// The outer (typical) sweep path gets converted to this, losing some of its variants in the conversion.
50#[allow(clippy::large_enum_variant)]
51enum InnerSweepPath {
52    Sketch(Sketch),
53    Helix(Box<Helix>),
54}
55
56/// Create a 3D surface or solid by sweeping a sketch along a path.
57pub async fn sweep(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
58    let sketch_values = args.get_unlabeled_kw_arg(
59        "sketches",
60        &RuntimeType::Array(
61            Box::new(RuntimeType::Union(vec![
62                RuntimeType::sketch(),
63                RuntimeType::segment(),
64                RuntimeType::face(),
65                RuntimeType::tagged_face(),
66            ])),
67            ArrayLen::Minimum(1),
68        ),
69        exec_state,
70    )?;
71    let path: SweepPath = args.get_kw_arg(
72        "path",
73        &RuntimeType::Union(vec![
74            RuntimeType::sketch(),
75            RuntimeType::helix(),
76            RuntimeType::Array(Box::new(RuntimeType::segment()), ArrayLen::Minimum(1)),
77        ]),
78        exec_state,
79    )?;
80    let sectional = args.get_kw_arg_opt("sectional", &RuntimeType::bool(), exec_state)?;
81    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
82    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
83    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
84    let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
85    // KCL 3.0 removes the version parameter (`removed_in` in sketch.kcl),
86    // so from 3.0 on this is always None, and the newest algorithm is used.
87    let version: Option<u32> = args.get_kw_arg_opt("version", &RuntimeType::count(), exec_state)?;
88    // Replaced by 2 args below.
89    let relative_to: Option<String> = args.get_kw_arg_opt("relativeTo", &RuntimeType::string(), exec_state)?;
90    // Replaces `relative_to`.
91    let translate_profile_to_path: Option<bool> =
92        args.get_kw_arg_opt("translateProfileToPath", &RuntimeType::bool(), exec_state)?;
93    let orient_profile_perpendicular: Option<bool> =
94        args.get_kw_arg_opt("orientProfilePerpendicular", &RuntimeType::bool(), exec_state)?;
95
96    let path = match path {
97        SweepPath::Segments(segments) => InnerSweepPath::Sketch(
98            build_segment_surface_sketch(segments, exec_state, &args.ctx, args.source_range).await?,
99        ),
100        SweepPath::Sketch(sketch) => InnerSweepPath::Sketch(sketch),
101        SweepPath::Helix(helix) => InnerSweepPath::Helix(helix),
102    };
103
104    let sketches = coerce_extrude_targets(
105        sketch_values,
106        body_type.unwrap_or_default(),
107        tag_start.as_ref(),
108        tag_end.as_ref(),
109        exec_state,
110        &args.ctx,
111        args.source_range,
112    )
113    .await?;
114
115    let value = inner_sweep(
116        sketches,
117        path,
118        sectional,
119        tolerance,
120        relative_to,
121        translate_profile_to_path,
122        orient_profile_perpendicular,
123        tag_start,
124        tag_end,
125        body_type,
126        version,
127        exec_state,
128        args,
129    )
130    .await?;
131    Ok(value.into())
132}
133
134enum ProfileTransform {
135    RelativeTo(RelativeTo),
136    SeparateFlags {
137        translate_profile_to_path: bool,
138        orient_profile_perpendicular: bool,
139    },
140}
141
142impl ProfileTransform {
143    fn relative_to(&self) -> Option<RelativeTo> {
144        match self {
145            ProfileTransform::RelativeTo(relative_to) => Some(*relative_to),
146            ProfileTransform::SeparateFlags { .. } => None,
147        }
148    }
149
150    fn translate_profile_to_path(&self) -> Option<bool> {
151        match self {
152            ProfileTransform::RelativeTo(..) => None,
153            ProfileTransform::SeparateFlags {
154                translate_profile_to_path,
155                ..
156            } => Some(*translate_profile_to_path),
157        }
158    }
159    fn orient_profile_perpendicular(&self) -> Option<bool> {
160        match self {
161            ProfileTransform::RelativeTo(..) => None,
162            ProfileTransform::SeparateFlags {
163                orient_profile_perpendicular,
164                ..
165            } => Some(*orient_profile_perpendicular),
166        }
167    }
168}
169
170/// The sweep algorithm version to send when the user does not set `version`.
171/// KCL 3.0 removes the version parameter (`removed_in` in sketch.kcl), so
172/// from 3.0 on this is always what is sent.
173fn default_sweep_version(kcl_version: KclVersion) -> Option<u8> {
174    if kcl_version <= KclVersion::V2 {
175        // Unspecified, so the engine chooses. It currently chooses version 1.
176        None
177    } else {
178        // KCL 3.0 and later always use the newest algorithm.
179        Some(2)
180    }
181}
182
183/// The value of `orientProfilePerpendicular` when the user does not set it.
184fn default_orient_profile_perpendicular(kcl_version: KclVersion, translate_profile_to_path: bool) -> bool {
185    if kcl_version <= KclVersion::V2 {
186        false
187    } else {
188        // From a mechanical engineer on what is intuitive:
189        // - `translateProfileToPath` should default to false.
190        // - `orientProfilePerpendicular` should default to false,
191        //   unless `translateProfileToPath` is true, in which case both should be true.
192        translate_profile_to_path
193    }
194}
195
196#[allow(clippy::too_many_arguments)]
197async fn inner_sweep(
198    sketches: Vec<Extrudable>,
199    path: InnerSweepPath,
200    sectional: Option<bool>,
201    tolerance: Option<TyF64>,
202    relative_to: Option<String>,
203    translate_profile_to_path: Option<bool>,
204    orient_profile_perpendicular: Option<bool>,
205    tag_start: Option<TagNode>,
206    tag_end: Option<TagNode>,
207    body_type: Option<BodyType>,
208    version: Option<u32>,
209    exec_state: &mut ExecState,
210    args: Args,
211) -> Result<Vec<Solid>, KclError> {
212    let body_type = body_type.unwrap_or_default();
213    if matches!(body_type, BodyType::Solid) && sketches.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No)) {
214        return Err(KclError::new_semantic(KclErrorDetails::new(
215            "Cannot solid sweep an open profile. Either close the profile, or use a surface sweep.".to_owned(),
216            vec![args.source_range],
217        )));
218    }
219
220    let kcl_version = exec_state.kcl_version();
221    let version = version
222        .map(|v| {
223            u8::try_from(v).map_err(|_e| {
224                KclError::new_argument(KclErrorDetails::new(
225                    format!("Invalid version {}", v),
226                    vec![args.source_range],
227                ))
228            })
229        })
230        .transpose()?
231        .or_else(|| default_sweep_version(kcl_version));
232
233    let trajectory = ModelingCmdId::from(match path {
234        InnerSweepPath::Sketch(sketch) => sketch.id,
235        InnerSweepPath::Helix(helix) => helix.value,
236    });
237
238    let profile_transform = match (relative_to, translate_profile_to_path, orient_profile_perpendicular) {
239        // Before KCL 3.0, when the user doesn't give any flags at all, the
240        // legacy `relativeTo` behavior is implied by the algorithm version.
241        (None, None, None) if kcl_version <= KclVersion::V2 => ProfileTransform::RelativeTo(match version {
242            // We default to algorithm v1 if no choice was made.
243            None | Some(1) => RelativeTo::TrajectoryCurve,
244            // 0 means "let engine choose". Engine currently chooses version 1.
245            Some(0) => RelativeTo::TrajectoryCurve,
246            // Algorithm version 2 defaults to SketchPlane.
247            Some(2) => RelativeTo::SketchPlane,
248            // Error on unknown algorithm.
249            Some(other) => {
250                return Err(KclError::new_argument(KclErrorDetails::new(
251                    format!("Invalid version {}", other),
252                    vec![args.source_range],
253                )));
254            }
255        }),
256
257        // If the "new" profile transformation args are set. KCL 3.0 removed
258        // `relativeTo` (see `removed_in` in sketch.kcl), so from 3.0 on,
259        // this is also the case when no flags are set at all.
260        (None, translate, orient) => {
261            let translate_profile_to_path = translate.unwrap_or_default();
262            ProfileTransform::SeparateFlags {
263                translate_profile_to_path,
264                orient_profile_perpendicular: orient
265                    .unwrap_or_else(|| default_orient_profile_perpendicular(kcl_version, translate_profile_to_path)),
266            }
267        }
268
269        // RelativeTo was set, but none of its replacements were.
270        (Some(relative_to), None, None) => ProfileTransform::RelativeTo(match relative_to.as_str() {
271            "sketchPlane" => RelativeTo::SketchPlane,
272            "trajectoryCurve" => RelativeTo::TrajectoryCurve,
273            _ => {
274                return Err(KclError::new_syntax(crate::errors::KclErrorDetails::new(
275                    "If you provide relativeTo, it must either be 'sketchPlane' or 'trajectoryCurve'".to_owned(),
276                    vec![args.source_range],
277                )));
278            }
279        }),
280
281        // RelativeTo was set, but also one of its replacements was.
282        // This is an error.
283        (Some(_relative_to), _, _) => {
284            return Err(KclError::new_argument(crate::errors::KclErrorDetails::new(
285                    "If you provide 'relativeTo', you cannot provide 'translateProfileToPath' or 'orientProfilePerpendicular'. Those arguments replace 'relativeTo', please use them instead.".to_owned(),
286                    vec![args.source_range],
287                )));
288        }
289    };
290
291    let mut solids = Vec::new();
292    for sketch in &sketches {
293        let sweep_cmd_id = exec_state.next_uuid();
294        let sketch_or_face_id = sketch.id_to_extrude(exec_state, &args, false).await?;
295        let cmd = ModelingCmd::from(
296            mcmd::Sweep::builder()
297                .target(sketch_or_face_id.into())
298                .trajectory(trajectory)
299                .sectional(sectional.unwrap_or(false))
300                .tolerance(LengthUnit(
301                    tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM),
302                ))
303                .maybe_relative_to(profile_transform.relative_to())
304                .maybe_orient_profile_perpendicular(profile_transform.orient_profile_perpendicular())
305                .maybe_translate_profile_to_path(profile_transform.translate_profile_to_path())
306                .body_type(body_type)
307                .maybe_version(version)
308                .build(),
309        );
310
311        let being_extruded = match sketch {
312            Extrudable::Sketch(..) => BeingExtruded::Sketch,
313            Extrudable::FaceTag(face_tag) => {
314                let face_id = sketch_or_face_id;
315                let solid_id = match face_tag.geometry() {
316                    Some(crate::execution::Geometry::Solid(solid)) => solid.id,
317                    Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
318                        SketchSurface::Face(face) => face.parent_solid.solid_id,
319                        SketchSurface::Plane(_) => sketch.id,
320                    },
321                    None => face_id,
322                };
323                BeingExtruded::Face { face_id, solid_id }
324            }
325            Extrudable::Face(face) => BeingExtruded::Face {
326                face_id: face.id,
327                solid_id: face.parent_solid.solid_id,
328            },
329            Extrudable::EdgeTag(_) => BeingExtruded::Edge,
330            Extrudable::Edge(_) => BeingExtruded::Edge,
331            Extrudable::EdgeSpecifier(_) => BeingExtruded::Edge,
332        };
333
334        if let Some(post_extr_sketch) = sketch.as_sketch() {
335            let cmds = post_extr_sketch.build_sketch_mode_cmds(
336                exec_state,
337                ModelingCmdReq {
338                    cmd_id: sweep_cmd_id.into(),
339                    cmd,
340                },
341            );
342            exec_state
343                .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, sweep_cmd_id), &cmds)
344                .await?;
345            solids.push(
346                do_post_extrude(
347                    &post_extr_sketch,
348                    sweep_cmd_id.into(),
349                    sectional.unwrap_or(false),
350                    &super::extrude::NamedCapTags {
351                        start: tag_start.as_ref(),
352                        end: tag_end.as_ref(),
353                    },
354                    kittycad_modeling_cmds::shared::ExtrudeMethod::New,
355                    exec_state,
356                    &args,
357                    None,
358                    None,
359                    body_type,
360                    being_extruded,
361                )
362                .await?,
363            );
364        } else {
365            return Err(KclError::new_type(KclErrorDetails::new(
366                "Expected a sketch for sweeping".to_owned(),
367                vec![args.source_range],
368            )));
369        }
370    }
371
372    // Hide the artifact from the sketch or helix.
373    exec_state
374        .batch_modeling_cmd(
375            ModelingCmdMeta::from_args(exec_state, &args),
376            ModelingCmd::from(
377                mcmd::ObjectVisible::builder()
378                    .object_id(trajectory.into())
379                    .hidden(true)
380                    .build(),
381            ),
382        )
383        .await?;
384
385    Ok(solids)
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391    use crate::execution::ExecTestResults;
392    use crate::execution::parse_execute;
393
394    /// What each KCL version sends to the engine when the user leaves out
395    /// `translateProfileToPath`, `orientProfilePerpendicular`, and `version`.
396    #[tokio::test(flavor = "multi_thread")]
397    async fn sweep_defaults_depend_on_kcl_version() {
398        // Before KCL 3.0, the legacy `relative_to` field is sent instead of
399        // the two flags, and the algorithm version is left to the engine.
400        let cmd = emitted_sweep("2.0", "").await;
401        assert_eq!(cmd.relative_to, Some(RelativeTo::TrajectoryCurve));
402        assert_eq!(cmd.translate_profile_to_path, None);
403        assert_eq!(cmd.orient_profile_perpendicular, None);
404        assert_eq!(cmd.version, None);
405
406        // From KCL 3.0, the two flags are always sent, both false by default,
407        // and the algorithm is always version 2.
408        let cmd = emitted_sweep("\"3.0-preview\"", "").await;
409        assert_eq!(cmd.relative_to, None);
410        assert_eq!(cmd.translate_profile_to_path, Some(false));
411        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
412        assert_eq!(cmd.version, Some(2));
413    }
414
415    /// From KCL 3.0, `orientProfilePerpendicular` defaults to the value of
416    /// `translateProfileToPath`. Before that, the two flags are independent.
417    #[tokio::test(flavor = "multi_thread")]
418    async fn orient_profile_perpendicular_follows_translate_in_kcl_3() {
419        let cmd = emitted_sweep("\"3.0-preview\"", ", translateProfileToPath = true").await;
420        assert_eq!(cmd.translate_profile_to_path, Some(true));
421        assert_eq!(cmd.orient_profile_perpendicular, Some(true));
422
423        let cmd = emitted_sweep("\"3.0-preview\"", ", translateProfileToPath = false").await;
424        assert_eq!(cmd.translate_profile_to_path, Some(false));
425        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
426
427        let cmd = emitted_sweep("2.0", ", translateProfileToPath = true").await;
428        assert_eq!(cmd.translate_profile_to_path, Some(true));
429        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
430    }
431
432    /// An explicit `orientProfilePerpendicular` wins over the default,
433    /// whatever `translateProfileToPath` is.
434    #[tokio::test(flavor = "multi_thread")]
435    async fn explicit_orient_profile_perpendicular_overrides_kcl_default() {
436        let cmd = emitted_sweep(
437            "\"3.0-preview\"",
438            ", translateProfileToPath = true, orientProfilePerpendicular = false",
439        )
440        .await;
441        assert_eq!(cmd.translate_profile_to_path, Some(true));
442        assert_eq!(cmd.orient_profile_perpendicular, Some(false));
443
444        let cmd = emitted_sweep("\"3.0-preview\"", ", orientProfilePerpendicular = true").await;
445        assert_eq!(cmd.translate_profile_to_path, Some(false));
446        assert_eq!(cmd.orient_profile_perpendicular, Some(true));
447    }
448
449    /// If the user chooses a sweep algorithm version, KCL should respect it,
450    /// and not use that KCL version's default sweep algorithm version.
451    #[tokio::test(flavor = "multi_thread")]
452    async fn explicit_sweep_version_overrides_kcl_default() {
453        assert_eq!(emitted_sweep("2.0", ", version = 2").await.version, Some(2));
454        assert_eq!(emitted_sweep("2.0", ", version = 0").await.version, Some(0));
455    }
456
457    /// KCL 3.0 removed `sweep(version = )`. Passing it is reported like any
458    /// other unknown argument, and the newest algorithm is used.
459    #[tokio::test(flavor = "multi_thread")]
460    async fn sweep_version_is_removed_in_kcl_3() {
461        let result = run_sweep("\"3.0-preview\"", ", version = 1").await;
462        assert!(
463            result
464                .issues()
465                .iter()
466                .any(|issue| {
467                    issue.message
468                        == "`version` is not an argument of `sweep`; it was removed in KCL 3.0, but this program uses KCL 3.0-preview"
469                }),
470            "issues: {:#?}",
471            result.issues()
472        );
473        assert_eq!(emitted_sweep_cmd(&result).version, Some(2));
474    }
475
476    /// Sweep a circle along a line under the given KCL version, passing
477    /// `extra_args` to `sweep`, and return the `Sweep` command sent to the
478    /// engine.
479    async fn emitted_sweep(kcl_version: &str, extra_args: &str) -> mcmd::Sweep {
480        emitted_sweep_cmd(&run_sweep(kcl_version, extra_args).await)
481    }
482
483    /// Sweep a circle along a line under the given KCL version, passing
484    /// `extra_args` to `sweep`.
485    async fn run_sweep(kcl_version: &str, extra_args: &str) -> ExecTestResults {
486        let code = format!(
487            r#"@settings(defaultLengthUnit = mm, kclVersion = {kcl_version})
488
489profileSketch = sketch(on = XY) {{
490  c = circle(start = [var 10mm, var 0mm], center = [var 0mm, var 0mm])
491}}
492profile = region(segments = [profileSketch.c])
493
494pathSketch = sketch(on = XZ) {{
495  path = line(start = [var 0mm, var 0mm], end = [var 0mm, var 100mm])
496}}
497
498sweep(profile, path = pathSketch{extra_args})
499"#
500        );
501        parse_execute(&code).await.unwrap()
502    }
503
504    /// The `Sweep` command the run sent to the engine.
505    fn emitted_sweep_cmd(result: &ExecTestResults) -> mcmd::Sweep {
506        result
507            .root_module_artifact_commands()
508            .iter()
509            .find_map(|artifact_command| match &artifact_command.command {
510                ModelingCmd::Sweep(cmd) => Some(cmd.clone()),
511                _ => None,
512            })
513            .expect("sweep should emit a Sweep command")
514    }
515}