Skip to main content

kcl_lib/execution/
geometry.rs

1use std::f64::consts::TAU;
2use std::ops::Add;
3use std::ops::AddAssign;
4use std::ops::Mul;
5use std::ops::Sub;
6use std::ops::SubAssign;
7use std::sync::Arc;
8
9use anyhow::Result;
10use indexmap::IndexMap;
11use kcl_api::UnitLength;
12use kcl_error::SourceRange;
13use kittycad_modeling_cmds::ModelingCmd;
14use kittycad_modeling_cmds::each_cmd as mcmd;
15use kittycad_modeling_cmds::length_unit::LengthUnit;
16use kittycad_modeling_cmds::websocket::ModelingCmdReq;
17use kittycad_modeling_cmds::{self as kcmc};
18use parse_display::Display;
19use parse_display::FromStr;
20use serde::Deserialize;
21use serde::Serialize;
22use uuid::Uuid;
23
24use crate::NodePath;
25use crate::engine::DEFAULT_PLANE_INFO;
26use crate::engine::PlaneName;
27use crate::errors::KclError;
28use crate::errors::KclErrorDetails;
29use crate::exec::KclValue;
30use crate::execution::ArtifactId;
31use crate::execution::ExecState;
32use crate::execution::ExecutorContext;
33use crate::execution::Metadata;
34use crate::execution::TagEngineInfo;
35use crate::execution::TagIdentifier;
36use crate::execution::normalize_to_solver_distance_unit;
37use crate::execution::types::NumericType;
38use crate::execution::types::NumericTypeExt;
39use crate::execution::types::adjust_length;
40use crate::front::ArcCtor;
41use crate::front::ArcDirection;
42use crate::front::CircleCtor;
43use crate::front::ControlPointSplineCtor;
44use crate::front::Freedom;
45use crate::front::LineCtor;
46use crate::front::Number;
47use crate::front::ObjectId;
48use crate::front::Point2d as ApiPoint2d;
49use crate::front::PointCtor;
50use crate::parsing::ast::types::Node;
51use crate::parsing::ast::types::NodeRef;
52use crate::parsing::ast::types::TagDeclarator;
53use crate::parsing::ast::types::TagNode;
54use crate::std::Args;
55use crate::std::args::TyF64;
56use crate::std::edge::UnresolvedEdgeSpecifier;
57use crate::std::sketch::FaceTag;
58use crate::std::sketch::PlaneData;
59use crate::util::MathExt;
60
61type Point3D = kcmc::shared::Point3d<f64>;
62
63/// A GD&T annotation.
64#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
65#[ts(export)]
66#[serde(tag = "type", rename_all = "camelCase")]
67pub struct GdtAnnotation {
68    /// The engine ID.
69    pub id: uuid::Uuid,
70    #[serde(skip)]
71    pub meta: Vec<Metadata>,
72}
73
74/// A geometry.
75#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
76#[ts(export)]
77#[serde(tag = "type")]
78#[allow(clippy::large_enum_variant)]
79pub enum Geometry {
80    Sketch(Sketch),
81    Solid(Solid),
82}
83
84impl Geometry {
85    pub fn id(&self) -> uuid::Uuid {
86        match self {
87            Geometry::Sketch(s) => s.id,
88            Geometry::Solid(e) => e.id,
89        }
90    }
91
92    /// Return the topology root to target when a pattern requests its
93    /// original geometry.
94    pub fn pattern_source_id(&self) -> uuid::Uuid {
95        match self {
96            Geometry::Sketch(s) => s.original_id,
97            Geometry::Solid(e) => e.topology_id(),
98        }
99    }
100}
101
102/// A geometry including an imported geometry.
103#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
104#[ts(export)]
105#[serde(tag = "type")]
106#[allow(clippy::large_enum_variant)]
107pub enum GeometryWithImportedGeometry {
108    Sketch(Sketch),
109    Solid(Solid),
110    ImportedGeometry(Box<ImportedGeometry>),
111}
112
113impl GeometryWithImportedGeometry {
114    pub async fn id(&mut self, ctx: &ExecutorContext) -> Result<uuid::Uuid, KclError> {
115        match self {
116            GeometryWithImportedGeometry::Sketch(s) => Ok(s.id),
117            GeometryWithImportedGeometry::Solid(e) => Ok(e.id),
118            GeometryWithImportedGeometry::ImportedGeometry(i) => {
119                let id = i.id(ctx).await?;
120                Ok(id)
121            }
122        }
123    }
124
125    pub fn into_solid(self) -> Option<Solid> {
126        match self {
127            GeometryWithImportedGeometry::Sketch(_) => None,
128            GeometryWithImportedGeometry::Solid(solid) => Some(solid),
129            GeometryWithImportedGeometry::ImportedGeometry(_) => None,
130        }
131    }
132}
133
134/// A set of geometry.
135#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
136#[ts(export)]
137#[serde(tag = "type")]
138#[allow(clippy::vec_box)]
139pub enum Geometries {
140    Sketches(Vec<Sketch>),
141    Solids(Vec<Solid>),
142}
143
144impl From<Geometry> for Geometries {
145    fn from(value: Geometry) -> Self {
146        match value {
147            Geometry::Sketch(x) => Self::Sketches(vec![x]),
148            Geometry::Solid(x) => Self::Solids(vec![x]),
149        }
150    }
151}
152
153/// Data for an imported geometry.
154#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
155#[ts(export)]
156#[serde(rename_all = "camelCase")]
157pub struct ImportedGeometry {
158    /// The ID of the imported geometry.
159    pub id: uuid::Uuid,
160    /// The original file paths.
161    pub value: Vec<String>,
162    #[serde(skip)]
163    pub meta: Vec<Metadata>,
164    /// If the imported geometry has completed.
165    #[serde(skip)]
166    completed: bool,
167}
168
169impl ImportedGeometry {
170    pub fn new(id: uuid::Uuid, value: Vec<String>, meta: Vec<Metadata>) -> Self {
171        Self {
172            id,
173            value,
174            meta,
175            completed: false,
176        }
177    }
178
179    async fn wait_for_finish(&mut self, ctx: &ExecutorContext) -> Result<(), KclError> {
180        if self.completed {
181            return Ok(());
182        }
183
184        ctx.engine
185            .ensure_async_command_completed(self.id, self.meta.first().map(|m| m.source_range))
186            .await?;
187
188        self.completed = true;
189
190        Ok(())
191    }
192
193    pub async fn id(&mut self, ctx: &ExecutorContext) -> Result<uuid::Uuid, KclError> {
194        if !self.completed {
195            self.wait_for_finish(ctx).await?;
196        }
197
198        Ok(self.id)
199    }
200}
201
202/// Data for geometry that can be hidden.
203#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
204#[ts(export)]
205#[serde(tag = "type", rename_all = "camelCase")]
206#[allow(clippy::vec_box)]
207pub enum HideableGeometry {
208    ImportedGeometry(Box<ImportedGeometry>),
209    SolidSet(Vec<Solid>),
210    PlaneSet(Vec<Plane>),
211    SketchSet(Vec<Sketch>),
212    HelixSet(Vec<Helix>),
213    GdtAnnotationSet(Vec<GdtAnnotation>),
214}
215
216impl From<HideableGeometry> for crate::execution::KclValue {
217    fn from(value: HideableGeometry) -> Self {
218        match value {
219            HideableGeometry::ImportedGeometry(s) => crate::execution::KclValue::ImportedGeometry(*s),
220            HideableGeometry::PlaneSet(mut s) => {
221                if s.len() == 1
222                    && let Some(s) = s.pop()
223                {
224                    crate::execution::KclValue::Plane { value: Box::new(s) }
225                } else {
226                    crate::execution::KclValue::HomArray {
227                        value: s
228                            .into_iter()
229                            .map(|s| crate::execution::KclValue::Plane { value: Box::new(s) })
230                            .collect(),
231                        ty: crate::execution::types::RuntimeType::plane(),
232                    }
233                }
234            }
235            HideableGeometry::SolidSet(mut s) => {
236                if s.len() == 1
237                    && let Some(s) = s.pop()
238                {
239                    crate::execution::KclValue::Solid { value: Box::new(s) }
240                } else {
241                    crate::execution::KclValue::HomArray {
242                        value: s
243                            .into_iter()
244                            .map(|s| crate::execution::KclValue::Solid { value: Box::new(s) })
245                            .collect(),
246                        ty: crate::execution::types::RuntimeType::solid(),
247                    }
248                }
249            }
250            HideableGeometry::GdtAnnotationSet(mut s) => {
251                if s.len() == 1
252                    && let Some(s) = s.pop()
253                {
254                    crate::execution::KclValue::GdtAnnotation { value: Box::new(s) }
255                } else {
256                    crate::execution::KclValue::HomArray {
257                        value: s
258                            .into_iter()
259                            .map(|s| crate::execution::KclValue::GdtAnnotation { value: Box::new(s) })
260                            .collect(),
261                        ty: crate::execution::types::RuntimeType::gdt(),
262                    }
263                }
264            }
265            HideableGeometry::SketchSet(mut s) => {
266                if s.len() == 1
267                    && let Some(s) = s.pop()
268                {
269                    crate::execution::KclValue::Sketch { value: Box::new(s) }
270                } else {
271                    crate::execution::KclValue::HomArray {
272                        value: s
273                            .into_iter()
274                            .map(|s| crate::execution::KclValue::Sketch { value: Box::new(s) })
275                            .collect(),
276                        ty: crate::execution::types::RuntimeType::sketch(),
277                    }
278                }
279            }
280            HideableGeometry::HelixSet(mut s) => {
281                if s.len() == 1
282                    && let Some(s) = s.pop()
283                {
284                    crate::execution::KclValue::Helix { value: Box::new(s) }
285                } else {
286                    crate::execution::KclValue::HomArray {
287                        value: s
288                            .into_iter()
289                            .map(|s| crate::execution::KclValue::Helix { value: Box::new(s) })
290                            .collect(),
291                        ty: crate::execution::types::RuntimeType::helices(),
292                    }
293                }
294            }
295        }
296    }
297}
298
299impl HideableGeometry {
300    pub(crate) async fn ids(&mut self, ctx: &ExecutorContext) -> Result<Vec<uuid::Uuid>, KclError> {
301        match self {
302            HideableGeometry::ImportedGeometry(s) => {
303                let id = s.id(ctx).await?;
304
305                Ok(vec![id])
306            }
307            HideableGeometry::PlaneSet(s) => Ok(s.iter().map(|s| s.id).collect()),
308            HideableGeometry::SolidSet(s) => Ok(s.iter().map(|s| s.id).collect()),
309            HideableGeometry::GdtAnnotationSet(s) => Ok(s.iter().map(|s| s.id).collect()),
310            HideableGeometry::SketchSet(s) => Ok(s.iter().map(|s| s.id).collect()),
311            HideableGeometry::HelixSet(s) => Ok(s.iter().map(|s| s.value).collect()),
312        }
313    }
314}
315
316/// Data for a solid, sketch, or an imported geometry.
317#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
318#[ts(export)]
319#[serde(tag = "type", rename_all = "camelCase")]
320#[allow(clippy::vec_box)]
321pub enum SolidOrSketchOrImportedGeometry {
322    ImportedGeometry(Box<ImportedGeometry>),
323    SolidSet(Vec<Solid>),
324    SketchSet(Vec<Sketch>),
325    HelixSet(Vec<Helix>),
326}
327
328impl From<SolidOrSketchOrImportedGeometry> for crate::execution::KclValue {
329    fn from(value: SolidOrSketchOrImportedGeometry) -> Self {
330        match value {
331            SolidOrSketchOrImportedGeometry::ImportedGeometry(s) => crate::execution::KclValue::ImportedGeometry(*s),
332            SolidOrSketchOrImportedGeometry::SolidSet(mut s) => {
333                if s.len() == 1
334                    && let Some(s) = s.pop()
335                {
336                    crate::execution::KclValue::Solid { value: Box::new(s) }
337                } else {
338                    crate::execution::KclValue::HomArray {
339                        value: s
340                            .into_iter()
341                            .map(|s| crate::execution::KclValue::Solid { value: Box::new(s) })
342                            .collect(),
343                        ty: crate::execution::types::RuntimeType::solid(),
344                    }
345                }
346            }
347            SolidOrSketchOrImportedGeometry::SketchSet(mut s) => {
348                if s.len() == 1
349                    && let Some(s) = s.pop()
350                {
351                    crate::execution::KclValue::Sketch { value: Box::new(s) }
352                } else {
353                    crate::execution::KclValue::HomArray {
354                        value: s
355                            .into_iter()
356                            .map(|s| crate::execution::KclValue::Sketch { value: Box::new(s) })
357                            .collect(),
358                        ty: crate::execution::types::RuntimeType::sketch(),
359                    }
360                }
361            }
362            SolidOrSketchOrImportedGeometry::HelixSet(mut s) => {
363                if s.len() == 1
364                    && let Some(s) = s.pop()
365                {
366                    crate::execution::KclValue::Helix { value: Box::new(s) }
367                } else {
368                    crate::execution::KclValue::HomArray {
369                        value: s
370                            .into_iter()
371                            .map(|s| crate::execution::KclValue::Helix { value: Box::new(s) })
372                            .collect(),
373                        ty: crate::execution::types::RuntimeType::helices(),
374                    }
375                }
376            }
377        }
378    }
379}
380
381impl SolidOrSketchOrImportedGeometry {
382    pub(crate) async fn ids(&mut self, ctx: &ExecutorContext) -> Result<Vec<uuid::Uuid>, KclError> {
383        match self {
384            SolidOrSketchOrImportedGeometry::ImportedGeometry(s) => {
385                let id = s.id(ctx).await?;
386
387                Ok(vec![id])
388            }
389            SolidOrSketchOrImportedGeometry::SolidSet(s) => Ok(s.iter().map(|s| s.id).collect()),
390            SolidOrSketchOrImportedGeometry::SketchSet(s) => Ok(s.iter().map(|s| s.id).collect()),
391            SolidOrSketchOrImportedGeometry::HelixSet(s) => Ok(s.iter().map(|s| s.value).collect()),
392        }
393    }
394}
395
396/// Data for a solid or an imported geometry.
397#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
398#[ts(export)]
399#[serde(tag = "type", rename_all = "camelCase")]
400#[allow(clippy::vec_box)]
401pub enum SolidOrImportedGeometry {
402    ImportedGeometry(Box<ImportedGeometry>),
403    SolidSet(Vec<Solid>),
404}
405
406impl From<SolidOrImportedGeometry> for crate::execution::KclValue {
407    fn from(value: SolidOrImportedGeometry) -> Self {
408        match value {
409            SolidOrImportedGeometry::ImportedGeometry(s) => crate::execution::KclValue::ImportedGeometry(*s),
410            SolidOrImportedGeometry::SolidSet(mut s) => {
411                if s.len() == 1
412                    && let Some(s) = s.pop()
413                {
414                    crate::execution::KclValue::Solid { value: Box::new(s) }
415                } else {
416                    crate::execution::KclValue::HomArray {
417                        value: s
418                            .into_iter()
419                            .map(|s| crate::execution::KclValue::Solid { value: Box::new(s) })
420                            .collect(),
421                        ty: crate::execution::types::RuntimeType::solid(),
422                    }
423                }
424            }
425        }
426    }
427}
428
429/// Something that you can change the color of.
430#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
431#[ts(export)]
432#[serde(tag = "type", rename_all = "camelCase")]
433#[allow(clippy::vec_box)]
434pub enum HasAppearance {
435    ImportedGeometry(Box<ImportedGeometry>),
436    SolidSet(Vec<Solid>),
437    Plane(Box<Plane>),
438}
439
440impl From<HasAppearance> for KclValue {
441    fn from(value: HasAppearance) -> Self {
442        match value {
443            HasAppearance::Plane(p) => KclValue::Plane { value: p },
444            HasAppearance::ImportedGeometry(s) => KclValue::ImportedGeometry(*s),
445            HasAppearance::SolidSet(mut s) => {
446                if s.len() == 1
447                    && let Some(s) = s.pop()
448                {
449                    KclValue::Solid { value: Box::new(s) }
450                } else {
451                    KclValue::HomArray {
452                        value: s.into_iter().map(|s| KclValue::Solid { value: Box::new(s) }).collect(),
453                        ty: crate::execution::types::RuntimeType::solid(),
454                    }
455                }
456            }
457        }
458    }
459}
460
461impl HasAppearance {
462    pub(crate) async fn ids(&mut self, ctx: &ExecutorContext) -> Result<Vec<uuid::Uuid>, KclError> {
463        match self {
464            HasAppearance::Plane(p) => Ok(vec![p.id]),
465            HasAppearance::ImportedGeometry(s) => {
466                let id = s.id(ctx).await?;
467
468                Ok(vec![id])
469            }
470            HasAppearance::SolidSet(s) => Ok(s.iter().map(|s| s.id).collect()),
471        }
472    }
473}
474
475/// A helix.
476#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
477#[ts(export)]
478#[serde(rename_all = "camelCase")]
479pub struct Helix {
480    /// The id of the helix.
481    pub value: uuid::Uuid,
482    /// The artifact ID.
483    pub artifact_id: ArtifactId,
484    /// Number of revolutions.
485    pub revolutions: f64,
486    /// Start angle (in degrees).
487    pub angle_start: f64,
488    /// Is the helix rotation counter clockwise?
489    pub ccw: bool,
490    /// The cylinder the helix was created on.
491    pub cylinder_id: Option<uuid::Uuid>,
492    pub units: UnitLength,
493    #[serde(skip)]
494    pub meta: Vec<Metadata>,
495}
496
497#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
498#[ts(export)]
499#[serde(rename_all = "camelCase")]
500pub struct Plane {
501    /// The id of the plane.
502    pub id: uuid::Uuid,
503    /// The artifact ID.
504    pub artifact_id: ArtifactId,
505    /// The scene object ID. If this is None, then the plane has not been
506    /// sent to the engine yet. It must be sent before it is used.
507    #[serde(skip_serializing_if = "Option::is_none")]
508    pub object_id: Option<ObjectId>,
509    /// The kind of plane or custom.
510    pub kind: PlaneKind,
511    /// The information for the plane.
512    #[serde(flatten)]
513    pub info: PlaneInfo,
514    #[serde(skip)]
515    pub meta: Vec<Metadata>,
516}
517
518#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ts_rs::TS)]
519#[ts(export)]
520#[serde(rename_all = "camelCase")]
521pub struct PlaneInfo {
522    /// Origin of the plane.
523    pub origin: Point3d,
524    /// What should the plane's X axis be?
525    pub x_axis: Point3d,
526    /// What should the plane's Y axis be?
527    pub y_axis: Point3d,
528    /// What should the plane's Z axis be?
529    pub z_axis: Point3d,
530}
531
532impl PlaneInfo {
533    pub(crate) fn into_plane_data(self) -> PlaneData {
534        if self.origin.is_zero() {
535            match self {
536                Self {
537                    origin:
538                        Point3d {
539                            x: 0.0,
540                            y: 0.0,
541                            z: 0.0,
542                            units: Some(UnitLength::Millimeters),
543                        },
544                    x_axis:
545                        Point3d {
546                            x: 1.0,
547                            y: 0.0,
548                            z: 0.0,
549                            units: _,
550                        },
551                    y_axis:
552                        Point3d {
553                            x: 0.0,
554                            y: 1.0,
555                            z: 0.0,
556                            units: _,
557                        },
558                    z_axis: _,
559                } => return PlaneData::XY,
560                Self {
561                    origin:
562                        Point3d {
563                            x: 0.0,
564                            y: 0.0,
565                            z: 0.0,
566                            units: Some(UnitLength::Millimeters),
567                        },
568                    x_axis:
569                        Point3d {
570                            x: -1.0,
571                            y: 0.0,
572                            z: 0.0,
573                            units: _,
574                        },
575                    y_axis:
576                        Point3d {
577                            x: 0.0,
578                            y: 1.0,
579                            z: 0.0,
580                            units: _,
581                        },
582                    z_axis: _,
583                } => return PlaneData::NegXY,
584                Self {
585                    origin:
586                        Point3d {
587                            x: 0.0,
588                            y: 0.0,
589                            z: 0.0,
590                            units: Some(UnitLength::Millimeters),
591                        },
592                    x_axis:
593                        Point3d {
594                            x: 1.0,
595                            y: 0.0,
596                            z: 0.0,
597                            units: _,
598                        },
599                    y_axis:
600                        Point3d {
601                            x: 0.0,
602                            y: 0.0,
603                            z: 1.0,
604                            units: _,
605                        },
606                    z_axis: _,
607                } => return PlaneData::XZ,
608                Self {
609                    origin:
610                        Point3d {
611                            x: 0.0,
612                            y: 0.0,
613                            z: 0.0,
614                            units: Some(UnitLength::Millimeters),
615                        },
616                    x_axis:
617                        Point3d {
618                            x: -1.0,
619                            y: 0.0,
620                            z: 0.0,
621                            units: _,
622                        },
623                    y_axis:
624                        Point3d {
625                            x: 0.0,
626                            y: 0.0,
627                            z: 1.0,
628                            units: _,
629                        },
630                    z_axis: _,
631                } => return PlaneData::NegXZ,
632                Self {
633                    origin:
634                        Point3d {
635                            x: 0.0,
636                            y: 0.0,
637                            z: 0.0,
638                            units: Some(UnitLength::Millimeters),
639                        },
640                    x_axis:
641                        Point3d {
642                            x: 0.0,
643                            y: 1.0,
644                            z: 0.0,
645                            units: _,
646                        },
647                    y_axis:
648                        Point3d {
649                            x: 0.0,
650                            y: 0.0,
651                            z: 1.0,
652                            units: _,
653                        },
654                    z_axis: _,
655                } => return PlaneData::YZ,
656                Self {
657                    origin:
658                        Point3d {
659                            x: 0.0,
660                            y: 0.0,
661                            z: 0.0,
662                            units: Some(UnitLength::Millimeters),
663                        },
664                    x_axis:
665                        Point3d {
666                            x: 0.0,
667                            y: -1.0,
668                            z: 0.0,
669                            units: _,
670                        },
671                    y_axis:
672                        Point3d {
673                            x: 0.0,
674                            y: 0.0,
675                            z: 1.0,
676                            units: _,
677                        },
678                    z_axis: _,
679                } => return PlaneData::NegYZ,
680                _ => {}
681            }
682        }
683
684        PlaneData::Plane(Self {
685            origin: self.origin,
686            x_axis: self.x_axis,
687            y_axis: self.y_axis,
688            z_axis: self.z_axis,
689        })
690    }
691
692    pub(crate) fn is_right_handed(&self) -> bool {
693        // Katie's formula:
694        // dot(cross(x, y), z) ~= sqrt(dot(x, x) * dot(y, y) * dot(z, z))
695        let lhs = self
696            .x_axis
697            .axes_cross_product(&self.y_axis)
698            .axes_dot_product(&self.z_axis);
699        let rhs_x = self.x_axis.axes_dot_product(&self.x_axis);
700        let rhs_y = self.y_axis.axes_dot_product(&self.y_axis);
701        let rhs_z = self.z_axis.axes_dot_product(&self.z_axis);
702        let rhs = (rhs_x * rhs_y * rhs_z).sqrt();
703        // Check LHS ~= RHS
704        (lhs - rhs).abs() <= 0.0001
705    }
706
707    #[cfg(test)]
708    pub(crate) fn is_left_handed(&self) -> bool {
709        !self.is_right_handed()
710    }
711
712    pub(crate) fn make_right_handed(self) -> Self {
713        if self.is_right_handed() {
714            return self;
715        }
716        // To make it right-handed, negate X, i.e. rotate the plane 180 degrees.
717        Self {
718            origin: self.origin,
719            x_axis: self.x_axis.negated(),
720            y_axis: self.y_axis,
721            z_axis: self.z_axis,
722        }
723    }
724}
725
726impl TryFrom<PlaneData> for PlaneInfo {
727    type Error = KclError;
728
729    fn try_from(value: PlaneData) -> Result<Self, Self::Error> {
730        let name = match value {
731            PlaneData::XY => PlaneName::Xy,
732            PlaneData::NegXY => PlaneName::NegXy,
733            PlaneData::XZ => PlaneName::Xz,
734            PlaneData::NegXZ => PlaneName::NegXz,
735            PlaneData::YZ => PlaneName::Yz,
736            PlaneData::NegYZ => PlaneName::NegYz,
737            PlaneData::Plane(info) => {
738                return Ok(info);
739            }
740        };
741
742        let info = DEFAULT_PLANE_INFO.get(&name).ok_or_else(|| {
743            KclError::new_internal(KclErrorDetails::new(
744                format!("Plane {name} not found"),
745                Default::default(),
746            ))
747        })?;
748
749        Ok(info.clone())
750    }
751}
752
753impl From<&PlaneData> for PlaneKind {
754    fn from(value: &PlaneData) -> Self {
755        match value {
756            PlaneData::XY => PlaneKind::XY,
757            PlaneData::NegXY => PlaneKind::XY,
758            PlaneData::XZ => PlaneKind::XZ,
759            PlaneData::NegXZ => PlaneKind::XZ,
760            PlaneData::YZ => PlaneKind::YZ,
761            PlaneData::NegYZ => PlaneKind::YZ,
762            PlaneData::Plane(_) => PlaneKind::Custom,
763        }
764    }
765}
766
767impl From<&PlaneInfo> for PlaneKind {
768    fn from(value: &PlaneInfo) -> Self {
769        let data = PlaneData::Plane(value.clone());
770        PlaneKind::from(&data)
771    }
772}
773
774impl From<PlaneInfo> for PlaneKind {
775    fn from(value: PlaneInfo) -> Self {
776        let data = PlaneData::Plane(value);
777        PlaneKind::from(&data)
778    }
779}
780
781impl Plane {
782    #[cfg(test)]
783    pub(crate) fn from_plane_data_skipping_engine(
784        value: PlaneData,
785        exec_state: &mut ExecState,
786    ) -> Result<Self, KclError> {
787        let id = exec_state.next_uuid();
788        let kind = PlaneKind::from(&value);
789        Ok(Plane {
790            id,
791            artifact_id: id.into(),
792            info: PlaneInfo::try_from(value)?,
793            object_id: None,
794            kind,
795            meta: vec![],
796        })
797    }
798
799    /// Returns true if the plane has been sent to the engine.
800    pub fn is_initialized(&self) -> bool {
801        self.object_id.is_some()
802    }
803
804    /// Returns true if the plane has not been sent to the engine yet.
805    pub fn is_uninitialized(&self) -> bool {
806        !self.is_initialized()
807    }
808
809    /// The standard planes are XY, YZ and XZ (in both positive and negative)
810    pub fn is_standard(&self) -> bool {
811        match &self.kind {
812            PlaneKind::XY | PlaneKind::YZ | PlaneKind::XZ => true,
813            PlaneKind::Custom => false,
814        }
815    }
816
817    /// Project a point onto a plane by calculating how far away it is and moving it along the
818    /// normal of the plane so that it now lies on the plane.
819    pub fn project(&self, point: Point3d) -> Point3d {
820        let v = point - self.info.origin;
821        let dot = v.axes_dot_product(&self.info.z_axis);
822
823        point - self.info.z_axis * dot
824    }
825}
826
827/// A face.
828#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
829#[ts(export)]
830#[serde(rename_all = "camelCase")]
831pub struct Face {
832    /// The id of the face.
833    pub id: uuid::Uuid,
834    /// The artifact ID.
835    pub artifact_id: ArtifactId,
836    /// The scene object ID.
837    pub object_id: ObjectId,
838    /// The tag of the face.
839    pub value: String,
840    /// What should the face's X axis be?
841    pub x_axis: Point3d,
842    /// What should the face's Y axis be?
843    pub y_axis: Point3d,
844    /// The solid the face is on.
845    pub parent_solid: FaceParentSolid,
846    pub units: UnitLength,
847    #[serde(skip)]
848    pub meta: Vec<Metadata>,
849}
850
851/// The limited subset of a face's parent solid needed by face-backed sketches.
852#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
853#[ts(export)]
854#[serde(rename_all = "camelCase")]
855pub struct FaceParentSolid {
856    /// Which solid does this face belong to?
857    pub solid_id: Uuid,
858    /// ID of the sketch which created this solid, if any.
859    pub creator_sketch_id: Option<Uuid>,
860    /// Has the creator sketch been closed? This is only relevant if `creator_sketch_id` is Some, and we cannot infer the closed status otherwise.
861    pub creator_sketch_is_closed: Option<ProfileClosed>,
862    /// Pending edge cut IDs that may need to be flushed before referencing the face.
863    #[serde(default, skip_serializing_if = "Vec::is_empty")]
864    pub edge_cut_ids: Vec<Uuid>,
865}
866
867impl FaceParentSolid {
868    pub(crate) fn sketch_or_solid_id(&self) -> Uuid {
869        self.creator_sketch_id.unwrap_or(self.solid_id)
870    }
871}
872
873/// A bounded edge.
874/// Carries either `edge_id` (resolved) or `edge_specifier` (payload passed through for resolution in blend).
875#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
876#[ts(export)]
877#[serde(rename_all = "camelCase")]
878pub struct BoundedEdge {
879    /// The id of the face this edge belongs to.
880    pub face_id: uuid::Uuid,
881    /// The id of the edge (when resolved from a tag or UUID). Mutually exclusive with `edge_specifier`.
882    #[serde(skip_serializing_if = "Option::is_none")]
883    pub edge_id: Option<uuid::Uuid>,
884    /// Edge specifier payload (sideFaces, endFaces, index) when not resolved. Resolved in blend().
885    #[serde(skip_serializing_if = "Option::is_none")]
886    pub edge_specifier: Option<UnresolvedEdgeSpecifier>,
887    /// A percentage bound of the edge, used to restrict what portion of the edge will be used.
888    /// Range (0, 1)
889    pub lower_bound: f32,
890    /// A percentage bound of the edge, used to restrict what portion of the edge will be used.
891    /// Range (0, 1)
892    pub upper_bound: f32,
893}
894
895/// Kind of plane.
896#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, ts_rs::TS, FromStr, Display)]
897#[ts(export)]
898#[display(style = "camelCase")]
899pub enum PlaneKind {
900    #[serde(rename = "XY", alias = "xy")]
901    #[display("XY")]
902    XY,
903    #[serde(rename = "XZ", alias = "xz")]
904    #[display("XZ")]
905    XZ,
906    #[serde(rename = "YZ", alias = "yz")]
907    #[display("YZ")]
908    YZ,
909    /// A custom plane.
910    #[display("Custom")]
911    Custom,
912}
913
914#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
915#[ts(export)]
916#[serde(tag = "type", rename_all = "camelCase")]
917pub struct Sketch {
918    /// The id of the sketch (this will change when the engine's reference to it changes).
919    pub id: uuid::Uuid,
920    /// The paths in the sketch.
921    /// Only paths on the "outside" i.e. the perimeter.
922    /// Does not include paths "inside" the profile (for example, edges made by subtracting a profile)
923    pub paths: Vec<Path>,
924    /// Inner paths, resulting from subtract2d to carve profiles out of the sketch.
925    #[serde(default, skip_serializing_if = "Vec::is_empty")]
926    pub inner_paths: Vec<Path>,
927    /// What the sketch is on (can be a plane or a face).
928    pub on: SketchSurface,
929    /// The starting path.
930    pub start: BasePath,
931    /// Tag identifiers that have been declared in this sketch.
932    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
933    pub tags: IndexMap<String, TagIdentifier>,
934    /// The original id of the sketch. This stays the same even if the sketch is
935    /// is sketched on face etc.
936    pub artifact_id: ArtifactId,
937    #[ts(skip)]
938    pub original_id: uuid::Uuid,
939    /// If this sketch represents a region created from `region()`, the origin
940    /// sketch ID is the ID of the sketch block it was created from. None,
941    /// otherwise. This field corresponds to the `origin_path_id` of the `Path`
942    /// artifact.
943    #[serde(skip_serializing_if = "Option::is_none")]
944    #[ts(skip)]
945    pub origin_sketch_id: Option<uuid::Uuid>,
946    /// If the sketch includes a mirror.
947    #[serde(skip)]
948    pub mirror: Option<uuid::Uuid>,
949    /// If the sketch is a clone of another sketch.
950    #[serde(skip)]
951    pub clone: Option<uuid::Uuid>,
952    /// Synthetic pen-jump paths inserted to replay disconnected segment selections.
953    #[serde(skip)]
954    #[ts(skip)]
955    pub synthetic_jump_path_ids: Vec<uuid::Uuid>,
956    pub units: UnitLength,
957    /// Metadata.
958    #[serde(skip)]
959    pub meta: Vec<Metadata>,
960    /// Has the profile been closed?
961    /// If not given, defaults to yes, closed explicitly.
962    #[serde(
963        default = "ProfileClosed::explicitly",
964        skip_serializing_if = "ProfileClosed::is_explicitly"
965    )]
966    pub is_closed: ProfileClosed,
967}
968
969impl ProfileClosed {
970    #[expect(dead_code, reason = "it's not actually dead, it's called by serde")]
971    fn explicitly() -> Self {
972        Self::Explicitly
973    }
974
975    fn is_explicitly(&self) -> bool {
976        matches!(self, ProfileClosed::Explicitly)
977    }
978}
979
980/// Has the profile been closed?
981#[derive(Debug, Serialize, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd, ts_rs::TS)]
982#[serde(rename_all = "camelCase")]
983pub enum ProfileClosed {
984    /// It's definitely open.
985    No,
986    /// Unknown.
987    Maybe,
988    /// Yes, by adding a segment which loops back to the start.
989    Implicitly,
990    /// Yes, by calling `close()` or by making a closed shape (e.g. circle).
991    Explicitly,
992}
993
994impl Sketch {
995    // Tell the engine to enter sketch mode on the sketch.
996    // Run a specific command, then exit sketch mode.
997    pub(crate) fn build_sketch_mode_cmds(
998        &self,
999        exec_state: &mut ExecState,
1000        inner_cmd: ModelingCmdReq,
1001    ) -> Vec<ModelingCmdReq> {
1002        vec![
1003            // Before we extrude, we need to enable the sketch mode.
1004            // We do this here in case extrude is called out of order.
1005            ModelingCmdReq {
1006                cmd: ModelingCmd::from(
1007                    mcmd::EnableSketchMode::builder()
1008                        .animated(false)
1009                        .ortho(false)
1010                        .entity_id(self.on.id())
1011                        .adjust_camera(false)
1012                        .maybe_planar_normal(if let SketchSurface::Plane(plane) = &self.on {
1013                            // We pass in the normal for the plane here.
1014                            let normal = plane.info.x_axis.axes_cross_product(&plane.info.y_axis);
1015                            Some(normal.into())
1016                        } else {
1017                            None
1018                        })
1019                        .build(),
1020                ),
1021                cmd_id: exec_state.next_uuid().into(),
1022            },
1023            inner_cmd,
1024            ModelingCmdReq {
1025                cmd: ModelingCmd::SketchModeDisable(mcmd::SketchModeDisable::builder().build()),
1026                cmd_id: exec_state.next_uuid().into(),
1027            },
1028        ]
1029    }
1030}
1031
1032/// A sketch type.
1033#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1034#[ts(export)]
1035#[serde(tag = "type", rename_all = "camelCase")]
1036pub enum SketchSurface {
1037    Plane(Box<Plane>),
1038    Face(Box<Face>),
1039}
1040
1041impl SketchSurface {
1042    pub(crate) fn id(&self) -> uuid::Uuid {
1043        match self {
1044            SketchSurface::Plane(plane) => plane.id,
1045            SketchSurface::Face(face) => face.id,
1046        }
1047    }
1048    pub(crate) fn x_axis(&self) -> Point3d {
1049        match self {
1050            SketchSurface::Plane(plane) => plane.info.x_axis,
1051            SketchSurface::Face(face) => face.x_axis,
1052        }
1053    }
1054    pub(crate) fn y_axis(&self) -> Point3d {
1055        match self {
1056            SketchSurface::Plane(plane) => plane.info.y_axis,
1057            SketchSurface::Face(face) => face.y_axis,
1058        }
1059    }
1060
1061    pub(crate) fn object_id(&self) -> Option<ObjectId> {
1062        match self {
1063            SketchSurface::Plane(plane) => plane.object_id,
1064            SketchSurface::Face(face) => Some(face.object_id),
1065        }
1066    }
1067
1068    pub(crate) fn set_object_id(&mut self, object_id: ObjectId) {
1069        match self {
1070            SketchSurface::Plane(plane) => plane.object_id = Some(object_id),
1071            SketchSurface::Face(face) => face.object_id = object_id,
1072        }
1073    }
1074}
1075
1076/// A Sketch, Face, or TaggedFace.
1077#[derive(Debug, Clone, PartialEq)]
1078pub enum Extrudable {
1079    /// Sketch.
1080    Sketch(Box<Sketch>),
1081    /// Tagged Face.
1082    FaceTag(FaceTag),
1083    /// Face.
1084    Face(Box<Face>),
1085    /// Tagged Edge.
1086    EdgeTag(Box<TagIdentifier>),
1087    /// Edge.
1088    Edge(Uuid),
1089    /// Edge specifier payload.
1090    EdgeSpecifier(UnresolvedEdgeSpecifier),
1091}
1092
1093impl Extrudable {
1094    /// Get the relevant id.
1095    pub async fn id_to_extrude(
1096        &self,
1097        exec_state: &mut ExecState,
1098        args: &Args,
1099        must_be_planar: bool,
1100    ) -> Result<uuid::Uuid, KclError> {
1101        match self {
1102            Extrudable::Sketch(sketch) => Ok(sketch.id),
1103            Extrudable::FaceTag(face_tag) => face_tag.get_face_id_from_tag(exec_state, args, must_be_planar).await,
1104            Extrudable::Face(face) => Ok(face.id),
1105            Extrudable::EdgeTag(edge_tag) => match edge_tag.get_cur_info() {
1106                Some(info) => Ok(info.id),
1107                None => Err(KclError::new_type(KclErrorDetails::new(
1108                    "Could not find a valid id to extrude".to_owned(),
1109                    vec![args.source_range],
1110                ))),
1111            },
1112            Extrudable::Edge(edge) => Ok(*edge),
1113            Extrudable::EdgeSpecifier(_) => Err(KclError::new_type(KclErrorDetails::new(
1114                "Could not find a legacy id for edge specifier".to_owned(),
1115                vec![args.source_range],
1116            ))),
1117        }
1118    }
1119
1120    pub fn as_sketch(&self) -> Option<Sketch> {
1121        match self {
1122            Extrudable::Sketch(sketch) => Some((**sketch).clone()),
1123            Extrudable::FaceTag(face) => match face.geometry() {
1124                Some(Geometry::Sketch(sketch)) => Some(sketch),
1125                Some(Geometry::Solid(solid)) => solid.sketch().cloned(),
1126                None => None,
1127            },
1128            Extrudable::Face(_) => None,
1129            Extrudable::EdgeTag(tag_identifier) => match tag_identifier.geometry() {
1130                Some(Geometry::Sketch(sketch)) => Some(sketch),
1131                Some(Geometry::Solid(solid)) => solid.sketch().cloned(),
1132                None => None,
1133            },
1134            Extrudable::Edge(_) => None,
1135            Extrudable::EdgeSpecifier(_) => None,
1136        }
1137    }
1138
1139    pub fn is_closed(&self) -> ProfileClosed {
1140        match self {
1141            Extrudable::Sketch(sketch) => sketch.is_closed,
1142            Extrudable::FaceTag(face_tag) => match face_tag.geometry() {
1143                Some(Geometry::Sketch(sketch)) => sketch.is_closed,
1144                Some(Geometry::Solid(solid)) => solid
1145                    .sketch()
1146                    .map(|sketch| sketch.is_closed)
1147                    .unwrap_or(ProfileClosed::Maybe),
1148                _ => ProfileClosed::Maybe,
1149            },
1150            Extrudable::Face(face) => match face.parent_solid.creator_sketch_is_closed {
1151                Some(is_closed) => is_closed,
1152                None => ProfileClosed::Maybe,
1153            },
1154            Extrudable::EdgeTag(edge_tag) => match edge_tag.geometry() {
1155                Some(Geometry::Sketch(sketch)) => sketch.is_closed,
1156                Some(Geometry::Solid(solid)) => solid
1157                    .sketch()
1158                    .map(|sketch| sketch.is_closed)
1159                    .unwrap_or(ProfileClosed::Maybe),
1160                _ => ProfileClosed::Maybe,
1161            },
1162            Extrudable::Edge(_) => ProfileClosed::Maybe,
1163            Extrudable::EdgeSpecifier(_) => ProfileClosed::Maybe,
1164        }
1165    }
1166}
1167
1168impl From<Sketch> for Extrudable {
1169    fn from(value: Sketch) -> Self {
1170        Extrudable::Sketch(Box::new(value))
1171    }
1172}
1173
1174#[derive(Debug, Clone)]
1175pub(crate) enum GetTangentialInfoFromPathsResult {
1176    PreviousPoint([f64; 2]),
1177    Arc {
1178        center: [f64; 2],
1179        ccw: bool,
1180    },
1181    Circle {
1182        center: [f64; 2],
1183        ccw: bool,
1184        radius: f64,
1185    },
1186    Ellipse {
1187        center: [f64; 2],
1188        ccw: bool,
1189        major_axis: [f64; 2],
1190        _minor_radius: f64,
1191    },
1192}
1193
1194impl GetTangentialInfoFromPathsResult {
1195    pub(crate) fn tan_previous_point(&self, last_arc_end: [f64; 2]) -> [f64; 2] {
1196        match self {
1197            GetTangentialInfoFromPathsResult::PreviousPoint(p) => *p,
1198            GetTangentialInfoFromPathsResult::Arc { center, ccw } => {
1199                crate::std::utils::get_tangent_point_from_previous_arc(*center, *ccw, last_arc_end)
1200            }
1201            // The circle always starts at 0 degrees, so a suitable tangent
1202            // point is either directly above or below.
1203            GetTangentialInfoFromPathsResult::Circle {
1204                center, radius, ccw, ..
1205            } => [center[0] + radius, center[1] + if *ccw { -1.0 } else { 1.0 }],
1206            GetTangentialInfoFromPathsResult::Ellipse {
1207                center,
1208                major_axis,
1209                ccw,
1210                ..
1211            } => [center[0] + major_axis[0], center[1] + if *ccw { -1.0 } else { 1.0 }],
1212        }
1213    }
1214}
1215
1216impl Sketch {
1217    pub(crate) fn add_tag(
1218        &mut self,
1219        tag: NodeRef<'_, TagDeclarator>,
1220        current_path: &Path,
1221        exec_state: &ExecState,
1222        surface: Option<&ExtrudeSurface>,
1223    ) {
1224        let mut tag_identifier: TagIdentifier = tag.into();
1225        let base = current_path.get_base();
1226        let mut sketch_copy = self.clone();
1227        sketch_copy.tags.clear();
1228        tag_identifier.info.push((
1229            exec_state.stack().current_epoch(),
1230            TagEngineInfo {
1231                id: base.geo_meta.id,
1232                geometry: Geometry::Sketch(sketch_copy),
1233                path: Some(current_path.clone()),
1234                surface: surface.cloned(),
1235            },
1236        ));
1237
1238        self.tags.insert(tag.name.to_string(), tag_identifier);
1239    }
1240
1241    pub(crate) fn merge_tags<'a>(&mut self, tags: impl Iterator<Item = &'a TagIdentifier>) {
1242        for t in tags {
1243            match self.tags.get_mut(&t.value) {
1244                Some(id) => {
1245                    id.merge_info(t);
1246                }
1247                None => {
1248                    self.tags.insert(t.value.clone(), t.clone());
1249                }
1250            }
1251        }
1252    }
1253
1254    /// Get the path most recently sketched.
1255    pub(crate) fn latest_path(&self) -> Option<&Path> {
1256        self.paths.last()
1257    }
1258
1259    /// The "pen" is an imaginary pen drawing the path.
1260    /// This gets the current point the pen is hovering over, i.e. the point
1261    /// where the last path segment ends, and the next path segment will begin.
1262    pub(crate) fn current_pen_position(&self) -> Result<Point2d, KclError> {
1263        let Some(path) = self.latest_path() else {
1264            return Ok(Point2d::new(self.start.to[0], self.start.to[1], self.start.units));
1265        };
1266
1267        let to = path.get_base().to;
1268        Ok(Point2d::new(to[0], to[1], path.get_base().units))
1269    }
1270
1271    pub(crate) fn get_tangential_info_from_paths(&self) -> GetTangentialInfoFromPathsResult {
1272        let Some(path) = self.latest_path() else {
1273            return GetTangentialInfoFromPathsResult::PreviousPoint(self.start.to);
1274        };
1275        path.get_tangential_info()
1276    }
1277}
1278
1279#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1280#[ts(export)]
1281#[serde(tag = "type", rename_all = "camelCase")]
1282pub struct Solid {
1283    /// The id of the solid.
1284    pub id: uuid::Uuid,
1285    /// Internal KCL value generation. The engine may reuse `id` for a new value.
1286    #[serde(skip)]
1287    #[ts(skip)]
1288    pub value_id: uuid::Uuid,
1289    /// The engine entity whose children correspond to the topology references
1290    /// stored on this solid. Pattern copies retain their source topology,
1291    /// while consuming operations and clones replace it with their output.
1292    #[serde(skip)]
1293    #[ts(skip)]
1294    pub(crate) topology_id: uuid::Uuid,
1295    /// The semantic body artifact from which a pattern copy was created.
1296    /// Pattern commands replace `artifact_id` with the copy's engine entity
1297    /// ID, so retain this to distinguish Sweep-backed bodies from composites.
1298    #[serde(skip)]
1299    #[ts(skip)]
1300    pub(crate) pattern_source_artifact_id: Option<ArtifactId>,
1301    /// The artifact ID of the solid.  Unlike `id`, this doesn't change.
1302    pub artifact_id: ArtifactId,
1303    /// The extrude surfaces.
1304    pub value: Vec<ExtrudeSurface>,
1305    /// Tag identifiers for the faces of this body, declared via tag arguments
1306    /// (e.g. `tag`, `tagStart`, `tagEnd`) on the call that created it.
1307    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
1308    pub faces: IndexMap<String, TagIdentifier>,
1309    /// How this solid was created.
1310    #[serde(rename = "sketch")]
1311    pub creator: SolidCreator,
1312    /// The id of the extrusion start cap
1313    pub start_cap_id: Option<uuid::Uuid>,
1314    /// The id of the extrusion end cap
1315    pub end_cap_id: Option<uuid::Uuid>,
1316    /// Chamfers or fillets on this solid.
1317    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1318    pub edge_cuts: Vec<EdgeCut>,
1319    /// Batch-end fillet/chamfer command ids that do not have concrete edge ids.
1320    #[serde(skip)]
1321    #[ts(skip)]
1322    pub pending_edge_cut_ids: Vec<uuid::Uuid>,
1323    /// The units of the solid.
1324    pub units: UnitLength,
1325    /// Is this a sectional solid?
1326    pub sectional: bool,
1327    /// Metadata.
1328    #[serde(skip)]
1329    pub meta: Vec<Metadata>,
1330}
1331
1332#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1333#[ts(export)]
1334pub struct CreatorFace {
1335    /// The face id that served as the base.
1336    pub face_id: uuid::Uuid,
1337    /// The solid id that owned the face.
1338    pub solid_id: uuid::Uuid,
1339    /// The sketch used for the operation.
1340    pub sketch: Sketch,
1341}
1342
1343#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1344#[ts(export)]
1345pub struct CreatorEdge {
1346    /// The edge id that served as the base.
1347    pub edge_id: uuid::Uuid,
1348    /// The solid id that owned the edge.
1349    pub body_id: uuid::Uuid,
1350}
1351
1352/// How a solid was created.
1353#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1354#[ts(export)]
1355#[serde(tag = "creatorType", rename_all = "camelCase")]
1356pub enum SolidCreator {
1357    /// Created from a sketch.
1358    Sketch(Sketch),
1359    /// Created by extruding or modifying a face.
1360    Face(CreatorFace),
1361    /// Created by extruding or modifying an edge.
1362    Edge(CreatorEdge),
1363    /// Created procedurally without a sketch.
1364    Procedural,
1365}
1366
1367impl Solid {
1368    pub fn sketch(&self) -> Option<&Sketch> {
1369        match &self.creator {
1370            SolidCreator::Sketch(sketch) => Some(sketch),
1371            SolidCreator::Face(CreatorFace { sketch, .. }) => Some(sketch),
1372            SolidCreator::Edge(_) => None,
1373            SolidCreator::Procedural => None,
1374        }
1375    }
1376
1377    pub fn sketch_mut(&mut self) -> Option<&mut Sketch> {
1378        match &mut self.creator {
1379            SolidCreator::Sketch(sketch) => Some(sketch),
1380            SolidCreator::Face(CreatorFace { sketch, .. }) => Some(sketch),
1381            SolidCreator::Edge(_) => None,
1382            SolidCreator::Procedural => None,
1383        }
1384    }
1385
1386    pub fn sketch_id(&self) -> Option<uuid::Uuid> {
1387        self.sketch().map(|sketch| sketch.id)
1388    }
1389
1390    pub fn original_id(&self) -> uuid::Uuid {
1391        self.sketch().map(|sketch| sketch.original_id).unwrap_or(self.id)
1392    }
1393
1394    pub(crate) fn topology_id(&self) -> uuid::Uuid {
1395        self.topology_id
1396    }
1397
1398    /// Make this solid a brand-new body produced by an operation. It now owns
1399    /// the topology of `engine_id`, and any retained pattern provenance no
1400    /// longer applies.
1401    pub(crate) fn become_new_body(&mut self, engine_id: uuid::Uuid, artifact_id: ArtifactId) {
1402        self.topology_id = engine_id;
1403        self.pattern_source_artifact_id = None;
1404        self.artifact_id = artifact_id;
1405    }
1406
1407    /// Make this solid a pattern copy. It gets a new top-level entity artifact
1408    /// while retaining the source body's topology and semantic artifact
1409    /// provenance.
1410    pub(crate) fn become_pattern_copy(&mut self, copy_engine_id: uuid::Uuid) {
1411        self.pattern_source_artifact_id.get_or_insert(self.artifact_id);
1412        self.artifact_id = ArtifactId::new(copy_engine_id);
1413    }
1414
1415    pub(crate) fn get_all_edge_cut_ids(&self) -> impl Iterator<Item = uuid::Uuid> + '_ {
1416        self.edge_cuts
1417            .iter()
1418            .map(|foc| foc.id())
1419            .chain(self.pending_edge_cut_ids.iter().copied())
1420    }
1421}
1422
1423impl From<&Solid> for FaceParentSolid {
1424    fn from(solid: &Solid) -> Self {
1425        Self {
1426            solid_id: solid.id,
1427            creator_sketch_id: solid.sketch_id(),
1428            creator_sketch_is_closed: solid.sketch().map(|sketch| sketch.is_closed),
1429            edge_cut_ids: solid.get_all_edge_cut_ids().collect(),
1430        }
1431    }
1432}
1433
1434/// A fillet or a chamfer.
1435#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1436#[ts(export)]
1437#[serde(tag = "type", rename_all = "camelCase")]
1438pub enum EdgeCut {
1439    /// A fillet.
1440    Fillet {
1441        /// The id of the engine command that called this fillet.
1442        id: uuid::Uuid,
1443        radius: TyF64,
1444        /// The engine id of the edge to fillet.
1445        #[serde(rename = "edgeId")]
1446        edge_id: uuid::Uuid,
1447        tag: Box<Option<TagNode>>,
1448    },
1449    /// A chamfer.
1450    Chamfer {
1451        /// The id of the engine command that called this chamfer.
1452        id: uuid::Uuid,
1453        length: TyF64,
1454        /// The engine id of the edge to chamfer.
1455        #[serde(rename = "edgeId")]
1456        edge_id: uuid::Uuid,
1457        tag: Box<Option<TagNode>>,
1458    },
1459}
1460
1461impl EdgeCut {
1462    pub fn id(&self) -> uuid::Uuid {
1463        match self {
1464            EdgeCut::Fillet { id, .. } => *id,
1465            EdgeCut::Chamfer { id, .. } => *id,
1466        }
1467    }
1468
1469    pub fn set_id(&mut self, id: uuid::Uuid) {
1470        match self {
1471            EdgeCut::Fillet { id: i, .. } => *i = id,
1472            EdgeCut::Chamfer { id: i, .. } => *i = id,
1473        }
1474    }
1475
1476    pub fn edge_id(&self) -> uuid::Uuid {
1477        match self {
1478            EdgeCut::Fillet { edge_id, .. } => *edge_id,
1479            EdgeCut::Chamfer { edge_id, .. } => *edge_id,
1480        }
1481    }
1482
1483    pub fn set_edge_id(&mut self, id: uuid::Uuid) {
1484        match self {
1485            EdgeCut::Fillet { edge_id: i, .. } => *i = id,
1486            EdgeCut::Chamfer { edge_id: i, .. } => *i = id,
1487        }
1488    }
1489
1490    pub fn tag(&self) -> Option<TagNode> {
1491        match self {
1492            EdgeCut::Fillet { tag, .. } => *tag.clone(),
1493            EdgeCut::Chamfer { tag, .. } => *tag.clone(),
1494        }
1495    }
1496}
1497
1498#[derive(Debug, Serialize, PartialEq, Clone, Copy, ts_rs::TS)]
1499#[ts(export)]
1500pub struct Point2d {
1501    pub x: f64,
1502    pub y: f64,
1503    pub units: UnitLength,
1504}
1505
1506impl Point2d {
1507    pub const ZERO: Self = Self {
1508        x: 0.0,
1509        y: 0.0,
1510        units: UnitLength::Millimeters,
1511    };
1512
1513    pub fn new(x: f64, y: f64, units: UnitLength) -> Self {
1514        Self { x, y, units }
1515    }
1516
1517    pub fn into_x(self) -> TyF64 {
1518        TyF64::new(self.x, NumericType::length(self.units))
1519    }
1520
1521    pub fn into_y(self) -> TyF64 {
1522        TyF64::new(self.y, NumericType::length(self.units))
1523    }
1524
1525    pub fn ignore_units(self) -> [f64; 2] {
1526        [self.x, self.y]
1527    }
1528}
1529
1530#[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, ts_rs::TS, Default)]
1531#[ts(export)]
1532pub struct Point3d {
1533    pub x: f64,
1534    pub y: f64,
1535    pub z: f64,
1536    pub units: Option<UnitLength>,
1537}
1538
1539impl Point3d {
1540    pub const ZERO: Self = Self {
1541        x: 0.0,
1542        y: 0.0,
1543        z: 0.0,
1544        units: Some(UnitLength::Millimeters),
1545    };
1546
1547    pub fn new(x: f64, y: f64, z: f64, units: Option<UnitLength>) -> Self {
1548        Self { x, y, z, units }
1549    }
1550
1551    pub const fn is_zero(&self) -> bool {
1552        self.x == 0.0 && self.y == 0.0 && self.z == 0.0
1553    }
1554
1555    /// Calculate the cross product of this vector with another.
1556    ///
1557    /// This should only be applied to axes or other vectors which represent only a direction (and
1558    /// no magnitude) since units are ignored.
1559    pub fn axes_cross_product(&self, other: &Self) -> Self {
1560        Self {
1561            x: self.y * other.z - self.z * other.y,
1562            y: self.z * other.x - self.x * other.z,
1563            z: self.x * other.y - self.y * other.x,
1564            units: None,
1565        }
1566    }
1567
1568    /// Normalize `-0.0` to `0.0` for cleaner serialized axis data.
1569    pub fn canonicalize_signed_zero(&mut self) {
1570        if self.x == 0.0 {
1571            self.x = 0.0;
1572        }
1573        if self.y == 0.0 {
1574            self.y = 0.0;
1575        }
1576        if self.z == 0.0 {
1577            self.z = 0.0;
1578        }
1579    }
1580
1581    /// Calculate the dot product of this vector with another.
1582    ///
1583    /// This should only be applied to axes or other vectors which represent only a direction (and
1584    /// no magnitude) since units are ignored.
1585    pub fn axes_dot_product(&self, other: &Self) -> f64 {
1586        let x = self.x * other.x;
1587        let y = self.y * other.y;
1588        let z = self.z * other.z;
1589        x + y + z
1590    }
1591
1592    pub fn normalize(&self) -> Self {
1593        let len = f64::sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
1594        Point3d {
1595            x: self.x / len,
1596            y: self.y / len,
1597            z: self.z / len,
1598            units: None,
1599        }
1600    }
1601
1602    pub fn as_3_dims(&self) -> ([f64; 3], Option<UnitLength>) {
1603        let p = [self.x, self.y, self.z];
1604        let u = self.units;
1605        (p, u)
1606    }
1607
1608    pub(crate) fn negated(self) -> Self {
1609        Self {
1610            x: -self.x,
1611            y: -self.y,
1612            z: -self.z,
1613            units: self.units,
1614        }
1615    }
1616}
1617
1618impl From<[TyF64; 3]> for Point3d {
1619    fn from(p: [TyF64; 3]) -> Self {
1620        Self {
1621            x: p[0].n,
1622            y: p[1].n,
1623            z: p[2].n,
1624            units: p[0].ty.as_length(),
1625        }
1626    }
1627}
1628
1629impl From<Point3d> for Point3D {
1630    fn from(p: Point3d) -> Self {
1631        Self { x: p.x, y: p.y, z: p.z }
1632    }
1633}
1634
1635impl From<Point3d> for kittycad_modeling_cmds::shared::Point3d<LengthUnit> {
1636    fn from(p: Point3d) -> Self {
1637        if let Some(units) = p.units {
1638            Self {
1639                x: LengthUnit(adjust_length(units, p.x, UnitLength::Millimeters).0),
1640                y: LengthUnit(adjust_length(units, p.y, UnitLength::Millimeters).0),
1641                z: LengthUnit(adjust_length(units, p.z, UnitLength::Millimeters).0),
1642            }
1643        } else {
1644            Self {
1645                x: LengthUnit(p.x),
1646                y: LengthUnit(p.y),
1647                z: LengthUnit(p.z),
1648            }
1649        }
1650    }
1651}
1652
1653impl Add for Point3d {
1654    type Output = Point3d;
1655
1656    fn add(self, rhs: Self) -> Self::Output {
1657        // TODO should assert that self and rhs the same units or coerce them
1658        Point3d {
1659            x: self.x + rhs.x,
1660            y: self.y + rhs.y,
1661            z: self.z + rhs.z,
1662            units: self.units,
1663        }
1664    }
1665}
1666
1667impl AddAssign for Point3d {
1668    fn add_assign(&mut self, rhs: Self) {
1669        *self = *self + rhs
1670    }
1671}
1672
1673impl Sub for Point3d {
1674    type Output = Point3d;
1675
1676    fn sub(self, rhs: Self) -> Self::Output {
1677        let (x, y, z) = if rhs.units != self.units
1678            && let Some(sunits) = self.units
1679            && let Some(runits) = rhs.units
1680        {
1681            (
1682                adjust_length(runits, rhs.x, sunits).0,
1683                adjust_length(runits, rhs.y, sunits).0,
1684                adjust_length(runits, rhs.z, sunits).0,
1685            )
1686        } else {
1687            (rhs.x, rhs.y, rhs.z)
1688        };
1689        Point3d {
1690            x: self.x - x,
1691            y: self.y - y,
1692            z: self.z - z,
1693            units: self.units,
1694        }
1695    }
1696}
1697
1698impl SubAssign for Point3d {
1699    fn sub_assign(&mut self, rhs: Self) {
1700        *self = *self - rhs
1701    }
1702}
1703
1704impl Mul<f64> for Point3d {
1705    type Output = Point3d;
1706
1707    fn mul(self, rhs: f64) -> Self::Output {
1708        Point3d {
1709            x: self.x * rhs,
1710            y: self.y * rhs,
1711            z: self.z * rhs,
1712            units: self.units,
1713        }
1714    }
1715}
1716
1717/// A base path.
1718#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1719#[ts(export)]
1720#[serde(rename_all = "camelCase")]
1721pub struct BasePath {
1722    /// The from point.
1723    #[ts(type = "[number, number]")]
1724    pub from: [f64; 2],
1725    /// The to point.
1726    #[ts(type = "[number, number]")]
1727    pub to: [f64; 2],
1728    pub units: UnitLength,
1729    /// The tag of the path.
1730    pub tag: Option<TagNode>,
1731    /// Metadata.
1732    #[serde(rename = "__geoMeta")]
1733    pub geo_meta: GeoMeta,
1734}
1735
1736impl BasePath {
1737    pub fn get_to(&self) -> [TyF64; 2] {
1738        let ty = NumericType::length(self.units);
1739        [TyF64::new(self.to[0], ty), TyF64::new(self.to[1], ty)]
1740    }
1741
1742    pub fn get_from(&self) -> [TyF64; 2] {
1743        let ty = NumericType::length(self.units);
1744        [TyF64::new(self.from[0], ty), TyF64::new(self.from[1], ty)]
1745    }
1746}
1747
1748/// Geometry metadata.
1749#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1750#[ts(export)]
1751#[serde(rename_all = "camelCase")]
1752pub struct GeoMeta {
1753    /// The id of the geometry.
1754    pub id: uuid::Uuid,
1755    /// Metadata.
1756    #[serde(flatten)]
1757    pub metadata: Metadata,
1758}
1759
1760/// A path.
1761#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1762#[ts(export)]
1763#[serde(tag = "type")]
1764pub enum Path {
1765    /// A straight line which ends at the given point.
1766    ToPoint {
1767        #[serde(flatten)]
1768        base: BasePath,
1769    },
1770    /// A arc that is tangential to the last path segment that goes to a point
1771    TangentialArcTo {
1772        #[serde(flatten)]
1773        base: BasePath,
1774        /// the arc's center
1775        #[ts(type = "[number, number]")]
1776        center: [f64; 2],
1777        /// arc's direction
1778        ccw: bool,
1779    },
1780    /// A arc that is tangential to the last path segment
1781    TangentialArc {
1782        #[serde(flatten)]
1783        base: BasePath,
1784        /// the arc's center
1785        #[ts(type = "[number, number]")]
1786        center: [f64; 2],
1787        /// arc's direction
1788        ccw: bool,
1789    },
1790    // TODO: consolidate segment enums, remove Circle. https://github.com/KittyCAD/modeling-app/issues/3940
1791    /// a complete arc
1792    Circle {
1793        #[serde(flatten)]
1794        base: BasePath,
1795        /// the arc's center
1796        #[ts(type = "[number, number]")]
1797        center: [f64; 2],
1798        /// the arc's radius
1799        radius: f64,
1800        /// arc's direction
1801        /// This is used to compute the tangential angle.
1802        ccw: bool,
1803    },
1804    CircleThreePoint {
1805        #[serde(flatten)]
1806        base: BasePath,
1807        /// Point 1 of the circle
1808        #[ts(type = "[number, number]")]
1809        p1: [f64; 2],
1810        /// Point 2 of the circle
1811        #[ts(type = "[number, number]")]
1812        p2: [f64; 2],
1813        /// Point 3 of the circle
1814        #[ts(type = "[number, number]")]
1815        p3: [f64; 2],
1816    },
1817    ArcThreePoint {
1818        #[serde(flatten)]
1819        base: BasePath,
1820        /// Point 1 of the arc (base on the end of previous segment)
1821        #[ts(type = "[number, number]")]
1822        p1: [f64; 2],
1823        /// Point 2 of the arc (interiorAbsolute kwarg)
1824        #[ts(type = "[number, number]")]
1825        p2: [f64; 2],
1826        /// Point 3 of the arc (endAbsolute kwarg)
1827        #[ts(type = "[number, number]")]
1828        p3: [f64; 2],
1829    },
1830    /// A path that is horizontal.
1831    Horizontal {
1832        #[serde(flatten)]
1833        base: BasePath,
1834        /// The x coordinate.
1835        x: f64,
1836    },
1837    /// An angled line to.
1838    AngledLineTo {
1839        #[serde(flatten)]
1840        base: BasePath,
1841        /// The x coordinate.
1842        x: Option<f64>,
1843        /// The y coordinate.
1844        y: Option<f64>,
1845    },
1846    /// A base path.
1847    Base {
1848        #[serde(flatten)]
1849        base: BasePath,
1850    },
1851    /// A circular arc, not necessarily tangential to the current point.
1852    Arc {
1853        #[serde(flatten)]
1854        base: BasePath,
1855        /// Center of the circle that this arc is drawn on.
1856        center: [f64; 2],
1857        /// Radius of the circle that this arc is drawn on.
1858        radius: f64,
1859        /// True if the arc is counterclockwise.
1860        ccw: bool,
1861    },
1862    Ellipse {
1863        #[serde(flatten)]
1864        base: BasePath,
1865        center: [f64; 2],
1866        major_axis: [f64; 2],
1867        minor_radius: f64,
1868        ccw: bool,
1869    },
1870    //TODO: (bc) figure this out
1871    Conic {
1872        #[serde(flatten)]
1873        base: BasePath,
1874    },
1875    /// A cubic Bezier curve.
1876    Bezier {
1877        #[serde(flatten)]
1878        base: BasePath,
1879        /// First control point (absolute coordinates).
1880        #[ts(type = "[number, number]")]
1881        control1: [f64; 2],
1882        /// Second control point (absolute coordinates).
1883        #[ts(type = "[number, number]")]
1884        control2: [f64; 2],
1885    },
1886}
1887
1888impl Path {
1889    pub fn get_id(&self) -> uuid::Uuid {
1890        match self {
1891            Path::ToPoint { base } => base.geo_meta.id,
1892            Path::Horizontal { base, .. } => base.geo_meta.id,
1893            Path::AngledLineTo { base, .. } => base.geo_meta.id,
1894            Path::Base { base } => base.geo_meta.id,
1895            Path::TangentialArcTo { base, .. } => base.geo_meta.id,
1896            Path::TangentialArc { base, .. } => base.geo_meta.id,
1897            Path::Circle { base, .. } => base.geo_meta.id,
1898            Path::CircleThreePoint { base, .. } => base.geo_meta.id,
1899            Path::Arc { base, .. } => base.geo_meta.id,
1900            Path::ArcThreePoint { base, .. } => base.geo_meta.id,
1901            Path::Ellipse { base, .. } => base.geo_meta.id,
1902            Path::Conic { base, .. } => base.geo_meta.id,
1903            Path::Bezier { base, .. } => base.geo_meta.id,
1904        }
1905    }
1906
1907    pub fn set_id(&mut self, id: uuid::Uuid) {
1908        match self {
1909            Path::ToPoint { base } => base.geo_meta.id = id,
1910            Path::Horizontal { base, .. } => base.geo_meta.id = id,
1911            Path::AngledLineTo { base, .. } => base.geo_meta.id = id,
1912            Path::Base { base } => base.geo_meta.id = id,
1913            Path::TangentialArcTo { base, .. } => base.geo_meta.id = id,
1914            Path::TangentialArc { base, .. } => base.geo_meta.id = id,
1915            Path::Circle { base, .. } => base.geo_meta.id = id,
1916            Path::CircleThreePoint { base, .. } => base.geo_meta.id = id,
1917            Path::Arc { base, .. } => base.geo_meta.id = id,
1918            Path::ArcThreePoint { base, .. } => base.geo_meta.id = id,
1919            Path::Ellipse { base, .. } => base.geo_meta.id = id,
1920            Path::Conic { base, .. } => base.geo_meta.id = id,
1921            Path::Bezier { base, .. } => base.geo_meta.id = id,
1922        }
1923    }
1924
1925    pub fn get_tag(&self) -> Option<TagNode> {
1926        match self {
1927            Path::ToPoint { base } => base.tag.clone(),
1928            Path::Horizontal { base, .. } => base.tag.clone(),
1929            Path::AngledLineTo { base, .. } => base.tag.clone(),
1930            Path::Base { base } => base.tag.clone(),
1931            Path::TangentialArcTo { base, .. } => base.tag.clone(),
1932            Path::TangentialArc { base, .. } => base.tag.clone(),
1933            Path::Circle { base, .. } => base.tag.clone(),
1934            Path::CircleThreePoint { base, .. } => base.tag.clone(),
1935            Path::Arc { base, .. } => base.tag.clone(),
1936            Path::ArcThreePoint { base, .. } => base.tag.clone(),
1937            Path::Ellipse { base, .. } => base.tag.clone(),
1938            Path::Conic { base, .. } => base.tag.clone(),
1939            Path::Bezier { base, .. } => base.tag.clone(),
1940        }
1941    }
1942
1943    pub fn get_base(&self) -> &BasePath {
1944        match self {
1945            Path::ToPoint { base } => base,
1946            Path::Horizontal { base, .. } => base,
1947            Path::AngledLineTo { base, .. } => base,
1948            Path::Base { base } => base,
1949            Path::TangentialArcTo { base, .. } => base,
1950            Path::TangentialArc { base, .. } => base,
1951            Path::Circle { base, .. } => base,
1952            Path::CircleThreePoint { base, .. } => base,
1953            Path::Arc { base, .. } => base,
1954            Path::ArcThreePoint { base, .. } => base,
1955            Path::Ellipse { base, .. } => base,
1956            Path::Conic { base, .. } => base,
1957            Path::Bezier { base, .. } => base,
1958        }
1959    }
1960
1961    /// Where does this path segment start?
1962    pub fn get_from(&self) -> [TyF64; 2] {
1963        let p = &self.get_base().from;
1964        let ty = NumericType::length(self.get_base().units);
1965        [TyF64::new(p[0], ty), TyF64::new(p[1], ty)]
1966    }
1967
1968    /// Where does this path segment end?
1969    pub fn get_to(&self) -> [TyF64; 2] {
1970        let p = &self.get_base().to;
1971        let ty = NumericType::length(self.get_base().units);
1972        [TyF64::new(p[0], ty), TyF64::new(p[1], ty)]
1973    }
1974
1975    /// The path segment start point and its type.
1976    pub fn start_point_components(&self) -> ([f64; 2], NumericType) {
1977        let p = &self.get_base().from;
1978        let ty = NumericType::length(self.get_base().units);
1979        (*p, ty)
1980    }
1981
1982    /// The path segment end point and its type.
1983    pub fn end_point_components(&self) -> ([f64; 2], NumericType) {
1984        let p = &self.get_base().to;
1985        let ty = NumericType::length(self.get_base().units);
1986        (*p, ty)
1987    }
1988
1989    /// Length of this path segment, in cartesian plane. Not all segment types
1990    /// are supported.
1991    pub fn length(&self) -> Option<TyF64> {
1992        let n = match self {
1993            Self::ToPoint { .. } | Self::Base { .. } | Self::Horizontal { .. } | Self::AngledLineTo { .. } => {
1994                Some(linear_distance(&self.get_base().from, &self.get_base().to))
1995            }
1996            Self::TangentialArc {
1997                base: _,
1998                center,
1999                ccw: _,
2000            }
2001            | Self::TangentialArcTo {
2002                base: _,
2003                center,
2004                ccw: _,
2005            } => {
2006                // The radius can be calculated as the linear distance between `to` and `center`,
2007                // or between `from` and `center`. They should be the same.
2008                let radius = linear_distance(&self.get_base().from, center);
2009                debug_assert_eq!(radius, linear_distance(&self.get_base().to, center));
2010                // TODO: Call engine utils to figure this out.
2011                Some(linear_distance(&self.get_base().from, &self.get_base().to))
2012            }
2013            Self::Circle { radius, .. } => Some(TAU * radius),
2014            Self::CircleThreePoint { .. } => {
2015                let circle_center = crate::std::utils::calculate_circle_from_3_points([
2016                    self.get_base().from,
2017                    self.get_base().to,
2018                    self.get_base().to,
2019                ]);
2020                let radius = linear_distance(
2021                    &[circle_center.center[0], circle_center.center[1]],
2022                    &self.get_base().from,
2023                );
2024                Some(TAU * radius)
2025            }
2026            Self::Arc { .. } => {
2027                // TODO: Call engine utils to figure this out.
2028                Some(linear_distance(&self.get_base().from, &self.get_base().to))
2029            }
2030            Self::ArcThreePoint { .. } => {
2031                // TODO: Call engine utils to figure this out.
2032                Some(linear_distance(&self.get_base().from, &self.get_base().to))
2033            }
2034            Self::Ellipse { .. } => {
2035                // Not supported.
2036                None
2037            }
2038            Self::Conic { .. } => {
2039                // Not supported.
2040                None
2041            }
2042            Self::Bezier { .. } => {
2043                // Not supported - Bezier curve length requires numerical integration.
2044                None
2045            }
2046        };
2047        n.map(|n| TyF64::new(n, NumericType::length(self.get_base().units)))
2048    }
2049
2050    pub fn get_base_mut(&mut self) -> &mut BasePath {
2051        match self {
2052            Path::ToPoint { base } => base,
2053            Path::Horizontal { base, .. } => base,
2054            Path::AngledLineTo { base, .. } => base,
2055            Path::Base { base } => base,
2056            Path::TangentialArcTo { base, .. } => base,
2057            Path::TangentialArc { base, .. } => base,
2058            Path::Circle { base, .. } => base,
2059            Path::CircleThreePoint { base, .. } => base,
2060            Path::Arc { base, .. } => base,
2061            Path::ArcThreePoint { base, .. } => base,
2062            Path::Ellipse { base, .. } => base,
2063            Path::Conic { base, .. } => base,
2064            Path::Bezier { base, .. } => base,
2065        }
2066    }
2067
2068    pub(crate) fn get_tangential_info(&self) -> GetTangentialInfoFromPathsResult {
2069        match self {
2070            Path::TangentialArc { center, ccw, .. }
2071            | Path::TangentialArcTo { center, ccw, .. }
2072            | Path::Arc { center, ccw, .. } => GetTangentialInfoFromPathsResult::Arc {
2073                center: *center,
2074                ccw: *ccw,
2075            },
2076            Path::ArcThreePoint { p1, p2, p3, .. } => {
2077                let circle = crate::std::utils::calculate_circle_from_3_points([*p1, *p2, *p3]);
2078                GetTangentialInfoFromPathsResult::Arc {
2079                    center: circle.center,
2080                    ccw: crate::std::utils::is_points_ccw(&[*p1, *p2, *p3]) > 0,
2081                }
2082            }
2083            Path::Circle {
2084                center, ccw, radius, ..
2085            } => GetTangentialInfoFromPathsResult::Circle {
2086                center: *center,
2087                ccw: *ccw,
2088                radius: *radius,
2089            },
2090            Path::CircleThreePoint { p1, p2, p3, .. } => {
2091                let circle = crate::std::utils::calculate_circle_from_3_points([*p1, *p2, *p3]);
2092                let center_point = [circle.center[0], circle.center[1]];
2093                GetTangentialInfoFromPathsResult::Circle {
2094                    center: center_point,
2095                    // Note: a circle is always ccw regardless of the order of points
2096                    ccw: true,
2097                    radius: circle.radius,
2098                }
2099            }
2100            // TODO: (bc) fix me
2101            Path::Ellipse {
2102                center,
2103                major_axis,
2104                minor_radius,
2105                ccw,
2106                ..
2107            } => GetTangentialInfoFromPathsResult::Ellipse {
2108                center: *center,
2109                major_axis: *major_axis,
2110                _minor_radius: *minor_radius,
2111                ccw: *ccw,
2112            },
2113            Path::Conic { .. }
2114            | Path::ToPoint { .. }
2115            | Path::Horizontal { .. }
2116            | Path::AngledLineTo { .. }
2117            | Path::Base { .. }
2118            | Path::Bezier { .. } => {
2119                let base = self.get_base();
2120                GetTangentialInfoFromPathsResult::PreviousPoint(base.from)
2121            }
2122        }
2123    }
2124
2125    /// i.e. not a curve
2126    pub(crate) fn is_straight_line(&self) -> bool {
2127        matches!(self, Path::AngledLineTo { .. } | Path::ToPoint { .. })
2128    }
2129}
2130
2131/// Compute the straight-line distance between a pair of (2D) points.
2132#[rustfmt::skip]
2133fn linear_distance(
2134    [x0, y0]: &[f64; 2],
2135    [x1, y1]: &[f64; 2]
2136) -> f64 {
2137    let y_sq = (y1 - y0).squared();
2138    let x_sq = (x1 - x0).squared();
2139    (y_sq + x_sq).sqrt()
2140}
2141
2142/// An extrude surface.
2143#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2144#[ts(export)]
2145#[serde(tag = "type", rename_all = "camelCase")]
2146pub enum ExtrudeSurface {
2147    /// An extrude plane.
2148    ExtrudePlane(ExtrudePlane),
2149    ExtrudeArc(ExtrudeArc),
2150    Chamfer(ChamferSurface),
2151    Fillet(FilletSurface),
2152}
2153
2154// Chamfer surface.
2155#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2156#[ts(export)]
2157#[serde(rename_all = "camelCase")]
2158pub struct ChamferSurface {
2159    /// The id for the chamfer surface.
2160    pub face_id: uuid::Uuid,
2161    /// The tag.
2162    pub tag: Option<Node<TagDeclarator>>,
2163    /// Metadata.
2164    #[serde(flatten)]
2165    pub geo_meta: GeoMeta,
2166}
2167
2168// Fillet surface.
2169#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2170#[ts(export)]
2171#[serde(rename_all = "camelCase")]
2172pub struct FilletSurface {
2173    /// The id for the fillet surface.
2174    pub face_id: uuid::Uuid,
2175    /// The tag.
2176    pub tag: Option<Node<TagDeclarator>>,
2177    /// Metadata.
2178    #[serde(flatten)]
2179    pub geo_meta: GeoMeta,
2180}
2181
2182/// An extruded plane.
2183#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2184#[ts(export)]
2185#[serde(rename_all = "camelCase")]
2186pub struct ExtrudePlane {
2187    /// The face id for the extrude plane.
2188    pub face_id: uuid::Uuid,
2189    /// The tag.
2190    pub tag: Option<Node<TagDeclarator>>,
2191    /// Metadata.
2192    #[serde(flatten)]
2193    pub geo_meta: GeoMeta,
2194}
2195
2196/// An extruded arc.
2197#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2198#[ts(export)]
2199#[serde(rename_all = "camelCase")]
2200pub struct ExtrudeArc {
2201    /// The face id for the extrude plane.
2202    pub face_id: uuid::Uuid,
2203    /// The tag.
2204    pub tag: Option<Node<TagDeclarator>>,
2205    /// Metadata.
2206    #[serde(flatten)]
2207    pub geo_meta: GeoMeta,
2208}
2209
2210impl ExtrudeSurface {
2211    pub fn get_id(&self) -> uuid::Uuid {
2212        match self {
2213            ExtrudeSurface::ExtrudePlane(ep) => ep.geo_meta.id,
2214            ExtrudeSurface::ExtrudeArc(ea) => ea.geo_meta.id,
2215            ExtrudeSurface::Fillet(f) => f.geo_meta.id,
2216            ExtrudeSurface::Chamfer(c) => c.geo_meta.id,
2217        }
2218    }
2219
2220    pub fn face_id(&self) -> uuid::Uuid {
2221        match self {
2222            ExtrudeSurface::ExtrudePlane(ep) => ep.face_id,
2223            ExtrudeSurface::ExtrudeArc(ea) => ea.face_id,
2224            ExtrudeSurface::Fillet(f) => f.face_id,
2225            ExtrudeSurface::Chamfer(c) => c.face_id,
2226        }
2227    }
2228
2229    pub fn set_face_id(&mut self, face_id: uuid::Uuid) {
2230        match self {
2231            ExtrudeSurface::ExtrudePlane(ep) => ep.face_id = face_id,
2232            ExtrudeSurface::ExtrudeArc(ea) => ea.face_id = face_id,
2233            ExtrudeSurface::Fillet(f) => f.face_id = face_id,
2234            ExtrudeSurface::Chamfer(c) => c.face_id = face_id,
2235        }
2236    }
2237
2238    pub fn set_surface_tag(&mut self, tag: &TagNode) {
2239        match self {
2240            ExtrudeSurface::ExtrudePlane(extrude_plane) => extrude_plane.tag = Some(tag.clone()),
2241            ExtrudeSurface::ExtrudeArc(extrude_arc) => extrude_arc.tag = Some(tag.clone()),
2242            ExtrudeSurface::Chamfer(chamfer) => chamfer.tag = Some(tag.clone()),
2243            ExtrudeSurface::Fillet(fillet) => fillet.tag = Some(tag.clone()),
2244        }
2245    }
2246
2247    pub fn get_tag(&self) -> Option<Node<TagDeclarator>> {
2248        match self {
2249            ExtrudeSurface::ExtrudePlane(ep) => ep.tag.clone(),
2250            ExtrudeSurface::ExtrudeArc(ea) => ea.tag.clone(),
2251            ExtrudeSurface::Fillet(f) => f.tag.clone(),
2252            ExtrudeSurface::Chamfer(c) => c.tag.clone(),
2253        }
2254    }
2255}
2256
2257#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, ts_rs::TS)]
2258pub struct SketchVarId(pub usize);
2259
2260impl SketchVarId {
2261    pub const INVALID: Self = Self(usize::MAX);
2262
2263    pub fn to_constraint_id(self, range: SourceRange) -> Result<ezpz::Id, KclError> {
2264        self.0.try_into().map_err(|_| {
2265            KclError::new_type(KclErrorDetails::new(
2266                "Cannot convert to constraint ID since the sketch variable ID is too large".to_owned(),
2267                vec![range],
2268            ))
2269        })
2270    }
2271}
2272
2273#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2274#[ts(export_to = "Geometry.ts")]
2275#[serde(rename_all = "camelCase")]
2276pub struct SketchVar {
2277    pub id: SketchVarId,
2278    pub initial_value: f64,
2279    pub ty: NumericType,
2280    /// Used for solver feedback to source.
2281    pub node_path: Option<NodePath>,
2282    #[serde(skip)]
2283    pub meta: Vec<Metadata>,
2284}
2285
2286impl SketchVar {
2287    pub fn initial_value_to_solver_units(
2288        &self,
2289        exec_state: &mut ExecState,
2290        source_range: SourceRange,
2291        description: &str,
2292    ) -> Result<TyF64, KclError> {
2293        let x_initial_value = KclValue::Number {
2294            value: self.initial_value,
2295            ty: self.ty,
2296            meta: vec![source_range.into()],
2297        };
2298        let normalized_value =
2299            normalize_to_solver_distance_unit(&x_initial_value, source_range, exec_state, description)?;
2300        normalized_value.as_ty_f64().ok_or_else(|| {
2301            let message = format!(
2302                "Expected number after coercion, but found {}",
2303                normalized_value.human_friendly_type()
2304            );
2305            debug_assert!(false, "{}", &message);
2306            KclError::new_internal(KclErrorDetails::new(message, vec![source_range]))
2307        })
2308    }
2309}
2310
2311#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2312#[ts(export_to = "Geometry.ts")]
2313#[serde(tag = "type")]
2314pub enum UnsolvedExpr {
2315    Known(TyF64),
2316    Unknown(SketchVarId),
2317}
2318
2319impl UnsolvedExpr {
2320    pub fn var(&self) -> Option<SketchVarId> {
2321        match self {
2322            UnsolvedExpr::Known(_) => None,
2323            UnsolvedExpr::Unknown(id) => Some(*id),
2324        }
2325    }
2326}
2327
2328pub type UnsolvedPoint2dExpr = [UnsolvedExpr; 2];
2329
2330#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2331#[ts(export_to = "Geometry.ts")]
2332#[serde(rename_all = "camelCase")]
2333pub struct ConstrainablePoint2d {
2334    pub vars: crate::front::Point2d<SketchVarId>,
2335    pub object_id: ObjectId,
2336}
2337
2338#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2339#[ts(export_to = "Geometry.ts")]
2340pub enum ConstrainablePoint2dOrOrigin {
2341    Point(ConstrainablePoint2d),
2342    Origin,
2343}
2344
2345#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2346#[ts(export_to = "Geometry.ts")]
2347#[serde(rename_all = "camelCase")]
2348pub struct ConstrainableLine2d {
2349    pub vars: [crate::front::Point2d<SketchVarId>; 2],
2350    pub object_id: ObjectId,
2351}
2352
2353#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2354#[ts(export_to = "Geometry.ts")]
2355#[serde(rename_all = "camelCase")]
2356pub struct UnsolvedSegment {
2357    /// The engine ID.
2358    pub id: Uuid,
2359    pub object_id: ObjectId,
2360    pub kind: UnsolvedSegmentKind,
2361    #[serde(skip_serializing_if = "Option::is_none")]
2362    pub tag: Option<TagIdentifier>,
2363    #[serde(skip)]
2364    pub node_path: Option<NodePath>,
2365    #[serde(skip)]
2366    pub meta: Vec<Metadata>,
2367}
2368
2369#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2370#[ts(export_to = "Geometry.ts")]
2371#[serde(rename_all = "camelCase")]
2372pub enum UnsolvedSegmentKind {
2373    Point {
2374        position: UnsolvedPoint2dExpr,
2375        ctor: Box<PointCtor>,
2376    },
2377    Line {
2378        start: UnsolvedPoint2dExpr,
2379        end: UnsolvedPoint2dExpr,
2380        ctor: Box<LineCtor>,
2381        start_object_id: ObjectId,
2382        end_object_id: ObjectId,
2383        construction: bool,
2384    },
2385    Arc {
2386        start: UnsolvedPoint2dExpr,
2387        end: UnsolvedPoint2dExpr,
2388        center: UnsolvedPoint2dExpr,
2389        ctor: Box<ArcCtor>,
2390        start_object_id: ObjectId,
2391        end_object_id: ObjectId,
2392        center_object_id: ObjectId,
2393        /// The direction that the arc sweeps from its declared start to its
2394        /// declared end. The solver and engine only understand
2395        /// counterclockwise arcs, so code sending them the arc must use
2396        /// [`ArcDirection::ccw_order`] to resolve which points to treat as the
2397        /// sweep's start and end.
2398        #[serde(default, skip_serializing_if = "ArcDirection::is_ccw")]
2399        #[ts(as = "Option<ArcDirection>")]
2400        #[ts(optional)]
2401        direction: ArcDirection,
2402        construction: bool,
2403    },
2404    Circle {
2405        start: UnsolvedPoint2dExpr,
2406        center: UnsolvedPoint2dExpr,
2407        ctor: Box<CircleCtor>,
2408        start_object_id: ObjectId,
2409        center_object_id: ObjectId,
2410        construction: bool,
2411    },
2412    ControlPointSpline {
2413        controls: Vec<UnsolvedPoint2dExpr>,
2414        ctor: Box<ControlPointSplineCtor>,
2415        control_object_ids: Vec<ObjectId>,
2416        control_polygon_edge_object_ids: Vec<ObjectId>,
2417        degree: u32,
2418        construction: bool,
2419    },
2420}
2421
2422impl UnsolvedSegmentKind {
2423    /// What kind of object is this (point, line, arc, etc)
2424    /// Suitable for use in user-facing messages.
2425    pub fn human_friendly_kind_with_article(&self) -> &'static str {
2426        match self {
2427            Self::Point { .. } => "a Point",
2428            Self::Line { .. } => "a Line",
2429            Self::Arc { .. } => "an Arc",
2430            Self::Circle { .. } => "a Circle",
2431            Self::ControlPointSpline { .. } => "a Control Point Spline",
2432        }
2433    }
2434}
2435
2436#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2437#[ts(export_to = "Geometry.ts")]
2438#[serde(rename_all = "camelCase")]
2439pub struct Segment {
2440    /// The engine ID.
2441    pub id: Uuid,
2442    pub object_id: ObjectId,
2443    pub kind: SegmentKind,
2444    pub surface: SketchSurface,
2445    /// The engine ID of the sketch that this is a part of.
2446    pub sketch_id: Uuid,
2447    #[serde(skip)]
2448    #[ts(skip)]
2449    pub sketch: Option<Arc<Sketch>>,
2450    #[serde(skip_serializing_if = "Option::is_none")]
2451    pub tag: Option<TagIdentifier>,
2452    #[serde(skip)]
2453    pub node_path: Option<NodePath>,
2454    #[serde(skip)]
2455    pub meta: Vec<Metadata>,
2456}
2457
2458impl Segment {
2459    pub fn is_construction(&self) -> bool {
2460        match &self.kind {
2461            SegmentKind::Point { .. } => true,
2462            SegmentKind::Line { construction, .. } => *construction,
2463            SegmentKind::Arc { construction, .. } => *construction,
2464            SegmentKind::Circle { construction, .. } => *construction,
2465            SegmentKind::ControlPointSpline { construction, .. } => *construction,
2466        }
2467    }
2468}
2469
2470#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2471#[ts(export_to = "Geometry.ts")]
2472#[serde(rename_all = "camelCase")]
2473pub enum SegmentKind {
2474    Point {
2475        position: [TyF64; 2],
2476        ctor: Box<PointCtor>,
2477        #[serde(skip_serializing_if = "Option::is_none")]
2478        freedom: Option<Freedom>,
2479    },
2480    Line {
2481        start: [TyF64; 2],
2482        end: [TyF64; 2],
2483        ctor: Box<LineCtor>,
2484        start_object_id: ObjectId,
2485        end_object_id: ObjectId,
2486        #[serde(skip_serializing_if = "Option::is_none")]
2487        start_freedom: Option<Freedom>,
2488        #[serde(skip_serializing_if = "Option::is_none")]
2489        end_freedom: Option<Freedom>,
2490        construction: bool,
2491    },
2492    Arc {
2493        start: [TyF64; 2],
2494        end: [TyF64; 2],
2495        center: [TyF64; 2],
2496        ctor: Box<ArcCtor>,
2497        start_object_id: ObjectId,
2498        end_object_id: ObjectId,
2499        center_object_id: ObjectId,
2500        #[serde(skip_serializing_if = "Option::is_none")]
2501        start_freedom: Option<Freedom>,
2502        #[serde(skip_serializing_if = "Option::is_none")]
2503        end_freedom: Option<Freedom>,
2504        #[serde(skip_serializing_if = "Option::is_none")]
2505        center_freedom: Option<Freedom>,
2506        /// The direction that the arc sweeps from its declared start to its
2507        /// declared end.
2508        #[serde(default, skip_serializing_if = "ArcDirection::is_ccw")]
2509        #[ts(as = "Option<ArcDirection>")]
2510        #[ts(optional)]
2511        direction: ArcDirection,
2512        construction: bool,
2513    },
2514    Circle {
2515        start: [TyF64; 2],
2516        center: [TyF64; 2],
2517        ctor: Box<CircleCtor>,
2518        start_object_id: ObjectId,
2519        center_object_id: ObjectId,
2520        #[serde(skip_serializing_if = "Option::is_none")]
2521        start_freedom: Option<Freedom>,
2522        #[serde(skip_serializing_if = "Option::is_none")]
2523        center_freedom: Option<Freedom>,
2524        construction: bool,
2525    },
2526    ControlPointSpline {
2527        controls: Vec<[TyF64; 2]>,
2528        ctor: Box<ControlPointSplineCtor>,
2529        control_object_ids: Vec<ObjectId>,
2530        control_polygon_edge_object_ids: Vec<ObjectId>,
2531        #[serde(skip_serializing_if = "Vec::is_empty")]
2532        control_freedoms: Vec<Option<Freedom>>,
2533        degree: u32,
2534        construction: bool,
2535    },
2536}
2537
2538#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2539#[ts(export_to = "Geometry.ts")]
2540#[serde(rename_all = "camelCase")]
2541pub struct AbstractSegment {
2542    pub repr: SegmentRepr,
2543    #[serde(skip)]
2544    pub meta: Vec<Metadata>,
2545}
2546
2547#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2548pub enum SegmentRepr {
2549    Unsolved { segment: Box<UnsolvedSegment> },
2550    Solved { segment: Box<Segment> },
2551}
2552
2553#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2554#[ts(export_to = "Geometry.ts")]
2555#[serde(rename_all = "camelCase")]
2556pub struct SketchConstraint {
2557    pub kind: SketchConstraintKind,
2558    #[serde(skip)]
2559    pub meta: Vec<Metadata>,
2560}
2561
2562#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2563#[ts(export_to = "Geometry.ts")]
2564#[serde(rename_all = "camelCase")]
2565pub enum SketchConstraintKind {
2566    Angle {
2567        line0: ConstrainableLine2d,
2568        line1: ConstrainableLine2d,
2569    },
2570    Distance {
2571        points: [ConstrainablePoint2dOrOrigin; 2],
2572        #[serde(rename = "labelPosition")]
2573        #[serde(skip_serializing_if = "Option::is_none")]
2574        #[ts(rename = "labelPosition")]
2575        #[ts(optional)]
2576        label_position: Option<ApiPoint2d<Number>>,
2577    },
2578    PointLineDistance {
2579        point: ConstrainablePoint2dOrOrigin,
2580        line: ConstrainableLine2d,
2581        input_object_ids: [Option<ObjectId>; 2],
2582        #[serde(rename = "labelPosition")]
2583        #[serde(skip_serializing_if = "Option::is_none")]
2584        #[ts(rename = "labelPosition")]
2585        #[ts(optional)]
2586        label_position: Option<ApiPoint2d<Number>>,
2587    },
2588    LineLineDistance {
2589        line0: ConstrainableLine2d,
2590        line1: ConstrainableLine2d,
2591        input_object_ids: [ObjectId; 2],
2592        #[serde(rename = "labelPosition")]
2593        #[serde(skip_serializing_if = "Option::is_none")]
2594        #[ts(rename = "labelPosition")]
2595        #[ts(optional)]
2596        label_position: Option<ApiPoint2d<Number>>,
2597    },
2598    PointCircularDistance {
2599        point: ConstrainablePoint2dOrOrigin,
2600        center: ConstrainablePoint2d,
2601        start: ConstrainablePoint2d,
2602        end: Option<ConstrainablePoint2d>,
2603        input_object_ids: [Option<ObjectId>; 2],
2604        #[serde(rename = "labelPosition")]
2605        #[serde(skip_serializing_if = "Option::is_none")]
2606        #[ts(rename = "labelPosition")]
2607        #[ts(optional)]
2608        label_position: Option<ApiPoint2d<Number>>,
2609    },
2610    LineCircularDistance {
2611        line: ConstrainableLine2d,
2612        center: ConstrainablePoint2d,
2613        start: ConstrainablePoint2d,
2614        end: Option<ConstrainablePoint2d>,
2615        input_object_ids: [ObjectId; 2],
2616        #[serde(rename = "labelPosition")]
2617        #[serde(skip_serializing_if = "Option::is_none")]
2618        #[ts(rename = "labelPosition")]
2619        #[ts(optional)]
2620        label_position: Option<ApiPoint2d<Number>>,
2621    },
2622    CircularCircularDistance {
2623        center0: ConstrainablePoint2d,
2624        start0: ConstrainablePoint2d,
2625        end0: Option<ConstrainablePoint2d>,
2626        center1: ConstrainablePoint2d,
2627        start1: ConstrainablePoint2d,
2628        end1: Option<ConstrainablePoint2d>,
2629        input_object_ids: [ObjectId; 2],
2630        #[serde(rename = "labelPosition")]
2631        #[serde(skip_serializing_if = "Option::is_none")]
2632        #[ts(rename = "labelPosition")]
2633        #[ts(optional)]
2634        label_position: Option<ApiPoint2d<Number>>,
2635    },
2636    Radius {
2637        points: [ConstrainablePoint2d; 2],
2638        #[serde(rename = "labelPosition")]
2639        #[serde(skip_serializing_if = "Option::is_none")]
2640        #[ts(rename = "labelPosition")]
2641        #[ts(optional)]
2642        label_position: Option<ApiPoint2d<Number>>,
2643    },
2644    Diameter {
2645        points: [ConstrainablePoint2d; 2],
2646        #[serde(rename = "labelPosition")]
2647        #[serde(skip_serializing_if = "Option::is_none")]
2648        #[ts(rename = "labelPosition")]
2649        #[ts(optional)]
2650        label_position: Option<ApiPoint2d<Number>>,
2651    },
2652    HorizontalDistance {
2653        points: [ConstrainablePoint2dOrOrigin; 2],
2654        #[serde(rename = "labelPosition")]
2655        #[serde(skip_serializing_if = "Option::is_none")]
2656        #[ts(rename = "labelPosition")]
2657        #[ts(optional)]
2658        label_position: Option<ApiPoint2d<Number>>,
2659    },
2660    VerticalDistance {
2661        points: [ConstrainablePoint2dOrOrigin; 2],
2662        #[serde(rename = "labelPosition")]
2663        #[serde(skip_serializing_if = "Option::is_none")]
2664        #[ts(rename = "labelPosition")]
2665        #[ts(optional)]
2666        label_position: Option<ApiPoint2d<Number>>,
2667    },
2668}
2669
2670impl SketchConstraintKind {
2671    pub fn name(&self) -> &'static str {
2672        match self {
2673            SketchConstraintKind::Angle { .. } => "angle",
2674            SketchConstraintKind::Distance { .. } => "distance",
2675            SketchConstraintKind::PointLineDistance { .. } => "distance",
2676            SketchConstraintKind::LineLineDistance { .. } => "distance",
2677            SketchConstraintKind::PointCircularDistance { .. } => "distance",
2678            SketchConstraintKind::LineCircularDistance { .. } => "distance",
2679            SketchConstraintKind::CircularCircularDistance { .. } => "distance",
2680            SketchConstraintKind::Radius { .. } => "radius",
2681            SketchConstraintKind::Diameter { .. } => "diameter",
2682            SketchConstraintKind::HorizontalDistance { .. } => "horizontalDistance",
2683            SketchConstraintKind::VerticalDistance { .. } => "verticalDistance",
2684        }
2685    }
2686}