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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
65#[ts(export)]
66#[serde(tag = "type", rename_all = "camelCase")]
67pub struct GdtAnnotation {
68 pub id: uuid::Uuid,
70 #[serde(skip)]
71 pub meta: Vec<Metadata>,
72}
73
74#[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 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#[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#[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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
155#[ts(export)]
156#[serde(rename_all = "camelCase")]
157pub struct ImportedGeometry {
158 pub id: uuid::Uuid,
160 pub value: Vec<String>,
162 #[serde(skip)]
163 pub meta: Vec<Metadata>,
164 #[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#[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#[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#[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#[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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
477#[ts(export)]
478#[serde(rename_all = "camelCase")]
479pub struct Helix {
480 pub value: uuid::Uuid,
482 pub artifact_id: ArtifactId,
484 pub revolutions: f64,
486 pub angle_start: f64,
488 pub ccw: bool,
490 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 pub id: uuid::Uuid,
503 pub artifact_id: ArtifactId,
505 #[serde(skip_serializing_if = "Option::is_none")]
508 pub object_id: Option<ObjectId>,
509 pub kind: PlaneKind,
511 #[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 pub origin: Point3d,
524 pub x_axis: Point3d,
526 pub y_axis: Point3d,
528 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 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 (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 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 | PlaneData::NegXY => PlaneKind::XY,
757 PlaneData::XZ | PlaneData::NegXZ => PlaneKind::XZ,
758 PlaneData::YZ | PlaneData::NegYZ => PlaneKind::YZ,
759 PlaneData::Plane(_) => PlaneKind::Custom,
760 }
761 }
762}
763
764impl From<&PlaneInfo> for PlaneKind {
765 fn from(value: &PlaneInfo) -> Self {
766 PlaneKind::from(&PlaneData::Plane(value.clone()))
767 }
768}
769
770impl From<PlaneInfo> for PlaneKind {
771 fn from(value: PlaneInfo) -> Self {
772 PlaneKind::from(&PlaneData::Plane(value))
773 }
774}
775
776impl Plane {
777 #[cfg(test)]
778 pub(crate) fn from_plane_data_skipping_engine(
779 value: PlaneData,
780 exec_state: &mut ExecState,
781 ) -> Result<Self, KclError> {
782 let id = exec_state.next_uuid();
783 let kind = PlaneKind::from(&value);
784 Ok(Plane {
785 id,
786 artifact_id: id.into(),
787 info: PlaneInfo::try_from(value)?,
788 object_id: None,
789 kind,
790 meta: vec![],
791 })
792 }
793
794 pub fn is_initialized(&self) -> bool {
796 self.object_id.is_some()
797 }
798
799 pub fn is_uninitialized(&self) -> bool {
801 !self.is_initialized()
802 }
803
804 pub fn is_standard(&self) -> bool {
806 match &self.kind {
807 PlaneKind::XY | PlaneKind::YZ | PlaneKind::XZ => true,
808 PlaneKind::Custom => false,
809 }
810 }
811
812 pub fn project(&self, point: Point3d) -> Point3d {
815 let v = point - self.info.origin;
816 let dot = v.axes_dot_product(&self.info.z_axis);
817
818 point - self.info.z_axis * dot
819 }
820}
821
822#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
824#[ts(export)]
825#[serde(rename_all = "camelCase")]
826pub struct Face {
827 pub id: uuid::Uuid,
829 pub artifact_id: ArtifactId,
831 pub object_id: ObjectId,
833 pub value: String,
835 pub x_axis: Point3d,
837 pub y_axis: Point3d,
839 pub parent_solid: FaceParentSolid,
841 pub units: UnitLength,
842 #[serde(skip)]
843 pub meta: Vec<Metadata>,
844}
845
846#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
848#[ts(export)]
849#[serde(rename_all = "camelCase")]
850pub struct FaceParentSolid {
851 pub solid_id: Uuid,
853 pub creator_sketch_id: Option<Uuid>,
855 pub creator_sketch_is_closed: Option<ProfileClosed>,
857 #[serde(default, skip_serializing_if = "Vec::is_empty")]
859 pub edge_cut_ids: Vec<Uuid>,
860}
861
862impl FaceParentSolid {
863 pub(crate) fn sketch_or_solid_id(&self) -> Uuid {
864 self.creator_sketch_id.unwrap_or(self.solid_id)
865 }
866}
867
868#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
871#[ts(export)]
872#[serde(rename_all = "camelCase")]
873pub struct BoundedEdge {
874 pub face_id: uuid::Uuid,
876 #[serde(skip_serializing_if = "Option::is_none")]
878 pub edge_id: Option<uuid::Uuid>,
879 #[serde(skip_serializing_if = "Option::is_none")]
881 pub edge_specifier: Option<UnresolvedEdgeSpecifier>,
882 pub lower_bound: f32,
885 pub upper_bound: f32,
888}
889
890#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, ts_rs::TS, FromStr, Display)]
892#[ts(export)]
893#[display(style = "camelCase")]
894pub enum PlaneKind {
895 #[serde(rename = "XY", alias = "xy")]
896 #[display("XY")]
897 XY,
898 #[serde(rename = "XZ", alias = "xz")]
899 #[display("XZ")]
900 XZ,
901 #[serde(rename = "YZ", alias = "yz")]
902 #[display("YZ")]
903 YZ,
904 #[display("Custom")]
906 Custom,
907}
908
909#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
910#[ts(export)]
911#[serde(tag = "type", rename_all = "camelCase")]
912pub struct Sketch {
913 pub id: uuid::Uuid,
915 #[ts(as = "Vec<Path>")]
920 pub paths: imbl::Vector<Path>,
921 #[serde(default, skip_serializing_if = "Vec::is_empty")]
923 pub inner_paths: Vec<Path>,
924 pub on: SketchSurface,
926 pub start: BasePath,
928 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
930 pub tags: IndexMap<String, TagIdentifier>,
931 pub artifact_id: ArtifactId,
934 #[ts(skip)]
935 pub original_id: uuid::Uuid,
936 #[serde(skip_serializing_if = "Option::is_none")]
941 #[ts(skip)]
942 pub origin_sketch_id: Option<uuid::Uuid>,
943 #[serde(skip)]
945 pub mirror: Option<uuid::Uuid>,
946 #[serde(skip)]
948 pub clone: Option<uuid::Uuid>,
949 #[serde(skip)]
951 #[ts(skip)]
952 pub synthetic_jump_path_ids: Vec<uuid::Uuid>,
953 pub units: UnitLength,
954 #[serde(skip)]
956 pub meta: Vec<Metadata>,
957 #[serde(
960 default = "ProfileClosed::explicitly",
961 skip_serializing_if = "ProfileClosed::is_explicitly"
962 )]
963 pub is_closed: ProfileClosed,
964}
965
966impl ProfileClosed {
967 #[expect(dead_code, reason = "it's not actually dead, it's called by serde")]
968 fn explicitly() -> Self {
969 Self::Explicitly
970 }
971
972 fn is_explicitly(&self) -> bool {
973 matches!(self, ProfileClosed::Explicitly)
974 }
975}
976
977#[derive(Debug, Serialize, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd, ts_rs::TS)]
979#[serde(rename_all = "camelCase")]
980pub enum ProfileClosed {
981 No,
983 Maybe,
985 Implicitly,
987 Explicitly,
989}
990
991impl Sketch {
992 pub(crate) fn build_sketch_mode_cmds(
995 &self,
996 exec_state: &mut ExecState,
997 inner_cmd: ModelingCmdReq,
998 ) -> Vec<ModelingCmdReq> {
999 vec![
1000 ModelingCmdReq {
1003 cmd: ModelingCmd::from(
1004 mcmd::EnableSketchMode::builder()
1005 .animated(false)
1006 .ortho(false)
1007 .entity_id(self.on.id())
1008 .adjust_camera(false)
1009 .maybe_planar_normal(if let SketchSurface::Plane(plane) = &self.on {
1010 let normal = plane.info.x_axis.axes_cross_product(&plane.info.y_axis);
1012 Some(normal.into())
1013 } else {
1014 None
1015 })
1016 .build(),
1017 ),
1018 cmd_id: exec_state.next_uuid().into(),
1019 },
1020 inner_cmd,
1021 ModelingCmdReq {
1022 cmd: ModelingCmd::SketchModeDisable(mcmd::SketchModeDisable::builder().build()),
1023 cmd_id: exec_state.next_uuid().into(),
1024 },
1025 ]
1026 }
1027}
1028
1029#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1031#[ts(export)]
1032#[serde(tag = "type", rename_all = "camelCase")]
1033pub enum SketchSurface {
1034 Plane(Box<Plane>),
1035 Face(Box<Face>),
1036}
1037
1038impl SketchSurface {
1039 pub(crate) fn id(&self) -> uuid::Uuid {
1040 match self {
1041 SketchSurface::Plane(plane) => plane.id,
1042 SketchSurface::Face(face) => face.id,
1043 }
1044 }
1045 pub(crate) fn x_axis(&self) -> Point3d {
1046 match self {
1047 SketchSurface::Plane(plane) => plane.info.x_axis,
1048 SketchSurface::Face(face) => face.x_axis,
1049 }
1050 }
1051 pub(crate) fn y_axis(&self) -> Point3d {
1052 match self {
1053 SketchSurface::Plane(plane) => plane.info.y_axis,
1054 SketchSurface::Face(face) => face.y_axis,
1055 }
1056 }
1057
1058 pub(crate) fn object_id(&self) -> Option<ObjectId> {
1059 match self {
1060 SketchSurface::Plane(plane) => plane.object_id,
1061 SketchSurface::Face(face) => Some(face.object_id),
1062 }
1063 }
1064
1065 pub(crate) fn set_object_id(&mut self, object_id: ObjectId) {
1066 match self {
1067 SketchSurface::Plane(plane) => plane.object_id = Some(object_id),
1068 SketchSurface::Face(face) => face.object_id = object_id,
1069 }
1070 }
1071}
1072
1073#[derive(Debug, Clone, PartialEq)]
1075pub enum Extrudable {
1076 Sketch(Box<Sketch>),
1078 FaceTag(FaceTag),
1080 Face(Box<Face>),
1082 EdgeTag(Box<TagIdentifier>),
1084 Edge(Uuid),
1086 EdgeSpecifier(UnresolvedEdgeSpecifier),
1088}
1089
1090impl Extrudable {
1091 pub async fn id_to_extrude(
1093 &self,
1094 exec_state: &mut ExecState,
1095 args: &Args,
1096 must_be_planar: bool,
1097 ) -> Result<uuid::Uuid, KclError> {
1098 match self {
1099 Extrudable::Sketch(sketch) => Ok(sketch.id),
1100 Extrudable::FaceTag(face_tag) => face_tag.get_face_id_from_tag(exec_state, args, must_be_planar).await,
1101 Extrudable::Face(face) => Ok(face.id),
1102 Extrudable::EdgeTag(edge_tag) => match edge_tag.get_cur_info() {
1103 Some(info) => Ok(info.id),
1104 None => Err(KclError::new_type(KclErrorDetails::new(
1105 "Could not find a valid id to extrude".to_owned(),
1106 vec![args.source_range],
1107 ))),
1108 },
1109 Extrudable::Edge(edge) => Ok(*edge),
1110 Extrudable::EdgeSpecifier(_) => Err(KclError::new_type(KclErrorDetails::new(
1111 "Could not find a legacy id for edge specifier".to_owned(),
1112 vec![args.source_range],
1113 ))),
1114 }
1115 }
1116
1117 pub fn as_sketch(&self) -> Option<Sketch> {
1118 match self {
1119 Extrudable::Sketch(sketch) => Some((**sketch).clone()),
1120 Extrudable::FaceTag(face) => match face.geometry() {
1121 Some(Geometry::Sketch(sketch)) => Some(sketch),
1122 Some(Geometry::Solid(solid)) => solid.sketch().cloned(),
1123 None => None,
1124 },
1125 Extrudable::Face(_) => None,
1126 Extrudable::EdgeTag(tag_identifier) => match tag_identifier.geometry() {
1127 Some(Geometry::Sketch(sketch)) => Some(sketch),
1128 Some(Geometry::Solid(solid)) => solid.sketch().cloned(),
1129 None => None,
1130 },
1131 Extrudable::Edge(_) => None,
1132 Extrudable::EdgeSpecifier(_) => None,
1133 }
1134 }
1135
1136 pub fn is_closed(&self) -> ProfileClosed {
1137 match self {
1138 Extrudable::Sketch(sketch) => sketch.is_closed,
1139 Extrudable::FaceTag(face_tag) => match face_tag.geometry() {
1140 Some(Geometry::Sketch(sketch)) => sketch.is_closed,
1141 Some(Geometry::Solid(solid)) => solid
1142 .sketch()
1143 .map(|sketch| sketch.is_closed)
1144 .unwrap_or(ProfileClosed::Maybe),
1145 _ => ProfileClosed::Maybe,
1146 },
1147 Extrudable::Face(face) => match face.parent_solid.creator_sketch_is_closed {
1148 Some(is_closed) => is_closed,
1149 None => ProfileClosed::Maybe,
1150 },
1151 Extrudable::EdgeTag(edge_tag) => match edge_tag.geometry() {
1152 Some(Geometry::Sketch(sketch)) => sketch.is_closed,
1153 Some(Geometry::Solid(solid)) => solid
1154 .sketch()
1155 .map(|sketch| sketch.is_closed)
1156 .unwrap_or(ProfileClosed::Maybe),
1157 _ => ProfileClosed::Maybe,
1158 },
1159 Extrudable::Edge(_) => ProfileClosed::Maybe,
1160 Extrudable::EdgeSpecifier(_) => ProfileClosed::Maybe,
1161 }
1162 }
1163}
1164
1165impl From<Sketch> for Extrudable {
1166 fn from(value: Sketch) -> Self {
1167 Extrudable::Sketch(Box::new(value))
1168 }
1169}
1170
1171#[derive(Debug, Clone)]
1172pub(crate) enum GetTangentialInfoFromPathsResult {
1173 PreviousPoint([f64; 2]),
1174 Arc {
1175 center: [f64; 2],
1176 ccw: bool,
1177 },
1178 Circle {
1179 center: [f64; 2],
1180 ccw: bool,
1181 radius: f64,
1182 },
1183 Ellipse {
1184 center: [f64; 2],
1185 ccw: bool,
1186 major_axis: [f64; 2],
1187 _minor_radius: f64,
1188 },
1189}
1190
1191impl GetTangentialInfoFromPathsResult {
1192 pub(crate) fn tan_previous_point(&self, last_arc_end: [f64; 2]) -> [f64; 2] {
1193 match self {
1194 GetTangentialInfoFromPathsResult::PreviousPoint(p) => *p,
1195 GetTangentialInfoFromPathsResult::Arc { center, ccw } => {
1196 crate::std::utils::get_tangent_point_from_previous_arc(*center, *ccw, last_arc_end)
1197 }
1198 GetTangentialInfoFromPathsResult::Circle {
1201 center, radius, ccw, ..
1202 } => [center[0] + radius, center[1] + if *ccw { -1.0 } else { 1.0 }],
1203 GetTangentialInfoFromPathsResult::Ellipse {
1204 center,
1205 major_axis,
1206 ccw,
1207 ..
1208 } => [center[0] + major_axis[0], center[1] + if *ccw { -1.0 } else { 1.0 }],
1209 }
1210 }
1211}
1212
1213impl Sketch {
1214 pub(crate) fn add_tag(
1215 &mut self,
1216 tag: NodeRef<'_, TagDeclarator>,
1217 current_path: &Path,
1218 exec_state: &ExecState,
1219 surface: Option<&ExtrudeSurface>,
1220 ) {
1221 let mut tag_identifier: TagIdentifier = tag.into();
1222 let base = current_path.get_base();
1223 let mut sketch_copy = self.clone();
1224 sketch_copy.tags.clear();
1225 tag_identifier.info.push((
1226 exec_state.stack().current_epoch(),
1227 TagEngineInfo {
1228 id: base.geo_meta.id,
1229 geometry: Geometry::Sketch(sketch_copy),
1230 path: Some(current_path.clone()),
1231 surface: surface.cloned(),
1232 },
1233 ));
1234
1235 self.tags.insert(tag.name.to_string(), tag_identifier);
1236 }
1237
1238 pub(crate) fn merge_tags<'a>(&mut self, tags: impl Iterator<Item = &'a TagIdentifier>) {
1239 for t in tags {
1240 match self.tags.get_mut(&t.value) {
1241 Some(id) => {
1242 id.merge_info(t);
1243 }
1244 None => {
1245 self.tags.insert(t.value.clone(), t.clone());
1246 }
1247 }
1248 }
1249 }
1250
1251 pub(crate) fn latest_path(&self) -> Option<&Path> {
1253 self.paths.last()
1254 }
1255
1256 pub(crate) fn current_pen_position(&self) -> Result<Point2d, KclError> {
1260 let Some(path) = self.latest_path() else {
1261 return Ok(Point2d::new(self.start.to[0], self.start.to[1], self.start.units));
1262 };
1263
1264 let to = path.get_base().to;
1265 Ok(Point2d::new(to[0], to[1], path.get_base().units))
1266 }
1267
1268 pub(crate) fn get_tangential_info_from_paths(&self) -> GetTangentialInfoFromPathsResult {
1269 let Some(path) = self.latest_path() else {
1270 return GetTangentialInfoFromPathsResult::PreviousPoint(self.start.to);
1271 };
1272 path.get_tangential_info()
1273 }
1274}
1275
1276#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1277#[ts(export)]
1278#[serde(tag = "type", rename_all = "camelCase")]
1279pub struct Solid {
1280 pub id: uuid::Uuid,
1282 #[serde(skip)]
1284 #[ts(skip)]
1285 pub value_id: uuid::Uuid,
1286 #[serde(skip)]
1290 #[ts(skip)]
1291 pub(crate) topology_id: uuid::Uuid,
1292 #[serde(skip)]
1296 #[ts(skip)]
1297 pub(crate) pattern_source_artifact_id: Option<ArtifactId>,
1298 #[serde(skip)]
1304 #[ts(skip)]
1305 pub(crate) best_guess_body_type: Option<kcmc::shared::BodyType>,
1306 pub artifact_id: ArtifactId,
1308 pub value: Vec<ExtrudeSurface>,
1310 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
1313 pub faces: IndexMap<String, TagIdentifier>,
1314 #[serde(rename = "sketch")]
1316 pub creator: SolidCreator,
1317 pub start_cap_id: Option<uuid::Uuid>,
1319 pub end_cap_id: Option<uuid::Uuid>,
1321 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1323 pub edge_cuts: Vec<EdgeCut>,
1324 #[serde(skip)]
1326 #[ts(skip)]
1327 pub pending_edge_cut_ids: Vec<uuid::Uuid>,
1328 pub units: UnitLength,
1330 pub sectional: bool,
1332 #[serde(skip)]
1334 pub meta: Vec<Metadata>,
1335}
1336
1337#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1338#[ts(export)]
1339pub struct CreatorFace {
1340 pub face_id: uuid::Uuid,
1342 pub solid_id: uuid::Uuid,
1344 pub sketch: Sketch,
1346}
1347
1348#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1349#[ts(export)]
1350pub struct CreatorEdge {
1351 pub edge_id: uuid::Uuid,
1353 pub body_id: uuid::Uuid,
1355}
1356
1357#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1359#[ts(export)]
1360#[serde(tag = "creatorType", rename_all = "camelCase")]
1361pub enum SolidCreator {
1362 Sketch(Sketch),
1364 Face(CreatorFace),
1366 Edge(CreatorEdge),
1368 Procedural,
1370}
1371
1372impl Solid {
1373 pub fn sketch(&self) -> Option<&Sketch> {
1374 match &self.creator {
1375 SolidCreator::Sketch(sketch) => Some(sketch),
1376 SolidCreator::Face(CreatorFace { sketch, .. }) => Some(sketch),
1377 SolidCreator::Edge(_) => None,
1378 SolidCreator::Procedural => None,
1379 }
1380 }
1381
1382 pub fn sketch_mut(&mut self) -> Option<&mut Sketch> {
1383 match &mut self.creator {
1384 SolidCreator::Sketch(sketch) => Some(sketch),
1385 SolidCreator::Face(CreatorFace { sketch, .. }) => Some(sketch),
1386 SolidCreator::Edge(_) => None,
1387 SolidCreator::Procedural => None,
1388 }
1389 }
1390
1391 pub fn sketch_id(&self) -> Option<uuid::Uuid> {
1392 self.sketch().map(|sketch| sketch.id)
1393 }
1394
1395 pub fn original_id(&self) -> uuid::Uuid {
1396 self.sketch().map(|sketch| sketch.original_id).unwrap_or(self.id)
1397 }
1398
1399 pub(crate) fn topology_id(&self) -> uuid::Uuid {
1400 self.topology_id
1401 }
1402
1403 pub(crate) fn become_new_body(&mut self, engine_id: uuid::Uuid, artifact_id: ArtifactId) {
1407 self.topology_id = engine_id;
1408 self.pattern_source_artifact_id = None;
1409 self.artifact_id = artifact_id;
1410 }
1411
1412 pub(crate) fn become_pattern_copy(&mut self, copy_engine_id: uuid::Uuid) {
1416 self.pattern_source_artifact_id.get_or_insert(self.artifact_id);
1417 self.artifact_id = ArtifactId::new(copy_engine_id);
1418 }
1419
1420 pub(crate) fn get_all_edge_cut_ids(&self) -> impl Iterator<Item = uuid::Uuid> + '_ {
1421 self.edge_cuts
1422 .iter()
1423 .map(|foc| foc.id())
1424 .chain(self.pending_edge_cut_ids.iter().copied())
1425 }
1426}
1427
1428impl From<&Solid> for FaceParentSolid {
1429 fn from(solid: &Solid) -> Self {
1430 Self {
1431 solid_id: solid.id,
1432 creator_sketch_id: solid.sketch_id(),
1433 creator_sketch_is_closed: solid.sketch().map(|sketch| sketch.is_closed),
1434 edge_cut_ids: solid.get_all_edge_cut_ids().collect(),
1435 }
1436 }
1437}
1438
1439#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1441#[ts(export)]
1442#[serde(tag = "type", rename_all = "camelCase")]
1443pub enum EdgeCut {
1444 Fillet {
1446 id: uuid::Uuid,
1448 radius: TyF64,
1449 #[serde(rename = "edgeId")]
1451 edge_id: uuid::Uuid,
1452 tag: Box<Option<TagNode>>,
1453 },
1454 Chamfer {
1456 id: uuid::Uuid,
1458 length: TyF64,
1459 #[serde(rename = "edgeId")]
1461 edge_id: uuid::Uuid,
1462 tag: Box<Option<TagNode>>,
1463 },
1464}
1465
1466impl EdgeCut {
1467 pub fn id(&self) -> uuid::Uuid {
1468 match self {
1469 EdgeCut::Fillet { id, .. } => *id,
1470 EdgeCut::Chamfer { id, .. } => *id,
1471 }
1472 }
1473
1474 pub fn set_id(&mut self, id: uuid::Uuid) {
1475 match self {
1476 EdgeCut::Fillet { id: i, .. } => *i = id,
1477 EdgeCut::Chamfer { id: i, .. } => *i = id,
1478 }
1479 }
1480
1481 pub fn edge_id(&self) -> uuid::Uuid {
1482 match self {
1483 EdgeCut::Fillet { edge_id, .. } => *edge_id,
1484 EdgeCut::Chamfer { edge_id, .. } => *edge_id,
1485 }
1486 }
1487
1488 pub fn set_edge_id(&mut self, id: uuid::Uuid) {
1489 match self {
1490 EdgeCut::Fillet { edge_id: i, .. } => *i = id,
1491 EdgeCut::Chamfer { edge_id: i, .. } => *i = id,
1492 }
1493 }
1494
1495 pub fn tag(&self) -> Option<TagNode> {
1496 match self {
1497 EdgeCut::Fillet { tag, .. } => *tag.clone(),
1498 EdgeCut::Chamfer { tag, .. } => *tag.clone(),
1499 }
1500 }
1501}
1502
1503#[derive(Debug, Serialize, PartialEq, Clone, Copy, ts_rs::TS)]
1504#[ts(export)]
1505pub struct Point2d {
1506 pub x: f64,
1507 pub y: f64,
1508 pub units: UnitLength,
1509}
1510
1511impl Point2d {
1512 pub const ZERO: Self = Self {
1513 x: 0.0,
1514 y: 0.0,
1515 units: UnitLength::Millimeters,
1516 };
1517
1518 pub fn new(x: f64, y: f64, units: UnitLength) -> Self {
1519 Self { x, y, units }
1520 }
1521
1522 pub fn into_x(self) -> TyF64 {
1523 TyF64::new(self.x, NumericType::length(self.units))
1524 }
1525
1526 pub fn into_y(self) -> TyF64 {
1527 TyF64::new(self.y, NumericType::length(self.units))
1528 }
1529
1530 pub fn ignore_units(self) -> [f64; 2] {
1531 [self.x, self.y]
1532 }
1533}
1534
1535#[derive(Debug, Deserialize, Serialize, PartialEq, Clone, Copy, ts_rs::TS, Default)]
1536#[ts(export)]
1537pub struct Point3d {
1538 pub x: f64,
1539 pub y: f64,
1540 pub z: f64,
1541 pub units: Option<UnitLength>,
1542}
1543
1544impl Point3d {
1545 pub const ZERO: Self = Self {
1546 x: 0.0,
1547 y: 0.0,
1548 z: 0.0,
1549 units: Some(UnitLength::Millimeters),
1550 };
1551
1552 pub fn new(x: f64, y: f64, z: f64, units: Option<UnitLength>) -> Self {
1553 Self { x, y, z, units }
1554 }
1555
1556 pub const fn is_zero(&self) -> bool {
1557 self.x == 0.0 && self.y == 0.0 && self.z == 0.0
1558 }
1559
1560 pub fn axes_cross_product(&self, other: &Self) -> Self {
1565 Self {
1566 x: self.y * other.z - self.z * other.y,
1567 y: self.z * other.x - self.x * other.z,
1568 z: self.x * other.y - self.y * other.x,
1569 units: None,
1570 }
1571 }
1572
1573 pub fn canonicalize_signed_zero(&mut self) {
1575 if self.x == 0.0 {
1576 self.x = 0.0;
1577 }
1578 if self.y == 0.0 {
1579 self.y = 0.0;
1580 }
1581 if self.z == 0.0 {
1582 self.z = 0.0;
1583 }
1584 }
1585
1586 pub fn axes_dot_product(&self, other: &Self) -> f64 {
1591 let x = self.x * other.x;
1592 let y = self.y * other.y;
1593 let z = self.z * other.z;
1594 x + y + z
1595 }
1596
1597 pub fn normalize(&self) -> Self {
1598 let len = f64::sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
1599 Point3d {
1600 x: self.x / len,
1601 y: self.y / len,
1602 z: self.z / len,
1603 units: None,
1604 }
1605 }
1606
1607 pub fn as_3_dims(&self) -> ([f64; 3], Option<UnitLength>) {
1608 let p = [self.x, self.y, self.z];
1609 let u = self.units;
1610 (p, u)
1611 }
1612
1613 pub(crate) fn negated(self) -> Self {
1614 Self {
1615 x: -self.x,
1616 y: -self.y,
1617 z: -self.z,
1618 units: self.units,
1619 }
1620 }
1621}
1622
1623impl From<[TyF64; 3]> for Point3d {
1624 fn from(p: [TyF64; 3]) -> Self {
1625 Self {
1626 x: p[0].n,
1627 y: p[1].n,
1628 z: p[2].n,
1629 units: p[0].ty.as_length(),
1630 }
1631 }
1632}
1633
1634impl From<Point3d> for Point3D {
1635 fn from(p: Point3d) -> Self {
1636 Self { x: p.x, y: p.y, z: p.z }
1637 }
1638}
1639
1640impl From<Point3d> for kittycad_modeling_cmds::shared::Point3d<LengthUnit> {
1641 fn from(p: Point3d) -> Self {
1642 if let Some(units) = p.units {
1643 Self {
1644 x: LengthUnit(adjust_length(units, p.x, UnitLength::Millimeters).0),
1645 y: LengthUnit(adjust_length(units, p.y, UnitLength::Millimeters).0),
1646 z: LengthUnit(adjust_length(units, p.z, UnitLength::Millimeters).0),
1647 }
1648 } else {
1649 Self {
1650 x: LengthUnit(p.x),
1651 y: LengthUnit(p.y),
1652 z: LengthUnit(p.z),
1653 }
1654 }
1655 }
1656}
1657
1658impl Add for Point3d {
1659 type Output = Point3d;
1660
1661 fn add(self, rhs: Self) -> Self::Output {
1662 Point3d {
1664 x: self.x + rhs.x,
1665 y: self.y + rhs.y,
1666 z: self.z + rhs.z,
1667 units: self.units,
1668 }
1669 }
1670}
1671
1672impl AddAssign for Point3d {
1673 fn add_assign(&mut self, rhs: Self) {
1674 *self = *self + rhs
1675 }
1676}
1677
1678impl Sub for Point3d {
1679 type Output = Point3d;
1680
1681 fn sub(self, rhs: Self) -> Self::Output {
1682 let (x, y, z) = if rhs.units != self.units
1683 && let Some(sunits) = self.units
1684 && let Some(runits) = rhs.units
1685 {
1686 (
1687 adjust_length(runits, rhs.x, sunits).0,
1688 adjust_length(runits, rhs.y, sunits).0,
1689 adjust_length(runits, rhs.z, sunits).0,
1690 )
1691 } else {
1692 (rhs.x, rhs.y, rhs.z)
1693 };
1694 Point3d {
1695 x: self.x - x,
1696 y: self.y - y,
1697 z: self.z - z,
1698 units: self.units,
1699 }
1700 }
1701}
1702
1703impl SubAssign for Point3d {
1704 fn sub_assign(&mut self, rhs: Self) {
1705 *self = *self - rhs
1706 }
1707}
1708
1709impl Mul<f64> for Point3d {
1710 type Output = Point3d;
1711
1712 fn mul(self, rhs: f64) -> Self::Output {
1713 Point3d {
1714 x: self.x * rhs,
1715 y: self.y * rhs,
1716 z: self.z * rhs,
1717 units: self.units,
1718 }
1719 }
1720}
1721
1722#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1724#[ts(export)]
1725#[serde(rename_all = "camelCase")]
1726pub struct BasePath {
1727 #[ts(type = "[number, number]")]
1729 pub from: [f64; 2],
1730 #[ts(type = "[number, number]")]
1732 pub to: [f64; 2],
1733 pub units: UnitLength,
1734 pub tag: Option<TagNode>,
1736 #[serde(rename = "__geoMeta")]
1738 pub geo_meta: GeoMeta,
1739}
1740
1741impl BasePath {
1742 pub fn get_to(&self) -> [TyF64; 2] {
1743 let ty = NumericType::length(self.units);
1744 [TyF64::new(self.to[0], ty), TyF64::new(self.to[1], ty)]
1745 }
1746
1747 pub fn get_from(&self) -> [TyF64; 2] {
1748 let ty = NumericType::length(self.units);
1749 [TyF64::new(self.from[0], ty), TyF64::new(self.from[1], ty)]
1750 }
1751}
1752
1753#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1755#[ts(export)]
1756#[serde(rename_all = "camelCase")]
1757pub struct GeoMeta {
1758 pub id: uuid::Uuid,
1760 #[serde(flatten)]
1762 pub metadata: Metadata,
1763}
1764
1765#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1767#[ts(export)]
1768#[serde(tag = "type")]
1769pub enum Path {
1770 ToPoint {
1772 #[serde(flatten)]
1773 base: BasePath,
1774 },
1775 TangentialArcTo {
1777 #[serde(flatten)]
1778 base: BasePath,
1779 #[ts(type = "[number, number]")]
1781 center: [f64; 2],
1782 ccw: bool,
1784 },
1785 TangentialArc {
1787 #[serde(flatten)]
1788 base: BasePath,
1789 #[ts(type = "[number, number]")]
1791 center: [f64; 2],
1792 ccw: bool,
1794 },
1795 Circle {
1798 #[serde(flatten)]
1799 base: BasePath,
1800 #[ts(type = "[number, number]")]
1802 center: [f64; 2],
1803 radius: f64,
1805 ccw: bool,
1808 },
1809 CircleThreePoint {
1810 #[serde(flatten)]
1811 base: BasePath,
1812 #[ts(type = "[number, number]")]
1814 p1: [f64; 2],
1815 #[ts(type = "[number, number]")]
1817 p2: [f64; 2],
1818 #[ts(type = "[number, number]")]
1820 p3: [f64; 2],
1821 },
1822 ArcThreePoint {
1823 #[serde(flatten)]
1824 base: BasePath,
1825 #[ts(type = "[number, number]")]
1827 p1: [f64; 2],
1828 #[ts(type = "[number, number]")]
1830 p2: [f64; 2],
1831 #[ts(type = "[number, number]")]
1833 p3: [f64; 2],
1834 },
1835 Horizontal {
1837 #[serde(flatten)]
1838 base: BasePath,
1839 x: f64,
1841 },
1842 AngledLineTo {
1844 #[serde(flatten)]
1845 base: BasePath,
1846 x: Option<f64>,
1848 y: Option<f64>,
1850 },
1851 Base {
1853 #[serde(flatten)]
1854 base: BasePath,
1855 },
1856 Arc {
1858 #[serde(flatten)]
1859 base: BasePath,
1860 center: [f64; 2],
1862 radius: f64,
1864 ccw: bool,
1866 },
1867 Ellipse {
1868 #[serde(flatten)]
1869 base: BasePath,
1870 center: [f64; 2],
1871 major_axis: [f64; 2],
1872 minor_radius: f64,
1873 ccw: bool,
1874 },
1875 Conic {
1877 #[serde(flatten)]
1878 base: BasePath,
1879 },
1880 Bezier {
1882 #[serde(flatten)]
1883 base: BasePath,
1884 #[ts(type = "[number, number]")]
1886 control1: [f64; 2],
1887 #[ts(type = "[number, number]")]
1889 control2: [f64; 2],
1890 },
1891}
1892
1893impl Path {
1894 pub fn get_id(&self) -> uuid::Uuid {
1895 match self {
1896 Path::ToPoint { base } => base.geo_meta.id,
1897 Path::Horizontal { base, .. } => base.geo_meta.id,
1898 Path::AngledLineTo { base, .. } => base.geo_meta.id,
1899 Path::Base { base } => base.geo_meta.id,
1900 Path::TangentialArcTo { base, .. } => base.geo_meta.id,
1901 Path::TangentialArc { base, .. } => base.geo_meta.id,
1902 Path::Circle { base, .. } => base.geo_meta.id,
1903 Path::CircleThreePoint { base, .. } => base.geo_meta.id,
1904 Path::Arc { base, .. } => base.geo_meta.id,
1905 Path::ArcThreePoint { base, .. } => base.geo_meta.id,
1906 Path::Ellipse { base, .. } => base.geo_meta.id,
1907 Path::Conic { base, .. } => base.geo_meta.id,
1908 Path::Bezier { base, .. } => base.geo_meta.id,
1909 }
1910 }
1911
1912 pub fn set_id(&mut self, id: uuid::Uuid) {
1913 match self {
1914 Path::ToPoint { base } => base.geo_meta.id = id,
1915 Path::Horizontal { base, .. } => base.geo_meta.id = id,
1916 Path::AngledLineTo { base, .. } => base.geo_meta.id = id,
1917 Path::Base { base } => base.geo_meta.id = id,
1918 Path::TangentialArcTo { base, .. } => base.geo_meta.id = id,
1919 Path::TangentialArc { base, .. } => base.geo_meta.id = id,
1920 Path::Circle { base, .. } => base.geo_meta.id = id,
1921 Path::CircleThreePoint { base, .. } => base.geo_meta.id = id,
1922 Path::Arc { base, .. } => base.geo_meta.id = id,
1923 Path::ArcThreePoint { base, .. } => base.geo_meta.id = id,
1924 Path::Ellipse { base, .. } => base.geo_meta.id = id,
1925 Path::Conic { base, .. } => base.geo_meta.id = id,
1926 Path::Bezier { base, .. } => base.geo_meta.id = id,
1927 }
1928 }
1929
1930 pub fn get_tag(&self) -> Option<TagNode> {
1931 match self {
1932 Path::ToPoint { base } => base.tag.clone(),
1933 Path::Horizontal { base, .. } => base.tag.clone(),
1934 Path::AngledLineTo { base, .. } => base.tag.clone(),
1935 Path::Base { base } => base.tag.clone(),
1936 Path::TangentialArcTo { base, .. } => base.tag.clone(),
1937 Path::TangentialArc { base, .. } => base.tag.clone(),
1938 Path::Circle { base, .. } => base.tag.clone(),
1939 Path::CircleThreePoint { base, .. } => base.tag.clone(),
1940 Path::Arc { base, .. } => base.tag.clone(),
1941 Path::ArcThreePoint { base, .. } => base.tag.clone(),
1942 Path::Ellipse { base, .. } => base.tag.clone(),
1943 Path::Conic { base, .. } => base.tag.clone(),
1944 Path::Bezier { base, .. } => base.tag.clone(),
1945 }
1946 }
1947
1948 pub fn get_base(&self) -> &BasePath {
1949 match self {
1950 Path::ToPoint { base } => base,
1951 Path::Horizontal { base, .. } => base,
1952 Path::AngledLineTo { base, .. } => base,
1953 Path::Base { base } => base,
1954 Path::TangentialArcTo { base, .. } => base,
1955 Path::TangentialArc { base, .. } => base,
1956 Path::Circle { base, .. } => base,
1957 Path::CircleThreePoint { base, .. } => base,
1958 Path::Arc { base, .. } => base,
1959 Path::ArcThreePoint { base, .. } => base,
1960 Path::Ellipse { base, .. } => base,
1961 Path::Conic { base, .. } => base,
1962 Path::Bezier { base, .. } => base,
1963 }
1964 }
1965
1966 pub fn get_from(&self) -> [TyF64; 2] {
1968 let p = &self.get_base().from;
1969 let ty = NumericType::length(self.get_base().units);
1970 [TyF64::new(p[0], ty), TyF64::new(p[1], ty)]
1971 }
1972
1973 pub fn get_to(&self) -> [TyF64; 2] {
1975 let p = &self.get_base().to;
1976 let ty = NumericType::length(self.get_base().units);
1977 [TyF64::new(p[0], ty), TyF64::new(p[1], ty)]
1978 }
1979
1980 pub fn start_point_components(&self) -> ([f64; 2], NumericType) {
1982 let p = &self.get_base().from;
1983 let ty = NumericType::length(self.get_base().units);
1984 (*p, ty)
1985 }
1986
1987 pub fn end_point_components(&self) -> ([f64; 2], NumericType) {
1989 let p = &self.get_base().to;
1990 let ty = NumericType::length(self.get_base().units);
1991 (*p, ty)
1992 }
1993
1994 pub fn length(&self) -> Option<TyF64> {
1997 let n = match self {
1998 Self::ToPoint { .. } | Self::Base { .. } | Self::Horizontal { .. } | Self::AngledLineTo { .. } => {
1999 Some(linear_distance(&self.get_base().from, &self.get_base().to))
2000 }
2001 Self::TangentialArc {
2002 base: _,
2003 center,
2004 ccw: _,
2005 }
2006 | Self::TangentialArcTo {
2007 base: _,
2008 center,
2009 ccw: _,
2010 } => {
2011 let radius = linear_distance(&self.get_base().from, center);
2014 debug_assert_eq!(radius, linear_distance(&self.get_base().to, center));
2015 Some(linear_distance(&self.get_base().from, &self.get_base().to))
2017 }
2018 Self::Circle { radius, .. } => Some(TAU * radius),
2019 Self::CircleThreePoint { .. } => {
2020 let circle_center = crate::std::utils::calculate_circle_from_3_points([
2021 self.get_base().from,
2022 self.get_base().to,
2023 self.get_base().to,
2024 ]);
2025 let radius = linear_distance(
2026 &[circle_center.center[0], circle_center.center[1]],
2027 &self.get_base().from,
2028 );
2029 Some(TAU * radius)
2030 }
2031 Self::Arc { .. } => {
2032 Some(linear_distance(&self.get_base().from, &self.get_base().to))
2034 }
2035 Self::ArcThreePoint { .. } => {
2036 Some(linear_distance(&self.get_base().from, &self.get_base().to))
2038 }
2039 Self::Ellipse { .. } => {
2040 None
2042 }
2043 Self::Conic { .. } => {
2044 None
2046 }
2047 Self::Bezier { .. } => {
2048 None
2050 }
2051 };
2052 n.map(|n| TyF64::new(n, NumericType::length(self.get_base().units)))
2053 }
2054
2055 pub fn get_base_mut(&mut self) -> &mut BasePath {
2056 match self {
2057 Path::ToPoint { base } => base,
2058 Path::Horizontal { base, .. } => base,
2059 Path::AngledLineTo { base, .. } => base,
2060 Path::Base { base } => base,
2061 Path::TangentialArcTo { base, .. } => base,
2062 Path::TangentialArc { base, .. } => base,
2063 Path::Circle { base, .. } => base,
2064 Path::CircleThreePoint { base, .. } => base,
2065 Path::Arc { base, .. } => base,
2066 Path::ArcThreePoint { base, .. } => base,
2067 Path::Ellipse { base, .. } => base,
2068 Path::Conic { base, .. } => base,
2069 Path::Bezier { base, .. } => base,
2070 }
2071 }
2072
2073 pub(crate) fn get_tangential_info(&self) -> GetTangentialInfoFromPathsResult {
2074 match self {
2075 Path::TangentialArc { center, ccw, .. }
2076 | Path::TangentialArcTo { center, ccw, .. }
2077 | Path::Arc { center, ccw, .. } => GetTangentialInfoFromPathsResult::Arc {
2078 center: *center,
2079 ccw: *ccw,
2080 },
2081 Path::ArcThreePoint { p1, p2, p3, .. } => {
2082 let circle = crate::std::utils::calculate_circle_from_3_points([*p1, *p2, *p3]);
2083 GetTangentialInfoFromPathsResult::Arc {
2084 center: circle.center,
2085 ccw: crate::std::utils::is_points_ccw(&[*p1, *p2, *p3]) > 0,
2086 }
2087 }
2088 Path::Circle {
2089 center, ccw, radius, ..
2090 } => GetTangentialInfoFromPathsResult::Circle {
2091 center: *center,
2092 ccw: *ccw,
2093 radius: *radius,
2094 },
2095 Path::CircleThreePoint { p1, p2, p3, .. } => {
2096 let circle = crate::std::utils::calculate_circle_from_3_points([*p1, *p2, *p3]);
2097 let center_point = [circle.center[0], circle.center[1]];
2098 GetTangentialInfoFromPathsResult::Circle {
2099 center: center_point,
2100 ccw: true,
2102 radius: circle.radius,
2103 }
2104 }
2105 Path::Ellipse {
2107 center,
2108 major_axis,
2109 minor_radius,
2110 ccw,
2111 ..
2112 } => GetTangentialInfoFromPathsResult::Ellipse {
2113 center: *center,
2114 major_axis: *major_axis,
2115 _minor_radius: *minor_radius,
2116 ccw: *ccw,
2117 },
2118 Path::Conic { .. }
2119 | Path::ToPoint { .. }
2120 | Path::Horizontal { .. }
2121 | Path::AngledLineTo { .. }
2122 | Path::Base { .. }
2123 | Path::Bezier { .. } => {
2124 let base = self.get_base();
2125 GetTangentialInfoFromPathsResult::PreviousPoint(base.from)
2126 }
2127 }
2128 }
2129
2130 pub(crate) fn is_straight_line(&self) -> bool {
2132 matches!(self, Path::AngledLineTo { .. } | Path::ToPoint { .. })
2133 }
2134}
2135
2136#[rustfmt::skip]
2138fn linear_distance(
2139 [x0, y0]: &[f64; 2],
2140 [x1, y1]: &[f64; 2]
2141) -> f64 {
2142 let y_sq = (y1 - y0).squared();
2143 let x_sq = (x1 - x0).squared();
2144 (y_sq + x_sq).sqrt()
2145}
2146
2147#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2149#[ts(export)]
2150#[serde(tag = "type", rename_all = "camelCase")]
2151pub enum ExtrudeSurface {
2152 ExtrudePlane(ExtrudePlane),
2154 ExtrudeArc(ExtrudeArc),
2155 Chamfer(ChamferSurface),
2156 Fillet(FilletSurface),
2157}
2158
2159#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2161#[ts(export)]
2162#[serde(rename_all = "camelCase")]
2163pub struct ChamferSurface {
2164 pub face_id: uuid::Uuid,
2166 pub tag: Option<Node<TagDeclarator>>,
2168 #[serde(flatten)]
2170 pub geo_meta: GeoMeta,
2171}
2172
2173#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2175#[ts(export)]
2176#[serde(rename_all = "camelCase")]
2177pub struct FilletSurface {
2178 pub face_id: uuid::Uuid,
2180 pub tag: Option<Node<TagDeclarator>>,
2182 #[serde(flatten)]
2184 pub geo_meta: GeoMeta,
2185}
2186
2187#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2189#[ts(export)]
2190#[serde(rename_all = "camelCase")]
2191pub struct ExtrudePlane {
2192 pub face_id: uuid::Uuid,
2194 pub tag: Option<Node<TagDeclarator>>,
2196 #[serde(flatten)]
2198 pub geo_meta: GeoMeta,
2199}
2200
2201#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2203#[ts(export)]
2204#[serde(rename_all = "camelCase")]
2205pub struct ExtrudeArc {
2206 pub face_id: uuid::Uuid,
2208 pub tag: Option<Node<TagDeclarator>>,
2210 #[serde(flatten)]
2212 pub geo_meta: GeoMeta,
2213}
2214
2215impl ExtrudeSurface {
2216 pub fn get_id(&self) -> uuid::Uuid {
2217 match self {
2218 ExtrudeSurface::ExtrudePlane(ep) => ep.geo_meta.id,
2219 ExtrudeSurface::ExtrudeArc(ea) => ea.geo_meta.id,
2220 ExtrudeSurface::Fillet(f) => f.geo_meta.id,
2221 ExtrudeSurface::Chamfer(c) => c.geo_meta.id,
2222 }
2223 }
2224
2225 pub fn set_id(&mut self, id: uuid::Uuid) {
2226 match self {
2227 ExtrudeSurface::ExtrudePlane(ep) => ep.geo_meta.id = id,
2228 ExtrudeSurface::ExtrudeArc(ea) => ea.geo_meta.id = id,
2229 ExtrudeSurface::Fillet(f) => f.geo_meta.id = id,
2230 ExtrudeSurface::Chamfer(c) => c.geo_meta.id = id,
2231 }
2232 }
2233
2234 pub fn face_id(&self) -> uuid::Uuid {
2235 match self {
2236 ExtrudeSurface::ExtrudePlane(ep) => ep.face_id,
2237 ExtrudeSurface::ExtrudeArc(ea) => ea.face_id,
2238 ExtrudeSurface::Fillet(f) => f.face_id,
2239 ExtrudeSurface::Chamfer(c) => c.face_id,
2240 }
2241 }
2242
2243 pub fn set_face_id(&mut self, face_id: uuid::Uuid) {
2244 match self {
2245 ExtrudeSurface::ExtrudePlane(ep) => ep.face_id = face_id,
2246 ExtrudeSurface::ExtrudeArc(ea) => ea.face_id = face_id,
2247 ExtrudeSurface::Fillet(f) => f.face_id = face_id,
2248 ExtrudeSurface::Chamfer(c) => c.face_id = face_id,
2249 }
2250 }
2251
2252 pub fn set_surface_tag(&mut self, tag: &TagNode) {
2253 match self {
2254 ExtrudeSurface::ExtrudePlane(extrude_plane) => extrude_plane.tag = Some(tag.clone()),
2255 ExtrudeSurface::ExtrudeArc(extrude_arc) => extrude_arc.tag = Some(tag.clone()),
2256 ExtrudeSurface::Chamfer(chamfer) => chamfer.tag = Some(tag.clone()),
2257 ExtrudeSurface::Fillet(fillet) => fillet.tag = Some(tag.clone()),
2258 }
2259 }
2260
2261 pub fn get_tag(&self) -> Option<Node<TagDeclarator>> {
2262 match self {
2263 ExtrudeSurface::ExtrudePlane(ep) => ep.tag.clone(),
2264 ExtrudeSurface::ExtrudeArc(ea) => ea.tag.clone(),
2265 ExtrudeSurface::Fillet(f) => f.tag.clone(),
2266 ExtrudeSurface::Chamfer(c) => c.tag.clone(),
2267 }
2268 }
2269}
2270
2271#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, ts_rs::TS)]
2272pub struct SketchVarId(pub usize);
2273
2274impl SketchVarId {
2275 pub const INVALID: Self = Self(usize::MAX);
2276
2277 pub fn to_constraint_id(self, range: SourceRange) -> Result<ezpz::Id, KclError> {
2278 self.0.try_into().map_err(|_| {
2279 KclError::new_type(KclErrorDetails::new(
2280 "Cannot convert to constraint ID since the sketch variable ID is too large".to_owned(),
2281 vec![range],
2282 ))
2283 })
2284 }
2285}
2286
2287#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2288#[ts(export_to = "Geometry.ts")]
2289#[serde(rename_all = "camelCase")]
2290pub struct SketchVar {
2291 pub id: SketchVarId,
2292 pub initial_value: f64,
2293 pub ty: NumericType,
2294 pub node_path: Option<NodePath>,
2296 #[serde(skip)]
2297 pub meta: Vec<Metadata>,
2298}
2299
2300impl SketchVar {
2301 pub fn initial_value_to_solver_units(
2302 &self,
2303 exec_state: &mut ExecState,
2304 source_range: SourceRange,
2305 description: &str,
2306 ) -> Result<TyF64, KclError> {
2307 let x_initial_value = KclValue::Number {
2308 value: self.initial_value,
2309 ty: self.ty,
2310 meta: vec![source_range.into()],
2311 };
2312 let normalized_value =
2313 normalize_to_solver_distance_unit(&x_initial_value, source_range, exec_state, description)?;
2314 normalized_value.as_ty_f64().ok_or_else(|| {
2315 let message = format!(
2316 "Expected number after coercion, but found {}",
2317 normalized_value.human_friendly_type()
2318 );
2319 debug_assert!(false, "{}", &message);
2320 KclError::new_internal(KclErrorDetails::new(message, vec![source_range]))
2321 })
2322 }
2323}
2324
2325#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2326#[ts(export_to = "Geometry.ts")]
2327#[serde(tag = "type")]
2328pub enum UnsolvedExpr {
2329 Known(TyF64),
2330 Unknown(SketchVarId),
2331}
2332
2333impl UnsolvedExpr {
2334 pub fn var(&self) -> Option<SketchVarId> {
2335 match self {
2336 UnsolvedExpr::Known(_) => None,
2337 UnsolvedExpr::Unknown(id) => Some(*id),
2338 }
2339 }
2340}
2341
2342pub type UnsolvedPoint2dExpr = [UnsolvedExpr; 2];
2343
2344#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2345#[ts(export_to = "Geometry.ts")]
2346#[serde(rename_all = "camelCase")]
2347pub struct ConstrainablePoint2d {
2348 pub vars: crate::front::Point2d<SketchVarId>,
2349 pub object_id: ObjectId,
2350}
2351
2352#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2353#[ts(export_to = "Geometry.ts")]
2354pub enum ConstrainablePoint2dOrOrigin {
2355 Point(ConstrainablePoint2d),
2356 Origin,
2357}
2358
2359#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2360#[ts(export_to = "Geometry.ts")]
2361#[serde(rename_all = "camelCase")]
2362pub struct ConstrainableLine2d {
2363 pub vars: [crate::front::Point2d<SketchVarId>; 2],
2364 pub object_id: ObjectId,
2365}
2366
2367#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2368#[ts(export_to = "Geometry.ts")]
2369#[serde(rename_all = "camelCase")]
2370pub struct UnsolvedSegment {
2371 pub id: Uuid,
2373 pub object_id: ObjectId,
2374 pub kind: UnsolvedSegmentKind,
2375 #[serde(skip_serializing_if = "Option::is_none")]
2376 pub tag: Option<TagIdentifier>,
2377 #[serde(skip)]
2378 pub node_path: Option<NodePath>,
2379 #[serde(skip)]
2380 pub meta: Vec<Metadata>,
2381}
2382
2383#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2384#[ts(export_to = "Geometry.ts")]
2385#[serde(rename_all = "camelCase")]
2386pub enum UnsolvedSegmentKind {
2387 Point {
2388 position: UnsolvedPoint2dExpr,
2389 ctor: Box<PointCtor>,
2390 },
2391 Line {
2392 start: UnsolvedPoint2dExpr,
2393 end: UnsolvedPoint2dExpr,
2394 ctor: Box<LineCtor>,
2395 start_object_id: ObjectId,
2396 end_object_id: ObjectId,
2397 construction: bool,
2398 },
2399 Arc {
2400 start: UnsolvedPoint2dExpr,
2401 end: UnsolvedPoint2dExpr,
2402 center: UnsolvedPoint2dExpr,
2403 ctor: Box<ArcCtor>,
2404 start_object_id: ObjectId,
2405 end_object_id: ObjectId,
2406 center_object_id: ObjectId,
2407 #[serde(default, skip_serializing_if = "ArcDirection::is_ccw")]
2413 #[ts(as = "Option<ArcDirection>")]
2414 #[ts(optional)]
2415 direction: ArcDirection,
2416 construction: bool,
2417 },
2418 Circle {
2419 start: UnsolvedPoint2dExpr,
2420 center: UnsolvedPoint2dExpr,
2421 ctor: Box<CircleCtor>,
2422 start_object_id: ObjectId,
2423 center_object_id: ObjectId,
2424 construction: bool,
2425 },
2426 ControlPointSpline {
2427 controls: Vec<UnsolvedPoint2dExpr>,
2428 ctor: Box<ControlPointSplineCtor>,
2429 control_object_ids: Vec<ObjectId>,
2430 control_polygon_edge_object_ids: Vec<ObjectId>,
2431 degree: u32,
2432 construction: bool,
2433 },
2434}
2435
2436impl UnsolvedSegmentKind {
2437 pub fn human_friendly_kind_with_article(&self) -> &'static str {
2440 match self {
2441 Self::Point { .. } => "a Point",
2442 Self::Line { .. } => "a Line",
2443 Self::Arc { .. } => "an Arc",
2444 Self::Circle { .. } => "a Circle",
2445 Self::ControlPointSpline { .. } => "a Control Point Spline",
2446 }
2447 }
2448}
2449
2450#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2451#[ts(export_to = "Geometry.ts")]
2452#[serde(rename_all = "camelCase")]
2453pub struct Segment {
2454 pub id: Uuid,
2456 pub object_id: ObjectId,
2457 pub kind: SegmentKind,
2458 pub surface: SketchSurface,
2459 pub sketch_id: Uuid,
2461 #[serde(skip)]
2462 #[ts(skip)]
2463 pub sketch: Option<Arc<Sketch>>,
2464 #[serde(skip_serializing_if = "Option::is_none")]
2465 pub tag: Option<TagIdentifier>,
2466 #[serde(skip)]
2467 pub node_path: Option<NodePath>,
2468 #[serde(skip)]
2469 pub meta: Vec<Metadata>,
2470}
2471
2472impl Segment {
2473 pub fn is_construction(&self) -> bool {
2474 match &self.kind {
2475 SegmentKind::Point { .. } => true,
2476 SegmentKind::Line { construction, .. } => *construction,
2477 SegmentKind::Arc { construction, .. } => *construction,
2478 SegmentKind::Circle { construction, .. } => *construction,
2479 SegmentKind::ControlPointSpline { construction, .. } => *construction,
2480 }
2481 }
2482}
2483
2484#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2485#[ts(export_to = "Geometry.ts")]
2486#[serde(rename_all = "camelCase")]
2487pub enum SegmentKind {
2488 Point {
2489 position: [TyF64; 2],
2490 ctor: Box<PointCtor>,
2491 #[serde(skip_serializing_if = "Option::is_none")]
2492 freedom: Option<Freedom>,
2493 },
2494 Line {
2495 start: [TyF64; 2],
2496 end: [TyF64; 2],
2497 ctor: Box<LineCtor>,
2498 start_object_id: ObjectId,
2499 end_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 construction: bool,
2505 },
2506 Arc {
2507 start: [TyF64; 2],
2508 end: [TyF64; 2],
2509 center: [TyF64; 2],
2510 ctor: Box<ArcCtor>,
2511 start_object_id: ObjectId,
2512 end_object_id: ObjectId,
2513 center_object_id: ObjectId,
2514 #[serde(skip_serializing_if = "Option::is_none")]
2515 start_freedom: Option<Freedom>,
2516 #[serde(skip_serializing_if = "Option::is_none")]
2517 end_freedom: Option<Freedom>,
2518 #[serde(skip_serializing_if = "Option::is_none")]
2519 center_freedom: Option<Freedom>,
2520 #[serde(default, skip_serializing_if = "ArcDirection::is_ccw")]
2523 #[ts(as = "Option<ArcDirection>")]
2524 #[ts(optional)]
2525 direction: ArcDirection,
2526 construction: bool,
2527 },
2528 Circle {
2529 start: [TyF64; 2],
2530 center: [TyF64; 2],
2531 ctor: Box<CircleCtor>,
2532 start_object_id: ObjectId,
2533 center_object_id: ObjectId,
2534 #[serde(skip_serializing_if = "Option::is_none")]
2535 start_freedom: Option<Freedom>,
2536 #[serde(skip_serializing_if = "Option::is_none")]
2537 center_freedom: Option<Freedom>,
2538 construction: bool,
2539 },
2540 ControlPointSpline {
2541 controls: Vec<[TyF64; 2]>,
2542 ctor: Box<ControlPointSplineCtor>,
2543 control_object_ids: Vec<ObjectId>,
2544 control_polygon_edge_object_ids: Vec<ObjectId>,
2545 #[serde(skip_serializing_if = "Vec::is_empty")]
2546 control_freedoms: Vec<Option<Freedom>>,
2547 degree: u32,
2548 construction: bool,
2549 },
2550}
2551
2552#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2553#[ts(export_to = "Geometry.ts")]
2554#[serde(rename_all = "camelCase")]
2555pub struct AbstractSegment {
2556 pub repr: SegmentRepr,
2557 #[serde(skip)]
2558 pub meta: Vec<Metadata>,
2559}
2560
2561#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2562pub enum SegmentRepr {
2563 Unsolved { segment: Box<UnsolvedSegment> },
2564 Solved { segment: Box<Segment> },
2565}
2566
2567#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2568#[ts(export_to = "Geometry.ts")]
2569#[serde(rename_all = "camelCase")]
2570pub struct SketchConstraint {
2571 pub kind: SketchConstraintKind,
2572 #[serde(skip)]
2573 pub meta: Vec<Metadata>,
2574}
2575
2576#[derive(Debug, Clone, Copy, PartialEq)]
2577pub enum AngleRayDirection {
2578 Forward,
2579 Reverse,
2580}
2581
2582#[derive(Debug, Clone, Copy, PartialEq)]
2583pub enum AngleSector {
2584 One,
2585 Two,
2586 Three,
2587 Four,
2588}
2589
2590#[derive(Debug, Clone, Copy, PartialEq)]
2591pub enum AngleConstraintMode {
2592 LinesAtAngle,
2593 PointsAtAngle { sector: AngleSector, inverse: bool },
2594}
2595
2596#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2597#[ts(export_to = "Geometry.ts")]
2598#[serde(rename_all = "camelCase")]
2599pub enum SketchConstraintKind {
2600 Angle {
2601 line0: ConstrainableLine2d,
2602 line1: ConstrainableLine2d,
2603 #[serde(skip)]
2604 #[ts(skip)]
2605 mode: AngleConstraintMode,
2606 #[serde(rename = "labelPosition")]
2607 #[serde(skip_serializing_if = "Option::is_none")]
2608 #[ts(rename = "labelPosition")]
2609 #[ts(optional)]
2610 label_position: Option<ApiPoint2d<Number>>,
2611 },
2612 Distance {
2613 points: [ConstrainablePoint2dOrOrigin; 2],
2614 #[serde(rename = "labelPosition")]
2615 #[serde(skip_serializing_if = "Option::is_none")]
2616 #[ts(rename = "labelPosition")]
2617 #[ts(optional)]
2618 label_position: Option<ApiPoint2d<Number>>,
2619 },
2620 PointLineDistance {
2621 point: ConstrainablePoint2dOrOrigin,
2622 line: ConstrainableLine2d,
2623 input_object_ids: [Option<ObjectId>; 2],
2624 #[serde(rename = "labelPosition")]
2625 #[serde(skip_serializing_if = "Option::is_none")]
2626 #[ts(rename = "labelPosition")]
2627 #[ts(optional)]
2628 label_position: Option<ApiPoint2d<Number>>,
2629 },
2630 LineLineDistance {
2631 line0: ConstrainableLine2d,
2632 line1: ConstrainableLine2d,
2633 input_object_ids: [ObjectId; 2],
2634 #[serde(rename = "labelPosition")]
2635 #[serde(skip_serializing_if = "Option::is_none")]
2636 #[ts(rename = "labelPosition")]
2637 #[ts(optional)]
2638 label_position: Option<ApiPoint2d<Number>>,
2639 },
2640 PointCircularDistance {
2641 point: ConstrainablePoint2dOrOrigin,
2642 center: ConstrainablePoint2d,
2643 start: ConstrainablePoint2d,
2644 end: Option<ConstrainablePoint2d>,
2645 input_object_ids: [Option<ObjectId>; 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 LineCircularDistance {
2653 line: ConstrainableLine2d,
2654 center: ConstrainablePoint2d,
2655 start: ConstrainablePoint2d,
2656 end: Option<ConstrainablePoint2d>,
2657 input_object_ids: [ObjectId; 2],
2658 #[serde(rename = "labelPosition")]
2659 #[serde(skip_serializing_if = "Option::is_none")]
2660 #[ts(rename = "labelPosition")]
2661 #[ts(optional)]
2662 label_position: Option<ApiPoint2d<Number>>,
2663 },
2664 CircularCircularDistance {
2665 center0: ConstrainablePoint2d,
2666 start0: ConstrainablePoint2d,
2667 end0: Option<ConstrainablePoint2d>,
2668 center1: ConstrainablePoint2d,
2669 start1: ConstrainablePoint2d,
2670 end1: Option<ConstrainablePoint2d>,
2671 input_object_ids: [ObjectId; 2],
2672 #[serde(rename = "labelPosition")]
2673 #[serde(skip_serializing_if = "Option::is_none")]
2674 #[ts(rename = "labelPosition")]
2675 #[ts(optional)]
2676 label_position: Option<ApiPoint2d<Number>>,
2677 },
2678 Radius {
2679 points: [ConstrainablePoint2d; 2],
2680 #[serde(rename = "labelPosition")]
2681 #[serde(skip_serializing_if = "Option::is_none")]
2682 #[ts(rename = "labelPosition")]
2683 #[ts(optional)]
2684 label_position: Option<ApiPoint2d<Number>>,
2685 },
2686 Diameter {
2687 points: [ConstrainablePoint2d; 2],
2688 #[serde(rename = "labelPosition")]
2689 #[serde(skip_serializing_if = "Option::is_none")]
2690 #[ts(rename = "labelPosition")]
2691 #[ts(optional)]
2692 label_position: Option<ApiPoint2d<Number>>,
2693 },
2694 HorizontalDistance {
2695 points: [ConstrainablePoint2dOrOrigin; 2],
2696 #[serde(rename = "labelPosition")]
2697 #[serde(skip_serializing_if = "Option::is_none")]
2698 #[ts(rename = "labelPosition")]
2699 #[ts(optional)]
2700 label_position: Option<ApiPoint2d<Number>>,
2701 },
2702 VerticalDistance {
2703 points: [ConstrainablePoint2dOrOrigin; 2],
2704 #[serde(rename = "labelPosition")]
2705 #[serde(skip_serializing_if = "Option::is_none")]
2706 #[ts(rename = "labelPosition")]
2707 #[ts(optional)]
2708 label_position: Option<ApiPoint2d<Number>>,
2709 },
2710}
2711
2712impl SketchConstraintKind {
2713 pub fn name(&self) -> &'static str {
2714 match self {
2715 SketchConstraintKind::Angle { .. } => "angle",
2716 SketchConstraintKind::Distance { .. } => "distance",
2717 SketchConstraintKind::PointLineDistance { .. } => "distance",
2718 SketchConstraintKind::LineLineDistance { .. } => "distance",
2719 SketchConstraintKind::PointCircularDistance { .. } => "distance",
2720 SketchConstraintKind::LineCircularDistance { .. } => "distance",
2721 SketchConstraintKind::CircularCircularDistance { .. } => "distance",
2722 SketchConstraintKind::Radius { .. } => "radius",
2723 SketchConstraintKind::Diameter { .. } => "diameter",
2724 SketchConstraintKind::HorizontalDistance { .. } => "horizontalDistance",
2725 SketchConstraintKind::VerticalDistance { .. } => "verticalDistance",
2726 }
2727 }
2728}