Skip to main content

kcl_lib/std/
extrude.rs

1//! Functions related to extruding.
2
3use std::collections::HashMap;
4
5use anyhow::Result;
6use indexmap::IndexMap;
7use kcmc::ModelingCmd;
8use kcmc::each_cmd as mcmd;
9use kcmc::length_unit::LengthUnit;
10use kcmc::ok_response::OkModelingCmdResponse;
11use kcmc::output::ExtrusionFaceInfo;
12use kcmc::shared::ExtrudeReference;
13use kcmc::shared::ExtrusionFaceCapType;
14use kcmc::shared::Opposite;
15use kcmc::shared::Point3d as KPoint3d; // Point3d is already defined in this pkg, to impl ts_rs traits.
16use kcmc::websocket::ModelingCmdReq;
17use kcmc::websocket::OkWebSocketResponseData;
18use kittycad_modeling_cmds::shared::Angle;
19use kittycad_modeling_cmds::shared::BodyType;
20use kittycad_modeling_cmds::shared::DirectionType;
21use kittycad_modeling_cmds::shared::EntityReference;
22use kittycad_modeling_cmds::shared::ExtrudeMethod;
23use kittycad_modeling_cmds::shared::Point2d;
24use kittycad_modeling_cmds::{self as kcmc};
25use uuid::Uuid;
26
27use super::DEFAULT_TOLERANCE_MM;
28use super::args::FromKclValue;
29use super::args::TyF64;
30use super::utils::point_to_mm;
31use crate::errors::KclError;
32use crate::errors::KclErrorDetails;
33use crate::execution::ArtifactId;
34use crate::execution::CreatorEdge;
35use crate::execution::CreatorFace;
36use crate::execution::ExecState;
37use crate::execution::ExecutorContext;
38use crate::execution::Extrudable;
39use crate::execution::ExtrudePlane;
40use crate::execution::ExtrudeSurface;
41use crate::execution::GeoMeta;
42use crate::execution::KclValue;
43use crate::execution::ModelingCmdMeta;
44use crate::execution::Path;
45use crate::execution::ProfileClosed;
46use crate::execution::Segment;
47use crate::execution::SegmentKind;
48use crate::execution::Sketch;
49use crate::execution::SketchSurface;
50use crate::execution::Solid;
51use crate::execution::SolidCreator;
52use crate::execution::annotations;
53use crate::execution::types::ArrayLen;
54use crate::execution::types::PrimitiveType;
55use crate::execution::types::RuntimeType;
56use crate::parsing::ast::types::TagDeclarator;
57use crate::parsing::ast::types::TagNode;
58use crate::std::Args;
59use crate::std::axis_or_reference::Point3dAxis3dOrGeometryReference;
60use crate::std::axis_or_reference::Point3dOrEdgeReference;
61use crate::std::edge::{self};
62use crate::std::solver::create_segments_in_engine;
63
64/// Extrudes by a given amount.
65pub async fn extrude(exec_state: &mut ExecState, args: Args) -> Result<KclValue, KclError> {
66    let sketch_values: Vec<KclValue> = args.get_unlabeled_kw_arg(
67        "sketches",
68        &RuntimeType::Array(
69            Box::new(RuntimeType::Primitive(PrimitiveType::Any)),
70            ArrayLen::Minimum(1),
71        ),
72        exec_state,
73    )?;
74
75    let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
76    let to_raw = args.get_kw_arg_opt(
77        "to",
78        &RuntimeType::Union(vec![
79            RuntimeType::point3d(),
80            RuntimeType::Primitive(PrimitiveType::Axis3d),
81            RuntimeType::Primitive(PrimitiveType::Edge),
82            RuntimeType::plane(),
83            RuntimeType::Primitive(PrimitiveType::Face),
84            RuntimeType::sketch(),
85            RuntimeType::Primitive(PrimitiveType::Solid),
86            RuntimeType::tagged_edge(),
87            RuntimeType::tagged_face(),
88            RuntimeType::Primitive(PrimitiveType::Any),
89        ]),
90        exec_state,
91    )?;
92    let to = match to_raw {
93        None => None,
94        Some(v) => {
95            let inner = if let KclValue::Object { value: ref obj, .. } = v {
96                if edge::is_edge_specifier_object(&v) {
97                    Point3dAxis3dOrGeometryReference::EdgeToReference(edge::parse_edge_specifier_object(obj, &args)?)
98                } else {
99                    Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
100                        KclError::new_type(KclErrorDetails::new(
101                            "Invalid value for `to`".to_owned(),
102                            vec![args.source_range],
103                        ))
104                    })?
105                }
106            } else {
107                Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
108                    KclError::new_type(KclErrorDetails::new(
109                        "Invalid value for `to`".to_owned(),
110                        vec![args.source_range],
111                    ))
112                })?
113            };
114            Some(inner)
115        }
116    };
117    let symmetric = args.get_kw_arg_opt("symmetric", &RuntimeType::bool(), exec_state)?;
118    let bidirectional_length: Option<TyF64> =
119        args.get_kw_arg_opt("bidirectionalLength", &RuntimeType::length(), exec_state)?;
120    let direction_raw = args.get_kw_arg_opt("direction", &RuntimeType::any(), exec_state)?;
121    let direction = match direction_raw {
122        None => None,
123        Some(v) => {
124            let inner = if edge::is_edge_specifier_object(&v) {
125                Point3dOrEdgeReference::EdgeSpecifier(edge::parse_edge_specifier_value(&v, &args)?)
126            } else {
127                Point3dOrEdgeReference::from_kcl_val(&v).ok_or_else(|| {
128                    KclError::new_type(KclErrorDetails::new(
129                        "Invalid value for `direction`".to_owned(),
130                        vec![args.source_range],
131                    ))
132                })?
133            };
134            Some(inner)
135        }
136    };
137    let tag_start = args.get_kw_arg_opt("tagStart", &RuntimeType::tag_decl(), exec_state)?;
138    let tag_end = args.get_kw_arg_opt("tagEnd", &RuntimeType::tag_decl(), exec_state)?;
139    let draft_angle: Option<TyF64> = args.get_kw_arg_opt("draftAngle", &RuntimeType::degrees(), exec_state)?;
140    let twist_angle: Option<TyF64> = args.get_kw_arg_opt("twistAngle", &RuntimeType::degrees(), exec_state)?;
141    let twist_angle_step: Option<TyF64> = args.get_kw_arg_opt("twistAngleStep", &RuntimeType::degrees(), exec_state)?;
142    let twist_center: Option<[TyF64; 2]> = args.get_kw_arg_opt("twistCenter", &RuntimeType::point2d(), exec_state)?;
143    let tolerance: Option<TyF64> = args.get_kw_arg_opt("tolerance", &RuntimeType::length(), exec_state)?;
144    let method: Option<String> = args.get_kw_arg_opt("method", &RuntimeType::string(), exec_state)?;
145    let hide_seams: Option<bool> = args.get_kw_arg_opt("hideSeams", &RuntimeType::bool(), exec_state)?;
146    let body_type: Option<BodyType> = args.get_kw_arg_opt("bodyType", &RuntimeType::string(), exec_state)?;
147    let sketches = coerce_extrude_targets(
148        sketch_values,
149        body_type.unwrap_or_default(),
150        tag_start.as_ref(),
151        tag_end.as_ref(),
152        exec_state,
153        &args.ctx,
154        args.source_range,
155    )
156    .await?;
157
158    let result = inner_extrude(
159        sketches,
160        length,
161        to,
162        symmetric,
163        direction,
164        bidirectional_length,
165        tag_start,
166        tag_end,
167        draft_angle,
168        twist_angle,
169        twist_angle_step,
170        twist_center,
171        tolerance,
172        method,
173        hide_seams,
174        body_type,
175        exec_state,
176        args,
177    )
178    .await?;
179
180    Ok(result.into())
181}
182
183pub async fn coerce_extrude_targets(
184    sketch_values: Vec<KclValue>,
185    body_type: BodyType,
186    tag_start: Option<&TagNode>,
187    tag_end: Option<&TagNode>,
188    exec_state: &mut ExecState,
189    ctx: &ExecutorContext,
190    source_range: crate::SourceRange,
191) -> Result<Vec<Extrudable>, KclError> {
192    let mut extrudables = Vec::new();
193    let mut segments = Vec::new();
194
195    for value in sketch_values {
196        if let Some(segment) = value.clone().into_segment() {
197            segments.push(segment);
198            continue;
199        }
200
201        if edge::is_edge_specifier_object(&value) {
202            extrudables.push(Extrudable::EdgeSpecifier(edge::parse_edge_specifier_value_at(
203                &value,
204                source_range,
205            )?));
206            continue;
207        }
208
209        let Some(extrudable) = Extrudable::from_kcl_val(&value) else {
210            return Err(KclError::new_type(KclErrorDetails::new(
211                "Expected sketches, faces, tagged faces, or solved sketch segments for extrusion.".to_owned(),
212                vec![source_range],
213            )));
214        };
215        extrudables.push(extrudable);
216    }
217
218    if !segments.is_empty() && !extrudables.is_empty() {
219        return Err(KclError::new_semantic(KclErrorDetails::new(
220            "Cannot extrude sketch segments together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
221            vec![source_range],
222        )));
223    }
224
225    if !segments.is_empty() {
226        if !matches!(body_type, BodyType::Surface) {
227            let kind_of_extrude = match body_type {
228                BodyType::Solid => "solid extrude",
229                BodyType::Surface => "surface extrude",
230                _ => "non-surface extrude",
231            };
232            return Err(KclError::new_semantic(KclErrorDetails::new(
233                format!(
234                    "You're trying to perform a {kind_of_extrude} on an edge, but edges can only be extruded with surface extrudes. To do a solid extrude, select a closed sketch region instead. To extrude these edges, do a surface extrude by using `bodyType = SURFACE` instead."
235                ),
236                vec![source_range],
237            )));
238        }
239
240        if tag_start.is_some() || tag_end.is_some() {
241            return Err(KclError::new_semantic(KclErrorDetails::new(
242                "`tagStart` and `tagEnd` are not supported when extruding sketch segments. Segment surface extrudes do not create start or end caps."
243                    .to_owned(),
244                vec![source_range],
245            )));
246        }
247
248        let synthetic_sketch = build_segment_surface_sketch(segments, exec_state, ctx, source_range).await?;
249        return Ok(vec![Extrudable::from(synthetic_sketch)]);
250    }
251
252    // Edges behave like sketch segments: they can only be surface-extruded, they
253    // don't create caps, and they can't be mixed with sketches or faces. Enforce
254    // the same rules so these cases fail loudly instead of silently producing a
255    // surface (or silently ignoring `tagStart`/`tagEnd`).
256    let has_edge = extrudables.iter().any(|e| {
257        matches!(
258            e,
259            Extrudable::Edge(_) | Extrudable::EdgeTag(_) | Extrudable::EdgeSpecifier(_)
260        )
261    });
262    if has_edge {
263        let has_non_edge = extrudables.iter().any(|e| {
264            !matches!(
265                e,
266                Extrudable::Edge(_) | Extrudable::EdgeTag(_) | Extrudable::EdgeSpecifier(_)
267            )
268        });
269        if has_non_edge {
270            return Err(KclError::new_semantic(KclErrorDetails::new(
271                "Cannot extrude edges together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
272                vec![source_range],
273            )));
274        }
275
276        if !matches!(body_type, BodyType::Surface) {
277            let kind_of_extrude = match body_type {
278                BodyType::Solid => "solid extrude",
279                BodyType::Surface => "surface extrude",
280                _ => "non-surface extrude",
281            };
282            return Err(KclError::new_semantic(KclErrorDetails::new(
283                format!(
284                    "You're trying to perform a {kind_of_extrude} on an edge, but edges can only be extruded with surface extrudes. To do a solid extrude, select a closed sketch region instead. To extrude these edges, do a surface extrude by using `bodyType = SURFACE` instead."
285                ),
286                vec![source_range],
287            )));
288        }
289
290        if tag_start.is_some() || tag_end.is_some() {
291            return Err(KclError::new_semantic(KclErrorDetails::new(
292                "`tagStart` and `tagEnd` are not supported when extruding edges. Edge surface extrudes do not create start or end caps."
293                    .to_owned(),
294                vec![source_range],
295            )));
296        }
297    }
298
299    Ok(extrudables)
300}
301
302pub(crate) async fn build_segment_surface_sketch(
303    mut segments: Vec<Segment>,
304    exec_state: &mut ExecState,
305    ctx: &ExecutorContext,
306    source_range: crate::SourceRange,
307) -> Result<Sketch, KclError> {
308    let Some(first_segment) = segments.first() else {
309        return Err(KclError::new_semantic(KclErrorDetails::new(
310            "Expected at least one sketch segment.".to_owned(),
311            vec![source_range],
312        )));
313    };
314
315    let sketch_id = first_segment.sketch_id;
316    let sketch_surface = first_segment.surface.clone();
317    for segment in &segments {
318        if segment.sketch_id != sketch_id {
319            return Err(KclError::new_semantic(KclErrorDetails::new(
320                "All sketch segments passed to this operation must come from the same sketch.".to_owned(),
321                vec![source_range],
322            )));
323        }
324
325        if segment.surface != sketch_surface {
326            return Err(KclError::new_semantic(KclErrorDetails::new(
327                "All sketch segments passed to this operation must lie on the same sketch surface.".to_owned(),
328                vec![source_range],
329            )));
330        }
331
332        if matches!(segment.kind, SegmentKind::Point { .. }) {
333            return Err(KclError::new_semantic(KclErrorDetails::new(
334                "Point segments cannot be used here. Select line, arc, or circle segments instead.".to_owned(),
335                vec![source_range],
336            )));
337        }
338
339        if segment.is_construction() {
340            return Err(KclError::new_semantic(KclErrorDetails::new(
341                "Construction segments cannot be used here. Select non-construction sketch segments instead."
342                    .to_owned(),
343                vec![source_range],
344            )));
345        }
346    }
347
348    let synthetic_sketch_id = exec_state.next_uuid();
349    let segment_tags = IndexMap::from_iter(segments.iter().filter_map(|segment| {
350        segment
351            .tag
352            .as_ref()
353            .map(|tag| (segment.object_id, TagDeclarator::new(&tag.value)))
354    }));
355
356    for segment in &mut segments {
357        segment.id = exec_state.next_uuid();
358        segment.sketch_id = synthetic_sketch_id;
359        segment.sketch = None;
360    }
361
362    create_segments_in_engine(
363        &sketch_surface,
364        synthetic_sketch_id,
365        &mut segments,
366        &segment_tags,
367        ctx,
368        exec_state,
369        source_range,
370    )
371    .await?
372    .ok_or_else(|| {
373        KclError::new_semantic(KclErrorDetails::new(
374            "Expected at least one usable sketch segment.".to_owned(),
375            vec![source_range],
376        ))
377    })
378}
379
380#[allow(clippy::too_many_arguments)]
381async fn inner_extrude(
382    extrudables: Vec<Extrudable>,
383    length: Option<TyF64>,
384    to: Option<Point3dAxis3dOrGeometryReference>,
385    symmetric: Option<bool>,
386    direction: Option<Point3dOrEdgeReference>,
387    bidirectional_length: Option<TyF64>,
388    tag_start: Option<TagNode>,
389    tag_end: Option<TagNode>,
390    draft_angle: Option<TyF64>,
391    twist_angle: Option<TyF64>,
392    twist_angle_step: Option<TyF64>,
393    twist_center: Option<[TyF64; 2]>,
394    tolerance: Option<TyF64>,
395    method: Option<String>,
396    hide_seams: Option<bool>,
397    body_type: Option<BodyType>,
398    exec_state: &mut ExecState,
399    args: Args,
400) -> Result<Vec<Solid>, KclError> {
401    let body_type = body_type.unwrap_or_default();
402
403    if matches!(body_type, BodyType::Solid) && extrudables.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No))
404    {
405        return Err(KclError::new_semantic(KclErrorDetails::new(
406            "Cannot solid extrude an open profile. Either close the profile, or use a surface extrude.".to_owned(),
407            vec![args.source_range],
408        )));
409    }
410
411    if draft_angle.is_some() && twist_angle.is_some() {
412        return Err(KclError::new_semantic(KclErrorDetails::new(
413            "Zoo currently does not support adding both draft angle and twist angle to an extrude simultaneously"
414                .to_owned(),
415            vec![args.source_range],
416        )));
417    }
418
419    if direction.is_some() && twist_angle.is_some() {
420        return Err(KclError::new_semantic(KclErrorDetails::new(
421            "Zoo currently does not support adding both direction and twist angle to an extrude simultaneously"
422                .to_owned(),
423            vec![args.source_range],
424        )));
425    }
426
427    // Extrude the element(s).
428    let mut solids = Vec::new();
429    let tolerance = LengthUnit(tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM));
430
431    let extrude_method = match method.as_deref() {
432        Some("new" | "NEW") => ExtrudeMethod::New,
433        Some("merge" | "MERGE") => ExtrudeMethod::Merge,
434        None => ExtrudeMethod::default(),
435        Some(other) => {
436            return Err(KclError::new_semantic(KclErrorDetails::new(
437                format!("Unknown merge method {other}, try using `MERGE` or `NEW`"),
438                vec![args.source_range],
439            )));
440        }
441    };
442
443    if symmetric.unwrap_or(false) && bidirectional_length.is_some() {
444        return Err(KclError::new_semantic(KclErrorDetails::new(
445            "You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
446                .to_owned(),
447            vec![args.source_range],
448        )));
449    }
450
451    if (length.is_some() || twist_angle.is_some()) && to.is_some() {
452        return Err(KclError::new_semantic(KclErrorDetails::new(
453            "You cannot give `length` or `twist` params with the `to` param, you have to choose one or the other"
454                .to_owned(),
455            vec![args.source_range],
456        )));
457    }
458
459    let bidirection = bidirectional_length.map(|l| LengthUnit(l.to_mm()));
460
461    let opposite = match (symmetric, bidirection) {
462        (Some(true), _) => Opposite::Symmetric,
463        (None, None) => Opposite::None,
464        (Some(false), None) => Opposite::None,
465        (None, Some(length)) => Opposite::Other(length),
466        (Some(false), Some(length)) => Opposite::Other(length),
467    };
468
469    for extrudable in &extrudables {
470        let is_edge = match extrudable {
471            Extrudable::Sketch(..) => false,
472            Extrudable::FaceTag(_) => false,
473            Extrudable::Face(_) => false,
474            Extrudable::EdgeTag(_) => true,
475            Extrudable::Edge(_) => true,
476            Extrudable::EdgeSpecifier(_) => true,
477        };
478        let extrude_cmd_id = exec_state.next_uuid();
479        let (sketch_or_face_id, target_reference) = match extrudable {
480            Extrudable::EdgeSpecifier(spec) => (
481                None,
482                Some(edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?),
483            ),
484            _ => (Some(extrudable.id_to_extrude(exec_state, &args, false).await?), None),
485        };
486        if to.is_some() && sketch_or_face_id.is_none() {
487            return Err(KclError::new_semantic(KclErrorDetails::new(
488                "Edge specifiers cannot be extruded to a reference".to_owned(),
489                vec![args.source_range],
490            )));
491        }
492        let concrete_target = || {
493            sketch_or_face_id.ok_or_else(|| {
494                KclError::new_semantic(KclErrorDetails::new(
495                    "This extrusion requires a concrete target UUID".to_owned(),
496                    vec![args.source_range],
497                ))
498            })
499        };
500        if is_edge
501            && let Some(edge_id) = sketch_or_face_id
502            && let Some(target_source_range) = args.unlabeled_kw_arg_unconverted().map(|arg| arg.source_range)
503            && let Some(pending) = exec_state.pending_edge_refactor_meta(edge_id, target_source_range)
504            && let Ok(meta) =
505                edge::get_refactor_meta_for_edge(exec_state, edge_id, &args, pending.source_range, pending.stdlib_fn)
506                    .await
507        {
508            exec_state.record_edge_refactor_meta(meta);
509        }
510        let cmd = match (
511            &twist_angle,
512            &twist_angle_step,
513            &twist_center,
514            length.clone(),
515            &to,
516            &direction,
517        ) {
518            (Some(angle), angle_step, center, Some(length), None, None) => {
519                let center = center.clone().map(point_to_mm).map(Point2d::from).unwrap_or_default();
520                let total_rotation_angle = Angle::from_degrees(angle.to_degrees(exec_state, args.source_range));
521                let angle_step_size = Angle::from_degrees(
522                    angle_step
523                        .clone()
524                        .map(|a| a.to_degrees(exec_state, args.source_range))
525                        .unwrap_or(15.0),
526                );
527                ModelingCmd::from(
528                    mcmd::TwistExtrude::builder()
529                        .target(
530                            sketch_or_face_id
531                                .ok_or_else(|| {
532                                    KclError::new_semantic(KclErrorDetails::new(
533                                        "Edge specifiers cannot be used with twist extrusion".to_owned(),
534                                        vec![args.source_range],
535                                    ))
536                                })?
537                                .into(),
538                        )
539                        .distance(LengthUnit(length.to_mm()))
540                        .center_2d(center)
541                        .total_rotation_angle(total_rotation_angle)
542                        .angle_step_size(angle_step_size)
543                        .tolerance(tolerance)
544                        .body_type(body_type)
545                        .build(),
546                )
547            }
548            (None, None, None, Some(length), None, None) => ModelingCmd::from(
549                mcmd::Extrude::builder()
550                    .maybe_target(sketch_or_face_id.map(Into::into))
551                    .maybe_target_reference(target_reference.clone())
552                    .distance(LengthUnit(length.to_mm()))
553                    .opposite(opposite.clone())
554                    .maybe_draft_angle(
555                        draft_angle
556                            .clone()
557                            .map(|a| Angle::from_degrees(a.to_degrees(exec_state, args.source_range))),
558                    )
559                    .extrude_method(extrude_method)
560                    .body_type(body_type)
561                    .maybe_merge_coplanar_faces(hide_seams)
562                    .build(),
563            ),
564            (None, None, None, Some(length), None, Some(dir)) => {
565                let (direction3d, direction_edge_id) = match dir {
566                    Point3dOrEdgeReference::Point(p) => (
567                        Some(DirectionType::Axis {
568                            direction: KPoint3d {
569                                x: p[0].n,
570                                y: p[1].n,
571                                z: p[2].n,
572                            },
573                        }),
574                        None,
575                    ),
576                    Point3dOrEdgeReference::Edge(edge) => {
577                        let edge_id = match edge {
578                            crate::std::fillet::EdgeReference::Uuid(uuid) => *uuid,
579                            crate::std::fillet::EdgeReference::Tag(tag) => match tag.get_cur_info() {
580                                Some(info) => info.id,
581                                None => {
582                                    return Err(KclError::new_semantic(KclErrorDetails::new(
583                                        "Failed to get current info for tag".to_string(),
584                                        vec![args.source_range],
585                                    )));
586                                }
587                            },
588                        };
589                        (Some(DirectionType::Edge { id: edge_id }), Some(edge_id))
590                    }
591                    Point3dOrEdgeReference::EdgeSpecifier(_) => (None, None),
592                };
593                if let Some(edge_id) = direction_edge_id
594                    && let Some(direction_source_range) = args.labeled.get("direction").map(|arg| arg.source_range)
595                    && let Some(pending) = exec_state.pending_edge_refactor_meta(edge_id, direction_source_range)
596                    && let Ok(meta) = edge::get_refactor_meta_for_edge(
597                        exec_state,
598                        edge_id,
599                        &args,
600                        pending.source_range,
601                        pending.stdlib_fn,
602                    )
603                    .await
604                {
605                    exec_state.record_edge_refactor_meta(meta);
606                }
607                let direction_reference = match dir {
608                    Point3dOrEdgeReference::EdgeSpecifier(spec) => {
609                        Some(edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?)
610                    }
611                    _ => None,
612                };
613                ModelingCmd::from(
614                    mcmd::Extrude::builder()
615                        .maybe_target(sketch_or_face_id.map(Into::into))
616                        .maybe_target_reference(target_reference.clone())
617                        .distance(LengthUnit(length.to_mm()))
618                        .opposite(opposite.clone())
619                        .maybe_draft_angle(
620                            draft_angle
621                                .clone()
622                                .map(|a| Angle::from_degrees(a.to_degrees(exec_state, args.source_range))),
623                        )
624                        .extrude_method(extrude_method)
625                        .body_type(body_type)
626                        .maybe_merge_coplanar_faces(hide_seams)
627                        .maybe_direction(direction3d)
628                        .maybe_direction_reference(direction_reference)
629                        .build(),
630                )
631            }
632            (None, None, None, None, Some(to), None) => match to {
633                Point3dAxis3dOrGeometryReference::Point(point) => ModelingCmd::from(
634                    mcmd::ExtrudeToReference::builder()
635                        .target(concrete_target()?.into())
636                        .reference(ExtrudeReference::Point {
637                            point: KPoint3d {
638                                x: LengthUnit(point[0].to_mm()),
639                                y: LengthUnit(point[1].to_mm()),
640                                z: LengthUnit(point[2].to_mm()),
641                            },
642                        })
643                        .extrude_method(extrude_method)
644                        .body_type(body_type)
645                        .build(),
646                ),
647                Point3dAxis3dOrGeometryReference::Axis { direction, origin } => ModelingCmd::from(
648                    mcmd::ExtrudeToReference::builder()
649                        .target(concrete_target()?.into())
650                        .reference(ExtrudeReference::Axis {
651                            axis: KPoint3d {
652                                x: direction[0].to_mm(),
653                                y: direction[1].to_mm(),
654                                z: direction[2].to_mm(),
655                            },
656                            point: KPoint3d {
657                                x: LengthUnit(origin[0].to_mm()),
658                                y: LengthUnit(origin[1].to_mm()),
659                                z: LengthUnit(origin[2].to_mm()),
660                            },
661                        })
662                        .extrude_method(extrude_method)
663                        .body_type(body_type)
664                        .build(),
665                ),
666                Point3dAxis3dOrGeometryReference::Plane(plane) => {
667                    let plane_id = if plane.is_uninitialized() {
668                        if plane.info.origin.units.is_none() {
669                            return Err(KclError::new_semantic(KclErrorDetails::new(
670                                "Origin of plane has unknown units".to_string(),
671                                vec![args.source_range],
672                            )));
673                        }
674                        let sketch_plane = crate::std::sketch::make_sketch_plane_from_orientation(
675                            plane.clone().info.into_plane_data(),
676                            exec_state,
677                            &args,
678                        )
679                        .await?;
680                        sketch_plane.id
681                    } else {
682                        plane.id
683                    };
684                    ModelingCmd::from(
685                        mcmd::ExtrudeToReference::builder()
686                            .target(concrete_target()?.into())
687                            .reference(ExtrudeReference::EntityReference {
688                                entity_id: Some(plane_id),
689                                entity_reference: None,
690                            })
691                            .extrude_method(extrude_method)
692                            .body_type(body_type)
693                            .build(),
694                    )
695                }
696                Point3dAxis3dOrGeometryReference::Edge(edge_ref) => {
697                    let edge_id = edge_ref.get_engine_id(exec_state, &args)?;
698                    ModelingCmd::from(
699                        mcmd::ExtrudeToReference::builder()
700                            .target(concrete_target()?.into())
701                            .reference(ExtrudeReference::EntityReference {
702                                entity_id: Some(edge_id),
703                                entity_reference: None,
704                            })
705                            .extrude_method(extrude_method)
706                            .body_type(body_type)
707                            .build(),
708                    )
709                }
710                Point3dAxis3dOrGeometryReference::Face(face_tag) => {
711                    let face_id = face_tag.get_face_id_from_tag(exec_state, &args, false).await?;
712                    ModelingCmd::from(
713                        mcmd::ExtrudeToReference::builder()
714                            .target(concrete_target()?.into())
715                            .reference(ExtrudeReference::EntityReference {
716                                entity_id: Some(face_id),
717                                entity_reference: None,
718                            })
719                            .extrude_method(extrude_method)
720                            .body_type(body_type)
721                            .build(),
722                    )
723                }
724                Point3dAxis3dOrGeometryReference::Sketch(sketch_ref) => ModelingCmd::from(
725                    mcmd::ExtrudeToReference::builder()
726                        .target(concrete_target()?.into())
727                        .reference(ExtrudeReference::EntityReference {
728                            entity_id: Some(sketch_ref.id),
729                            entity_reference: None,
730                        })
731                        .extrude_method(extrude_method)
732                        .body_type(body_type)
733                        .build(),
734                ),
735                Point3dAxis3dOrGeometryReference::Solid(solid) => ModelingCmd::from(
736                    mcmd::ExtrudeToReference::builder()
737                        .target(concrete_target()?.into())
738                        .reference(ExtrudeReference::EntityReference {
739                            entity_id: Some(solid.id),
740                            entity_reference: None,
741                        })
742                        .extrude_method(extrude_method)
743                        .body_type(body_type)
744                        .build(),
745                ),
746                Point3dAxis3dOrGeometryReference::TaggedEdgeOrFace(tag) => {
747                    let tagged_edge_or_face = args.get_tag_engine_info(exec_state, tag)?;
748                    let tagged_edge_or_face_id = tagged_edge_or_face.id;
749                    ModelingCmd::from(
750                        mcmd::ExtrudeToReference::builder()
751                            .target(concrete_target()?.into())
752                            .reference(ExtrudeReference::EntityReference {
753                                entity_id: Some(tagged_edge_or_face_id),
754                                entity_reference: None,
755                            })
756                            .extrude_method(extrude_method)
757                            .body_type(body_type)
758                            .build(),
759                    )
760                }
761                Point3dAxis3dOrGeometryReference::EdgeToReference(spec) => {
762                    let inner = edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?;
763                    ModelingCmd::from(
764                        mcmd::ExtrudeToReference::builder()
765                            .target(concrete_target()?.into())
766                            .reference(ExtrudeReference::EntityReference {
767                                entity_id: None,
768                                entity_reference: Some(EntityReference::Edge {
769                                    inner,
770                                    topology_fallback: None,
771                                }),
772                            })
773                            .extrude_method(extrude_method)
774                            .body_type(body_type)
775                            .build(),
776                    )
777                }
778            },
779            (Some(_), _, _, None, None, None) => {
780                return Err(KclError::new_semantic(KclErrorDetails::new(
781                    "The `length` parameter must be provided when using twist angle for extrusion.".to_owned(),
782                    vec![args.source_range],
783                )));
784            }
785            (_, _, _, None, None, None) => {
786                return Err(KclError::new_semantic(KclErrorDetails::new(
787                    "Either `length` or `to` parameter must be provided for extrusion.".to_owned(),
788                    vec![args.source_range],
789                )));
790            }
791            (_, _, _, Some(_), Some(_), None) => {
792                return Err(KclError::new_semantic(KclErrorDetails::new(
793                    "You cannot give both `length` and `to` params, you have to choose one or the other".to_owned(),
794                    vec![args.source_range],
795                )));
796            }
797            (_, _, _, _, _, _) => {
798                return Err(KclError::new_semantic(KclErrorDetails::new(
799                    "Invalid combination of parameters for extrusion.".to_owned(),
800                    vec![args.source_range],
801                )));
802            }
803        };
804
805        let being_extruded = match extrudable {
806            Extrudable::Sketch(..) => BeingExtruded::Sketch,
807            Extrudable::FaceTag(face_tag) => {
808                let face_id = concrete_target()?;
809                let solid_id = match face_tag.geometry() {
810                    Some(crate::execution::Geometry::Solid(solid)) => solid.id,
811                    Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
812                        SketchSurface::Face(face) => face.parent_solid.solid_id,
813                        SketchSurface::Plane(_) => sketch.id,
814                    },
815                    None => face_id,
816                };
817                BeingExtruded::Face { face_id, solid_id }
818            }
819            Extrudable::Face(face) => BeingExtruded::Face {
820                face_id: face.id,
821                solid_id: face.parent_solid.solid_id,
822            },
823            Extrudable::EdgeTag(_) => BeingExtruded::Edge,
824            Extrudable::Edge(_) => BeingExtruded::Edge,
825            Extrudable::EdgeSpecifier(_) => BeingExtruded::Edge,
826        };
827        if let Some(post_extr_sketch) = extrudable.as_sketch() {
828            let cmds = post_extr_sketch.build_sketch_mode_cmds(
829                exec_state,
830                ModelingCmdReq {
831                    cmd_id: extrude_cmd_id.into(),
832                    cmd,
833                },
834            );
835            exec_state
836                .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), &cmds)
837                .await?;
838            solids.push(
839                do_post_extrude(
840                    &post_extr_sketch,
841                    extrude_cmd_id.into(),
842                    false,
843                    &NamedCapTags {
844                        start: tag_start.as_ref(),
845                        end: tag_end.as_ref(),
846                    },
847                    extrude_method,
848                    exec_state,
849                    &args,
850                    None,
851                    None,
852                    body_type,
853                    being_extruded,
854                )
855                .await?,
856            );
857        } else if is_edge {
858            // Ensure that edges do not use the MERGE method.
859            match extrude_method {
860                ExtrudeMethod::New => {
861                    // This is expected.
862                }
863                ExtrudeMethod::Merge => {
864                    return Err(KclError::new_semantic(KclErrorDetails::new(
865                        "Cannot use method MERGE with surface extrude of an edge".to_owned(),
866                        vec![args.source_range],
867                    )));
868                }
869                _ => {
870                    return Err(KclError::new_internal(KclErrorDetails::new(
871                        format!("Unknown extrude method: {extrude_method:?}"),
872                        vec![args.source_range],
873                    )));
874                }
875            }
876
877            // Surface-extrude an edge.
878            exec_state
879                .batch_modeling_cmd(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), cmd)
880                .await?;
881            // Extract the edge tag.
882            let edge_tag = match extrudable {
883                Extrudable::Sketch(_) => None,
884                Extrudable::FaceTag(_) => None,
885                Extrudable::Face(_) => None,
886                Extrudable::EdgeTag(tag) => Some(TagDeclarator::new(&tag.value)),
887                Extrudable::Edge(_) => None,
888                Extrudable::EdgeSpecifier(_) => None,
889            };
890            solids.push(after_surface_creation(extrude_cmd_id.into(), edge_tag, exec_state, &args).await?);
891        } else {
892            return Err(KclError::new_type(KclErrorDetails::new(
893                "Expected a sketch for extrusion".to_owned(),
894                vec![args.source_range],
895            )));
896        }
897    }
898
899    Ok(solids)
900}
901
902#[derive(Debug, Default)]
903pub(crate) struct NamedCapTags<'a> {
904    pub start: Option<&'a TagNode>,
905    pub end: Option<&'a TagNode>,
906}
907
908#[derive(Debug, Clone, Copy)]
909pub enum BeingExtruded {
910    Sketch,
911    Face { face_id: Uuid, solid_id: Uuid },
912    Edge,
913}
914
915/// Which edge should we use for querying Solid3dGetExtrusionInfo and GetAdjacencyInfo?
916/// It can be any edge of the body, but if our body is a clone, we should use an edge of
917/// the original body, not the new cloned body.
918fn get_extrusion_info_edge_id(
919    sketch: &Sketch,
920    any_edge_id: Uuid,
921    clone_id_map: Option<&HashMap<Uuid, Uuid>>,
922) -> Option<Uuid> {
923    // If this isn't a clone, there's no old/new body distinction.
924    // So just use the edge.
925    if sketch.clone.is_none() {
926        return Some(any_edge_id);
927    }
928    let Some(clone_map) = clone_id_map else {
929        return Some(any_edge_id);
930    };
931
932    // clone_map maps old IDs -> new IDs.
933    // If the `any_edge_id` is an ID of the OLD body
934    // (we know this if it's a _key_ of the map)
935    // we should use it (because that's the old body we're querying).
936    if clone_map.contains_key(&any_edge_id) {
937        return Some(any_edge_id);
938    }
939
940    // Otherwise, if the `any_edge_id` is an ID of the NEW body
941    // (we know this if it's a _value_ of the map),
942    // we should query the corresponding ID in the OLD body.
943    // i.e. if it's a hashmap value, find the corresponding key.
944    if let Some((old_edge_id, _)) = clone_map.iter().find(|(_, new_edge_id)| **new_edge_id == any_edge_id) {
945        return Some(*old_edge_id);
946    }
947
948    // Fall back to this if the clone_map doesn't have the data we expect.
949    // Engine will intuit an edge for the relevant calls, but it may mean the clone map was built wrong,
950    // or KCL and the engine disagree about what geometry exists.
951    None
952}
953
954/// This is similar to [`do_post_extrude()`], but for surfaces where a sketch
955/// isn't available.
956pub(crate) async fn after_surface_creation(
957    extrude_cmd_id: ArtifactId,
958    edge_tag: Option<crate::parsing::ast::types::Node<TagDeclarator>>,
959    exec_state: &mut ExecState,
960    args: &Args,
961) -> Result<Solid, KclError> {
962    let body_id = extrude_cmd_id.into();
963
964    // Bring the object to the front of the scene.
965    // See: https://github.com/KittyCAD/modeling-app/issues/806
966
967    exec_state
968        .batch_modeling_cmd(
969            ModelingCmdMeta::from_args(exec_state, args),
970            ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(body_id).build()),
971        )
972        .await?;
973
974    let (face_id, edge_id) = if args.ctx.no_engine_commands().await {
975        (exec_state.next_uuid(), exec_state.next_uuid())
976    } else {
977        // Get the body entity ids.
978        let response = exec_state
979            .send_modeling_cmd(
980                ModelingCmdMeta::from_args(exec_state, args),
981                ModelingCmd::from(mcmd::EntityGetAllChildUuids::builder().entity_id(body_id).build()),
982            )
983            .await?;
984        let OkWebSocketResponseData::Modeling {
985            modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(ref all_child_ids_resp),
986        } = response
987        else {
988            return Err(KclError::new_engine(KclErrorDetails::new(
989                format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
990                vec![args.source_range],
991            )));
992        };
993        let entity_ids = &all_child_ids_resp.entity_ids;
994        let Some(face_id) = entity_ids.first().copied() else {
995            return Err(KclError::new_internal(KclErrorDetails::new(
996                format!("Expected EntityGetAllChildUuids response to have at least 1 ID: {response:?}",),
997                vec![args.source_range],
998            )));
999        };
1000        let Some(edge_id) = entity_ids.get(1).copied() else {
1001            return Err(KclError::new_internal(KclErrorDetails::new(
1002                format!("Expected EntityGetAllChildUuids response to have at least 2 IDs: {response:?}"),
1003                vec![args.source_range],
1004            )));
1005        };
1006        (face_id, edge_id)
1007    };
1008
1009    // TODO: Do we need to use ExtrudeArc?
1010    let extrude_surface = ExtrudeSurface::ExtrudePlane(ExtrudePlane {
1011        face_id,
1012        tag: edge_tag,
1013        geo_meta: GeoMeta {
1014            id: face_id,
1015            metadata: args.source_range.into(),
1016        },
1017    });
1018    let new_value = vec![extrude_surface];
1019
1020    Ok(Solid {
1021        id: body_id,
1022        value_id: body_id,
1023        topology_id: body_id,
1024        pattern_source_artifact_id: None,
1025        best_guess_body_type: Some(BodyType::Surface),
1026        artifact_id: extrude_cmd_id,
1027        value: new_value,
1028        faces: Default::default(),
1029        meta: vec![args.source_range.into()],
1030        // Normally, we would propagate the units of the sketch. But an edge
1031        // doesn't have units. We also don't seem to use this field anywhere.
1032        units: kcl_api::UnitLength::Millimeters,
1033        sectional: false,
1034        creator: SolidCreator::Edge(CreatorEdge { edge_id, body_id }),
1035        start_cap_id: None,
1036        end_cap_id: None,
1037        edge_cuts: Vec::new(),
1038        pending_edge_cut_ids: Vec::new(),
1039    })
1040}
1041
1042#[allow(clippy::too_many_arguments)]
1043pub(crate) async fn do_post_extrude<'a>(
1044    sketch: &Sketch,
1045    extrude_cmd_id: ArtifactId,
1046    sectional: bool,
1047    named_cap_tags: &'a NamedCapTags<'a>,
1048    extrude_method: ExtrudeMethod,
1049    exec_state: &mut ExecState,
1050    args: &Args,
1051    edge_id: Option<Uuid>,
1052    clone_id_map: Option<&HashMap<Uuid, Uuid>>, // old sketch id -> new sketch id
1053    body_type: BodyType,
1054    being_extruded: BeingExtruded,
1055) -> Result<Solid, KclError> {
1056    // Bring the object to the front of the scene.
1057    // See: https://github.com/KittyCAD/modeling-app/issues/806
1058
1059    exec_state
1060        .batch_modeling_cmd(
1061            ModelingCmdMeta::from_args(exec_state, args),
1062            ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(sketch.id).build()),
1063        )
1064        .await?;
1065
1066    let any_edge_id = if let Some(edge_id) = sketch.mirror {
1067        edge_id
1068    } else if let Some(id) = edge_id {
1069        id
1070    } else {
1071        // The "get extrusion face info" API call requires *any* edge on the sketch being extruded.
1072        // So, let's just use the first one.
1073        let Some(any_edge_id) = sketch.paths.first().map(|edge| edge.get_base().geo_meta.id) else {
1074            return Err(KclError::new_type(KclErrorDetails::new(
1075                "Expected a non-empty sketch".to_owned(),
1076                vec![args.source_range],
1077            )));
1078        };
1079        any_edge_id
1080    };
1081
1082    // If the sketch is a clone, we will use the original info to get the extrusion face info.
1083    // So let's find an edge of the old body.
1084    let extrusion_info_edge_id = get_extrusion_info_edge_id(sketch, any_edge_id, clone_id_map);
1085
1086    let mut sketch = sketch.clone();
1087    match body_type {
1088        BodyType::Solid => {
1089            sketch.is_closed = ProfileClosed::Explicitly;
1090        }
1091        BodyType::Surface => {}
1092        _other => {
1093            // At some point in the future we'll add sheet metal or something.
1094            // Figure this out then.
1095        }
1096    }
1097
1098    match (extrude_method, being_extruded) {
1099        (ExtrudeMethod::Merge, BeingExtruded::Face { .. }) => {
1100            // Merge the IDs.
1101            // If we were sketching on a face, we need the original face id.
1102            if let SketchSurface::Face(ref face) = sketch.on {
1103                // If we're merging into an existing body, then assign the existing body's ID,
1104                // because the variable binding for this solid won't be its own object, it's just modifying the original one.
1105                sketch.id = face.parent_solid.sketch_or_solid_id();
1106            }
1107        }
1108        (ExtrudeMethod::New, BeingExtruded::Face { .. }) => {
1109            // We're creating a new solid, it's not based on any existing sketch (it's based on a face).
1110            // So we need a new ID, the extrude command ID.
1111            sketch.id = extrude_cmd_id.into();
1112        }
1113        (ExtrudeMethod::New, BeingExtruded::Sketch) => {
1114            // If we are creating a new body we need to preserve its new id.
1115            // The sketch's ID is already correct here, it should be the ID of the sketch.
1116        }
1117        (ExtrudeMethod::Merge, BeingExtruded::Sketch) => {
1118            if let SketchSurface::Face(ref face) = sketch.on {
1119                // If we're merging into an existing body, then assign the existing body's ID,
1120                // because the variable binding for this solid won't be its own object, it's just modifying the original one.
1121                sketch.id = face.parent_solid.sketch_or_solid_id();
1122            }
1123        }
1124        (other, _) => {
1125            // If you ever hit this, you should add a new arm to the match expression, and implement support for the new ExtrudeMethod variant.
1126            return Err(KclError::new_internal(KclErrorDetails::new(
1127                format!("Zoo does not yet support creating bodies via {other:?}"),
1128                vec![args.source_range],
1129            )));
1130        }
1131    }
1132
1133    // Similarly, if the sketch is a clone, we need to use the original sketch id to get the extrusion face info.
1134    let sketch_id = if let Some(cloned_from) = sketch.clone
1135        && clone_id_map.is_some()
1136    {
1137        cloned_from
1138    } else {
1139        sketch.id
1140    };
1141
1142    let solid3d_info = exec_state
1143        .send_modeling_cmd(
1144            ModelingCmdMeta::from_args(exec_state, args),
1145            ModelingCmd::from(
1146                mcmd::Solid3dGetExtrusionFaceInfo::builder()
1147                    .maybe_edge_id(extrusion_info_edge_id)
1148                    .object_id(sketch_id)
1149                    .build(),
1150            ),
1151        )
1152        .await?;
1153
1154    let face_infos = if let OkWebSocketResponseData::Modeling {
1155        modeling_response: OkModelingCmdResponse::Solid3dGetExtrusionFaceInfo(data),
1156    } = solid3d_info
1157    {
1158        data.faces
1159    } else {
1160        vec![]
1161    };
1162
1163    // Only do this if we need the artifact graph.
1164    if !args.ctx.settings.skip_artifact_graph {
1165        // Getting the ids of a sectional sweep does not work well and we cannot guarantee that
1166        // any of these call will not just fail.
1167        if !sectional {
1168            exec_state
1169                .batch_modeling_cmd(
1170                    ModelingCmdMeta::from_args(exec_state, args),
1171                    ModelingCmd::from(
1172                        mcmd::Solid3dGetAdjacencyInfo::builder()
1173                            .object_id(sketch_id)
1174                            .maybe_edge_id(extrusion_info_edge_id)
1175                            .build(),
1176                    ),
1177                )
1178                .await?;
1179        }
1180    }
1181
1182    let Faces {
1183        sides: mut face_id_map,
1184        mut start_cap_id,
1185        mut end_cap_id,
1186    } = analyze_faces(exec_state, args, face_infos).await;
1187
1188    // If this is a clone, we will use the clone_id_map to map the face info from the original sketch to the clone sketch.
1189    if sketch.clone.is_some()
1190        && let Some(clone_id_map) = clone_id_map
1191    {
1192        face_id_map = face_id_map
1193            .into_iter()
1194            .filter_map(|(k, v)| {
1195                let fe_key = clone_id_map.get(&k)?;
1196                let fe_value = clone_id_map.get(&(v?)).copied();
1197                Some((*fe_key, fe_value))
1198            })
1199            .collect::<HashMap<Uuid, Option<Uuid>>>();
1200        // The face info above was queried using the original solid's id, so
1201        // the cap ids belong to the original. Map them to the clone's ids.
1202        start_cap_id = start_cap_id.and_then(|id| clone_id_map.get(&id).copied());
1203        end_cap_id = end_cap_id.and_then(|id| clone_id_map.get(&id).copied());
1204    }
1205
1206    // Iterate over the sketch.value array and add face_id to GeoMeta
1207    let no_engine_commands = args.ctx.no_engine_commands().await;
1208    let mut new_value: Vec<ExtrudeSurface> = Vec::with_capacity(sketch.paths.len() + sketch.inner_paths.len() + 2);
1209    let outer_surfaces = sketch.paths.iter().flat_map(|path| {
1210        if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1211            surface_of(path, *actual_face_id)
1212        } else if no_engine_commands {
1213            crate::log::logln!(
1214                "No face ID found for path ID {:?}, but in no-engine-commands mode, so faking it",
1215                path.get_base().geo_meta.id
1216            );
1217            // Only pre-populate the extrude surface if we are in mock mode.
1218            fake_extrude_surface(exec_state, path)
1219        } else if sketch.clone.is_some()
1220            && let Some(clone_map) = clone_id_map
1221        {
1222            let new_path = clone_map.get(&(path.get_base().geo_meta.id));
1223
1224            if let Some(new_path) = new_path {
1225                match face_id_map.get(new_path) {
1226                    Some(Some(actual_face_id)) => clone_surface_of(path, *new_path, *actual_face_id),
1227                    _ => {
1228                        let actual_face_id = face_id_map.iter().find_map(|(key, value)| {
1229                            if let Some(value) = value {
1230                                if value == new_path { Some(key) } else { None }
1231                            } else {
1232                                None
1233                            }
1234                        });
1235                        match actual_face_id {
1236                            Some(actual_face_id) => clone_surface_of(path, *new_path, *actual_face_id),
1237                            None => {
1238                                crate::log::logln!("No face ID found for clone path ID {:?}, so skipping it", new_path);
1239                                None
1240                            }
1241                        }
1242                    }
1243                }
1244            } else {
1245                None
1246            }
1247        } else {
1248            crate::log::logln!(
1249                "No face ID found for path ID {:?}, and not in no-engine-commands mode, so skipping it",
1250                path.get_base().geo_meta.id
1251            );
1252            None
1253        }
1254    });
1255
1256    new_value.extend(outer_surfaces);
1257    let inner_surfaces = sketch.inner_paths.iter().flat_map(|path| {
1258        if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1259            surface_of(path, *actual_face_id)
1260        } else if no_engine_commands {
1261            // Only pre-populate the extrude surface if we are in mock mode.
1262            fake_extrude_surface(exec_state, path)
1263        } else {
1264            None
1265        }
1266    });
1267    new_value.extend(inner_surfaces);
1268
1269    // Add the tags for the start or end caps. A CSG can split or remove a
1270    // canonical cap before a body is cloned or mirrored, so reconstruction
1271    // cannot preserve that tag as one cap when the engine no longer reports it.
1272    if let Some(tag_start) = named_cap_tags.start {
1273        if let Some(start_cap_id) = start_cap_id {
1274            new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1275                face_id: start_cap_id,
1276                tag: Some(tag_start.clone()),
1277                geo_meta: GeoMeta {
1278                    id: start_cap_id,
1279                    metadata: args.source_range.into(),
1280                },
1281            }));
1282        } else if clone_id_map.is_none() {
1283            return Err(KclError::new_type(KclErrorDetails::new(
1284                format!(
1285                    "Expected a start cap ID for tag `{}` for extrusion of sketch {:?}",
1286                    tag_start.name, sketch.id
1287                ),
1288                vec![args.source_range],
1289            )));
1290        }
1291    }
1292    if let Some(tag_end) = named_cap_tags.end {
1293        if let Some(end_cap_id) = end_cap_id {
1294            new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1295                face_id: end_cap_id,
1296                tag: Some(tag_end.clone()),
1297                geo_meta: GeoMeta {
1298                    id: end_cap_id,
1299                    metadata: args.source_range.into(),
1300                },
1301            }));
1302        } else if clone_id_map.is_none() {
1303            return Err(KclError::new_type(KclErrorDetails::new(
1304                format!(
1305                    "Expected an end cap ID for tag `{}` for extrusion of sketch {:?}",
1306                    tag_end.name, sketch.id
1307                ),
1308                vec![args.source_range],
1309            )));
1310        }
1311    }
1312
1313    let meta = sketch.meta.clone();
1314    let units = sketch.units;
1315    let id = sketch.id;
1316    let topology_id = sketch.original_id;
1317    let creator = match being_extruded {
1318        BeingExtruded::Sketch => SolidCreator::Sketch(sketch),
1319        BeingExtruded::Face { face_id, solid_id } => SolidCreator::Face(CreatorFace {
1320            face_id,
1321            solid_id,
1322            sketch,
1323        }),
1324        BeingExtruded::Edge => {
1325            let message = "Expected an edge to have been extruded via another code path";
1326            debug_assert!(false, "{message}");
1327            return Err(KclError::new_internal(KclErrorDetails::new(
1328                message.to_owned(),
1329                vec![args.source_range],
1330            )));
1331        }
1332    };
1333
1334    Ok(Solid {
1335        id,
1336        value_id: extrude_cmd_id.into(),
1337        topology_id,
1338        pattern_source_artifact_id: None,
1339        best_guess_body_type: Some(body_type),
1340        artifact_id: extrude_cmd_id,
1341        value: new_value,
1342        faces: Default::default(),
1343        meta,
1344        units,
1345        sectional,
1346        creator,
1347        start_cap_id,
1348        end_cap_id,
1349        edge_cuts: vec![],
1350        pending_edge_cut_ids: vec![],
1351    })
1352}
1353
1354#[derive(Debug, Default)]
1355struct Faces {
1356    /// Maps curve ID to face ID for each side.
1357    sides: HashMap<Uuid, Option<Uuid>>,
1358    /// Top face ID.
1359    end_cap_id: Option<Uuid>,
1360    /// Bottom face ID.
1361    start_cap_id: Option<Uuid>,
1362}
1363
1364async fn analyze_faces(exec_state: &mut ExecState, args: &Args, face_infos: Vec<ExtrusionFaceInfo>) -> Faces {
1365    let mut faces = Faces {
1366        sides: HashMap::with_capacity(face_infos.len()),
1367        ..Default::default()
1368    };
1369    if args.ctx.no_engine_commands().await {
1370        // Create fake IDs for start and end caps, to make extrudes mock-execute safe
1371        faces.start_cap_id = Some(exec_state.next_uuid());
1372        faces.end_cap_id = Some(exec_state.next_uuid());
1373    }
1374    for face_info in face_infos {
1375        match face_info.cap {
1376            ExtrusionFaceCapType::Bottom => faces.start_cap_id = face_info.face_id,
1377            ExtrusionFaceCapType::Top => faces.end_cap_id = face_info.face_id,
1378            ExtrusionFaceCapType::Both => {
1379                faces.end_cap_id = face_info.face_id;
1380                faces.start_cap_id = face_info.face_id;
1381            }
1382            ExtrusionFaceCapType::None => {
1383                if let Some(curve_id) = face_info.curve_id {
1384                    faces.sides.insert(curve_id, face_info.face_id);
1385                }
1386            }
1387            other => {
1388                exec_state.warn(
1389                    crate::CompilationIssue {
1390                        source_range: args.source_range,
1391                        message: format!("unknown extrusion face type {other:?}"),
1392                        suggestion: None,
1393                        severity: crate::errors::Severity::Warning,
1394                        tag: crate::errors::Tag::Unnecessary,
1395                    },
1396                    annotations::WARN_NOT_YET_SUPPORTED,
1397                );
1398            }
1399        }
1400    }
1401    faces
1402}
1403fn surface_of(path: &Path, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1404    match path {
1405        Path::Arc { .. }
1406        | Path::TangentialArc { .. }
1407        | Path::TangentialArcTo { .. }
1408        // TODO: (bc) fix me
1409        | Path::Ellipse { .. }
1410        | Path::Conic {.. }
1411        | Path::Circle { .. }
1412        | Path::CircleThreePoint { .. } => {
1413            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1414                face_id: actual_face_id,
1415                tag: path.get_base().tag.clone(),
1416                geo_meta: GeoMeta {
1417                    id: path.get_base().geo_meta.id,
1418                    metadata: path.get_base().geo_meta.metadata,
1419                },
1420            });
1421            Some(extrude_surface)
1422        }
1423        Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1424            let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1425                face_id: actual_face_id,
1426                tag: path.get_base().tag.clone(),
1427                geo_meta: GeoMeta {
1428                    id: path.get_base().geo_meta.id,
1429                    metadata: path.get_base().geo_meta.metadata,
1430                },
1431            });
1432            Some(extrude_surface)
1433        }
1434        Path::ArcThreePoint { .. } => {
1435            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1436                face_id: actual_face_id,
1437                tag: path.get_base().tag.clone(),
1438                geo_meta: GeoMeta {
1439                    id: path.get_base().geo_meta.id,
1440                    metadata: path.get_base().geo_meta.metadata,
1441                },
1442            });
1443            Some(extrude_surface)
1444        }
1445    }
1446}
1447
1448fn clone_surface_of(path: &Path, clone_path_id: Uuid, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1449    match path {
1450        Path::Arc { .. }
1451        | Path::TangentialArc { .. }
1452        | Path::TangentialArcTo { .. }
1453        // TODO: (gserena) fix me
1454        | Path::Ellipse { .. }
1455        | Path::Conic {.. }
1456        | Path::Circle { .. }
1457        | Path::CircleThreePoint { .. } => {
1458            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1459                face_id: actual_face_id,
1460                tag: path.get_base().tag.clone(),
1461                geo_meta: GeoMeta {
1462                    id: clone_path_id,
1463                    metadata: path.get_base().geo_meta.metadata,
1464                },
1465            });
1466            Some(extrude_surface)
1467        }
1468        Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1469            let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1470                face_id: actual_face_id,
1471                tag: path.get_base().tag.clone(),
1472                geo_meta: GeoMeta {
1473                    id: clone_path_id,
1474                    metadata: path.get_base().geo_meta.metadata,
1475                },
1476            });
1477            Some(extrude_surface)
1478        }
1479        Path::ArcThreePoint { .. } => {
1480            let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1481                face_id: actual_face_id,
1482                tag: path.get_base().tag.clone(),
1483                geo_meta: GeoMeta {
1484                    id: clone_path_id,
1485                    metadata: path.get_base().geo_meta.metadata,
1486                },
1487            });
1488            Some(extrude_surface)
1489        }
1490    }
1491}
1492
1493/// Create a fake extrude surface to report for mock execution, when there's no engine response.
1494fn fake_extrude_surface(exec_state: &mut ExecState, path: &Path) -> Option<ExtrudeSurface> {
1495    let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1496        // pushing this values with a fake face_id to make extrudes mock-execute safe
1497        face_id: exec_state.next_uuid(),
1498        tag: path.get_base().tag.clone(),
1499        geo_meta: GeoMeta {
1500            id: path.get_base().geo_meta.id,
1501            metadata: path.get_base().geo_meta.metadata,
1502        },
1503    });
1504    Some(extrude_surface)
1505}
1506
1507#[cfg(test)]
1508mod tests {
1509    use kcl_api::UnitLength;
1510
1511    use super::*;
1512    use crate::execution::AbstractSegment;
1513    use crate::execution::Plane;
1514    use crate::execution::SegmentRepr;
1515    use crate::execution::parse_execute;
1516    use crate::execution::types::NumericType;
1517    use crate::execution::types::NumericTypeExt;
1518    use crate::front::Expr;
1519    use crate::front::Number;
1520    use crate::front::ObjectId;
1521    use crate::front::Point2d;
1522    use crate::front::PointCtor;
1523    use crate::std::sketch::PlaneData;
1524
1525    fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
1526        Point2d {
1527            x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
1528            y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
1529        }
1530    }
1531
1532    fn segment_value(exec_state: &mut ExecState) -> KclValue {
1533        let plane = Plane::from_plane_data_skipping_engine(PlaneData::XY, exec_state).unwrap();
1534        let segment = Segment {
1535            id: exec_state.next_uuid(),
1536            object_id: ObjectId(1),
1537            kind: SegmentKind::Point {
1538                position: [TyF64::new(0.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())],
1539                ctor: Box::new(PointCtor {
1540                    position: point_expr(0.0, 0.0),
1541                }),
1542                freedom: None,
1543            },
1544            surface: SketchSurface::Plane(Box::new(plane)),
1545            sketch_id: exec_state.next_uuid(),
1546            sketch: None,
1547            tag: None,
1548            node_path: None,
1549            meta: vec![],
1550        };
1551        KclValue::Segment {
1552            value: Box::new(AbstractSegment {
1553                repr: SegmentRepr::Solved {
1554                    segment: Box::new(segment),
1555                },
1556                meta: vec![],
1557            }),
1558        }
1559    }
1560
1561    #[tokio::test(flavor = "multi_thread")]
1562    async fn extrude_accepts_negative_bidirectional_length_in_mock_exec() {
1563        let code = r#"
1564profile001 = startSketchOn(XY)
1565  |> startProfile(at = [0, 0])
1566  |> line(end = [1, 0])
1567  |> line(end = [0, 1])
1568  |> close()
1569
1570extrude(profile001, length = 1, bidirectionalLength = -1)
1571"#;
1572
1573        let result = parse_execute(code).await.unwrap();
1574        let extrude = result
1575            .root_module_artifact_commands()
1576            .iter()
1577            .find_map(|artifact_command| match &artifact_command.command {
1578                ModelingCmd::Extrude(extrude) => Some(extrude),
1579                _ => None,
1580            })
1581            .expect("expected an extrude command");
1582
1583        assert_eq!(extrude.opposite, Opposite::Other(LengthUnit(-1.0)));
1584    }
1585
1586    #[tokio::test(flavor = "multi_thread")]
1587    async fn extrude_rejects_an_empty_target_array() {
1588        let err = parse_execute("nothing = extrude([], length = 5)").await.unwrap_err();
1589
1590        assert!(matches!(err, KclError::Argument { .. }), "{err:?}");
1591        assert!(err.message().contains("requires one or more"), "{err:?}");
1592    }
1593
1594    #[tokio::test(flavor = "multi_thread")]
1595    async fn edge_extrude_succeeds_in_mock_exec() {
1596        let code = r#"
1597@settings(kclVersion = 2.0)
1598
1599sketch001 = sketch(on = XZ) {
1600  line1 = line(start = [0mm, 0mm], end = [1mm, 0mm])
1601}
1602extrude001 = extrude(sketch001.line1, length = 5, bodyType = SURFACE)
1603extrude(
1604  getOppositeEdge(extrude001.sketch.tags.line1),
1605  length = 1,
1606  method = NEW,
1607  bodyType = SURFACE,
1608)
1609"#;
1610
1611        parse_execute(code).await.unwrap();
1612    }
1613
1614    #[tokio::test(flavor = "multi_thread")]
1615    async fn edge_specifier_target_cannot_be_extruded_to_a_reference() {
1616        let code = r#"
1617@settings(kclVersion = 2.0, experimentalFeatures = allow)
1618
1619profile = startSketchOn(XY)
1620  |> startProfile(at = [0, 0])
1621  |> line(end = [1, 0], tag = $sideFace)
1622  |> line(end = [0, 1])
1623  |> line(end = [-1, 0])
1624  |> close()
1625body = extrude(profile, length = 1, tagEnd = $endFace)
1626
1627extrude(
1628  { sideFaces = [sideFace, endFace] },
1629  to = offsetPlane(XY, offset = 10),
1630  bodyType = SURFACE,
1631  method = NEW,
1632)
1633"#;
1634
1635        let err = parse_execute(code).await.unwrap_err();
1636
1637        assert!(matches!(err, KclError::Semantic { .. }), "{err:?}");
1638        assert!(
1639            err.message()
1640                .contains("Edge specifiers cannot be extruded to a reference"),
1641            "{err:?}"
1642        );
1643    }
1644
1645    #[tokio::test(flavor = "multi_thread")]
1646    async fn segment_extrude_rejects_cap_tags() {
1647        let ctx = ExecutorContext::new_mock(None).await;
1648        let mut exec_state = ExecState::new(&ctx);
1649        let err = coerce_extrude_targets(
1650            vec![segment_value(&mut exec_state)],
1651            BodyType::Surface,
1652            Some(&TagDeclarator::new("cap_start")),
1653            None,
1654            &mut exec_state,
1655            &ctx,
1656            crate::SourceRange::default(),
1657        )
1658        .await
1659        .unwrap_err();
1660
1661        assert!(
1662            err.message()
1663                .contains("`tagStart` and `tagEnd` are not supported when extruding sketch segments"),
1664            "{err:?}"
1665        );
1666        ctx.close().await;
1667    }
1668
1669    /// `getOppositeEdge()` and the other edge getters return a raw edge as
1670    /// `KclValue::Uuid`, which coerces to `Extrudable::Edge`.
1671    fn edge_value(exec_state: &mut ExecState) -> KclValue {
1672        KclValue::Uuid {
1673            value: exec_state.next_uuid(),
1674            meta: vec![],
1675        }
1676    }
1677
1678    #[tokio::test(flavor = "multi_thread")]
1679    async fn edge_extrude_rejects_solid_body_type() {
1680        let ctx = ExecutorContext::new_mock(None).await;
1681        let mut exec_state = ExecState::new(&ctx);
1682        let edge = edge_value(&mut exec_state);
1683        let err = coerce_extrude_targets(
1684            vec![edge],
1685            BodyType::Solid,
1686            None,
1687            None,
1688            &mut exec_state,
1689            &ctx,
1690            crate::SourceRange::default(),
1691        )
1692        .await
1693        .unwrap_err();
1694
1695        assert!(
1696            err.message()
1697                .contains("edges can only be extruded with surface extrudes"),
1698            "{err:?}"
1699        );
1700        ctx.close().await;
1701    }
1702
1703    #[tokio::test(flavor = "multi_thread")]
1704    async fn edge_extrude_rejects_cap_tags() {
1705        let ctx = ExecutorContext::new_mock(None).await;
1706        let mut exec_state = ExecState::new(&ctx);
1707        let edge = edge_value(&mut exec_state);
1708        let err = coerce_extrude_targets(
1709            vec![edge],
1710            BodyType::Surface,
1711            Some(&TagDeclarator::new("cap_start")),
1712            None,
1713            &mut exec_state,
1714            &ctx,
1715            crate::SourceRange::default(),
1716        )
1717        .await
1718        .unwrap_err();
1719
1720        assert!(
1721            err.message()
1722                .contains("`tagStart` and `tagEnd` are not supported when extruding edges"),
1723            "{err:?}"
1724        );
1725        ctx.close().await;
1726    }
1727
1728    #[tokio::test(flavor = "multi_thread")]
1729    async fn edge_extrude_rejects_mixing_with_face() {
1730        let ctx = ExecutorContext::new_mock(None).await;
1731        let mut exec_state = ExecState::new(&ctx);
1732        let edge = edge_value(&mut exec_state);
1733        // The string "START" coerces to a `FaceTag`, i.e. a non-edge extrudable.
1734        let face = KclValue::String {
1735            value: "START".to_owned(),
1736            meta: vec![],
1737        };
1738        let err = coerce_extrude_targets(
1739            vec![edge, face],
1740            BodyType::Surface,
1741            None,
1742            None,
1743            &mut exec_state,
1744            &ctx,
1745            crate::SourceRange::default(),
1746        )
1747        .await
1748        .unwrap_err();
1749
1750        assert!(
1751            err.message()
1752                .contains("Cannot extrude edges together with sketches or faces"),
1753            "{err:?}"
1754        );
1755        ctx.close().await;
1756    }
1757}