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 => 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 pub fn is_initialized(&self) -> bool {
801 self.object_id.is_some()
802 }
803
804 pub fn is_uninitialized(&self) -> bool {
806 !self.is_initialized()
807 }
808
809 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 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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
829#[ts(export)]
830#[serde(rename_all = "camelCase")]
831pub struct Face {
832 pub id: uuid::Uuid,
834 pub artifact_id: ArtifactId,
836 pub object_id: ObjectId,
838 pub value: String,
840 pub x_axis: Point3d,
842 pub y_axis: Point3d,
844 pub parent_solid: FaceParentSolid,
846 pub units: UnitLength,
847 #[serde(skip)]
848 pub meta: Vec<Metadata>,
849}
850
851#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
853#[ts(export)]
854#[serde(rename_all = "camelCase")]
855pub struct FaceParentSolid {
856 pub solid_id: Uuid,
858 pub creator_sketch_id: Option<Uuid>,
860 pub creator_sketch_is_closed: Option<ProfileClosed>,
862 #[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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
876#[ts(export)]
877#[serde(rename_all = "camelCase")]
878pub struct BoundedEdge {
879 pub face_id: uuid::Uuid,
881 #[serde(skip_serializing_if = "Option::is_none")]
883 pub edge_id: Option<uuid::Uuid>,
884 #[serde(skip_serializing_if = "Option::is_none")]
886 pub edge_specifier: Option<UnresolvedEdgeSpecifier>,
887 pub lower_bound: f32,
890 pub upper_bound: f32,
893}
894
895#[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 #[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 pub id: uuid::Uuid,
920 pub paths: Vec<Path>,
924 #[serde(default, skip_serializing_if = "Vec::is_empty")]
926 pub inner_paths: Vec<Path>,
927 pub on: SketchSurface,
929 pub start: BasePath,
931 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
933 pub tags: IndexMap<String, TagIdentifier>,
934 pub artifact_id: ArtifactId,
937 #[ts(skip)]
938 pub original_id: uuid::Uuid,
939 #[serde(skip_serializing_if = "Option::is_none")]
944 #[ts(skip)]
945 pub origin_sketch_id: Option<uuid::Uuid>,
946 #[serde(skip)]
948 pub mirror: Option<uuid::Uuid>,
949 #[serde(skip)]
951 pub clone: Option<uuid::Uuid>,
952 #[serde(skip)]
954 #[ts(skip)]
955 pub synthetic_jump_path_ids: Vec<uuid::Uuid>,
956 pub units: UnitLength,
957 #[serde(skip)]
959 pub meta: Vec<Metadata>,
960 #[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#[derive(Debug, Serialize, Eq, PartialEq, Clone, Copy, Hash, Ord, PartialOrd, ts_rs::TS)]
982#[serde(rename_all = "camelCase")]
983pub enum ProfileClosed {
984 No,
986 Maybe,
988 Implicitly,
990 Explicitly,
992}
993
994impl Sketch {
995 pub(crate) fn build_sketch_mode_cmds(
998 &self,
999 exec_state: &mut ExecState,
1000 inner_cmd: ModelingCmdReq,
1001 ) -> Vec<ModelingCmdReq> {
1002 vec![
1003 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 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#[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#[derive(Debug, Clone, PartialEq)]
1078pub enum Extrudable {
1079 Sketch(Box<Sketch>),
1081 FaceTag(FaceTag),
1083 Face(Box<Face>),
1085 EdgeTag(Box<TagIdentifier>),
1087 Edge(Uuid),
1089 EdgeSpecifier(UnresolvedEdgeSpecifier),
1091}
1092
1093impl Extrudable {
1094 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 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 pub(crate) fn latest_path(&self) -> Option<&Path> {
1256 self.paths.last()
1257 }
1258
1259 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 pub id: uuid::Uuid,
1285 #[serde(skip)]
1287 #[ts(skip)]
1288 pub value_id: uuid::Uuid,
1289 #[serde(skip)]
1293 #[ts(skip)]
1294 pub(crate) topology_id: uuid::Uuid,
1295 #[serde(skip)]
1299 #[ts(skip)]
1300 pub(crate) pattern_source_artifact_id: Option<ArtifactId>,
1301 pub artifact_id: ArtifactId,
1303 pub value: Vec<ExtrudeSurface>,
1305 #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
1308 pub faces: IndexMap<String, TagIdentifier>,
1309 #[serde(rename = "sketch")]
1311 pub creator: SolidCreator,
1312 pub start_cap_id: Option<uuid::Uuid>,
1314 pub end_cap_id: Option<uuid::Uuid>,
1316 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1318 pub edge_cuts: Vec<EdgeCut>,
1319 #[serde(skip)]
1321 #[ts(skip)]
1322 pub pending_edge_cut_ids: Vec<uuid::Uuid>,
1323 pub units: UnitLength,
1325 pub sectional: bool,
1327 #[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 pub face_id: uuid::Uuid,
1337 pub solid_id: uuid::Uuid,
1339 pub sketch: Sketch,
1341}
1342
1343#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1344#[ts(export)]
1345pub struct CreatorEdge {
1346 pub edge_id: uuid::Uuid,
1348 pub body_id: uuid::Uuid,
1350}
1351
1352#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1354#[ts(export)]
1355#[serde(tag = "creatorType", rename_all = "camelCase")]
1356pub enum SolidCreator {
1357 Sketch(Sketch),
1359 Face(CreatorFace),
1361 Edge(CreatorEdge),
1363 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 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 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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1436#[ts(export)]
1437#[serde(tag = "type", rename_all = "camelCase")]
1438pub enum EdgeCut {
1439 Fillet {
1441 id: uuid::Uuid,
1443 radius: TyF64,
1444 #[serde(rename = "edgeId")]
1446 edge_id: uuid::Uuid,
1447 tag: Box<Option<TagNode>>,
1448 },
1449 Chamfer {
1451 id: uuid::Uuid,
1453 length: TyF64,
1454 #[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 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 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 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 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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1719#[ts(export)]
1720#[serde(rename_all = "camelCase")]
1721pub struct BasePath {
1722 #[ts(type = "[number, number]")]
1724 pub from: [f64; 2],
1725 #[ts(type = "[number, number]")]
1727 pub to: [f64; 2],
1728 pub units: UnitLength,
1729 pub tag: Option<TagNode>,
1731 #[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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1750#[ts(export)]
1751#[serde(rename_all = "camelCase")]
1752pub struct GeoMeta {
1753 pub id: uuid::Uuid,
1755 #[serde(flatten)]
1757 pub metadata: Metadata,
1758}
1759
1760#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
1762#[ts(export)]
1763#[serde(tag = "type")]
1764pub enum Path {
1765 ToPoint {
1767 #[serde(flatten)]
1768 base: BasePath,
1769 },
1770 TangentialArcTo {
1772 #[serde(flatten)]
1773 base: BasePath,
1774 #[ts(type = "[number, number]")]
1776 center: [f64; 2],
1777 ccw: bool,
1779 },
1780 TangentialArc {
1782 #[serde(flatten)]
1783 base: BasePath,
1784 #[ts(type = "[number, number]")]
1786 center: [f64; 2],
1787 ccw: bool,
1789 },
1790 Circle {
1793 #[serde(flatten)]
1794 base: BasePath,
1795 #[ts(type = "[number, number]")]
1797 center: [f64; 2],
1798 radius: f64,
1800 ccw: bool,
1803 },
1804 CircleThreePoint {
1805 #[serde(flatten)]
1806 base: BasePath,
1807 #[ts(type = "[number, number]")]
1809 p1: [f64; 2],
1810 #[ts(type = "[number, number]")]
1812 p2: [f64; 2],
1813 #[ts(type = "[number, number]")]
1815 p3: [f64; 2],
1816 },
1817 ArcThreePoint {
1818 #[serde(flatten)]
1819 base: BasePath,
1820 #[ts(type = "[number, number]")]
1822 p1: [f64; 2],
1823 #[ts(type = "[number, number]")]
1825 p2: [f64; 2],
1826 #[ts(type = "[number, number]")]
1828 p3: [f64; 2],
1829 },
1830 Horizontal {
1832 #[serde(flatten)]
1833 base: BasePath,
1834 x: f64,
1836 },
1837 AngledLineTo {
1839 #[serde(flatten)]
1840 base: BasePath,
1841 x: Option<f64>,
1843 y: Option<f64>,
1845 },
1846 Base {
1848 #[serde(flatten)]
1849 base: BasePath,
1850 },
1851 Arc {
1853 #[serde(flatten)]
1854 base: BasePath,
1855 center: [f64; 2],
1857 radius: f64,
1859 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 Conic {
1872 #[serde(flatten)]
1873 base: BasePath,
1874 },
1875 Bezier {
1877 #[serde(flatten)]
1878 base: BasePath,
1879 #[ts(type = "[number, number]")]
1881 control1: [f64; 2],
1882 #[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 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 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 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 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 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 let radius = linear_distance(&self.get_base().from, center);
2009 debug_assert_eq!(radius, linear_distance(&self.get_base().to, center));
2010 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 Some(linear_distance(&self.get_base().from, &self.get_base().to))
2029 }
2030 Self::ArcThreePoint { .. } => {
2031 Some(linear_distance(&self.get_base().from, &self.get_base().to))
2033 }
2034 Self::Ellipse { .. } => {
2035 None
2037 }
2038 Self::Conic { .. } => {
2039 None
2041 }
2042 Self::Bezier { .. } => {
2043 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 ccw: true,
2097 radius: circle.radius,
2098 }
2099 }
2100 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 pub(crate) fn is_straight_line(&self) -> bool {
2127 matches!(self, Path::AngledLineTo { .. } | Path::ToPoint { .. })
2128 }
2129}
2130
2131#[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#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2144#[ts(export)]
2145#[serde(tag = "type", rename_all = "camelCase")]
2146pub enum ExtrudeSurface {
2147 ExtrudePlane(ExtrudePlane),
2149 ExtrudeArc(ExtrudeArc),
2150 Chamfer(ChamferSurface),
2151 Fillet(FilletSurface),
2152}
2153
2154#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2156#[ts(export)]
2157#[serde(rename_all = "camelCase")]
2158pub struct ChamferSurface {
2159 pub face_id: uuid::Uuid,
2161 pub tag: Option<Node<TagDeclarator>>,
2163 #[serde(flatten)]
2165 pub geo_meta: GeoMeta,
2166}
2167
2168#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2170#[ts(export)]
2171#[serde(rename_all = "camelCase")]
2172pub struct FilletSurface {
2173 pub face_id: uuid::Uuid,
2175 pub tag: Option<Node<TagDeclarator>>,
2177 #[serde(flatten)]
2179 pub geo_meta: GeoMeta,
2180}
2181
2182#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2184#[ts(export)]
2185#[serde(rename_all = "camelCase")]
2186pub struct ExtrudePlane {
2187 pub face_id: uuid::Uuid,
2189 pub tag: Option<Node<TagDeclarator>>,
2191 #[serde(flatten)]
2193 pub geo_meta: GeoMeta,
2194}
2195
2196#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
2198#[ts(export)]
2199#[serde(rename_all = "camelCase")]
2200pub struct ExtrudeArc {
2201 pub face_id: uuid::Uuid,
2203 pub tag: Option<Node<TagDeclarator>>,
2205 #[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 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 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 #[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 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 pub id: Uuid,
2442 pub object_id: ObjectId,
2443 pub kind: SegmentKind,
2444 pub surface: SketchSurface,
2445 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 #[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}