kcl-lib 0.2.147

KittyCAD Language implementation and tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
#![allow(async_fn_in_trait)]

use serde::Deserialize;
use serde::Serialize;

use crate::ExecutorContext;
use crate::KclErrorWithOutputs;
use crate::front::Plane;
use crate::frontend::api::Expr;
use crate::frontend::api::FileId;
use crate::frontend::api::Number;
use crate::frontend::api::ObjectId;
use crate::frontend::api::ProjectId;
use crate::frontend::api::SceneGraph;
use crate::frontend::api::SceneGraphDelta;
use crate::frontend::api::SourceDelta;
use crate::frontend::api::Version;

pub type ExecResult<T> = std::result::Result<T, KclErrorWithOutputs>;

/// Information about a newly created segment for batch operations
#[derive(Debug, Clone)]
pub struct NewSegmentInfo {
    pub segment_id: ObjectId,
    pub start_point_id: ObjectId,
    pub end_point_id: ObjectId,
    pub center_point_id: Option<ObjectId>,
}

pub trait SketchApi {
    /// Execute the sketch in mock mode, without changing anything. This is
    /// useful after editing segments, and the user releases the mouse button.
    async fn execute_mock(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn new_sketch(
        &mut self,
        ctx: &ExecutorContext,
        project: ProjectId,
        file: FileId,
        version: Version,
        args: SketchCtor,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta, ObjectId)>;

    // Enters sketch mode
    async fn edit_sketch(
        &mut self,
        ctx: &ExecutorContext,
        project: ProjectId,
        file: FileId,
        version: Version,
        sketch: ObjectId,
    ) -> ExecResult<SceneGraphDelta>;

    async fn exit_sketch(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
    ) -> ExecResult<SceneGraph>;

    async fn delete_sketch(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn add_segment(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        segment: SegmentCtor,
        label: Option<String>,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn edit_segments(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        segments: Vec<ExistingSegmentCtor>,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn delete_objects(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        constraint_ids: Vec<ObjectId>,
        segment_ids: Vec<ObjectId>,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn add_constraint(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        constraint: Constraint,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn chain_segment(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        previous_segment_end_point_id: ObjectId,
        segment: SegmentCtor,
        label: Option<String>,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    async fn edit_constraint(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        constraint_id: ObjectId,
        value_expression: String,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    /// Batch operations for split segment: edit segments, add constraints, delete objects.
    /// All operations are applied to a single AST and execute_after_edit is called once at the end.
    /// new_segment_info contains the IDs from the segment(s) added in a previous step.
    #[allow(clippy::too_many_arguments)]
    async fn batch_split_segment_operations(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        edit_segments: Vec<ExistingSegmentCtor>,
        add_constraints: Vec<Constraint>,
        delete_constraint_ids: Vec<ObjectId>,
        new_segment_info: NewSegmentInfo,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;

    /// Batch operations for tail-cut trim: edit a segment, add coincident constraints,
    /// delete constraints, and execute once.
    async fn batch_tail_cut_operations(
        &mut self,
        ctx: &ExecutorContext,
        version: Version,
        sketch: ObjectId,
        edit_segments: Vec<ExistingSegmentCtor>,
        add_constraints: Vec<Constraint>,
        delete_constraint_ids: Vec<ObjectId>,
    ) -> ExecResult<(SourceDelta, SceneGraphDelta)>;
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiSketch")]
pub struct Sketch {
    pub args: SketchCtor,
    pub plane: ObjectId,
    pub segments: Vec<ObjectId>,
    pub constraints: Vec<ObjectId>,
}

/// Arguments for creating a new sketch. This is similar to the constructor of
/// other kinds of objects in that it is the inputs to the sketch, not the
/// outputs.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct SketchCtor {
    /// The sketch surface.
    pub on: Plane,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiPoint")]
pub struct Point {
    pub position: Point2d<Number>,
    pub ctor: Option<PointCtor>,
    pub owner: Option<ObjectId>,
    pub freedom: Freedom,
    pub constraints: Vec<ObjectId>,
}

impl Point {
    /// The freedom of this point.
    pub fn freedom(&self) -> Freedom {
        self.freedom
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub enum Freedom {
    Free,
    Fixed,
    Conflict,
}

impl Freedom {
    /// Merges two Freedom values. For example, a point has a solver variable
    /// for each dimension, x and y. If one dimension is `Free` and the other is
    /// `Fixed`, the point overall is `Free` since it isn't fully constrained.
    /// `Conflict` infects the most, followed by `Free`. An object must be fully
    /// `Fixed` to be `Fixed` overall.
    pub fn merge(self, other: Self) -> Self {
        match (self, other) {
            (Self::Conflict, _) | (_, Self::Conflict) => Self::Conflict,
            (Self::Free, _) | (_, Self::Free) => Self::Free,
            (Self::Fixed, Self::Fixed) => Self::Fixed,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiSegment")]
#[serde(tag = "type")]
pub enum Segment {
    Point(Point),
    Line(Line),
    Arc(Arc),
    Circle(Circle),
}

impl Segment {
    /// What kind of geometry is this (point, line, arc, etc)
    /// Suitable for use in user-facing messages.
    pub fn human_friendly_kind_with_article(&self) -> &'static str {
        match self {
            Self::Point(_) => "a Point",
            Self::Line(_) => "a Line",
            Self::Arc(_) => "an Arc",
            Self::Circle(_) => "a Circle",
        }
    }

    /// Compute the overall freedom of this segment. For geometry types (Line,
    /// Arc, Circle) this looks up and merges the freedom of their constituent
    /// points. For points, returns the point's own freedom directly.
    /// Returns `None` if a required point lookup failed.
    pub fn freedom(&self, lookup: impl Fn(ObjectId) -> Option<Freedom>) -> Option<Freedom> {
        match self {
            Self::Point(p) => Some(p.freedom()),
            Self::Line(l) => l.freedom(&lookup),
            Self::Arc(a) => a.freedom(&lookup),
            Self::Circle(c) => c.freedom(&lookup),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct ExistingSegmentCtor {
    pub id: ObjectId,
    pub ctor: SegmentCtor,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
#[serde(tag = "type")]
pub enum SegmentCtor {
    Point(PointCtor),
    Line(LineCtor),
    Arc(ArcCtor),
    Circle(CircleCtor),
}

impl SegmentCtor {
    /// What kind of geometry is this (point, line, arc, etc)
    /// Suitable for use in user-facing messages.
    pub fn human_friendly_kind_with_article(&self) -> &'static str {
        match self {
            Self::Point(_) => "a Point constructor",
            Self::Line(_) => "a Line constructor",
            Self::Arc(_) => "an Arc constructor",
            Self::Circle(_) => "a Circle constructor",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct PointCtor {
    pub position: Point2d<Expr>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiPoint2d")]
pub struct Point2d<U: std::fmt::Debug + Clone + ts_rs::TS> {
    pub x: U,
    pub y: U,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiLine")]
pub struct Line {
    pub start: ObjectId,
    pub end: ObjectId,
    // Invariant: Line or MidPointLine
    pub ctor: SegmentCtor,
    // The constructor is applicable if changing the values of the constructor will change the rendering
    // of the segment (modulo multiple valid solutions). I.e., whether the object is constrained with
    // respect to the constructor inputs.
    // The frontend should only display handles for the constructor inputs if the ctor is applicable.
    // (Or because they are the (locked) start/end of the segment).
    pub ctor_applicable: bool,
    pub construction: bool,
}

impl Line {
    /// Compute the overall freedom of this line by merging the freedom of its
    /// start and end points. Returns `None` if a point lookup failed.
    pub fn freedom(&self, lookup: impl Fn(ObjectId) -> Option<Freedom>) -> Option<Freedom> {
        let start = lookup(self.start)?;
        let end = lookup(self.end)?;
        Some(start.merge(end))
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct LineCtor {
    pub start: Point2d<Expr>,
    pub end: Point2d<Expr>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub construction: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiStartOrEnd")]
#[serde(tag = "type")]
pub enum StartOrEnd<T> {
    Start(T),
    End(T),
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiArc")]
pub struct Arc {
    pub start: ObjectId,
    pub end: ObjectId,
    pub center: ObjectId,
    // Invariant: Arc
    pub ctor: SegmentCtor,
    pub ctor_applicable: bool,
    pub construction: bool,
}

impl Arc {
    /// Compute the overall freedom of this arc by merging the freedom of its
    /// start, end, and center points. Returns `None` if a point lookup failed.
    pub fn freedom(&self, lookup: impl Fn(ObjectId) -> Option<Freedom>) -> Option<Freedom> {
        let start = lookup(self.start)?;
        let end = lookup(self.end)?;
        let center = lookup(self.center)?;
        Some(start.merge(end).merge(center))
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct ArcCtor {
    pub start: Point2d<Expr>,
    pub end: Point2d<Expr>,
    pub center: Point2d<Expr>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub construction: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiCircle")]
pub struct Circle {
    pub start: ObjectId,
    pub center: ObjectId,
    // Invariant: Circle
    pub ctor: SegmentCtor,
    pub ctor_applicable: bool,
    pub construction: bool,
}

impl Circle {
    /// Compute the overall freedom of this circle by merging the freedom of its
    /// start and center points. Returns `None` if a point lookup failed.
    pub fn freedom(&self, lookup: impl Fn(ObjectId) -> Option<Freedom>) -> Option<Freedom> {
        let start = lookup(self.start)?;
        let center = lookup(self.center)?;
        Some(start.merge(center))
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct CircleCtor {
    pub start: Point2d<Expr>,
    pub center: Point2d<Expr>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[ts(optional)]
    pub construction: Option<bool>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", rename = "ApiConstraint")]
#[serde(tag = "type")]
pub enum Constraint {
    Coincident(Coincident),
    Distance(Distance),
    Angle(Angle),
    Diameter(Diameter),
    EqualRadius(EqualRadius),
    Fixed(Fixed),
    HorizontalDistance(Distance),
    VerticalDistance(Distance),
    Horizontal(Horizontal),
    LinesEqualLength(LinesEqualLength),
    Midpoint(Midpoint),
    Parallel(Parallel),
    Perpendicular(Perpendicular),
    Radius(Radius),
    Tangent(Tangent),
    Vertical(Vertical),
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Coincident {
    pub segments: Vec<ConstraintSegment>,
}

impl Coincident {
    pub fn get_segments(&self) -> Vec<ObjectId> {
        self.segments
            .iter()
            .filter_map(|segment| match segment {
                ConstraintSegment::Segment(id) => Some(*id),
                ConstraintSegment::Origin(_) => None,
            })
            .collect()
    }

    pub fn segment_ids(&self) -> impl Iterator<Item = ObjectId> + '_ {
        self.segments.iter().filter_map(|segment| match segment {
            ConstraintSegment::Segment(id) => Some(*id),
            ConstraintSegment::Origin(_) => None,
        })
    }

    pub fn contains_segment(&self, segment_id: ObjectId) -> bool {
        self.segment_ids().any(|id| id == segment_id)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
#[serde(untagged)]
pub enum ConstraintSegment {
    Segment(ObjectId),
    Origin(OriginLiteral),
}

impl ConstraintSegment {
    pub const ORIGIN: Self = Self::Origin(OriginLiteral::Origin);
}

#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OriginLiteral {
    Origin,
}

impl From<ObjectId> for ConstraintSegment {
    fn from(value: ObjectId) -> Self {
        Self::Segment(value)
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Distance {
    pub points: Vec<ConstraintSegment>,
    pub distance: Number,
    pub source: ConstraintSource,
}

impl Distance {
    pub fn point_ids(&self) -> impl Iterator<Item = ObjectId> + '_ {
        self.points.iter().filter_map(|point| match point {
            ConstraintSegment::Segment(id) => Some(*id),
            ConstraintSegment::Origin(_) => None,
        })
    }

    pub fn contains_point(&self, point_id: ObjectId) -> bool {
        self.point_ids().any(|id| id == point_id)
    }
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Angle {
    pub lines: Vec<ObjectId>,
    pub angle: Number,
    pub source: ConstraintSource,
}

#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct ConstraintSource {
    pub expr: String,
    pub is_literal: bool,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Radius {
    pub arc: ObjectId,
    pub radius: Number,
    #[serde(default)]
    pub source: ConstraintSource,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Diameter {
    pub arc: ObjectId,
    pub diameter: Number,
    #[serde(default)]
    pub source: ConstraintSource,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", optional_fields)]
pub struct EqualRadius {
    pub input: Vec<ObjectId>,
}

/// Multiple fixed constraints, allowing callers to add fixed constraints on
/// multiple points at once.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Fixed {
    pub points: Vec<FixedPoint>,
}

/// A fixed constraint on a single point.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct FixedPoint {
    pub point: ObjectId,
    pub position: Point2d<Number>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
#[serde(untagged)]
pub enum Horizontal {
    Line { line: ObjectId },
    Points { points: Vec<ConstraintSegment> },
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct LinesEqualLength {
    pub lines: Vec<ObjectId>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
pub struct Midpoint {
    pub point: ObjectId,
    #[serde(alias = "line")]
    pub segment: ObjectId,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts")]
#[serde(untagged)]
pub enum Vertical {
    Line { line: ObjectId },
    Points { points: Vec<ConstraintSegment> },
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", optional_fields)]
pub struct Parallel {
    pub lines: Vec<ObjectId>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", optional_fields)]
pub struct Perpendicular {
    pub lines: Vec<ObjectId>,
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize, ts_rs::TS)]
#[ts(export, export_to = "FrontendApi.ts", optional_fields)]
pub struct Tangent {
    pub input: Vec<ObjectId>,
}