Skip to main content

kcl_lib/std/
sketch.rs

1//! Functions related to sketching.
2
3use std::f64;
4
5use anyhow::Result;
6use kcl_error::SourceRange;
7use kcmc::ModelingCmd;
8use kcmc::each_cmd as mcmd;
9use kcmc::length_unit::LengthUnit;
10use kcmc::shared::Angle;
11use kcmc::shared::Point2d as KPoint2d; // Point2d is already defined in this pkg, to impl ts_rs traits.
12use kcmc::shared::Point3d as KPoint3d; // Point3d is already defined in this pkg, to impl ts_rs traits.
13use kcmc::websocket::ModelingCmdReq;
14use kittycad_modeling_cmds as kcmc;
15use kittycad_modeling_cmds::shared::PathSegment;
16use kittycad_modeling_cmds::units::UnitLength;
17use parse_display::Display;
18use parse_display::FromStr;
19use serde::Deserialize;
20use serde::Serialize;
21use uuid::Uuid;
22
23use super::shapes::get_radius;
24use super::shapes::get_radius_labelled;
25use super::utils::untype_array;
26use crate::ExecutorContext;
27use crate::errors::KclError;
28use crate::errors::KclErrorDetails;
29use crate::exec::PlaneKind;
30#[cfg(feature = "artifact-graph")]
31use crate::execution::Artifact;
32#[cfg(feature = "artifact-graph")]
33use crate::execution::ArtifactId;
34use crate::execution::BasePath;
35#[cfg(feature = "artifact-graph")]
36use crate::execution::CodeRef;
37use crate::execution::ExecState;
38use crate::execution::GeoMeta;
39use crate::execution::Geometry;
40use crate::execution::KclValue;
41use crate::execution::ModelingCmdMeta;
42use crate::execution::Path;
43use crate::execution::Plane;
44use crate::execution::PlaneInfo;
45use crate::execution::Point2d;
46use crate::execution::Point3d;
47use crate::execution::ProfileClosed;
48use crate::execution::Sketch;
49use crate::execution::SketchSurface;
50use crate::execution::Solid;
51#[cfg(feature = "artifact-graph")]
52use crate::execution::StartSketchOnFace;
53#[cfg(feature = "artifact-graph")]
54use crate::execution::StartSketchOnPlane;
55use crate::execution::TagIdentifier;
56use crate::execution::annotations;
57use crate::execution::types::ArrayLen;
58use crate::execution::types::NumericType;
59use crate::execution::types::PrimitiveType;
60use crate::execution::types::RuntimeType;
61use crate::parsing::ast::types::TagNode;
62use crate::std::EQUAL_POINTS_DIST_EPSILON;
63use crate::std::args::Args;
64use crate::std::args::TyF64;
65use crate::std::axis_or_reference::Axis2dOrEdgeReference;
66use crate::std::faces::FaceSpecifier;
67use crate::std::faces::make_face;
68use crate::std::planes::inner_plane_of;
69use crate::std::utils::TangentialArcInfoInput;
70use crate::std::utils::arc_center_and_end;
71use crate::std::utils::get_tangential_arc_to_info;
72use crate::std::utils::get_x_component;
73use crate::std::utils::get_y_component;
74use crate::std::utils::intersection_with_parallel_line;
75use crate::std::utils::point_to_len_unit;
76use crate::std::utils::point_to_mm;
77use crate::std::utils::untyped_point_to_mm;
78
79/// A tag for a face.
80#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS)]
81#[ts(export)]
82#[serde(rename_all = "snake_case", untagged)]
83pub enum FaceTag {
84    StartOrEnd(StartOrEnd),
85    /// A tag for the face.
86    Tag(Box<TagIdentifier>),
87}
88
89impl std::fmt::Display for FaceTag {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        match self {
92            FaceTag::Tag(t) => write!(f, "{t}"),
93            FaceTag::StartOrEnd(StartOrEnd::Start) => write!(f, "start"),
94            FaceTag::StartOrEnd(StartOrEnd::End) => write!(f, "end"),
95        }
96    }
97}
98
99impl FaceTag {
100    /// Get the face id from the tag.
101    pub async fn get_face_id(
102        &self,
103        solid: &Solid,
104        exec_state: &mut ExecState,
105        args: &Args,
106        must_be_planar: bool,
107    ) -> Result<uuid::Uuid, KclError> {
108        match self {
109            FaceTag::Tag(t) => args.get_adjacent_face_to_tag(exec_state, t, must_be_planar).await,
110            FaceTag::StartOrEnd(StartOrEnd::Start) => solid.start_cap_id.ok_or_else(|| {
111                KclError::new_type(KclErrorDetails::new(
112                    "Expected a start face".to_string(),
113                    vec![args.source_range],
114                ))
115            }),
116            FaceTag::StartOrEnd(StartOrEnd::End) => solid.end_cap_id.ok_or_else(|| {
117                KclError::new_type(KclErrorDetails::new(
118                    "Expected an end face".to_string(),
119                    vec![args.source_range],
120                ))
121            }),
122        }
123    }
124
125    pub async fn get_face_id_from_tag(
126        &self,
127        exec_state: &mut ExecState,
128        args: &Args,
129        must_be_planar: bool,
130    ) -> Result<uuid::Uuid, KclError> {
131        match self {
132            FaceTag::Tag(t) => args.get_adjacent_face_to_tag(exec_state, t, must_be_planar).await,
133            _ => Err(KclError::new_type(KclErrorDetails::new(
134                "Could not find the face corresponding to this tag".to_string(),
135                vec![args.source_range],
136            ))),
137        }
138    }
139
140    pub fn geometry(&self) -> Option<Geometry> {
141        match self {
142            FaceTag::Tag(t) => t.geometry(),
143            _ => None,
144        }
145    }
146}
147
148#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS, FromStr, Display)]
149#[ts(export)]
150#[serde(rename_all = "snake_case")]
151#[display(style = "snake_case")]
152pub enum StartOrEnd {
153    /// The start face as in before you extruded. This could also be known as the bottom
154    /// face. But we do not call it bottom because it would be the top face if you
155    /// extruded it in the opposite direction or flipped the camera.
156    #[serde(rename = "start", alias = "START")]
157    Start,
158    /// The end face after you extruded. This could also be known as the top
159    /// face. But we do not call it top because it would be the bottom face if you
160    /// extruded it in the opposite direction or flipped the camera.
161    #[serde(rename = "end", alias = "END")]
162    End,
163}
164
165pub const NEW_TAG_KW: &str = "tag";
166
167pub async fn involute_circular(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
168    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::sketch(), exec_state)?;
169
170    let start_radius: Option<TyF64> = args.get_kw_arg_opt("startRadius", &RuntimeType::length(), exec_state)?;
171    let end_radius: Option<TyF64> = args.get_kw_arg_opt("endRadius", &RuntimeType::length(), exec_state)?;
172    let start_diameter: Option<TyF64> = args.get_kw_arg_opt("startDiameter", &RuntimeType::length(), exec_state)?;
173    let end_diameter: Option<TyF64> = args.get_kw_arg_opt("endDiameter", &RuntimeType::length(), exec_state)?;
174    let angle: TyF64 = args.get_kw_arg("angle", &RuntimeType::angle(), exec_state)?;
175    let reverse = args.get_kw_arg_opt("reverse", &RuntimeType::bool(), exec_state)?;
176    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
177    let new_sketch = inner_involute_circular(
178        sketch,
179        start_radius,
180        end_radius,
181        start_diameter,
182        end_diameter,
183        angle,
184        reverse,
185        tag,
186        exec_state,
187        args,
188    )
189    .await?;
190    Ok(KclValue::Sketch {
191        value: Box::new(new_sketch),
192    })
193}
194
195fn involute_curve(radius: f64, angle: f64) -> (f64, f64) {
196    (
197        radius * (libm::cos(angle) + angle * libm::sin(angle)),
198        radius * (libm::sin(angle) - angle * libm::cos(angle)),
199    )
200}
201
202#[allow(clippy::too_many_arguments)]
203async fn inner_involute_circular(
204    sketch: Sketch,
205    start_radius: Option<TyF64>,
206    end_radius: Option<TyF64>,
207    start_diameter: Option<TyF64>,
208    end_diameter: Option<TyF64>,
209    angle: TyF64,
210    reverse: Option<bool>,
211    tag: Option<TagNode>,
212    exec_state: &mut ExecState,
213    args: Args,
214) -> Result<Sketch, KclError> {
215    let id = exec_state.next_uuid();
216    let angle_deg = angle.to_degrees(exec_state, args.source_range);
217    let angle_rad = angle.to_radians(exec_state, args.source_range);
218
219    let longer_args_dot_source_range = args.source_range;
220    let start_radius = get_radius_labelled(
221        start_radius,
222        start_diameter,
223        args.source_range,
224        "startRadius",
225        "startDiameter",
226    )?;
227    let end_radius = get_radius_labelled(
228        end_radius,
229        end_diameter,
230        longer_args_dot_source_range,
231        "endRadius",
232        "endDiameter",
233    )?;
234
235    exec_state
236        .batch_modeling_cmd(
237            ModelingCmdMeta::from_args_id(exec_state, &args, id),
238            ModelingCmd::from(
239                mcmd::ExtendPath::builder()
240                    .path(sketch.id.into())
241                    .segment(PathSegment::CircularInvolute {
242                        start_radius: LengthUnit(start_radius.to_mm()),
243                        end_radius: LengthUnit(end_radius.to_mm()),
244                        angle: Angle::from_degrees(angle_deg),
245                        reverse: reverse.unwrap_or_default(),
246                    })
247                    .build(),
248            ),
249        )
250        .await?;
251
252    let from = sketch.current_pen_position()?;
253
254    let start_radius = start_radius.to_length_units(from.units);
255    let end_radius = end_radius.to_length_units(from.units);
256
257    let mut end: KPoint3d<f64> = Default::default(); // ADAM: TODO impl this below.
258    let theta = f64::sqrt(end_radius * end_radius - start_radius * start_radius) / start_radius;
259    let (x, y) = involute_curve(start_radius, theta);
260
261    end.x = x * libm::cos(angle_rad) - y * libm::sin(angle_rad);
262    end.y = x * libm::sin(angle_rad) + y * libm::cos(angle_rad);
263
264    end.x -= start_radius * libm::cos(angle_rad);
265    end.y -= start_radius * libm::sin(angle_rad);
266
267    if reverse.unwrap_or_default() {
268        end.x = -end.x;
269    }
270
271    end.x += from.x;
272    end.y += from.y;
273
274    let current_path = Path::ToPoint {
275        base: BasePath {
276            from: from.ignore_units(),
277            to: [end.x, end.y],
278            tag: tag.clone(),
279            units: sketch.units,
280            geo_meta: GeoMeta {
281                id,
282                metadata: args.source_range.into(),
283            },
284        },
285    };
286
287    let mut new_sketch = sketch;
288    if let Some(tag) = &tag {
289        new_sketch.add_tag(tag, &current_path, exec_state, None);
290    }
291    new_sketch.paths.push(current_path);
292    Ok(new_sketch)
293}
294
295/// Draw a line to a point.
296pub async fn line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
297    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::sketch(), exec_state)?;
298    let end = args.get_kw_arg_opt("end", &RuntimeType::point2d(), exec_state)?;
299    let end_absolute = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
300    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
301
302    let new_sketch = inner_line(sketch, end_absolute, end, tag, exec_state, args).await?;
303    Ok(KclValue::Sketch {
304        value: Box::new(new_sketch),
305    })
306}
307
308async fn inner_line(
309    sketch: Sketch,
310    end_absolute: Option<[TyF64; 2]>,
311    end: Option<[TyF64; 2]>,
312    tag: Option<TagNode>,
313    exec_state: &mut ExecState,
314    args: Args,
315) -> Result<Sketch, KclError> {
316    straight_line_with_new_id(
317        StraightLineParams {
318            sketch,
319            end_absolute,
320            end,
321            tag,
322            relative_name: "end",
323        },
324        exec_state,
325        &args.ctx,
326        args.source_range,
327    )
328    .await
329}
330
331pub(super) struct StraightLineParams {
332    sketch: Sketch,
333    end_absolute: Option<[TyF64; 2]>,
334    end: Option<[TyF64; 2]>,
335    tag: Option<TagNode>,
336    relative_name: &'static str,
337}
338
339impl StraightLineParams {
340    fn relative(p: [TyF64; 2], sketch: Sketch, tag: Option<TagNode>) -> Self {
341        Self {
342            sketch,
343            tag,
344            end: Some(p),
345            end_absolute: None,
346            relative_name: "end",
347        }
348    }
349    pub(super) fn absolute(p: [TyF64; 2], sketch: Sketch, tag: Option<TagNode>) -> Self {
350        Self {
351            sketch,
352            tag,
353            end: None,
354            end_absolute: Some(p),
355            relative_name: "end",
356        }
357    }
358}
359
360pub(super) async fn straight_line_with_new_id(
361    straight_line_params: StraightLineParams,
362    exec_state: &mut ExecState,
363    ctx: &ExecutorContext,
364    source_range: SourceRange,
365) -> Result<Sketch, KclError> {
366    let id = exec_state.next_uuid();
367    straight_line(id, straight_line_params, true, exec_state, ctx, source_range).await
368}
369
370pub(super) async fn straight_line(
371    id: Uuid,
372    StraightLineParams {
373        sketch,
374        end,
375        end_absolute,
376        tag,
377        relative_name,
378    }: StraightLineParams,
379    send_to_engine: bool,
380    exec_state: &mut ExecState,
381    ctx: &ExecutorContext,
382    source_range: SourceRange,
383) -> Result<Sketch, KclError> {
384    let from = sketch.current_pen_position()?;
385    let (point, is_absolute) = match (end_absolute, end) {
386        (Some(_), Some(_)) => {
387            return Err(KclError::new_semantic(KclErrorDetails::new(
388                "You cannot give both `end` and `endAbsolute` params, you have to choose one or the other".to_owned(),
389                vec![source_range],
390            )));
391        }
392        (Some(end_absolute), None) => (end_absolute, true),
393        (None, Some(end)) => (end, false),
394        (None, None) => {
395            return Err(KclError::new_semantic(KclErrorDetails::new(
396                format!("You must supply either `{relative_name}` or `endAbsolute` arguments"),
397                vec![source_range],
398            )));
399        }
400    };
401
402    if send_to_engine {
403        exec_state
404            .batch_modeling_cmd(
405                ModelingCmdMeta::with_id(exec_state, ctx, source_range, id),
406                ModelingCmd::from(
407                    mcmd::ExtendPath::builder()
408                        .path(sketch.id.into())
409                        .segment(PathSegment::Line {
410                            end: KPoint2d::from(point_to_mm(point.clone())).with_z(0.0).map(LengthUnit),
411                            relative: !is_absolute,
412                        })
413                        .build(),
414                ),
415            )
416            .await?;
417    }
418
419    let end = if is_absolute {
420        point_to_len_unit(point, from.units)
421    } else {
422        let from = sketch.current_pen_position()?;
423        let point = point_to_len_unit(point, from.units);
424        [from.x + point[0], from.y + point[1]]
425    };
426
427    // Does it loop back on itself?
428    let loops_back_to_start = does_segment_close_sketch(end, sketch.start.from);
429
430    let current_path = Path::ToPoint {
431        base: BasePath {
432            from: from.ignore_units(),
433            to: end,
434            tag: tag.clone(),
435            units: sketch.units,
436            geo_meta: GeoMeta {
437                id,
438                metadata: source_range.into(),
439            },
440        },
441    };
442
443    let mut new_sketch = sketch;
444    if let Some(tag) = &tag {
445        new_sketch.add_tag(tag, &current_path, exec_state, None);
446    }
447    if loops_back_to_start {
448        new_sketch.is_closed = ProfileClosed::Implicitly;
449    }
450
451    new_sketch.paths.push(current_path);
452
453    Ok(new_sketch)
454}
455
456fn does_segment_close_sketch(end: [f64; 2], from: [f64; 2]) -> bool {
457    let same_x = (end[0] - from[0]).abs() < EQUAL_POINTS_DIST_EPSILON;
458    let same_y = (end[1] - from[1]).abs() < EQUAL_POINTS_DIST_EPSILON;
459    same_x && same_y
460}
461
462/// Draw a line on the x-axis.
463pub async fn x_line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
464    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
465    let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
466    let end_absolute: Option<TyF64> = args.get_kw_arg_opt("endAbsolute", &RuntimeType::length(), exec_state)?;
467    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
468
469    let new_sketch = inner_x_line(sketch, length, end_absolute, tag, exec_state, args).await?;
470    Ok(KclValue::Sketch {
471        value: Box::new(new_sketch),
472    })
473}
474
475async fn inner_x_line(
476    sketch: Sketch,
477    length: Option<TyF64>,
478    end_absolute: Option<TyF64>,
479    tag: Option<TagNode>,
480    exec_state: &mut ExecState,
481    args: Args,
482) -> Result<Sketch, KclError> {
483    let from = sketch.current_pen_position()?;
484    straight_line_with_new_id(
485        StraightLineParams {
486            sketch,
487            end_absolute: end_absolute.map(|x| [x, from.into_y()]),
488            end: length.map(|x| [x, TyF64::new(0.0, NumericType::mm())]),
489            tag,
490            relative_name: "length",
491        },
492        exec_state,
493        &args.ctx,
494        args.source_range,
495    )
496    .await
497}
498
499/// Draw a line on the y-axis.
500pub async fn y_line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
501    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
502    let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
503    let end_absolute: Option<TyF64> = args.get_kw_arg_opt("endAbsolute", &RuntimeType::length(), exec_state)?;
504    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
505
506    let new_sketch = inner_y_line(sketch, length, end_absolute, tag, exec_state, args).await?;
507    Ok(KclValue::Sketch {
508        value: Box::new(new_sketch),
509    })
510}
511
512async fn inner_y_line(
513    sketch: Sketch,
514    length: Option<TyF64>,
515    end_absolute: Option<TyF64>,
516    tag: Option<TagNode>,
517    exec_state: &mut ExecState,
518    args: Args,
519) -> Result<Sketch, KclError> {
520    let from = sketch.current_pen_position()?;
521    straight_line_with_new_id(
522        StraightLineParams {
523            sketch,
524            end_absolute: end_absolute.map(|y| [from.into_x(), y]),
525            end: length.map(|y| [TyF64::new(0.0, NumericType::mm()), y]),
526            tag,
527            relative_name: "length",
528        },
529        exec_state,
530        &args.ctx,
531        args.source_range,
532    )
533    .await
534}
535
536/// Draw an angled line.
537pub async fn angled_line(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
538    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::sketch(), exec_state)?;
539    let angle: TyF64 = args.get_kw_arg("angle", &RuntimeType::degrees(), exec_state)?;
540    let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
541    let length_x: Option<TyF64> = args.get_kw_arg_opt("lengthX", &RuntimeType::length(), exec_state)?;
542    let length_y: Option<TyF64> = args.get_kw_arg_opt("lengthY", &RuntimeType::length(), exec_state)?;
543    let end_absolute_x: Option<TyF64> = args.get_kw_arg_opt("endAbsoluteX", &RuntimeType::length(), exec_state)?;
544    let end_absolute_y: Option<TyF64> = args.get_kw_arg_opt("endAbsoluteY", &RuntimeType::length(), exec_state)?;
545    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
546
547    let new_sketch = inner_angled_line(
548        sketch,
549        angle.n,
550        length,
551        length_x,
552        length_y,
553        end_absolute_x,
554        end_absolute_y,
555        tag,
556        exec_state,
557        args,
558    )
559    .await?;
560    Ok(KclValue::Sketch {
561        value: Box::new(new_sketch),
562    })
563}
564
565#[allow(clippy::too_many_arguments)]
566async fn inner_angled_line(
567    sketch: Sketch,
568    angle: f64,
569    length: Option<TyF64>,
570    length_x: Option<TyF64>,
571    length_y: Option<TyF64>,
572    end_absolute_x: Option<TyF64>,
573    end_absolute_y: Option<TyF64>,
574    tag: Option<TagNode>,
575    exec_state: &mut ExecState,
576    args: Args,
577) -> Result<Sketch, KclError> {
578    let options_given = [&length, &length_x, &length_y, &end_absolute_x, &end_absolute_y]
579        .iter()
580        .filter(|x| x.is_some())
581        .count();
582    if options_given > 1 {
583        return Err(KclError::new_type(KclErrorDetails::new(
584            " one of `length`, `lengthX`, `lengthY`, `endAbsoluteX`, `endAbsoluteY` can be given".to_string(),
585            vec![args.source_range],
586        )));
587    }
588    if let Some(length_x) = length_x {
589        return inner_angled_line_of_x_length(angle, length_x, sketch, tag, exec_state, args).await;
590    }
591    if let Some(length_y) = length_y {
592        return inner_angled_line_of_y_length(angle, length_y, sketch, tag, exec_state, args).await;
593    }
594    let angle_degrees = angle;
595    match (length, length_x, length_y, end_absolute_x, end_absolute_y) {
596        (Some(length), None, None, None, None) => {
597            inner_angled_line_length(sketch, angle_degrees, length, tag, exec_state, args).await
598        }
599        (None, Some(length_x), None, None, None) => {
600            inner_angled_line_of_x_length(angle_degrees, length_x, sketch, tag, exec_state, args).await
601        }
602        (None, None, Some(length_y), None, None) => {
603            inner_angled_line_of_y_length(angle_degrees, length_y, sketch, tag, exec_state, args).await
604        }
605        (None, None, None, Some(end_absolute_x), None) => {
606            inner_angled_line_to_x(angle_degrees, end_absolute_x, sketch, tag, exec_state, args).await
607        }
608        (None, None, None, None, Some(end_absolute_y)) => {
609            inner_angled_line_to_y(angle_degrees, end_absolute_y, sketch, tag, exec_state, args).await
610        }
611        (None, None, None, None, None) => Err(KclError::new_type(KclErrorDetails::new(
612            "One of `length`, `lengthX`, `lengthY`, `endAbsoluteX`, `endAbsoluteY` must be given".to_string(),
613            vec![args.source_range],
614        ))),
615        _ => Err(KclError::new_type(KclErrorDetails::new(
616            "Only One of `length`, `lengthX`, `lengthY`, `endAbsoluteX`, `endAbsoluteY` can be given".to_owned(),
617            vec![args.source_range],
618        ))),
619    }
620}
621
622async fn inner_angled_line_length(
623    sketch: Sketch,
624    angle_degrees: f64,
625    length: TyF64,
626    tag: Option<TagNode>,
627    exec_state: &mut ExecState,
628    args: Args,
629) -> Result<Sketch, KclError> {
630    let from = sketch.current_pen_position()?;
631    let length = length.to_length_units(from.units);
632
633    //double check me on this one - mike
634    let delta: [f64; 2] = [
635        length * libm::cos(angle_degrees.to_radians()),
636        length * libm::sin(angle_degrees.to_radians()),
637    ];
638    let relative = true;
639
640    let to: [f64; 2] = [from.x + delta[0], from.y + delta[1]];
641    let loops_back_to_start = does_segment_close_sketch(to, sketch.start.from);
642
643    let id = exec_state.next_uuid();
644
645    exec_state
646        .batch_modeling_cmd(
647            ModelingCmdMeta::from_args_id(exec_state, &args, id),
648            ModelingCmd::from(
649                mcmd::ExtendPath::builder()
650                    .path(sketch.id.into())
651                    .segment(PathSegment::Line {
652                        end: KPoint2d::from(untyped_point_to_mm(delta, from.units))
653                            .with_z(0.0)
654                            .map(LengthUnit),
655                        relative,
656                    })
657                    .build(),
658            ),
659        )
660        .await?;
661
662    let current_path = Path::ToPoint {
663        base: BasePath {
664            from: from.ignore_units(),
665            to,
666            tag: tag.clone(),
667            units: sketch.units,
668            geo_meta: GeoMeta {
669                id,
670                metadata: args.source_range.into(),
671            },
672        },
673    };
674
675    let mut new_sketch = sketch;
676    if let Some(tag) = &tag {
677        new_sketch.add_tag(tag, &current_path, exec_state, None);
678    }
679    if loops_back_to_start {
680        new_sketch.is_closed = ProfileClosed::Implicitly;
681    }
682
683    new_sketch.paths.push(current_path);
684    Ok(new_sketch)
685}
686
687async fn inner_angled_line_of_x_length(
688    angle_degrees: f64,
689    length: TyF64,
690    sketch: Sketch,
691    tag: Option<TagNode>,
692    exec_state: &mut ExecState,
693    args: Args,
694) -> Result<Sketch, KclError> {
695    if angle_degrees.abs() == 270.0 {
696        return Err(KclError::new_type(KclErrorDetails::new(
697            "Cannot have an x constrained angle of 270 degrees".to_string(),
698            vec![args.source_range],
699        )));
700    }
701
702    if angle_degrees.abs() == 90.0 {
703        return Err(KclError::new_type(KclErrorDetails::new(
704            "Cannot have an x constrained angle of 90 degrees".to_string(),
705            vec![args.source_range],
706        )));
707    }
708
709    let to = get_y_component(Angle::from_degrees(angle_degrees), length.n);
710    let to = [TyF64::new(to[0], length.ty), TyF64::new(to[1], length.ty)];
711
712    let new_sketch = straight_line_with_new_id(
713        StraightLineParams::relative(to, sketch, tag),
714        exec_state,
715        &args.ctx,
716        args.source_range,
717    )
718    .await?;
719
720    Ok(new_sketch)
721}
722
723async fn inner_angled_line_to_x(
724    angle_degrees: f64,
725    x_to: TyF64,
726    sketch: Sketch,
727    tag: Option<TagNode>,
728    exec_state: &mut ExecState,
729    args: Args,
730) -> Result<Sketch, KclError> {
731    let from = sketch.current_pen_position()?;
732
733    if angle_degrees.abs() == 270.0 {
734        return Err(KclError::new_type(KclErrorDetails::new(
735            "Cannot have an x constrained angle of 270 degrees".to_string(),
736            vec![args.source_range],
737        )));
738    }
739
740    if angle_degrees.abs() == 90.0 {
741        return Err(KclError::new_type(KclErrorDetails::new(
742            "Cannot have an x constrained angle of 90 degrees".to_string(),
743            vec![args.source_range],
744        )));
745    }
746
747    let x_component = x_to.to_length_units(from.units) - from.x;
748    let y_component = x_component * libm::tan(angle_degrees.to_radians());
749    let y_to = from.y + y_component;
750
751    let new_sketch = straight_line_with_new_id(
752        StraightLineParams::absolute([x_to, TyF64::new(y_to, from.units.into())], sketch, tag),
753        exec_state,
754        &args.ctx,
755        args.source_range,
756    )
757    .await?;
758    Ok(new_sketch)
759}
760
761async fn inner_angled_line_of_y_length(
762    angle_degrees: f64,
763    length: TyF64,
764    sketch: Sketch,
765    tag: Option<TagNode>,
766    exec_state: &mut ExecState,
767    args: Args,
768) -> Result<Sketch, KclError> {
769    if angle_degrees.abs() == 0.0 {
770        return Err(KclError::new_type(KclErrorDetails::new(
771            "Cannot have a y constrained angle of 0 degrees".to_string(),
772            vec![args.source_range],
773        )));
774    }
775
776    if angle_degrees.abs() == 180.0 {
777        return Err(KclError::new_type(KclErrorDetails::new(
778            "Cannot have a y constrained angle of 180 degrees".to_string(),
779            vec![args.source_range],
780        )));
781    }
782
783    let to = get_x_component(Angle::from_degrees(angle_degrees), length.n);
784    let to = [TyF64::new(to[0], length.ty), TyF64::new(to[1], length.ty)];
785
786    let new_sketch = straight_line_with_new_id(
787        StraightLineParams::relative(to, sketch, tag),
788        exec_state,
789        &args.ctx,
790        args.source_range,
791    )
792    .await?;
793
794    Ok(new_sketch)
795}
796
797async fn inner_angled_line_to_y(
798    angle_degrees: f64,
799    y_to: TyF64,
800    sketch: Sketch,
801    tag: Option<TagNode>,
802    exec_state: &mut ExecState,
803    args: Args,
804) -> Result<Sketch, KclError> {
805    let from = sketch.current_pen_position()?;
806
807    if angle_degrees.abs() == 0.0 {
808        return Err(KclError::new_type(KclErrorDetails::new(
809            "Cannot have a y constrained angle of 0 degrees".to_string(),
810            vec![args.source_range],
811        )));
812    }
813
814    if angle_degrees.abs() == 180.0 {
815        return Err(KclError::new_type(KclErrorDetails::new(
816            "Cannot have a y constrained angle of 180 degrees".to_string(),
817            vec![args.source_range],
818        )));
819    }
820
821    let y_component = y_to.to_length_units(from.units) - from.y;
822    let x_component = y_component / libm::tan(angle_degrees.to_radians());
823    let x_to = from.x + x_component;
824
825    let new_sketch = straight_line_with_new_id(
826        StraightLineParams::absolute([TyF64::new(x_to, from.units.into()), y_to], sketch, tag),
827        exec_state,
828        &args.ctx,
829        args.source_range,
830    )
831    .await?;
832    Ok(new_sketch)
833}
834
835/// Draw an angled line that intersects with a given line.
836pub async fn angled_line_that_intersects(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
837    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
838    let angle: TyF64 = args.get_kw_arg("angle", &RuntimeType::angle(), exec_state)?;
839    let intersect_tag: TagIdentifier = args.get_kw_arg("intersectTag", &RuntimeType::tagged_edge(), exec_state)?;
840    let offset = args.get_kw_arg_opt("offset", &RuntimeType::length(), exec_state)?;
841    let tag: Option<TagNode> = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
842    let new_sketch =
843        inner_angled_line_that_intersects(sketch, angle, intersect_tag, offset, tag, exec_state, args).await?;
844    Ok(KclValue::Sketch {
845        value: Box::new(new_sketch),
846    })
847}
848
849pub async fn inner_angled_line_that_intersects(
850    sketch: Sketch,
851    angle: TyF64,
852    intersect_tag: TagIdentifier,
853    offset: Option<TyF64>,
854    tag: Option<TagNode>,
855    exec_state: &mut ExecState,
856    args: Args,
857) -> Result<Sketch, KclError> {
858    let intersect_path = args.get_tag_engine_info(exec_state, &intersect_tag)?;
859    let path = intersect_path.path.clone().ok_or_else(|| {
860        KclError::new_type(KclErrorDetails::new(
861            format!("Expected an intersect path with a path, found `{intersect_path:?}`"),
862            vec![args.source_range],
863        ))
864    })?;
865
866    let from = sketch.current_pen_position()?;
867    let to = intersection_with_parallel_line(
868        &[
869            point_to_len_unit(path.get_from(), from.units),
870            point_to_len_unit(path.get_to(), from.units),
871        ],
872        offset.map(|t| t.to_length_units(from.units)).unwrap_or_default(),
873        angle.to_degrees(exec_state, args.source_range),
874        from.ignore_units(),
875    );
876    let to = [
877        TyF64::new(to[0], from.units.into()),
878        TyF64::new(to[1], from.units.into()),
879    ];
880
881    straight_line_with_new_id(
882        StraightLineParams::absolute(to, sketch, tag),
883        exec_state,
884        &args.ctx,
885        args.source_range,
886    )
887    .await
888}
889
890/// Data for start sketch on.
891/// You can start a sketch on a plane or an solid.
892#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
893#[ts(export)]
894#[serde(rename_all = "camelCase", untagged)]
895#[allow(clippy::large_enum_variant)]
896pub enum SketchData {
897    PlaneOrientation(PlaneData),
898    Plane(Box<Plane>),
899    Solid(Box<Solid>),
900}
901
902/// Orientation data that can be used to construct a plane, not a plane in itself.
903#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, ts_rs::TS)]
904#[ts(export)]
905#[serde(rename_all = "camelCase")]
906#[allow(clippy::large_enum_variant)]
907pub enum PlaneData {
908    /// The XY plane.
909    #[serde(rename = "XY", alias = "xy")]
910    XY,
911    /// The opposite side of the XY plane.
912    #[serde(rename = "-XY", alias = "-xy")]
913    NegXY,
914    /// The XZ plane.
915    #[serde(rename = "XZ", alias = "xz")]
916    XZ,
917    /// The opposite side of the XZ plane.
918    #[serde(rename = "-XZ", alias = "-xz")]
919    NegXZ,
920    /// The YZ plane.
921    #[serde(rename = "YZ", alias = "yz")]
922    YZ,
923    /// The opposite side of the YZ plane.
924    #[serde(rename = "-YZ", alias = "-yz")]
925    NegYZ,
926    /// A defined plane.
927    Plane(PlaneInfo),
928}
929
930/// Start a sketch on a specific plane or face.
931pub async fn start_sketch_on(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
932    let data = args.get_unlabeled_kw_arg(
933        "planeOrSolid",
934        &RuntimeType::Union(vec![RuntimeType::solid(), RuntimeType::plane()]),
935        exec_state,
936    )?;
937    let face = args.get_kw_arg_opt("face", &RuntimeType::tagged_face_or_segment(), exec_state)?;
938    let normal_to_face = args.get_kw_arg_opt("normalToFace", &RuntimeType::tagged_face(), exec_state)?;
939    let align_axis = args.get_kw_arg_opt("alignAxis", &RuntimeType::Primitive(PrimitiveType::Axis2d), exec_state)?;
940    let normal_offset = args.get_kw_arg_opt("normalOffset", &RuntimeType::length(), exec_state)?;
941
942    match inner_start_sketch_on(data, face, normal_to_face, align_axis, normal_offset, exec_state, &args).await? {
943        SketchSurface::Plane(value) => Ok(KclValue::Plane { value }),
944        SketchSurface::Face(value) => Ok(KclValue::Face { value }),
945    }
946}
947
948async fn inner_start_sketch_on(
949    plane_or_solid: SketchData,
950    face: Option<FaceSpecifier>,
951    normal_to_face: Option<FaceSpecifier>,
952    align_axis: Option<Axis2dOrEdgeReference>,
953    normal_offset: Option<TyF64>,
954    exec_state: &mut ExecState,
955    args: &Args,
956) -> Result<SketchSurface, KclError> {
957    let face = match (face, normal_to_face, &align_axis, &normal_offset) {
958        (Some(_), Some(_), _, _) => {
959            return Err(KclError::new_semantic(KclErrorDetails::new(
960                "You cannot give both `face` and `normalToFace` params, you have to choose one or the other."
961                    .to_owned(),
962                vec![args.source_range],
963            )));
964        }
965        (Some(face), None, None, None) => Some(face),
966        (_, Some(_), None, _) => {
967            return Err(KclError::new_semantic(KclErrorDetails::new(
968                "`alignAxis` is required if `normalToFace` is specified.".to_owned(),
969                vec![args.source_range],
970            )));
971        }
972        (_, None, Some(_), _) => {
973            return Err(KclError::new_semantic(KclErrorDetails::new(
974                "`normalToFace` is required if `alignAxis` is specified.".to_owned(),
975                vec![args.source_range],
976            )));
977        }
978        (_, None, _, Some(_)) => {
979            return Err(KclError::new_semantic(KclErrorDetails::new(
980                "`normalToFace` is required if `normalOffset` is specified.".to_owned(),
981                vec![args.source_range],
982            )));
983        }
984        (_, Some(face), Some(_), _) => Some(face),
985        (None, None, None, None) => None,
986    };
987
988    match plane_or_solid {
989        SketchData::PlaneOrientation(plane_data) => {
990            let plane = make_sketch_plane_from_orientation(plane_data, exec_state, args).await?;
991            Ok(SketchSurface::Plane(plane))
992        }
993        SketchData::Plane(plane) => {
994            if plane.is_uninitialized() {
995                let plane = make_sketch_plane_from_orientation(plane.info.into_plane_data(), exec_state, args).await?;
996                Ok(SketchSurface::Plane(plane))
997            } else {
998                // Create artifact used only by the UI, not the engine.
999                #[cfg(feature = "artifact-graph")]
1000                {
1001                    let id = exec_state.next_uuid();
1002                    exec_state.add_artifact(Artifact::StartSketchOnPlane(StartSketchOnPlane {
1003                        id: ArtifactId::from(id),
1004                        plane_id: plane.artifact_id,
1005                        code_ref: CodeRef::placeholder(args.source_range),
1006                    }));
1007                }
1008
1009                Ok(SketchSurface::Plane(plane))
1010            }
1011        }
1012        SketchData::Solid(solid) => {
1013            let Some(tag) = face else {
1014                return Err(KclError::new_type(KclErrorDetails::new(
1015                    "Expected a tag for the face to sketch on".to_string(),
1016                    vec![args.source_range],
1017                )));
1018            };
1019            if let Some(align_axis) = align_axis {
1020                let plane_of = inner_plane_of(*solid, tag, exec_state, args).await?;
1021
1022                // plane_of info axis units are Some(UnitLength::Millimeters), see inner_plane_of and PlaneInfo
1023                let offset = normal_offset.map_or(0.0, |x| x.to_mm());
1024                let (x_axis, y_axis, normal_offset) = match align_axis {
1025                    Axis2dOrEdgeReference::Axis { direction, origin: _ } => {
1026                        if (direction[0].n - 1.0).abs() < f64::EPSILON {
1027                            //X axis chosen
1028                            (
1029                                plane_of.info.x_axis,
1030                                plane_of.info.z_axis,
1031                                plane_of.info.y_axis * offset,
1032                            )
1033                        } else if (direction[0].n + 1.0).abs() < f64::EPSILON {
1034                            // -X axis chosen
1035                            (
1036                                plane_of.info.x_axis.negated(),
1037                                plane_of.info.z_axis,
1038                                plane_of.info.y_axis * offset,
1039                            )
1040                        } else if (direction[1].n - 1.0).abs() < f64::EPSILON {
1041                            // Y axis chosen
1042                            (
1043                                plane_of.info.y_axis,
1044                                plane_of.info.z_axis,
1045                                plane_of.info.x_axis * offset,
1046                            )
1047                        } else if (direction[1].n + 1.0).abs() < f64::EPSILON {
1048                            // -Y axis chosen
1049                            (
1050                                plane_of.info.y_axis.negated(),
1051                                plane_of.info.z_axis,
1052                                plane_of.info.x_axis * offset,
1053                            )
1054                        } else {
1055                            return Err(KclError::new_semantic(KclErrorDetails::new(
1056                                "Unsupported axis detected. This function only supports using X, -X, Y and -Y."
1057                                    .to_owned(),
1058                                vec![args.source_range],
1059                            )));
1060                        }
1061                    }
1062                    Axis2dOrEdgeReference::Edge(_) => {
1063                        return Err(KclError::new_semantic(KclErrorDetails::new(
1064                            "Use of an edge here is unsupported, please specify an `Axis2d` (e.g. `X`) instead."
1065                                .to_owned(),
1066                            vec![args.source_range],
1067                        )));
1068                    }
1069                };
1070                let origin = Point3d::new(0.0, 0.0, 0.0, plane_of.info.origin.units);
1071                let plane_data = PlaneData::Plane(PlaneInfo {
1072                    origin: plane_of.project(origin) + normal_offset,
1073                    x_axis,
1074                    y_axis,
1075                    z_axis: x_axis.axes_cross_product(&y_axis),
1076                });
1077                let plane = make_sketch_plane_from_orientation(plane_data, exec_state, args).await?;
1078
1079                // Create artifact used only by the UI, not the engine.
1080                #[cfg(feature = "artifact-graph")]
1081                {
1082                    let id = exec_state.next_uuid();
1083                    exec_state.add_artifact(Artifact::StartSketchOnPlane(StartSketchOnPlane {
1084                        id: ArtifactId::from(id),
1085                        plane_id: plane.artifact_id,
1086                        code_ref: CodeRef::placeholder(args.source_range),
1087                    }));
1088                }
1089
1090                Ok(SketchSurface::Plane(plane))
1091            } else {
1092                let face = make_face(solid, tag, exec_state, args).await?;
1093
1094                #[cfg(feature = "artifact-graph")]
1095                {
1096                    // Create artifact used only by the UI, not the engine.
1097                    let id = exec_state.next_uuid();
1098                    exec_state.add_artifact(Artifact::StartSketchOnFace(StartSketchOnFace {
1099                        id: ArtifactId::from(id),
1100                        face_id: face.artifact_id,
1101                        code_ref: CodeRef::placeholder(args.source_range),
1102                    }));
1103                }
1104
1105                Ok(SketchSurface::Face(face))
1106            }
1107        }
1108    }
1109}
1110
1111pub async fn make_sketch_plane_from_orientation(
1112    data: PlaneData,
1113    exec_state: &mut ExecState,
1114    args: &Args,
1115) -> Result<Box<Plane>, KclError> {
1116    let id = exec_state.next_uuid();
1117    let kind = PlaneKind::from(&data);
1118    let mut plane = Plane {
1119        id,
1120        artifact_id: id.into(),
1121        object_id: None,
1122        kind,
1123        info: PlaneInfo::try_from(data)?,
1124        meta: vec![args.source_range.into()],
1125    };
1126
1127    // Create the plane on the fly.
1128    ensure_sketch_plane_in_engine(&mut plane, exec_state, &args.ctx, args.source_range).await?;
1129
1130    Ok(Box::new(plane))
1131}
1132
1133/// Ensure that the plane exists in the engine.
1134pub async fn ensure_sketch_plane_in_engine(
1135    plane: &mut Plane,
1136    exec_state: &mut ExecState,
1137    ctx: &ExecutorContext,
1138    source_range: SourceRange,
1139) -> Result<(), KclError> {
1140    if plane.is_initialized() {
1141        return Ok(());
1142    }
1143    #[cfg(feature = "artifact-graph")]
1144    {
1145        if let Some(existing_object_id) = exec_state.scene_object_id_by_artifact_id(ArtifactId::new(plane.id)) {
1146            plane.object_id = Some(existing_object_id);
1147            return Ok(());
1148        }
1149    }
1150
1151    let clobber = false;
1152    let size = LengthUnit(60.0);
1153    let hide = Some(true);
1154    let cmd = if let Some(hide) = hide {
1155        mcmd::MakePlane::builder()
1156            .clobber(clobber)
1157            .origin(plane.info.origin.into())
1158            .size(size)
1159            .x_axis(plane.info.x_axis.into())
1160            .y_axis(plane.info.y_axis.into())
1161            .hide(hide)
1162            .build()
1163    } else {
1164        mcmd::MakePlane::builder()
1165            .clobber(clobber)
1166            .origin(plane.info.origin.into())
1167            .size(size)
1168            .x_axis(plane.info.x_axis.into())
1169            .y_axis(plane.info.y_axis.into())
1170            .build()
1171    };
1172    exec_state
1173        .batch_modeling_cmd(
1174            ModelingCmdMeta::with_id(exec_state, ctx, source_range, plane.id),
1175            ModelingCmd::from(cmd),
1176        )
1177        .await?;
1178    let plane_object_id = exec_state.next_object_id();
1179    #[cfg(feature = "artifact-graph")]
1180    {
1181        let plane_object = crate::front::Object {
1182            id: plane_object_id,
1183            kind: crate::front::ObjectKind::Plane(crate::front::Plane::Object(plane_object_id)),
1184            label: Default::default(),
1185            comments: Default::default(),
1186            artifact_id: ArtifactId::new(plane.id),
1187            source: source_range.into(),
1188        };
1189        exec_state.add_scene_object(plane_object, source_range);
1190    }
1191    plane.object_id = Some(plane_object_id);
1192
1193    Ok(())
1194}
1195
1196/// Start a new profile at a given point.
1197pub async fn start_profile(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1198    let sketch_surface = args.get_unlabeled_kw_arg(
1199        "startProfileOn",
1200        &RuntimeType::Union(vec![RuntimeType::plane(), RuntimeType::face()]),
1201        exec_state,
1202    )?;
1203    let start: [TyF64; 2] = args.get_kw_arg("at", &RuntimeType::point2d(), exec_state)?;
1204    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
1205
1206    let sketch = inner_start_profile(sketch_surface, start, tag, exec_state, &args.ctx, args.source_range).await?;
1207    Ok(KclValue::Sketch {
1208        value: Box::new(sketch),
1209    })
1210}
1211
1212pub(crate) async fn inner_start_profile(
1213    sketch_surface: SketchSurface,
1214    at: [TyF64; 2],
1215    tag: Option<TagNode>,
1216    exec_state: &mut ExecState,
1217    ctx: &ExecutorContext,
1218    source_range: SourceRange,
1219) -> Result<Sketch, KclError> {
1220    let id = exec_state.next_uuid();
1221    create_sketch(id, sketch_surface, at, tag, true, exec_state, ctx, source_range).await
1222}
1223
1224#[expect(clippy::too_many_arguments)]
1225pub(crate) async fn create_sketch(
1226    id: Uuid,
1227    sketch_surface: SketchSurface,
1228    at: [TyF64; 2],
1229    tag: Option<TagNode>,
1230    send_to_engine: bool,
1231    exec_state: &mut ExecState,
1232    ctx: &ExecutorContext,
1233    source_range: SourceRange,
1234) -> Result<Sketch, KclError> {
1235    match &sketch_surface {
1236        SketchSurface::Face(face) => {
1237            // Flush the batch for our fillets/chamfers if there are any.
1238            // If we do not do these for sketch on face, things will fail with face does not exist.
1239            exec_state
1240                .flush_batch_for_solids(
1241                    ModelingCmdMeta::new(exec_state, ctx, source_range),
1242                    &[(*face.solid).clone()],
1243                )
1244                .await?;
1245        }
1246        SketchSurface::Plane(plane) if !plane.is_standard() => {
1247            // Hide whatever plane we are sketching on.
1248            // This is especially helpful for offset planes, which would be visible otherwise.
1249            exec_state
1250                .batch_end_cmd(
1251                    ModelingCmdMeta::new(exec_state, ctx, source_range),
1252                    ModelingCmd::from(mcmd::ObjectVisible::builder().object_id(plane.id).hidden(true).build()),
1253                )
1254                .await?;
1255        }
1256        _ => {}
1257    }
1258
1259    let path_id = id;
1260    let enable_sketch_id = exec_state.next_uuid();
1261    let move_pen_id = exec_state.next_uuid();
1262    let disable_sketch_id = exec_state.next_uuid();
1263    if send_to_engine {
1264        exec_state
1265            .batch_modeling_cmds(
1266                ModelingCmdMeta::new(exec_state, ctx, source_range),
1267                &[
1268                    // Enter sketch mode on the surface.
1269                    // We call this here so you can reuse the sketch surface for multiple sketches.
1270                    ModelingCmdReq {
1271                        cmd: ModelingCmd::from(if let SketchSurface::Plane(plane) = &sketch_surface {
1272                            // We pass in the normal for the plane here.
1273                            let normal = plane.info.x_axis.axes_cross_product(&plane.info.y_axis);
1274                            mcmd::EnableSketchMode::builder()
1275                                .animated(false)
1276                                .ortho(false)
1277                                .entity_id(sketch_surface.id())
1278                                .adjust_camera(false)
1279                                .planar_normal(normal.into())
1280                                .build()
1281                        } else {
1282                            mcmd::EnableSketchMode::builder()
1283                                .animated(false)
1284                                .ortho(false)
1285                                .entity_id(sketch_surface.id())
1286                                .adjust_camera(false)
1287                                .build()
1288                        }),
1289                        cmd_id: enable_sketch_id.into(),
1290                    },
1291                    ModelingCmdReq {
1292                        cmd: ModelingCmd::from(mcmd::StartPath::default()),
1293                        cmd_id: path_id.into(),
1294                    },
1295                    ModelingCmdReq {
1296                        cmd: ModelingCmd::from(
1297                            mcmd::MovePathPen::builder()
1298                                .path(path_id.into())
1299                                .to(KPoint2d::from(point_to_mm(at.clone())).with_z(0.0).map(LengthUnit))
1300                                .build(),
1301                        ),
1302                        cmd_id: move_pen_id.into(),
1303                    },
1304                    ModelingCmdReq {
1305                        cmd: ModelingCmd::SketchModeDisable(mcmd::SketchModeDisable::default()),
1306                        cmd_id: disable_sketch_id.into(),
1307                    },
1308                ],
1309            )
1310            .await?;
1311    }
1312
1313    // Convert to the units of the module.  This is what the frontend expects.
1314    let units = exec_state.length_unit();
1315    let to = point_to_len_unit(at, units);
1316    let current_path = BasePath {
1317        from: to,
1318        to,
1319        tag: tag.clone(),
1320        units,
1321        geo_meta: GeoMeta {
1322            id: move_pen_id,
1323            metadata: source_range.into(),
1324        },
1325    };
1326
1327    let mut sketch = Sketch {
1328        id: path_id,
1329        original_id: path_id,
1330        artifact_id: path_id.into(),
1331        on: sketch_surface,
1332        paths: vec![],
1333        inner_paths: vec![],
1334        units,
1335        mirror: Default::default(),
1336        clone: Default::default(),
1337        meta: vec![source_range.into()],
1338        tags: Default::default(),
1339        start: current_path.clone(),
1340        is_closed: ProfileClosed::No,
1341    };
1342    if let Some(tag) = &tag {
1343        let path = Path::Base { base: current_path };
1344        sketch.add_tag(tag, &path, exec_state, None);
1345    }
1346
1347    Ok(sketch)
1348}
1349
1350/// Returns the X component of the sketch profile start point.
1351pub async fn profile_start_x(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1352    let sketch: Sketch = args.get_unlabeled_kw_arg("profile", &RuntimeType::sketch(), exec_state)?;
1353    let ty = sketch.units.into();
1354    let x = inner_profile_start_x(sketch)?;
1355    Ok(args.make_user_val_from_f64_with_type(TyF64::new(x, ty)))
1356}
1357
1358pub(crate) fn inner_profile_start_x(profile: Sketch) -> Result<f64, KclError> {
1359    Ok(profile.start.to[0])
1360}
1361
1362/// Returns the Y component of the sketch profile start point.
1363pub async fn profile_start_y(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1364    let sketch: Sketch = args.get_unlabeled_kw_arg("profile", &RuntimeType::sketch(), exec_state)?;
1365    let ty = sketch.units.into();
1366    let x = inner_profile_start_y(sketch)?;
1367    Ok(args.make_user_val_from_f64_with_type(TyF64::new(x, ty)))
1368}
1369
1370pub(crate) fn inner_profile_start_y(profile: Sketch) -> Result<f64, KclError> {
1371    Ok(profile.start.to[1])
1372}
1373
1374/// Returns the sketch profile start point.
1375pub async fn profile_start(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1376    let sketch: Sketch = args.get_unlabeled_kw_arg("profile", &RuntimeType::sketch(), exec_state)?;
1377    let ty = sketch.units.into();
1378    let point = inner_profile_start(sketch)?;
1379    Ok(KclValue::from_point2d(point, ty, args.into()))
1380}
1381
1382pub(crate) fn inner_profile_start(profile: Sketch) -> Result<[f64; 2], KclError> {
1383    Ok(profile.start.to)
1384}
1385
1386/// Close the current sketch.
1387pub async fn close(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1388    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
1389    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
1390    let new_sketch = inner_close(sketch, tag, exec_state, args).await?;
1391    Ok(KclValue::Sketch {
1392        value: Box::new(new_sketch),
1393    })
1394}
1395
1396pub(crate) async fn inner_close(
1397    sketch: Sketch,
1398    tag: Option<TagNode>,
1399    exec_state: &mut ExecState,
1400    args: Args,
1401) -> Result<Sketch, KclError> {
1402    if matches!(sketch.is_closed, ProfileClosed::Explicitly) {
1403        exec_state.warn(
1404            crate::CompilationError {
1405                source_range: args.source_range,
1406                message: "This sketch is already closed. Remove this unnecessary `close()` call".to_string(),
1407                suggestion: None,
1408                severity: crate::errors::Severity::Warning,
1409                tag: crate::errors::Tag::Unnecessary,
1410            },
1411            annotations::WARN_UNNECESSARY_CLOSE,
1412        );
1413        return Ok(sketch);
1414    }
1415    let from = sketch.current_pen_position()?;
1416    let to = point_to_len_unit(sketch.start.get_from(), from.units);
1417
1418    let id = exec_state.next_uuid();
1419
1420    exec_state
1421        .batch_modeling_cmd(
1422            ModelingCmdMeta::from_args_id(exec_state, &args, id),
1423            ModelingCmd::from(mcmd::ClosePath::builder().path_id(sketch.id).build()),
1424        )
1425        .await?;
1426
1427    let mut new_sketch = sketch;
1428
1429    let distance = ((from.x - to[0]).powi(2) + (from.y - to[1]).powi(2)).sqrt();
1430    if distance > super::EQUAL_POINTS_DIST_EPSILON {
1431        // These will NOT be the same point in the engine, and an additional segment will be created.
1432        let current_path = Path::ToPoint {
1433            base: BasePath {
1434                from: from.ignore_units(),
1435                to,
1436                tag: tag.clone(),
1437                units: new_sketch.units,
1438                geo_meta: GeoMeta {
1439                    id,
1440                    metadata: args.source_range.into(),
1441                },
1442            },
1443        };
1444
1445        if let Some(tag) = &tag {
1446            new_sketch.add_tag(tag, &current_path, exec_state, None);
1447        }
1448        new_sketch.paths.push(current_path);
1449    } else if tag.is_some() {
1450        exec_state.warn(
1451            crate::CompilationError {
1452                source_range: args.source_range,
1453                message: "A tag declarator was specified, but no segment was created".to_string(),
1454                suggestion: None,
1455                severity: crate::errors::Severity::Warning,
1456                tag: crate::errors::Tag::Unnecessary,
1457            },
1458            annotations::WARN_UNUSED_TAGS,
1459        );
1460    }
1461
1462    new_sketch.is_closed = ProfileClosed::Explicitly;
1463
1464    Ok(new_sketch)
1465}
1466
1467/// Draw an arc.
1468pub async fn arc(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1469    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
1470
1471    let angle_start: Option<TyF64> = args.get_kw_arg_opt("angleStart", &RuntimeType::degrees(), exec_state)?;
1472    let angle_end: Option<TyF64> = args.get_kw_arg_opt("angleEnd", &RuntimeType::degrees(), exec_state)?;
1473    let radius: Option<TyF64> = args.get_kw_arg_opt("radius", &RuntimeType::length(), exec_state)?;
1474    let diameter: Option<TyF64> = args.get_kw_arg_opt("diameter", &RuntimeType::length(), exec_state)?;
1475    let end_absolute: Option<[TyF64; 2]> = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
1476    let interior_absolute: Option<[TyF64; 2]> =
1477        args.get_kw_arg_opt("interiorAbsolute", &RuntimeType::point2d(), exec_state)?;
1478    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
1479    let new_sketch = inner_arc(
1480        sketch,
1481        angle_start,
1482        angle_end,
1483        radius,
1484        diameter,
1485        interior_absolute,
1486        end_absolute,
1487        tag,
1488        exec_state,
1489        args,
1490    )
1491    .await?;
1492    Ok(KclValue::Sketch {
1493        value: Box::new(new_sketch),
1494    })
1495}
1496
1497#[allow(clippy::too_many_arguments)]
1498pub(crate) async fn inner_arc(
1499    sketch: Sketch,
1500    angle_start: Option<TyF64>,
1501    angle_end: Option<TyF64>,
1502    radius: Option<TyF64>,
1503    diameter: Option<TyF64>,
1504    interior_absolute: Option<[TyF64; 2]>,
1505    end_absolute: Option<[TyF64; 2]>,
1506    tag: Option<TagNode>,
1507    exec_state: &mut ExecState,
1508    args: Args,
1509) -> Result<Sketch, KclError> {
1510    let from: Point2d = sketch.current_pen_position()?;
1511    let id = exec_state.next_uuid();
1512
1513    match (angle_start, angle_end, radius, diameter, interior_absolute, end_absolute) {
1514        (Some(angle_start), Some(angle_end), radius, diameter, None, None) => {
1515            let radius = get_radius(radius, diameter, args.source_range)?;
1516            relative_arc(id, exec_state, sketch, from, angle_start, angle_end, radius, tag, true, &args.ctx, args.source_range).await
1517        }
1518        (None, None, None, None, Some(interior_absolute), Some(end_absolute)) => {
1519            absolute_arc(&args, id, exec_state, sketch, from, interior_absolute, end_absolute, tag).await
1520        }
1521        _ => {
1522            Err(KclError::new_type(KclErrorDetails::new(
1523                "Invalid combination of arguments. Either provide (angleStart, angleEnd, radius) or (endAbsolute, interiorAbsolute)".to_owned(),
1524                vec![args.source_range],
1525            )))
1526        }
1527    }
1528}
1529
1530#[allow(clippy::too_many_arguments)]
1531pub async fn absolute_arc(
1532    args: &Args,
1533    id: uuid::Uuid,
1534    exec_state: &mut ExecState,
1535    sketch: Sketch,
1536    from: Point2d,
1537    interior_absolute: [TyF64; 2],
1538    end_absolute: [TyF64; 2],
1539    tag: Option<TagNode>,
1540) -> Result<Sketch, KclError> {
1541    // The start point is taken from the path you are extending.
1542    exec_state
1543        .batch_modeling_cmd(
1544            ModelingCmdMeta::from_args_id(exec_state, args, id),
1545            ModelingCmd::from(
1546                mcmd::ExtendPath::builder()
1547                    .path(sketch.id.into())
1548                    .segment(PathSegment::ArcTo {
1549                        end: kcmc::shared::Point3d {
1550                            x: LengthUnit(end_absolute[0].to_mm()),
1551                            y: LengthUnit(end_absolute[1].to_mm()),
1552                            z: LengthUnit(0.0),
1553                        },
1554                        interior: kcmc::shared::Point3d {
1555                            x: LengthUnit(interior_absolute[0].to_mm()),
1556                            y: LengthUnit(interior_absolute[1].to_mm()),
1557                            z: LengthUnit(0.0),
1558                        },
1559                        relative: false,
1560                    })
1561                    .build(),
1562            ),
1563        )
1564        .await?;
1565
1566    let start = [from.x, from.y];
1567    let end = point_to_len_unit(end_absolute, from.units);
1568    let loops_back_to_start = does_segment_close_sketch(end, sketch.start.from);
1569
1570    let current_path = Path::ArcThreePoint {
1571        base: BasePath {
1572            from: from.ignore_units(),
1573            to: end,
1574            tag: tag.clone(),
1575            units: sketch.units,
1576            geo_meta: GeoMeta {
1577                id,
1578                metadata: args.source_range.into(),
1579            },
1580        },
1581        p1: start,
1582        p2: point_to_len_unit(interior_absolute, from.units),
1583        p3: end,
1584    };
1585
1586    let mut new_sketch = sketch;
1587    if let Some(tag) = &tag {
1588        new_sketch.add_tag(tag, &current_path, exec_state, None);
1589    }
1590    if loops_back_to_start {
1591        new_sketch.is_closed = ProfileClosed::Implicitly;
1592    }
1593
1594    new_sketch.paths.push(current_path);
1595
1596    Ok(new_sketch)
1597}
1598
1599#[allow(clippy::too_many_arguments)]
1600pub async fn relative_arc(
1601    id: uuid::Uuid,
1602    exec_state: &mut ExecState,
1603    sketch: Sketch,
1604    from: Point2d,
1605    angle_start: TyF64,
1606    angle_end: TyF64,
1607    radius: TyF64,
1608    tag: Option<TagNode>,
1609    send_to_engine: bool,
1610    ctx: &ExecutorContext,
1611    source_range: SourceRange,
1612) -> Result<Sketch, KclError> {
1613    let a_start = Angle::from_degrees(angle_start.to_degrees(exec_state, source_range));
1614    let a_end = Angle::from_degrees(angle_end.to_degrees(exec_state, source_range));
1615    let radius = radius.to_length_units(from.units);
1616    let (center, end) = arc_center_and_end(from.ignore_units(), a_start, a_end, radius);
1617    if a_start == a_end {
1618        return Err(KclError::new_type(KclErrorDetails::new(
1619            "Arc start and end angles must be different".to_string(),
1620            vec![source_range],
1621        )));
1622    }
1623    let ccw = a_start < a_end;
1624
1625    if send_to_engine {
1626        exec_state
1627            .batch_modeling_cmd(
1628                ModelingCmdMeta::with_id(exec_state, ctx, source_range, id),
1629                ModelingCmd::from(
1630                    mcmd::ExtendPath::builder()
1631                        .path(sketch.id.into())
1632                        .segment(PathSegment::Arc {
1633                            start: a_start,
1634                            end: a_end,
1635                            center: KPoint2d::from(untyped_point_to_mm(center, from.units)).map(LengthUnit),
1636                            radius: LengthUnit(
1637                                crate::execution::types::adjust_length(from.units, radius, UnitLength::Millimeters).0,
1638                            ),
1639                            relative: false,
1640                        })
1641                        .build(),
1642                ),
1643            )
1644            .await?;
1645    }
1646
1647    let loops_back_to_start = does_segment_close_sketch(end, sketch.start.from);
1648    let current_path = Path::Arc {
1649        base: BasePath {
1650            from: from.ignore_units(),
1651            to: end,
1652            tag: tag.clone(),
1653            units: from.units,
1654            geo_meta: GeoMeta {
1655                id,
1656                metadata: source_range.into(),
1657            },
1658        },
1659        center,
1660        radius,
1661        ccw,
1662    };
1663
1664    let mut new_sketch = sketch;
1665    if let Some(tag) = &tag {
1666        new_sketch.add_tag(tag, &current_path, exec_state, None);
1667    }
1668    if loops_back_to_start {
1669        new_sketch.is_closed = ProfileClosed::Implicitly;
1670    }
1671
1672    new_sketch.paths.push(current_path);
1673
1674    Ok(new_sketch)
1675}
1676
1677/// Draw a tangential arc to a specific point.
1678pub async fn tangential_arc(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1679    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
1680    let end = args.get_kw_arg_opt("end", &RuntimeType::point2d(), exec_state)?;
1681    let end_absolute = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
1682    let radius = args.get_kw_arg_opt("radius", &RuntimeType::length(), exec_state)?;
1683    let diameter = args.get_kw_arg_opt("diameter", &RuntimeType::length(), exec_state)?;
1684    let angle = args.get_kw_arg_opt("angle", &RuntimeType::angle(), exec_state)?;
1685    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
1686
1687    let new_sketch = inner_tangential_arc(
1688        sketch,
1689        end_absolute,
1690        end,
1691        radius,
1692        diameter,
1693        angle,
1694        tag,
1695        exec_state,
1696        args,
1697    )
1698    .await?;
1699    Ok(KclValue::Sketch {
1700        value: Box::new(new_sketch),
1701    })
1702}
1703
1704#[allow(clippy::too_many_arguments)]
1705async fn inner_tangential_arc(
1706    sketch: Sketch,
1707    end_absolute: Option<[TyF64; 2]>,
1708    end: Option<[TyF64; 2]>,
1709    radius: Option<TyF64>,
1710    diameter: Option<TyF64>,
1711    angle: Option<TyF64>,
1712    tag: Option<TagNode>,
1713    exec_state: &mut ExecState,
1714    args: Args,
1715) -> Result<Sketch, KclError> {
1716    match (end_absolute, end, radius, diameter, angle) {
1717        (Some(point), None, None, None, None) => {
1718            inner_tangential_arc_to_point(sketch, point, true, tag, exec_state, args).await
1719        }
1720        (None, Some(point), None, None, None) => {
1721            inner_tangential_arc_to_point(sketch, point, false, tag, exec_state, args).await
1722        }
1723        (None, None, radius, diameter, Some(angle)) => {
1724            let radius = get_radius(radius, diameter, args.source_range)?;
1725            let data = TangentialArcData::RadiusAndOffset { radius, offset: angle };
1726            inner_tangential_arc_radius_angle(data, sketch, tag, exec_state, args).await
1727        }
1728        (Some(_), Some(_), None, None, None) => Err(KclError::new_semantic(KclErrorDetails::new(
1729            "You cannot give both `end` and `endAbsolute` params, you have to choose one or the other".to_owned(),
1730            vec![args.source_range],
1731        ))),
1732        (_, _, _, _, _) => Err(KclError::new_semantic(KclErrorDetails::new(
1733            "You must supply `end`, `endAbsolute`, or both `angle` and `radius`/`diameter` arguments".to_owned(),
1734            vec![args.source_range],
1735        ))),
1736    }
1737}
1738
1739/// Data to draw a tangential arc.
1740#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1741#[ts(export)]
1742#[serde(rename_all = "camelCase", untagged)]
1743pub enum TangentialArcData {
1744    RadiusAndOffset {
1745        /// Radius of the arc.
1746        /// Not to be confused with Raiders of the Lost Ark.
1747        radius: TyF64,
1748        /// Offset of the arc, in degrees.
1749        offset: TyF64,
1750    },
1751}
1752
1753/// Draw a curved line segment along part of an imaginary circle.
1754///
1755/// The arc is constructed such that the last line segment is placed tangent
1756/// to the imaginary circle of the specified radius. The resulting arc is the
1757/// segment of the imaginary circle from that tangent point for 'angle'
1758/// degrees along the imaginary circle.
1759async fn inner_tangential_arc_radius_angle(
1760    data: TangentialArcData,
1761    sketch: Sketch,
1762    tag: Option<TagNode>,
1763    exec_state: &mut ExecState,
1764    args: Args,
1765) -> Result<Sketch, KclError> {
1766    let from: Point2d = sketch.current_pen_position()?;
1767    // next set of lines is some undocumented voodoo from get_tangential_arc_to_info
1768    let tangent_info = sketch.get_tangential_info_from_paths(); //this function desperately needs some documentation
1769    let tan_previous_point = tangent_info.tan_previous_point(from.ignore_units());
1770
1771    let id = exec_state.next_uuid();
1772
1773    let (center, to, ccw) = match data {
1774        TangentialArcData::RadiusAndOffset { radius, offset } => {
1775            // KCL stdlib types use degrees.
1776            let offset = Angle::from_degrees(offset.to_degrees(exec_state, args.source_range));
1777
1778            // Calculate the end point from the angle and radius.
1779            // atan2 outputs radians.
1780            let previous_end_tangent = Angle::from_radians(libm::atan2(
1781                from.y - tan_previous_point[1],
1782                from.x - tan_previous_point[0],
1783            ));
1784            // make sure the arc center is on the correct side to guarantee deterministic behavior
1785            // note the engine automatically rejects an offset of zero, if we want to flag that at KCL too to avoid engine errors
1786            let ccw = offset.to_degrees() > 0.0;
1787            let tangent_to_arc_start_angle = if ccw {
1788                // CCW turn
1789                Angle::from_degrees(-90.0)
1790            } else {
1791                // CW turn
1792                Angle::from_degrees(90.0)
1793            };
1794            // may need some logic and / or modulo on the various angle values to prevent them from going "backwards"
1795            // but the above logic *should* capture that behavior
1796            let start_angle = previous_end_tangent + tangent_to_arc_start_angle;
1797            let end_angle = start_angle + offset;
1798            let (center, to) = arc_center_and_end(
1799                from.ignore_units(),
1800                start_angle,
1801                end_angle,
1802                radius.to_length_units(from.units),
1803            );
1804
1805            exec_state
1806                .batch_modeling_cmd(
1807                    ModelingCmdMeta::from_args_id(exec_state, &args, id),
1808                    ModelingCmd::from(
1809                        mcmd::ExtendPath::builder()
1810                            .path(sketch.id.into())
1811                            .segment(PathSegment::TangentialArc {
1812                                radius: LengthUnit(radius.to_mm()),
1813                                offset,
1814                            })
1815                            .build(),
1816                    ),
1817                )
1818                .await?;
1819            (center, to, ccw)
1820        }
1821    };
1822    let loops_back_to_start = does_segment_close_sketch(to, sketch.start.from);
1823
1824    let current_path = Path::TangentialArc {
1825        ccw,
1826        center,
1827        base: BasePath {
1828            from: from.ignore_units(),
1829            to,
1830            tag: tag.clone(),
1831            units: sketch.units,
1832            geo_meta: GeoMeta {
1833                id,
1834                metadata: args.source_range.into(),
1835            },
1836        },
1837    };
1838
1839    let mut new_sketch = sketch;
1840    if let Some(tag) = &tag {
1841        new_sketch.add_tag(tag, &current_path, exec_state, None);
1842    }
1843    if loops_back_to_start {
1844        new_sketch.is_closed = ProfileClosed::Implicitly;
1845    }
1846
1847    new_sketch.paths.push(current_path);
1848
1849    Ok(new_sketch)
1850}
1851
1852// `to` must be in sketch.units
1853fn tan_arc_to(sketch: &Sketch, to: [f64; 2]) -> ModelingCmd {
1854    ModelingCmd::from(
1855        mcmd::ExtendPath::builder()
1856            .path(sketch.id.into())
1857            .segment(PathSegment::TangentialArcTo {
1858                angle_snap_increment: None,
1859                to: KPoint2d::from(untyped_point_to_mm(to, sketch.units))
1860                    .with_z(0.0)
1861                    .map(LengthUnit),
1862            })
1863            .build(),
1864    )
1865}
1866
1867async fn inner_tangential_arc_to_point(
1868    sketch: Sketch,
1869    point: [TyF64; 2],
1870    is_absolute: bool,
1871    tag: Option<TagNode>,
1872    exec_state: &mut ExecState,
1873    args: Args,
1874) -> Result<Sketch, KclError> {
1875    let from: Point2d = sketch.current_pen_position()?;
1876    let tangent_info = sketch.get_tangential_info_from_paths();
1877    let tan_previous_point = tangent_info.tan_previous_point(from.ignore_units());
1878
1879    let point = point_to_len_unit(point, from.units);
1880
1881    let to = if is_absolute {
1882        point
1883    } else {
1884        [from.x + point[0], from.y + point[1]]
1885    };
1886    let loops_back_to_start = does_segment_close_sketch(to, sketch.start.from);
1887    let [to_x, to_y] = to;
1888    let result = get_tangential_arc_to_info(TangentialArcInfoInput {
1889        arc_start_point: [from.x, from.y],
1890        arc_end_point: [to_x, to_y],
1891        tan_previous_point,
1892        obtuse: true,
1893    });
1894
1895    if result.center[0].is_infinite() {
1896        return Err(KclError::new_semantic(KclErrorDetails::new(
1897            "could not sketch tangential arc, because its center would be infinitely far away in the X direction"
1898                .to_owned(),
1899            vec![args.source_range],
1900        )));
1901    } else if result.center[1].is_infinite() {
1902        return Err(KclError::new_semantic(KclErrorDetails::new(
1903            "could not sketch tangential arc, because its center would be infinitely far away in the Y direction"
1904                .to_owned(),
1905            vec![args.source_range],
1906        )));
1907    }
1908
1909    let delta = if is_absolute {
1910        [to_x - from.x, to_y - from.y]
1911    } else {
1912        point
1913    };
1914    let id = exec_state.next_uuid();
1915    exec_state
1916        .batch_modeling_cmd(
1917            ModelingCmdMeta::from_args_id(exec_state, &args, id),
1918            tan_arc_to(&sketch, delta),
1919        )
1920        .await?;
1921
1922    let current_path = Path::TangentialArcTo {
1923        base: BasePath {
1924            from: from.ignore_units(),
1925            to,
1926            tag: tag.clone(),
1927            units: sketch.units,
1928            geo_meta: GeoMeta {
1929                id,
1930                metadata: args.source_range.into(),
1931            },
1932        },
1933        center: result.center,
1934        ccw: result.ccw > 0,
1935    };
1936
1937    let mut new_sketch = sketch;
1938    if let Some(tag) = &tag {
1939        new_sketch.add_tag(tag, &current_path, exec_state, None);
1940    }
1941    if loops_back_to_start {
1942        new_sketch.is_closed = ProfileClosed::Implicitly;
1943    }
1944
1945    new_sketch.paths.push(current_path);
1946
1947    Ok(new_sketch)
1948}
1949
1950/// Draw a bezier curve.
1951pub async fn bezier_curve(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
1952    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
1953    let control1 = args.get_kw_arg_opt("control1", &RuntimeType::point2d(), exec_state)?;
1954    let control2 = args.get_kw_arg_opt("control2", &RuntimeType::point2d(), exec_state)?;
1955    let end = args.get_kw_arg_opt("end", &RuntimeType::point2d(), exec_state)?;
1956    let control1_absolute = args.get_kw_arg_opt("control1Absolute", &RuntimeType::point2d(), exec_state)?;
1957    let control2_absolute = args.get_kw_arg_opt("control2Absolute", &RuntimeType::point2d(), exec_state)?;
1958    let end_absolute = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
1959    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
1960
1961    let new_sketch = inner_bezier_curve(
1962        sketch,
1963        control1,
1964        control2,
1965        end,
1966        control1_absolute,
1967        control2_absolute,
1968        end_absolute,
1969        tag,
1970        exec_state,
1971        args,
1972    )
1973    .await?;
1974    Ok(KclValue::Sketch {
1975        value: Box::new(new_sketch),
1976    })
1977}
1978
1979#[allow(clippy::too_many_arguments)]
1980async fn inner_bezier_curve(
1981    sketch: Sketch,
1982    control1: Option<[TyF64; 2]>,
1983    control2: Option<[TyF64; 2]>,
1984    end: Option<[TyF64; 2]>,
1985    control1_absolute: Option<[TyF64; 2]>,
1986    control2_absolute: Option<[TyF64; 2]>,
1987    end_absolute: Option<[TyF64; 2]>,
1988    tag: Option<TagNode>,
1989    exec_state: &mut ExecState,
1990    args: Args,
1991) -> Result<Sketch, KclError> {
1992    let from = sketch.current_pen_position()?;
1993    let id = exec_state.next_uuid();
1994
1995    let (to, control1_abs, control2_abs) = match (
1996        control1,
1997        control2,
1998        end,
1999        control1_absolute,
2000        control2_absolute,
2001        end_absolute,
2002    ) {
2003        // Relative
2004        (Some(control1), Some(control2), Some(end), None, None, None) => {
2005            let delta = end.clone();
2006            let to = [
2007                from.x + end[0].to_length_units(from.units),
2008                from.y + end[1].to_length_units(from.units),
2009            ];
2010            // Calculate absolute control points
2011            let control1_abs = [
2012                from.x + control1[0].to_length_units(from.units),
2013                from.y + control1[1].to_length_units(from.units),
2014            ];
2015            let control2_abs = [
2016                from.x + control2[0].to_length_units(from.units),
2017                from.y + control2[1].to_length_units(from.units),
2018            ];
2019
2020            exec_state
2021                .batch_modeling_cmd(
2022                    ModelingCmdMeta::from_args_id(exec_state, &args, id),
2023                    ModelingCmd::from(
2024                        mcmd::ExtendPath::builder()
2025                            .path(sketch.id.into())
2026                            .segment(PathSegment::Bezier {
2027                                control1: KPoint2d::from(point_to_mm(control1)).with_z(0.0).map(LengthUnit),
2028                                control2: KPoint2d::from(point_to_mm(control2)).with_z(0.0).map(LengthUnit),
2029                                end: KPoint2d::from(point_to_mm(delta)).with_z(0.0).map(LengthUnit),
2030                                relative: true,
2031                            })
2032                            .build(),
2033                    ),
2034                )
2035                .await?;
2036            (to, control1_abs, control2_abs)
2037        }
2038        // Absolute
2039        (None, None, None, Some(control1), Some(control2), Some(end)) => {
2040            let to = [end[0].to_length_units(from.units), end[1].to_length_units(from.units)];
2041            let control1_abs = control1.clone().map(|v| v.to_length_units(from.units));
2042            let control2_abs = control2.clone().map(|v| v.to_length_units(from.units));
2043            exec_state
2044                .batch_modeling_cmd(
2045                    ModelingCmdMeta::from_args_id(exec_state, &args, id),
2046                    ModelingCmd::from(
2047                        mcmd::ExtendPath::builder()
2048                            .path(sketch.id.into())
2049                            .segment(PathSegment::Bezier {
2050                                control1: KPoint2d::from(point_to_mm(control1)).with_z(0.0).map(LengthUnit),
2051                                control2: KPoint2d::from(point_to_mm(control2)).with_z(0.0).map(LengthUnit),
2052                                end: KPoint2d::from(point_to_mm(end)).with_z(0.0).map(LengthUnit),
2053                                relative: false,
2054                            })
2055                            .build(),
2056                    ),
2057                )
2058                .await?;
2059            (to, control1_abs, control2_abs)
2060        }
2061        _ => {
2062            return Err(KclError::new_semantic(KclErrorDetails::new(
2063                "You must either give `control1`, `control2` and `end`, or `control1Absolute`, `control2Absolute` and `endAbsolute`.".to_owned(),
2064                vec![args.source_range],
2065            )));
2066        }
2067    };
2068
2069    let loops_back_to_start = does_segment_close_sketch(to, sketch.start.from);
2070
2071    let current_path = Path::Bezier {
2072        base: BasePath {
2073            from: from.ignore_units(),
2074            to,
2075            tag: tag.clone(),
2076            units: sketch.units,
2077            geo_meta: GeoMeta {
2078                id,
2079                metadata: args.source_range.into(),
2080            },
2081        },
2082        control1: control1_abs,
2083        control2: control2_abs,
2084    };
2085
2086    let mut new_sketch = sketch;
2087    if let Some(tag) = &tag {
2088        new_sketch.add_tag(tag, &current_path, exec_state, None);
2089    }
2090    if loops_back_to_start {
2091        new_sketch.is_closed = ProfileClosed::Implicitly;
2092    }
2093
2094    new_sketch.paths.push(current_path);
2095
2096    Ok(new_sketch)
2097}
2098
2099/// Use a sketch to cut a hole in another sketch.
2100pub async fn subtract_2d(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2101    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
2102
2103    let tool: Vec<Sketch> = args.get_kw_arg(
2104        "tool",
2105        &RuntimeType::Array(
2106            Box::new(RuntimeType::Primitive(PrimitiveType::Sketch)),
2107            ArrayLen::Minimum(1),
2108        ),
2109        exec_state,
2110    )?;
2111
2112    let new_sketch = inner_subtract_2d(sketch, tool, exec_state, args).await?;
2113    Ok(KclValue::Sketch {
2114        value: Box::new(new_sketch),
2115    })
2116}
2117
2118async fn inner_subtract_2d(
2119    mut sketch: Sketch,
2120    tool: Vec<Sketch>,
2121    exec_state: &mut ExecState,
2122    args: Args,
2123) -> Result<Sketch, KclError> {
2124    for hole_sketch in tool {
2125        exec_state
2126            .batch_modeling_cmd(
2127                ModelingCmdMeta::from_args(exec_state, &args),
2128                ModelingCmd::from(
2129                    mcmd::Solid2dAddHole::builder()
2130                        .object_id(sketch.id)
2131                        .hole_id(hole_sketch.id)
2132                        .build(),
2133                ),
2134            )
2135            .await?;
2136
2137        // Hide the source hole since it's no longer its own profile,
2138        // it's just used to modify some other profile.
2139        exec_state
2140            .batch_modeling_cmd(
2141                ModelingCmdMeta::from_args(exec_state, &args),
2142                ModelingCmd::from(
2143                    mcmd::ObjectVisible::builder()
2144                        .object_id(hole_sketch.id)
2145                        .hidden(true)
2146                        .build(),
2147                ),
2148            )
2149            .await?;
2150
2151        // NOTE: We don't look at the inner paths of the hole/tool sketch.
2152        // So if you have circle A, and it has a circular hole cut out (B),
2153        // then you cut A out of an even bigger circle C, we will lose that info.
2154        // Not really sure what to do about this.
2155        sketch.inner_paths.extend_from_slice(&hole_sketch.paths);
2156    }
2157
2158    // Returns the input sketch, exactly as it was, zero modifications.
2159    // This means the edges from `tool` are basically ignored, they're not in the output.
2160    Ok(sketch)
2161}
2162
2163/// Calculate the (x, y) point on an ellipse given x or y and the major/minor radii of the ellipse.
2164pub async fn elliptic_point(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2165    let x = args.get_kw_arg_opt("x", &RuntimeType::length(), exec_state)?;
2166    let y = args.get_kw_arg_opt("y", &RuntimeType::length(), exec_state)?;
2167    let major_radius = args.get_kw_arg("majorRadius", &RuntimeType::num_any(), exec_state)?;
2168    let minor_radius = args.get_kw_arg("minorRadius", &RuntimeType::num_any(), exec_state)?;
2169
2170    let elliptic_point = inner_elliptic_point(x, y, major_radius, minor_radius, &args).await?;
2171
2172    args.make_kcl_val_from_point(elliptic_point, exec_state.length_unit().into())
2173}
2174
2175async fn inner_elliptic_point(
2176    x: Option<TyF64>,
2177    y: Option<TyF64>,
2178    major_radius: TyF64,
2179    minor_radius: TyF64,
2180    args: &Args,
2181) -> Result<[f64; 2], KclError> {
2182    let major_radius = major_radius.n;
2183    let minor_radius = minor_radius.n;
2184    if let Some(x) = x {
2185        if x.n.abs() > major_radius {
2186            Err(KclError::Type {
2187                details: KclErrorDetails::new(
2188                    format!(
2189                        "Invalid input. The x value, {}, cannot be larger than the major radius {}.",
2190                        x.n, major_radius
2191                    ),
2192                    vec![args.source_range],
2193                ),
2194            })
2195        } else {
2196            Ok((
2197                x.n,
2198                minor_radius * (1.0 - x.n.powf(2.0) / major_radius.powf(2.0)).sqrt(),
2199            )
2200                .into())
2201        }
2202    } else if let Some(y) = y {
2203        if y.n > minor_radius {
2204            Err(KclError::Type {
2205                details: KclErrorDetails::new(
2206                    format!(
2207                        "Invalid input. The y value, {}, cannot be larger than the minor radius {}.",
2208                        y.n, minor_radius
2209                    ),
2210                    vec![args.source_range],
2211                ),
2212            })
2213        } else {
2214            Ok((
2215                major_radius * (1.0 - y.n.powf(2.0) / minor_radius.powf(2.0)).sqrt(),
2216                y.n,
2217            )
2218                .into())
2219        }
2220    } else {
2221        Err(KclError::Type {
2222            details: KclErrorDetails::new(
2223                "Invalid input. Must have either x or y, you cannot have both or neither.".to_owned(),
2224                vec![args.source_range],
2225            ),
2226        })
2227    }
2228}
2229
2230/// Draw an elliptical arc.
2231pub async fn elliptic(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2232    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
2233
2234    let center = args.get_kw_arg("center", &RuntimeType::point2d(), exec_state)?;
2235    let angle_start = args.get_kw_arg("angleStart", &RuntimeType::degrees(), exec_state)?;
2236    let angle_end = args.get_kw_arg("angleEnd", &RuntimeType::degrees(), exec_state)?;
2237    let major_radius = args.get_kw_arg_opt("majorRadius", &RuntimeType::length(), exec_state)?;
2238    let major_axis = args.get_kw_arg_opt("majorAxis", &RuntimeType::point2d(), exec_state)?;
2239    let minor_radius = args.get_kw_arg("minorRadius", &RuntimeType::length(), exec_state)?;
2240    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
2241
2242    let new_sketch = inner_elliptic(
2243        sketch,
2244        center,
2245        angle_start,
2246        angle_end,
2247        major_radius,
2248        major_axis,
2249        minor_radius,
2250        tag,
2251        exec_state,
2252        args,
2253    )
2254    .await?;
2255    Ok(KclValue::Sketch {
2256        value: Box::new(new_sketch),
2257    })
2258}
2259
2260#[allow(clippy::too_many_arguments)]
2261pub(crate) async fn inner_elliptic(
2262    sketch: Sketch,
2263    center: [TyF64; 2],
2264    angle_start: TyF64,
2265    angle_end: TyF64,
2266    major_radius: Option<TyF64>,
2267    major_axis: Option<[TyF64; 2]>,
2268    minor_radius: TyF64,
2269    tag: Option<TagNode>,
2270    exec_state: &mut ExecState,
2271    args: Args,
2272) -> Result<Sketch, KclError> {
2273    let from: Point2d = sketch.current_pen_position()?;
2274    let id = exec_state.next_uuid();
2275
2276    let center_u = point_to_len_unit(center, from.units);
2277
2278    let major_axis = match (major_axis, major_radius) {
2279        (Some(_), Some(_)) | (None, None) => {
2280            return Err(KclError::new_type(KclErrorDetails::new(
2281                "Provide either `majorAxis` or `majorRadius`.".to_string(),
2282                vec![args.source_range],
2283            )));
2284        }
2285        (Some(major_axis), None) => major_axis,
2286        (None, Some(major_radius)) => [
2287            major_radius.clone(),
2288            TyF64 {
2289                n: 0.0,
2290                ty: major_radius.ty,
2291            },
2292        ],
2293    };
2294    let start_angle = Angle::from_degrees(angle_start.to_degrees(exec_state, args.source_range));
2295    let end_angle = Angle::from_degrees(angle_end.to_degrees(exec_state, args.source_range));
2296    let major_axis_magnitude = (major_axis[0].to_length_units(from.units) * major_axis[0].to_length_units(from.units)
2297        + major_axis[1].to_length_units(from.units) * major_axis[1].to_length_units(from.units))
2298    .sqrt();
2299    let to = [
2300        major_axis_magnitude * libm::cos(end_angle.to_radians()),
2301        minor_radius.to_length_units(from.units) * libm::sin(end_angle.to_radians()),
2302    ];
2303    let loops_back_to_start = does_segment_close_sketch(to, sketch.start.from);
2304    let major_axis_angle = libm::atan2(major_axis[1].n, major_axis[0].n);
2305
2306    let point = [
2307        center_u[0] + to[0] * libm::cos(major_axis_angle) - to[1] * libm::sin(major_axis_angle),
2308        center_u[1] + to[0] * libm::sin(major_axis_angle) + to[1] * libm::cos(major_axis_angle),
2309    ];
2310
2311    let axis = major_axis.map(|x| x.to_mm());
2312    exec_state
2313        .batch_modeling_cmd(
2314            ModelingCmdMeta::from_args_id(exec_state, &args, id),
2315            ModelingCmd::from(
2316                mcmd::ExtendPath::builder()
2317                    .path(sketch.id.into())
2318                    .segment(PathSegment::Ellipse {
2319                        center: KPoint2d::from(untyped_point_to_mm(center_u, from.units)).map(LengthUnit),
2320                        major_axis: axis.map(LengthUnit).into(),
2321                        minor_radius: LengthUnit(minor_radius.to_mm()),
2322                        start_angle,
2323                        end_angle,
2324                    })
2325                    .build(),
2326            ),
2327        )
2328        .await?;
2329
2330    let current_path = Path::Ellipse {
2331        ccw: start_angle < end_angle,
2332        center: center_u,
2333        major_axis: axis,
2334        minor_radius: minor_radius.to_mm(),
2335        base: BasePath {
2336            from: from.ignore_units(),
2337            to: point,
2338            tag: tag.clone(),
2339            units: sketch.units,
2340            geo_meta: GeoMeta {
2341                id,
2342                metadata: args.source_range.into(),
2343            },
2344        },
2345    };
2346    let mut new_sketch = sketch;
2347    if let Some(tag) = &tag {
2348        new_sketch.add_tag(tag, &current_path, exec_state, None);
2349    }
2350    if loops_back_to_start {
2351        new_sketch.is_closed = ProfileClosed::Implicitly;
2352    }
2353
2354    new_sketch.paths.push(current_path);
2355
2356    Ok(new_sketch)
2357}
2358
2359/// Calculate the (x, y) point on an hyperbola given x or y and the semi major/minor of the ellipse.
2360pub async fn hyperbolic_point(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2361    let x = args.get_kw_arg_opt("x", &RuntimeType::length(), exec_state)?;
2362    let y = args.get_kw_arg_opt("y", &RuntimeType::length(), exec_state)?;
2363    let semi_major = args.get_kw_arg("semiMajor", &RuntimeType::num_any(), exec_state)?;
2364    let semi_minor = args.get_kw_arg("semiMinor", &RuntimeType::num_any(), exec_state)?;
2365
2366    let hyperbolic_point = inner_hyperbolic_point(x, y, semi_major, semi_minor, &args).await?;
2367
2368    args.make_kcl_val_from_point(hyperbolic_point, exec_state.length_unit().into())
2369}
2370
2371async fn inner_hyperbolic_point(
2372    x: Option<TyF64>,
2373    y: Option<TyF64>,
2374    semi_major: TyF64,
2375    semi_minor: TyF64,
2376    args: &Args,
2377) -> Result<[f64; 2], KclError> {
2378    let semi_major = semi_major.n;
2379    let semi_minor = semi_minor.n;
2380    if let Some(x) = x {
2381        if x.n.abs() < semi_major {
2382            Err(KclError::Type {
2383                details: KclErrorDetails::new(
2384                    format!(
2385                        "Invalid input. The x value, {}, cannot be less than the semi major value, {}.",
2386                        x.n, semi_major
2387                    ),
2388                    vec![args.source_range],
2389                ),
2390            })
2391        } else {
2392            Ok((x.n, semi_minor * (x.n.powf(2.0) / semi_major.powf(2.0) - 1.0).sqrt()).into())
2393        }
2394    } else if let Some(y) = y {
2395        Ok((semi_major * (y.n.powf(2.0) / semi_minor.powf(2.0) + 1.0).sqrt(), y.n).into())
2396    } else {
2397        Err(KclError::Type {
2398            details: KclErrorDetails::new(
2399                "Invalid input. Must have either x or y, cannot have both or neither.".to_owned(),
2400                vec![args.source_range],
2401            ),
2402        })
2403    }
2404}
2405
2406/// Draw a hyperbolic arc.
2407pub async fn hyperbolic(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2408    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
2409
2410    let semi_major = args.get_kw_arg("semiMajor", &RuntimeType::length(), exec_state)?;
2411    let semi_minor = args.get_kw_arg("semiMinor", &RuntimeType::length(), exec_state)?;
2412    let interior = args.get_kw_arg_opt("interior", &RuntimeType::point2d(), exec_state)?;
2413    let end = args.get_kw_arg_opt("end", &RuntimeType::point2d(), exec_state)?;
2414    let interior_absolute = args.get_kw_arg_opt("interiorAbsolute", &RuntimeType::point2d(), exec_state)?;
2415    let end_absolute = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
2416    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
2417
2418    let new_sketch = inner_hyperbolic(
2419        sketch,
2420        semi_major,
2421        semi_minor,
2422        interior,
2423        end,
2424        interior_absolute,
2425        end_absolute,
2426        tag,
2427        exec_state,
2428        args,
2429    )
2430    .await?;
2431    Ok(KclValue::Sketch {
2432        value: Box::new(new_sketch),
2433    })
2434}
2435
2436/// Calculate the tangent of a hyperbolic given a point on the curve
2437fn hyperbolic_tangent(point: Point2d, semi_major: f64, semi_minor: f64) -> [f64; 2] {
2438    (point.y * semi_major.powf(2.0), point.x * semi_minor.powf(2.0)).into()
2439}
2440
2441#[allow(clippy::too_many_arguments)]
2442pub(crate) async fn inner_hyperbolic(
2443    sketch: Sketch,
2444    semi_major: TyF64,
2445    semi_minor: TyF64,
2446    interior: Option<[TyF64; 2]>,
2447    end: Option<[TyF64; 2]>,
2448    interior_absolute: Option<[TyF64; 2]>,
2449    end_absolute: Option<[TyF64; 2]>,
2450    tag: Option<TagNode>,
2451    exec_state: &mut ExecState,
2452    args: Args,
2453) -> Result<Sketch, KclError> {
2454    let from = sketch.current_pen_position()?;
2455    let id = exec_state.next_uuid();
2456
2457    let (interior, end, relative) = match (interior, end, interior_absolute, end_absolute) {
2458        (Some(interior), Some(end), None, None) => (interior, end, true),
2459        (None, None, Some(interior_absolute), Some(end_absolute)) => (interior_absolute, end_absolute, false),
2460        _ => return Err(KclError::Type {
2461            details: KclErrorDetails::new(
2462                "Invalid combination of arguments. Either provide (end, interior) or (endAbsolute, interiorAbsolute)"
2463                    .to_owned(),
2464                vec![args.source_range],
2465            ),
2466        }),
2467    };
2468
2469    let interior = point_to_len_unit(interior, from.units);
2470    let end = point_to_len_unit(end, from.units);
2471    let end_point = Point2d {
2472        x: end[0],
2473        y: end[1],
2474        units: from.units,
2475    };
2476    let loops_back_to_start = does_segment_close_sketch(end, sketch.start.from);
2477
2478    let semi_major_u = semi_major.to_length_units(from.units);
2479    let semi_minor_u = semi_minor.to_length_units(from.units);
2480
2481    let start_tangent = hyperbolic_tangent(from, semi_major_u, semi_minor_u);
2482    let end_tangent = hyperbolic_tangent(end_point, semi_major_u, semi_minor_u);
2483
2484    exec_state
2485        .batch_modeling_cmd(
2486            ModelingCmdMeta::from_args_id(exec_state, &args, id),
2487            ModelingCmd::from(
2488                mcmd::ExtendPath::builder()
2489                    .path(sketch.id.into())
2490                    .segment(PathSegment::ConicTo {
2491                        start_tangent: KPoint2d::from(untyped_point_to_mm(start_tangent, from.units)).map(LengthUnit),
2492                        end_tangent: KPoint2d::from(untyped_point_to_mm(end_tangent, from.units)).map(LengthUnit),
2493                        end: KPoint2d::from(untyped_point_to_mm(end, from.units)).map(LengthUnit),
2494                        interior: KPoint2d::from(untyped_point_to_mm(interior, from.units)).map(LengthUnit),
2495                        relative,
2496                    })
2497                    .build(),
2498            ),
2499        )
2500        .await?;
2501
2502    let current_path = Path::Conic {
2503        base: BasePath {
2504            from: from.ignore_units(),
2505            to: end,
2506            tag: tag.clone(),
2507            units: sketch.units,
2508            geo_meta: GeoMeta {
2509                id,
2510                metadata: args.source_range.into(),
2511            },
2512        },
2513    };
2514
2515    let mut new_sketch = sketch;
2516    if let Some(tag) = &tag {
2517        new_sketch.add_tag(tag, &current_path, exec_state, None);
2518    }
2519    if loops_back_to_start {
2520        new_sketch.is_closed = ProfileClosed::Implicitly;
2521    }
2522
2523    new_sketch.paths.push(current_path);
2524
2525    Ok(new_sketch)
2526}
2527
2528/// Calculate the point on a parabola given the coefficient of the parabola and either x or y
2529pub async fn parabolic_point(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2530    let x = args.get_kw_arg_opt("x", &RuntimeType::length(), exec_state)?;
2531    let y = args.get_kw_arg_opt("y", &RuntimeType::length(), exec_state)?;
2532    let coefficients = args.get_kw_arg(
2533        "coefficients",
2534        &RuntimeType::Array(Box::new(RuntimeType::num_any()), ArrayLen::Known(3)),
2535        exec_state,
2536    )?;
2537
2538    let parabolic_point = inner_parabolic_point(x, y, &coefficients, &args).await?;
2539
2540    args.make_kcl_val_from_point(parabolic_point, exec_state.length_unit().into())
2541}
2542
2543async fn inner_parabolic_point(
2544    x: Option<TyF64>,
2545    y: Option<TyF64>,
2546    coefficients: &[TyF64; 3],
2547    args: &Args,
2548) -> Result<[f64; 2], KclError> {
2549    let a = coefficients[0].n;
2550    let b = coefficients[1].n;
2551    let c = coefficients[2].n;
2552    if let Some(x) = x {
2553        Ok((x.n, a * x.n.powf(2.0) + b * x.n + c).into())
2554    } else if let Some(y) = y {
2555        let det = (b.powf(2.0) - 4.0 * a * (c - y.n)).sqrt();
2556        Ok(((-b + det) / (2.0 * a), y.n).into())
2557    } else {
2558        Err(KclError::Type {
2559            details: KclErrorDetails::new(
2560                "Invalid input. Must have either x or y, cannot have both or neither.".to_owned(),
2561                vec![args.source_range],
2562            ),
2563        })
2564    }
2565}
2566
2567/// Draw a parabolic arc.
2568pub async fn parabolic(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2569    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
2570
2571    let coefficients = args.get_kw_arg_opt(
2572        "coefficients",
2573        &RuntimeType::Array(Box::new(RuntimeType::num_any()), ArrayLen::Known(3)),
2574        exec_state,
2575    )?;
2576    let interior = args.get_kw_arg_opt("interior", &RuntimeType::point2d(), exec_state)?;
2577    let end = args.get_kw_arg_opt("end", &RuntimeType::point2d(), exec_state)?;
2578    let interior_absolute = args.get_kw_arg_opt("interiorAbsolute", &RuntimeType::point2d(), exec_state)?;
2579    let end_absolute = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
2580    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
2581
2582    let new_sketch = inner_parabolic(
2583        sketch,
2584        coefficients,
2585        interior,
2586        end,
2587        interior_absolute,
2588        end_absolute,
2589        tag,
2590        exec_state,
2591        args,
2592    )
2593    .await?;
2594    Ok(KclValue::Sketch {
2595        value: Box::new(new_sketch),
2596    })
2597}
2598
2599fn parabolic_tangent(point: Point2d, a: f64, b: f64) -> [f64; 2] {
2600    //f(x) = ax^2 + bx + c
2601    //f'(x) = 2ax + b
2602    (1.0, 2.0 * a * point.x + b).into()
2603}
2604
2605#[allow(clippy::too_many_arguments)]
2606pub(crate) async fn inner_parabolic(
2607    sketch: Sketch,
2608    coefficients: Option<[TyF64; 3]>,
2609    interior: Option<[TyF64; 2]>,
2610    end: Option<[TyF64; 2]>,
2611    interior_absolute: Option<[TyF64; 2]>,
2612    end_absolute: Option<[TyF64; 2]>,
2613    tag: Option<TagNode>,
2614    exec_state: &mut ExecState,
2615    args: Args,
2616) -> Result<Sketch, KclError> {
2617    let from = sketch.current_pen_position()?;
2618    let id = exec_state.next_uuid();
2619
2620    if (coefficients.is_some() && interior.is_some()) || (coefficients.is_none() && interior.is_none()) {
2621        return Err(KclError::Type {
2622            details: KclErrorDetails::new(
2623                "Invalid combination of arguments. Either provide (a, b, c) or (interior)".to_owned(),
2624                vec![args.source_range],
2625            ),
2626        });
2627    }
2628
2629    let (interior, end, relative) = match (coefficients.clone(), interior, end, interior_absolute, end_absolute) {
2630        (None, Some(interior), Some(end), None, None) => {
2631            let interior = point_to_len_unit(interior, from.units);
2632            let end = point_to_len_unit(end, from.units);
2633            (interior,end, true)
2634        },
2635        (None, None, None, Some(interior_absolute), Some(end_absolute)) => {
2636            let interior_absolute = point_to_len_unit(interior_absolute, from.units);
2637            let end_absolute = point_to_len_unit(end_absolute, from.units);
2638            (interior_absolute, end_absolute, false)
2639        }
2640        (Some(coefficients), _, Some(end), _, _) => {
2641            let end = point_to_len_unit(end, from.units);
2642            let interior =
2643            inner_parabolic_point(
2644                Some(TyF64::count(0.5 * (from.x + end[0]))),
2645                None,
2646                &coefficients,
2647                &args,
2648            )
2649            .await?;
2650            (interior, end, true)
2651        }
2652        (Some(coefficients), _, _, _, Some(end)) => {
2653            let end = point_to_len_unit(end, from.units);
2654            let interior =
2655            inner_parabolic_point(
2656                Some(TyF64::count(0.5 * (from.x + end[0]))),
2657                None,
2658                &coefficients,
2659                &args,
2660            )
2661            .await?;
2662            (interior, end, false)
2663        }
2664        _ => return
2665            Err(KclError::Type{details: KclErrorDetails::new(
2666                "Invalid combination of arguments. Either provide (end, interior) or (endAbsolute, interiorAbsolute) if coefficients are not provided."
2667                    .to_owned(),
2668                vec![args.source_range],
2669            )}),
2670    };
2671
2672    let end_point = Point2d {
2673        x: end[0],
2674        y: end[1],
2675        units: from.units,
2676    };
2677
2678    let (a, b, _c) = if let Some([a, b, c]) = coefficients {
2679        (a.n, b.n, c.n)
2680    } else {
2681        // Any three points is enough to uniquely define a parabola
2682        let denom = (from.x - interior[0]) * (from.x - end_point.x) * (interior[0] - end_point.x);
2683        let a = (end_point.x * (interior[1] - from.y)
2684            + interior[0] * (from.y - end_point.y)
2685            + from.x * (end_point.y - interior[1]))
2686            / denom;
2687        let b = (end_point.x.powf(2.0) * (from.y - interior[1])
2688            + interior[0].powf(2.0) * (end_point.y - from.y)
2689            + from.x.powf(2.0) * (interior[1] - end_point.y))
2690            / denom;
2691        let c = (interior[0] * end_point.x * (interior[0] - end_point.x) * from.y
2692            + end_point.x * from.x * (end_point.x - from.x) * interior[1]
2693            + from.x * interior[0] * (from.x - interior[0]) * end_point.y)
2694            / denom;
2695
2696        (a, b, c)
2697    };
2698
2699    let start_tangent = parabolic_tangent(from, a, b);
2700    let end_tangent = parabolic_tangent(end_point, a, b);
2701
2702    exec_state
2703        .batch_modeling_cmd(
2704            ModelingCmdMeta::from_args_id(exec_state, &args, id),
2705            ModelingCmd::from(
2706                mcmd::ExtendPath::builder()
2707                    .path(sketch.id.into())
2708                    .segment(PathSegment::ConicTo {
2709                        start_tangent: KPoint2d::from(untyped_point_to_mm(start_tangent, from.units)).map(LengthUnit),
2710                        end_tangent: KPoint2d::from(untyped_point_to_mm(end_tangent, from.units)).map(LengthUnit),
2711                        end: KPoint2d::from(untyped_point_to_mm(end, from.units)).map(LengthUnit),
2712                        interior: KPoint2d::from(untyped_point_to_mm(interior, from.units)).map(LengthUnit),
2713                        relative,
2714                    })
2715                    .build(),
2716            ),
2717        )
2718        .await?;
2719
2720    let current_path = Path::Conic {
2721        base: BasePath {
2722            from: from.ignore_units(),
2723            to: end,
2724            tag: tag.clone(),
2725            units: sketch.units,
2726            geo_meta: GeoMeta {
2727                id,
2728                metadata: args.source_range.into(),
2729            },
2730        },
2731    };
2732
2733    let mut new_sketch = sketch;
2734    if let Some(tag) = &tag {
2735        new_sketch.add_tag(tag, &current_path, exec_state, None);
2736    }
2737
2738    new_sketch.paths.push(current_path);
2739
2740    Ok(new_sketch)
2741}
2742
2743fn conic_tangent(coefficients: [f64; 6], point: [f64; 2]) -> [f64; 2] {
2744    let [a, b, c, d, e, _] = coefficients;
2745
2746    (
2747        c * point[0] + 2.0 * b * point[1] + e,
2748        -(2.0 * a * point[0] + c * point[1] + d),
2749    )
2750        .into()
2751}
2752
2753/// Draw a conic section
2754pub async fn conic(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
2755    let sketch = args.get_unlabeled_kw_arg("sketch", &RuntimeType::Primitive(PrimitiveType::Sketch), exec_state)?;
2756
2757    let start_tangent = args.get_kw_arg_opt("startTangent", &RuntimeType::point2d(), exec_state)?;
2758    let end_tangent = args.get_kw_arg_opt("endTangent", &RuntimeType::point2d(), exec_state)?;
2759    let end = args.get_kw_arg_opt("end", &RuntimeType::point2d(), exec_state)?;
2760    let interior = args.get_kw_arg_opt("interior", &RuntimeType::point2d(), exec_state)?;
2761    let end_absolute = args.get_kw_arg_opt("endAbsolute", &RuntimeType::point2d(), exec_state)?;
2762    let interior_absolute = args.get_kw_arg_opt("interiorAbsolute", &RuntimeType::point2d(), exec_state)?;
2763    let coefficients = args.get_kw_arg_opt(
2764        "coefficients",
2765        &RuntimeType::Array(Box::new(RuntimeType::num_any()), ArrayLen::Known(6)),
2766        exec_state,
2767    )?;
2768    let tag = args.get_kw_arg_opt("tag", &RuntimeType::tag_decl(), exec_state)?;
2769
2770    let new_sketch = inner_conic(
2771        sketch,
2772        start_tangent,
2773        end,
2774        end_tangent,
2775        interior,
2776        coefficients,
2777        interior_absolute,
2778        end_absolute,
2779        tag,
2780        exec_state,
2781        args,
2782    )
2783    .await?;
2784    Ok(KclValue::Sketch {
2785        value: Box::new(new_sketch),
2786    })
2787}
2788
2789#[allow(clippy::too_many_arguments)]
2790pub(crate) async fn inner_conic(
2791    sketch: Sketch,
2792    start_tangent: Option<[TyF64; 2]>,
2793    end: Option<[TyF64; 2]>,
2794    end_tangent: Option<[TyF64; 2]>,
2795    interior: Option<[TyF64; 2]>,
2796    coefficients: Option<[TyF64; 6]>,
2797    interior_absolute: Option<[TyF64; 2]>,
2798    end_absolute: Option<[TyF64; 2]>,
2799    tag: Option<TagNode>,
2800    exec_state: &mut ExecState,
2801    args: Args,
2802) -> Result<Sketch, KclError> {
2803    let from: Point2d = sketch.current_pen_position()?;
2804    let id = exec_state.next_uuid();
2805
2806    if (coefficients.is_some() && (start_tangent.is_some() || end_tangent.is_some()))
2807        || (coefficients.is_none() && (start_tangent.is_none() && end_tangent.is_none()))
2808    {
2809        return Err(KclError::Type {
2810            details: KclErrorDetails::new(
2811                "Invalid combination of arguments. Either provide coefficients or (startTangent, endTangent)"
2812                    .to_owned(),
2813                vec![args.source_range],
2814            ),
2815        });
2816    }
2817
2818    let (interior, end, relative) = match (interior, end, interior_absolute, end_absolute) {
2819        (Some(interior), Some(end), None, None) => (interior, end, true),
2820        (None, None, Some(interior_absolute), Some(end_absolute)) => (interior_absolute, end_absolute, false),
2821        _ => return Err(KclError::Type {
2822            details: KclErrorDetails::new(
2823                "Invalid combination of arguments. Either provide (end, interior) or (endAbsolute, interiorAbsolute)"
2824                    .to_owned(),
2825                vec![args.source_range],
2826            ),
2827        }),
2828    };
2829
2830    let end = point_to_len_unit(end, from.units);
2831    let interior = point_to_len_unit(interior, from.units);
2832
2833    let (start_tangent, end_tangent) = if let Some(coeffs) = coefficients {
2834        let (coeffs, _) = untype_array(coeffs);
2835        (conic_tangent(coeffs, [from.x, from.y]), conic_tangent(coeffs, end))
2836    } else {
2837        let start = if let Some(start_tangent) = start_tangent {
2838            point_to_len_unit(start_tangent, from.units)
2839        } else {
2840            let previous_point = sketch
2841                .get_tangential_info_from_paths()
2842                .tan_previous_point(from.ignore_units());
2843            let from = from.ignore_units();
2844            [from[0] - previous_point[0], from[1] - previous_point[1]]
2845        };
2846
2847        let Some(end_tangent) = end_tangent else {
2848            return Err(KclError::new_semantic(KclErrorDetails::new(
2849                "You must either provide either `coefficients` or `endTangent`.".to_owned(),
2850                vec![args.source_range],
2851            )));
2852        };
2853        let end_tan = point_to_len_unit(end_tangent, from.units);
2854        (start, end_tan)
2855    };
2856
2857    exec_state
2858        .batch_modeling_cmd(
2859            ModelingCmdMeta::from_args_id(exec_state, &args, id),
2860            ModelingCmd::from(
2861                mcmd::ExtendPath::builder()
2862                    .path(sketch.id.into())
2863                    .segment(PathSegment::ConicTo {
2864                        start_tangent: KPoint2d::from(untyped_point_to_mm(start_tangent, from.units)).map(LengthUnit),
2865                        end_tangent: KPoint2d::from(untyped_point_to_mm(end_tangent, from.units)).map(LengthUnit),
2866                        end: KPoint2d::from(untyped_point_to_mm(end, from.units)).map(LengthUnit),
2867                        interior: KPoint2d::from(untyped_point_to_mm(interior, from.units)).map(LengthUnit),
2868                        relative,
2869                    })
2870                    .build(),
2871            ),
2872        )
2873        .await?;
2874
2875    let current_path = Path::Conic {
2876        base: BasePath {
2877            from: from.ignore_units(),
2878            to: end,
2879            tag: tag.clone(),
2880            units: sketch.units,
2881            geo_meta: GeoMeta {
2882                id,
2883                metadata: args.source_range.into(),
2884            },
2885        },
2886    };
2887
2888    let mut new_sketch = sketch;
2889    if let Some(tag) = &tag {
2890        new_sketch.add_tag(tag, &current_path, exec_state, None);
2891    }
2892
2893    new_sketch.paths.push(current_path);
2894
2895    Ok(new_sketch)
2896}
2897#[cfg(test)]
2898mod tests {
2899
2900    use pretty_assertions::assert_eq;
2901
2902    use crate::execution::TagIdentifier;
2903    use crate::std::sketch::PlaneData;
2904    use crate::std::utils::calculate_circle_center;
2905
2906    #[test]
2907    fn test_deserialize_plane_data() {
2908        let data = PlaneData::XY;
2909        let mut str_json = serde_json::to_string(&data).unwrap();
2910        assert_eq!(str_json, "\"XY\"");
2911
2912        str_json = "\"YZ\"".to_string();
2913        let data: PlaneData = serde_json::from_str(&str_json).unwrap();
2914        assert_eq!(data, PlaneData::YZ);
2915
2916        str_json = "\"-YZ\"".to_string();
2917        let data: PlaneData = serde_json::from_str(&str_json).unwrap();
2918        assert_eq!(data, PlaneData::NegYZ);
2919
2920        str_json = "\"-xz\"".to_string();
2921        let data: PlaneData = serde_json::from_str(&str_json).unwrap();
2922        assert_eq!(data, PlaneData::NegXZ);
2923    }
2924
2925    #[test]
2926    fn test_deserialize_sketch_on_face_tag() {
2927        let data = "start";
2928        let mut str_json = serde_json::to_string(&data).unwrap();
2929        assert_eq!(str_json, "\"start\"");
2930
2931        str_json = "\"end\"".to_string();
2932        let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2933        assert_eq!(
2934            data,
2935            crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::End)
2936        );
2937
2938        str_json = serde_json::to_string(&TagIdentifier {
2939            value: "thing".to_string(),
2940            info: Vec::new(),
2941            meta: Default::default(),
2942        })
2943        .unwrap();
2944        let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2945        assert_eq!(
2946            data,
2947            crate::std::sketch::FaceTag::Tag(Box::new(TagIdentifier {
2948                value: "thing".to_string(),
2949                info: Vec::new(),
2950                meta: Default::default()
2951            }))
2952        );
2953
2954        str_json = "\"END\"".to_string();
2955        let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2956        assert_eq!(
2957            data,
2958            crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::End)
2959        );
2960
2961        str_json = "\"start\"".to_string();
2962        let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2963        assert_eq!(
2964            data,
2965            crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::Start)
2966        );
2967
2968        str_json = "\"START\"".to_string();
2969        let data: crate::std::sketch::FaceTag = serde_json::from_str(&str_json).unwrap();
2970        assert_eq!(
2971            data,
2972            crate::std::sketch::FaceTag::StartOrEnd(crate::std::sketch::StartOrEnd::Start)
2973        );
2974    }
2975
2976    #[test]
2977    fn test_circle_center() {
2978        let actual = calculate_circle_center([0.0, 0.0], [5.0, 5.0], [10.0, 0.0]);
2979        assert_eq!(actual[0], 5.0);
2980        assert_eq!(actual[1], 0.0);
2981    }
2982}