1use 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; use 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
64pub 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::Union(vec![
70 RuntimeType::sketch(),
71 RuntimeType::face(),
72 RuntimeType::tagged_face(),
73 RuntimeType::tagged_edge(),
74 RuntimeType::Primitive(PrimitiveType::Edge),
75 RuntimeType::segment(),
76 ])),
77 ArrayLen::Minimum(1),
78 ),
79 exec_state,
80 )?;
81
82 let length: Option<TyF64> = args.get_kw_arg_opt("length", &RuntimeType::length(), exec_state)?;
83 let to_raw = args.get_kw_arg_opt(
84 "to",
85 &RuntimeType::Union(vec![
86 RuntimeType::point3d(),
87 RuntimeType::Primitive(PrimitiveType::Axis3d),
88 RuntimeType::Primitive(PrimitiveType::Edge),
89 RuntimeType::plane(),
90 RuntimeType::Primitive(PrimitiveType::Face),
91 RuntimeType::sketch(),
92 RuntimeType::Primitive(PrimitiveType::Solid),
93 RuntimeType::tagged_edge(),
94 RuntimeType::tagged_face(),
95 RuntimeType::Primitive(PrimitiveType::Any),
96 ]),
97 exec_state,
98 )?;
99 let to = match to_raw {
100 None => None,
101 Some(v) => {
102 let inner = if let KclValue::Object { value: ref obj, .. } = v {
103 if edge::is_edge_specifier_object(&v) {
104 Point3dAxis3dOrGeometryReference::EdgeToReference(edge::parse_edge_specifier_object(obj, &args)?)
105 } else {
106 Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
107 KclError::new_type(KclErrorDetails::new(
108 "Invalid value for `to`".to_owned(),
109 vec![args.source_range],
110 ))
111 })?
112 }
113 } else {
114 Point3dAxis3dOrGeometryReference::from_kcl_val(&v).ok_or_else(|| {
115 KclError::new_type(KclErrorDetails::new(
116 "Invalid value for `to`".to_owned(),
117 vec![args.source_range],
118 ))
119 })?
120 };
121 Some(inner)
122 }
123 };
124 let symmetric = args.get_kw_arg_opt("symmetric", &RuntimeType::bool(), exec_state)?;
125 let bidirectional_length: Option<TyF64> =
126 args.get_kw_arg_opt("bidirectionalLength", &RuntimeType::length(), exec_state)?;
127 let direction = args.get_kw_arg_opt(
128 "direction",
129 &RuntimeType::Union(vec![
130 RuntimeType::point3d(),
131 RuntimeType::Primitive(PrimitiveType::Edge),
132 RuntimeType::tagged_edge(),
133 RuntimeType::segment(),
134 ]),
135 exec_state,
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 let Some(extrudable) = Extrudable::from_kcl_val(&value) else {
202 return Err(KclError::new_type(KclErrorDetails::new(
203 "Expected sketches, faces, tagged faces, or solved sketch segments for extrusion.".to_owned(),
204 vec![source_range],
205 )));
206 };
207 extrudables.push(extrudable);
208 }
209
210 if !segments.is_empty() && !extrudables.is_empty() {
211 return Err(KclError::new_semantic(KclErrorDetails::new(
212 "Cannot extrude sketch segments together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
213 vec![source_range],
214 )));
215 }
216
217 if !segments.is_empty() {
218 if !matches!(body_type, BodyType::Surface) {
219 let kind_of_extrude = match body_type {
220 BodyType::Solid => "solid extrude",
221 BodyType::Surface => "surface extrude",
222 _ => "non-surface extrude",
223 };
224 return Err(KclError::new_semantic(KclErrorDetails::new(
225 format!(
226 "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."
227 ),
228 vec![source_range],
229 )));
230 }
231
232 if tag_start.is_some() || tag_end.is_some() {
233 return Err(KclError::new_semantic(KclErrorDetails::new(
234 "`tagStart` and `tagEnd` are not supported when extruding sketch segments. Segment surface extrudes do not create start or end caps."
235 .to_owned(),
236 vec![source_range],
237 )));
238 }
239
240 let synthetic_sketch = build_segment_surface_sketch(segments, exec_state, ctx, source_range).await?;
241 return Ok(vec![Extrudable::from(synthetic_sketch)]);
242 }
243
244 let has_edge = extrudables
249 .iter()
250 .any(|e| matches!(e, Extrudable::Edge(_) | Extrudable::EdgeTag(_)));
251 if has_edge {
252 let has_non_edge = extrudables
253 .iter()
254 .any(|e| !matches!(e, Extrudable::Edge(_) | Extrudable::EdgeTag(_)));
255 if has_non_edge {
256 return Err(KclError::new_semantic(KclErrorDetails::new(
257 "Cannot extrude edges together with sketches or faces in the same call. Use separate `extrude()` calls.".to_owned(),
258 vec![source_range],
259 )));
260 }
261
262 if !matches!(body_type, BodyType::Surface) {
263 let kind_of_extrude = match body_type {
264 BodyType::Solid => "solid extrude",
265 BodyType::Surface => "surface extrude",
266 _ => "non-surface extrude",
267 };
268 return Err(KclError::new_semantic(KclErrorDetails::new(
269 format!(
270 "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."
271 ),
272 vec![source_range],
273 )));
274 }
275
276 if tag_start.is_some() || tag_end.is_some() {
277 return Err(KclError::new_semantic(KclErrorDetails::new(
278 "`tagStart` and `tagEnd` are not supported when extruding edges. Edge surface extrudes do not create start or end caps."
279 .to_owned(),
280 vec![source_range],
281 )));
282 }
283 }
284
285 Ok(extrudables)
286}
287
288pub(crate) async fn build_segment_surface_sketch(
289 mut segments: Vec<Segment>,
290 exec_state: &mut ExecState,
291 ctx: &ExecutorContext,
292 source_range: crate::SourceRange,
293) -> Result<Sketch, KclError> {
294 let Some(first_segment) = segments.first() else {
295 return Err(KclError::new_semantic(KclErrorDetails::new(
296 "Expected at least one sketch segment.".to_owned(),
297 vec![source_range],
298 )));
299 };
300
301 let sketch_id = first_segment.sketch_id;
302 let sketch_surface = first_segment.surface.clone();
303 for segment in &segments {
304 if segment.sketch_id != sketch_id {
305 return Err(KclError::new_semantic(KclErrorDetails::new(
306 "All sketch segments passed to this operation must come from the same sketch.".to_owned(),
307 vec![source_range],
308 )));
309 }
310
311 if segment.surface != sketch_surface {
312 return Err(KclError::new_semantic(KclErrorDetails::new(
313 "All sketch segments passed to this operation must lie on the same sketch surface.".to_owned(),
314 vec![source_range],
315 )));
316 }
317
318 if matches!(segment.kind, SegmentKind::Point { .. }) {
319 return Err(KclError::new_semantic(KclErrorDetails::new(
320 "Point segments cannot be used here. Select line, arc, or circle segments instead.".to_owned(),
321 vec![source_range],
322 )));
323 }
324
325 if segment.is_construction() {
326 return Err(KclError::new_semantic(KclErrorDetails::new(
327 "Construction segments cannot be used here. Select non-construction sketch segments instead."
328 .to_owned(),
329 vec![source_range],
330 )));
331 }
332 }
333
334 let synthetic_sketch_id = exec_state.next_uuid();
335 let segment_tags = IndexMap::from_iter(segments.iter().filter_map(|segment| {
336 segment
337 .tag
338 .as_ref()
339 .map(|tag| (segment.object_id, TagDeclarator::new(&tag.value)))
340 }));
341
342 for segment in &mut segments {
343 segment.id = exec_state.next_uuid();
344 segment.sketch_id = synthetic_sketch_id;
345 segment.sketch = None;
346 }
347
348 create_segments_in_engine(
349 &sketch_surface,
350 synthetic_sketch_id,
351 &mut segments,
352 &segment_tags,
353 ctx,
354 exec_state,
355 source_range,
356 )
357 .await?
358 .ok_or_else(|| {
359 KclError::new_semantic(KclErrorDetails::new(
360 "Expected at least one usable sketch segment.".to_owned(),
361 vec![source_range],
362 ))
363 })
364}
365
366#[allow(clippy::too_many_arguments)]
367async fn inner_extrude(
368 extrudables: Vec<Extrudable>,
369 length: Option<TyF64>,
370 to: Option<Point3dAxis3dOrGeometryReference>,
371 symmetric: Option<bool>,
372 direction: Option<Point3dOrEdgeReference>,
373 bidirectional_length: Option<TyF64>,
374 tag_start: Option<TagNode>,
375 tag_end: Option<TagNode>,
376 draft_angle: Option<TyF64>,
377 twist_angle: Option<TyF64>,
378 twist_angle_step: Option<TyF64>,
379 twist_center: Option<[TyF64; 2]>,
380 tolerance: Option<TyF64>,
381 method: Option<String>,
382 hide_seams: Option<bool>,
383 body_type: Option<BodyType>,
384 exec_state: &mut ExecState,
385 args: Args,
386) -> Result<Vec<Solid>, KclError> {
387 let body_type = body_type.unwrap_or_default();
388
389 if matches!(body_type, BodyType::Solid) && extrudables.iter().any(|sk| matches!(sk.is_closed(), ProfileClosed::No))
390 {
391 return Err(KclError::new_semantic(KclErrorDetails::new(
392 "Cannot solid extrude an open profile. Either close the profile, or use a surface extrude.".to_owned(),
393 vec![args.source_range],
394 )));
395 }
396
397 if draft_angle.is_some() && twist_angle.is_some() {
398 return Err(KclError::new_semantic(KclErrorDetails::new(
399 "Zoo currently does not support adding both draft angle and twist angle to an extrude simultaneously"
400 .to_owned(),
401 vec![args.source_range],
402 )));
403 }
404
405 if direction.is_some() && twist_angle.is_some() {
406 return Err(KclError::new_semantic(KclErrorDetails::new(
407 "Zoo currently does not support adding both direction and twist angle to an extrude simultaneously"
408 .to_owned(),
409 vec![args.source_range],
410 )));
411 }
412
413 let mut solids = Vec::new();
415 let tolerance = LengthUnit(tolerance.as_ref().map(|t| t.to_mm()).unwrap_or(DEFAULT_TOLERANCE_MM));
416
417 let extrude_method = match method.as_deref() {
418 Some("new" | "NEW") => ExtrudeMethod::New,
419 Some("merge" | "MERGE") => ExtrudeMethod::Merge,
420 None => ExtrudeMethod::default(),
421 Some(other) => {
422 return Err(KclError::new_semantic(KclErrorDetails::new(
423 format!("Unknown merge method {other}, try using `MERGE` or `NEW`"),
424 vec![args.source_range],
425 )));
426 }
427 };
428
429 if symmetric.unwrap_or(false) && bidirectional_length.is_some() {
430 return Err(KclError::new_semantic(KclErrorDetails::new(
431 "You cannot give both `symmetric` and `bidirectional` params, you have to choose one or the other"
432 .to_owned(),
433 vec![args.source_range],
434 )));
435 }
436
437 if let Some(bidirectional_length) = &bidirectional_length
438 && bidirectional_length.to_mm() < 0.0
439 {
440 return Err(KclError::new_semantic(KclErrorDetails::new(
441 "`bidirectionalLength` must be greater than or equal to 0".to_owned(),
442 vec![args.source_range],
443 )));
444 }
445
446 if (length.is_some() || twist_angle.is_some()) && to.is_some() {
447 return Err(KclError::new_semantic(KclErrorDetails::new(
448 "You cannot give `length` or `twist` params with the `to` param, you have to choose one or the other"
449 .to_owned(),
450 vec![args.source_range],
451 )));
452 }
453
454 let bidirection = bidirectional_length.map(|l| LengthUnit(l.to_mm()));
455
456 let opposite = match (symmetric, bidirection) {
457 (Some(true), _) => Opposite::Symmetric,
458 (None, None) => Opposite::None,
459 (Some(false), None) => Opposite::None,
460 (None, Some(length)) => Opposite::Other(length),
461 (Some(false), Some(length)) => Opposite::Other(length),
462 };
463
464 for extrudable in &extrudables {
465 let is_edge = match extrudable {
466 Extrudable::Sketch(..) => false,
467 Extrudable::FaceTag(_) => false,
468 Extrudable::Face(_) => false,
469 Extrudable::EdgeTag(_) => true,
470 Extrudable::Edge(_) => true,
471 };
472 let extrude_cmd_id = exec_state.next_uuid();
473 let sketch_or_face_id = extrudable.id_to_extrude(exec_state, &args, false).await?;
474 let cmd = match (
475 &twist_angle,
476 &twist_angle_step,
477 &twist_center,
478 length.clone(),
479 &to,
480 &direction,
481 ) {
482 (Some(angle), angle_step, center, Some(length), None, None) => {
483 let center = center.clone().map(point_to_mm).map(Point2d::from).unwrap_or_default();
484 let total_rotation_angle = Angle::from_degrees(angle.to_degrees(exec_state, args.source_range));
485 let angle_step_size = Angle::from_degrees(
486 angle_step
487 .clone()
488 .map(|a| a.to_degrees(exec_state, args.source_range))
489 .unwrap_or(15.0),
490 );
491 ModelingCmd::from(
492 mcmd::TwistExtrude::builder()
493 .target(sketch_or_face_id.into())
494 .distance(LengthUnit(length.to_mm()))
495 .center_2d(center)
496 .total_rotation_angle(total_rotation_angle)
497 .angle_step_size(angle_step_size)
498 .tolerance(tolerance)
499 .body_type(body_type)
500 .build(),
501 )
502 }
503 (None, None, None, Some(length), None, None) => ModelingCmd::from(
504 mcmd::Extrude::builder()
505 .target(sketch_or_face_id.into())
506 .distance(LengthUnit(length.to_mm()))
507 .opposite(opposite.clone())
508 .maybe_draft_angle(
509 draft_angle
510 .clone()
511 .map(|a| Angle::from_degrees(a.to_degrees(exec_state, args.source_range))),
512 )
513 .extrude_method(extrude_method)
514 .body_type(body_type)
515 .maybe_merge_coplanar_faces(hide_seams)
516 .build(),
517 ),
518 (None, None, None, Some(length), None, Some(dir)) => {
519 let direction3d = match dir {
520 Point3dOrEdgeReference::Point(p) => DirectionType::Axis {
521 direction: KPoint3d {
522 x: p[0].n,
523 y: p[1].n,
524 z: p[2].n,
525 },
526 },
527 Point3dOrEdgeReference::Edge(edge) => match edge {
528 crate::std::fillet::EdgeReference::Uuid(uuid) => DirectionType::Edge { id: *uuid },
529 crate::std::fillet::EdgeReference::Tag(tag) => DirectionType::Edge {
530 id: match tag.get_cur_info() {
531 Some(info) => info.id,
532 None => {
533 return Err(KclError::new_semantic(KclErrorDetails::new(
534 "Failed to get current info for tag".to_string(),
535 vec![args.source_range],
536 )));
537 }
538 },
539 },
540 },
541 };
542 ModelingCmd::from(
543 mcmd::Extrude::builder()
544 .target(sketch_or_face_id.into())
545 .distance(LengthUnit(length.to_mm()))
546 .opposite(opposite.clone())
547 .maybe_draft_angle(
548 draft_angle
549 .clone()
550 .map(|a| Angle::from_degrees(a.to_degrees(exec_state, args.source_range))),
551 )
552 .extrude_method(extrude_method)
553 .body_type(body_type)
554 .maybe_merge_coplanar_faces(hide_seams)
555 .direction(direction3d)
556 .build(),
557 )
558 }
559 (None, None, None, None, Some(_), None) if is_edge => {
560 return Err(KclError::new_semantic(KclErrorDetails::new(
561 "Extruding an edge with the `to` parameter isn't supported yet. Use an explicit length instead."
562 .to_owned(),
563 vec![args.source_range],
564 )));
565 }
566 (None, None, None, None, Some(to), None) => match to {
567 Point3dAxis3dOrGeometryReference::Point(point) => ModelingCmd::from(
568 mcmd::ExtrudeToReference::builder()
569 .target(sketch_or_face_id.into())
570 .reference(ExtrudeReference::Point {
571 point: KPoint3d {
572 x: LengthUnit(point[0].to_mm()),
573 y: LengthUnit(point[1].to_mm()),
574 z: LengthUnit(point[2].to_mm()),
575 },
576 })
577 .extrude_method(extrude_method)
578 .body_type(body_type)
579 .build(),
580 ),
581 Point3dAxis3dOrGeometryReference::Axis { direction, origin } => ModelingCmd::from(
582 mcmd::ExtrudeToReference::builder()
583 .target(sketch_or_face_id.into())
584 .reference(ExtrudeReference::Axis {
585 axis: KPoint3d {
586 x: direction[0].to_mm(),
587 y: direction[1].to_mm(),
588 z: direction[2].to_mm(),
589 },
590 point: KPoint3d {
591 x: LengthUnit(origin[0].to_mm()),
592 y: LengthUnit(origin[1].to_mm()),
593 z: LengthUnit(origin[2].to_mm()),
594 },
595 })
596 .extrude_method(extrude_method)
597 .body_type(body_type)
598 .build(),
599 ),
600 Point3dAxis3dOrGeometryReference::Plane(plane) => {
601 let plane_id = if plane.is_uninitialized() {
602 if plane.info.origin.units.is_none() {
603 return Err(KclError::new_semantic(KclErrorDetails::new(
604 "Origin of plane has unknown units".to_string(),
605 vec![args.source_range],
606 )));
607 }
608 let sketch_plane = crate::std::sketch::make_sketch_plane_from_orientation(
609 plane.clone().info.into_plane_data(),
610 exec_state,
611 &args,
612 )
613 .await?;
614 sketch_plane.id
615 } else {
616 plane.id
617 };
618 ModelingCmd::from(
619 mcmd::ExtrudeToReference::builder()
620 .target(sketch_or_face_id.into())
621 .reference(ExtrudeReference::EntityReference {
622 entity_id: Some(plane_id),
623 entity_reference: None,
624 })
625 .extrude_method(extrude_method)
626 .body_type(body_type)
627 .build(),
628 )
629 }
630 Point3dAxis3dOrGeometryReference::Edge(edge_ref) => {
631 let edge_id = edge_ref.get_engine_id(exec_state, &args)?;
632 ModelingCmd::from(
633 mcmd::ExtrudeToReference::builder()
634 .target(sketch_or_face_id.into())
635 .reference(ExtrudeReference::EntityReference {
636 entity_id: Some(edge_id),
637 entity_reference: None,
638 })
639 .extrude_method(extrude_method)
640 .body_type(body_type)
641 .build(),
642 )
643 }
644 Point3dAxis3dOrGeometryReference::Face(face_tag) => {
645 let face_id = face_tag.get_face_id_from_tag(exec_state, &args, false).await?;
646 ModelingCmd::from(
647 mcmd::ExtrudeToReference::builder()
648 .target(sketch_or_face_id.into())
649 .reference(ExtrudeReference::EntityReference {
650 entity_id: Some(face_id),
651 entity_reference: None,
652 })
653 .extrude_method(extrude_method)
654 .body_type(body_type)
655 .build(),
656 )
657 }
658 Point3dAxis3dOrGeometryReference::Sketch(sketch_ref) => ModelingCmd::from(
659 mcmd::ExtrudeToReference::builder()
660 .target(sketch_or_face_id.into())
661 .reference(ExtrudeReference::EntityReference {
662 entity_id: Some(sketch_ref.id),
663 entity_reference: None,
664 })
665 .extrude_method(extrude_method)
666 .body_type(body_type)
667 .build(),
668 ),
669 Point3dAxis3dOrGeometryReference::Solid(solid) => ModelingCmd::from(
670 mcmd::ExtrudeToReference::builder()
671 .target(sketch_or_face_id.into())
672 .reference(ExtrudeReference::EntityReference {
673 entity_id: Some(solid.id),
674 entity_reference: None,
675 })
676 .extrude_method(extrude_method)
677 .body_type(body_type)
678 .build(),
679 ),
680 Point3dAxis3dOrGeometryReference::TaggedEdgeOrFace(tag) => {
681 let tagged_edge_or_face = args.get_tag_engine_info(exec_state, tag)?;
682 let tagged_edge_or_face_id = tagged_edge_or_face.id;
683 ModelingCmd::from(
684 mcmd::ExtrudeToReference::builder()
685 .target(sketch_or_face_id.into())
686 .reference(ExtrudeReference::EntityReference {
687 entity_id: Some(tagged_edge_or_face_id),
688 entity_reference: None,
689 })
690 .extrude_method(extrude_method)
691 .body_type(body_type)
692 .build(),
693 )
694 }
695 Point3dAxis3dOrGeometryReference::EdgeToReference(spec) => {
696 let inner = edge::resolve_edge_specifier_with_face_tags(spec, None, exec_state, &args).await?;
697 ModelingCmd::from(
698 mcmd::ExtrudeToReference::builder()
699 .target(sketch_or_face_id.into())
700 .reference(ExtrudeReference::EntityReference {
701 entity_id: None,
702 entity_reference: Some(EntityReference::Edge {
703 inner,
704 topology_fallback: None,
705 }),
706 })
707 .extrude_method(extrude_method)
708 .body_type(body_type)
709 .build(),
710 )
711 }
712 },
713 (Some(_), _, _, None, None, None) => {
714 return Err(KclError::new_semantic(KclErrorDetails::new(
715 "The `length` parameter must be provided when using twist angle for extrusion.".to_owned(),
716 vec![args.source_range],
717 )));
718 }
719 (_, _, _, None, None, None) => {
720 return Err(KclError::new_semantic(KclErrorDetails::new(
721 "Either `length` or `to` parameter must be provided for extrusion.".to_owned(),
722 vec![args.source_range],
723 )));
724 }
725 (_, _, _, Some(_), Some(_), None) => {
726 return Err(KclError::new_semantic(KclErrorDetails::new(
727 "You cannot give both `length` and `to` params, you have to choose one or the other".to_owned(),
728 vec![args.source_range],
729 )));
730 }
731 (_, _, _, _, _, _) => {
732 return Err(KclError::new_semantic(KclErrorDetails::new(
733 "Invalid combination of parameters for extrusion.".to_owned(),
734 vec![args.source_range],
735 )));
736 }
737 };
738
739 let being_extruded = match extrudable {
740 Extrudable::Sketch(..) => BeingExtruded::Sketch,
741 Extrudable::FaceTag(face_tag) => {
742 let face_id = sketch_or_face_id;
743 let solid_id = match face_tag.geometry() {
744 Some(crate::execution::Geometry::Solid(solid)) => solid.id,
745 Some(crate::execution::Geometry::Sketch(sketch)) => match sketch.on {
746 SketchSurface::Face(face) => face.parent_solid.solid_id,
747 SketchSurface::Plane(_) => sketch.id,
748 },
749 None => face_id,
750 };
751 BeingExtruded::Face { face_id, solid_id }
752 }
753 Extrudable::Face(face) => BeingExtruded::Face {
754 face_id: face.id,
755 solid_id: face.parent_solid.solid_id,
756 },
757 Extrudable::EdgeTag(_) => BeingExtruded::Edge,
758 Extrudable::Edge(_) => BeingExtruded::Edge,
759 };
760 if let Some(post_extr_sketch) = extrudable.as_sketch() {
761 let cmds = post_extr_sketch.build_sketch_mode_cmds(
762 exec_state,
763 ModelingCmdReq {
764 cmd_id: extrude_cmd_id.into(),
765 cmd,
766 },
767 );
768 exec_state
769 .batch_modeling_cmds(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), &cmds)
770 .await?;
771 solids.push(
772 do_post_extrude(
773 &post_extr_sketch,
774 extrude_cmd_id.into(),
775 false,
776 &NamedCapTags {
777 start: tag_start.as_ref(),
778 end: tag_end.as_ref(),
779 },
780 extrude_method,
781 exec_state,
782 &args,
783 None,
784 None,
785 body_type,
786 being_extruded,
787 )
788 .await?,
789 );
790 } else if is_edge {
791 match extrude_method {
793 ExtrudeMethod::New => {
794 }
796 ExtrudeMethod::Merge => {
797 return Err(KclError::new_semantic(KclErrorDetails::new(
798 "Cannot use method MERGE with surface extrude of an edge".to_owned(),
799 vec![args.source_range],
800 )));
801 }
802 _ => {
803 return Err(KclError::new_internal(KclErrorDetails::new(
804 format!("Unknown extrude method: {extrude_method:?}"),
805 vec![args.source_range],
806 )));
807 }
808 }
809
810 exec_state
812 .batch_modeling_cmd(ModelingCmdMeta::from_args_id(exec_state, &args, extrude_cmd_id), cmd)
813 .await?;
814 let edge_tag = match extrudable {
816 Extrudable::Sketch(_) => None,
817 Extrudable::FaceTag(_) => None,
818 Extrudable::Face(_) => None,
819 Extrudable::EdgeTag(tag) => Some(TagDeclarator::new(&tag.value)),
820 Extrudable::Edge(_) => None,
821 };
822 solids.push(after_surface_creation(extrude_cmd_id.into(), edge_tag, exec_state, &args).await?);
823 } else {
824 return Err(KclError::new_type(KclErrorDetails::new(
825 "Expected a sketch for extrusion".to_owned(),
826 vec![args.source_range],
827 )));
828 }
829 }
830
831 Ok(solids)
832}
833
834#[derive(Debug, Default)]
835pub(crate) struct NamedCapTags<'a> {
836 pub start: Option<&'a TagNode>,
837 pub end: Option<&'a TagNode>,
838}
839
840#[derive(Debug, Clone, Copy)]
841pub enum BeingExtruded {
842 Sketch,
843 Face { face_id: Uuid, solid_id: Uuid },
844 Edge,
845}
846
847fn get_extrusion_info_edge_id(sketch: &Sketch, any_edge_id: Uuid, clone_id_map: Option<&HashMap<Uuid, Uuid>>) -> Uuid {
851 if sketch.clone.is_none() {
854 return any_edge_id;
855 }
856 let Some(clone_map) = clone_id_map else {
857 return any_edge_id;
858 };
859
860 if clone_map.contains_key(&any_edge_id) {
865 return any_edge_id;
866 }
867
868 if let Some((old_edge_id, _)) = clone_map.iter().find(|(_, new_edge_id)| **new_edge_id == any_edge_id) {
873 return *old_edge_id;
874 }
875
876 any_edge_id
880}
881
882pub(crate) async fn after_surface_creation(
885 extrude_cmd_id: ArtifactId,
886 edge_tag: Option<crate::parsing::ast::types::Node<TagDeclarator>>,
887 exec_state: &mut ExecState,
888 args: &Args,
889) -> Result<Solid, KclError> {
890 let body_id = extrude_cmd_id.into();
891
892 exec_state
896 .batch_modeling_cmd(
897 ModelingCmdMeta::from_args(exec_state, args),
898 ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(body_id).build()),
899 )
900 .await?;
901
902 let response = exec_state
904 .send_modeling_cmd(
905 ModelingCmdMeta::from_args(exec_state, args),
906 ModelingCmd::from(mcmd::EntityGetAllChildUuids::builder().entity_id(body_id).build()),
907 )
908 .await?;
909 let OkWebSocketResponseData::Modeling {
910 modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(ref all_child_ids_resp),
911 } = response
912 else {
913 return Err(KclError::new_engine(KclErrorDetails::new(
914 format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
915 vec![args.source_range],
916 )));
917 };
918 let entity_ids = &all_child_ids_resp.entity_ids;
919 let Some(face_id) = entity_ids.first().copied() else {
920 return Err(KclError::new_internal(KclErrorDetails::new(
921 format!("Expected EntityGetAllChildUuids response to have at least 1 ID: {response:?}",),
922 vec![args.source_range],
923 )));
924 };
925 let Some(edge_id) = entity_ids.get(1).copied() else {
926 return Err(KclError::new_internal(KclErrorDetails::new(
927 format!("Expected EntityGetAllChildUuids response to have at least 2 IDs: {response:?}"),
928 vec![args.source_range],
929 )));
930 };
931
932 let extrude_surface = ExtrudeSurface::ExtrudePlane(ExtrudePlane {
934 face_id,
935 tag: edge_tag,
936 geo_meta: GeoMeta {
937 id: face_id,
938 metadata: args.source_range.into(),
939 },
940 });
941 let new_value = vec![extrude_surface];
942
943 Ok(Solid {
944 id: body_id,
945 value_id: body_id,
946 artifact_id: extrude_cmd_id,
947 value: new_value,
948 faces: Default::default(),
949 meta: vec![args.source_range.into()],
950 units: kcl_api::UnitLength::Millimeters,
953 sectional: false,
954 creator: SolidCreator::Edge(CreatorEdge { edge_id, body_id }),
955 start_cap_id: None,
956 end_cap_id: None,
957 edge_cuts: Vec::new(),
958 pending_edge_cut_ids: Vec::new(),
959 })
960}
961
962#[allow(clippy::too_many_arguments)]
963pub(crate) async fn do_post_extrude<'a>(
964 sketch: &Sketch,
965 extrude_cmd_id: ArtifactId,
966 sectional: bool,
967 named_cap_tags: &'a NamedCapTags<'a>,
968 extrude_method: ExtrudeMethod,
969 exec_state: &mut ExecState,
970 args: &Args,
971 edge_id: Option<Uuid>,
972 clone_id_map: Option<&HashMap<Uuid, Uuid>>, body_type: BodyType,
974 being_extruded: BeingExtruded,
975) -> Result<Solid, KclError> {
976 exec_state
980 .batch_modeling_cmd(
981 ModelingCmdMeta::from_args(exec_state, args),
982 ModelingCmd::from(mcmd::ObjectBringToFront::builder().object_id(sketch.id).build()),
983 )
984 .await?;
985
986 let any_edge_id = if let Some(edge_id) = sketch.mirror {
987 edge_id
988 } else if let Some(id) = edge_id {
989 id
990 } else {
991 let Some(any_edge_id) = sketch.paths.first().map(|edge| edge.get_base().geo_meta.id) else {
994 return Err(KclError::new_type(KclErrorDetails::new(
995 "Expected a non-empty sketch".to_owned(),
996 vec![args.source_range],
997 )));
998 };
999 any_edge_id
1000 };
1001
1002 let extrusion_info_edge_id = get_extrusion_info_edge_id(sketch, any_edge_id, clone_id_map);
1005 let mut sketch = sketch.clone();
1006 match body_type {
1007 BodyType::Solid => {
1008 sketch.is_closed = ProfileClosed::Explicitly;
1009 }
1010 BodyType::Surface => {}
1011 _other => {
1012 }
1015 }
1016
1017 match (extrude_method, being_extruded) {
1018 (ExtrudeMethod::Merge, BeingExtruded::Face { .. }) => {
1019 if let SketchSurface::Face(ref face) = sketch.on {
1022 sketch.id = face.parent_solid.sketch_or_solid_id();
1025 }
1026 }
1027 (ExtrudeMethod::New, BeingExtruded::Face { .. }) => {
1028 sketch.id = extrude_cmd_id.into();
1031 }
1032 (ExtrudeMethod::New, BeingExtruded::Sketch) => {
1033 }
1036 (ExtrudeMethod::Merge, BeingExtruded::Sketch) => {
1037 if let SketchSurface::Face(ref face) = sketch.on {
1038 sketch.id = face.parent_solid.sketch_or_solid_id();
1041 }
1042 }
1043 (other, _) => {
1044 return Err(KclError::new_internal(KclErrorDetails::new(
1046 format!("Zoo does not yet support creating bodies via {other:?}"),
1047 vec![args.source_range],
1048 )));
1049 }
1050 }
1051
1052 let sketch_id = if let Some(cloned_from) = sketch.clone
1054 && clone_id_map.is_some()
1055 {
1056 cloned_from
1057 } else {
1058 sketch.id
1059 };
1060
1061 let solid3d_info = exec_state
1062 .send_modeling_cmd(
1063 ModelingCmdMeta::from_args(exec_state, args),
1064 ModelingCmd::from(
1065 mcmd::Solid3dGetExtrusionFaceInfo::builder()
1066 .edge_id(extrusion_info_edge_id)
1067 .object_id(sketch_id)
1068 .build(),
1069 ),
1070 )
1071 .await?;
1072
1073 let face_infos = if let OkWebSocketResponseData::Modeling {
1074 modeling_response: OkModelingCmdResponse::Solid3dGetExtrusionFaceInfo(data),
1075 } = solid3d_info
1076 {
1077 data.faces
1078 } else {
1079 vec![]
1080 };
1081
1082 if !args.ctx.settings.skip_artifact_graph {
1084 if !sectional {
1087 exec_state
1088 .batch_modeling_cmd(
1089 ModelingCmdMeta::from_args(exec_state, args),
1090 ModelingCmd::from(
1091 mcmd::Solid3dGetAdjacencyInfo::builder()
1092 .object_id(sketch_id)
1093 .edge_id(extrusion_info_edge_id)
1094 .build(),
1095 ),
1096 )
1097 .await?;
1098 }
1099 }
1100
1101 let Faces {
1102 sides: mut face_id_map,
1103 start_cap_id,
1104 end_cap_id,
1105 } = analyze_faces(exec_state, args, face_infos).await;
1106
1107 if sketch.clone.is_some()
1109 && let Some(clone_id_map) = clone_id_map
1110 {
1111 face_id_map = face_id_map
1112 .into_iter()
1113 .filter_map(|(k, v)| {
1114 let fe_key = clone_id_map.get(&k)?;
1115 let fe_value = clone_id_map.get(&(v?)).copied();
1116 Some((*fe_key, fe_value))
1117 })
1118 .collect::<HashMap<Uuid, Option<Uuid>>>();
1119 }
1120
1121 let no_engine_commands = args.ctx.no_engine_commands().await;
1123 let mut new_value: Vec<ExtrudeSurface> = Vec::with_capacity(sketch.paths.len() + sketch.inner_paths.len() + 2);
1124 let outer_surfaces = sketch.paths.iter().flat_map(|path| {
1125 if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1126 surface_of(path, *actual_face_id)
1127 } else if no_engine_commands {
1128 crate::log::logln!(
1129 "No face ID found for path ID {:?}, but in no-engine-commands mode, so faking it",
1130 path.get_base().geo_meta.id
1131 );
1132 fake_extrude_surface(exec_state, path)
1134 } else if sketch.clone.is_some()
1135 && let Some(clone_map) = clone_id_map
1136 {
1137 let new_path = clone_map.get(&(path.get_base().geo_meta.id));
1138
1139 if let Some(new_path) = new_path {
1140 match face_id_map.get(new_path) {
1141 Some(Some(actual_face_id)) => clone_surface_of(path, *new_path, *actual_face_id),
1142 _ => {
1143 let actual_face_id = face_id_map.iter().find_map(|(key, value)| {
1144 if let Some(value) = value {
1145 if value == new_path { Some(key) } else { None }
1146 } else {
1147 None
1148 }
1149 });
1150 match actual_face_id {
1151 Some(actual_face_id) => clone_surface_of(path, *new_path, *actual_face_id),
1152 None => {
1153 crate::log::logln!("No face ID found for clone path ID {:?}, so skipping it", new_path);
1154 None
1155 }
1156 }
1157 }
1158 }
1159 } else {
1160 None
1161 }
1162 } else {
1163 crate::log::logln!(
1164 "No face ID found for path ID {:?}, and not in no-engine-commands mode, so skipping it",
1165 path.get_base().geo_meta.id
1166 );
1167 None
1168 }
1169 });
1170
1171 new_value.extend(outer_surfaces);
1172 let inner_surfaces = sketch.inner_paths.iter().flat_map(|path| {
1173 if let Some(Some(actual_face_id)) = face_id_map.get(&path.get_base().geo_meta.id) {
1174 surface_of(path, *actual_face_id)
1175 } else if no_engine_commands {
1176 fake_extrude_surface(exec_state, path)
1178 } else {
1179 None
1180 }
1181 });
1182 new_value.extend(inner_surfaces);
1183
1184 if let Some(tag_start) = named_cap_tags.start {
1186 let Some(start_cap_id) = start_cap_id else {
1187 return Err(KclError::new_type(KclErrorDetails::new(
1188 format!(
1189 "Expected a start cap ID for tag `{}` for extrusion of sketch {:?}",
1190 tag_start.name, sketch.id
1191 ),
1192 vec![args.source_range],
1193 )));
1194 };
1195
1196 new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1197 face_id: start_cap_id,
1198 tag: Some(tag_start.clone()),
1199 geo_meta: GeoMeta {
1200 id: start_cap_id,
1201 metadata: args.source_range.into(),
1202 },
1203 }));
1204 }
1205 if let Some(tag_end) = named_cap_tags.end {
1206 let Some(end_cap_id) = end_cap_id else {
1207 return Err(KclError::new_type(KclErrorDetails::new(
1208 format!(
1209 "Expected an end cap ID for tag `{}` for extrusion of sketch {:?}",
1210 tag_end.name, sketch.id
1211 ),
1212 vec![args.source_range],
1213 )));
1214 };
1215
1216 new_value.push(ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1217 face_id: end_cap_id,
1218 tag: Some(tag_end.clone()),
1219 geo_meta: GeoMeta {
1220 id: end_cap_id,
1221 metadata: args.source_range.into(),
1222 },
1223 }));
1224 }
1225
1226 let meta = sketch.meta.clone();
1227 let units = sketch.units;
1228 let id = sketch.id;
1229 let creator = match being_extruded {
1230 BeingExtruded::Sketch => SolidCreator::Sketch(sketch),
1231 BeingExtruded::Face { face_id, solid_id } => SolidCreator::Face(CreatorFace {
1232 face_id,
1233 solid_id,
1234 sketch,
1235 }),
1236 BeingExtruded::Edge => {
1237 let message = "Expected an edge to have been extruded via another code path";
1238 debug_assert!(false, "{message}");
1239 return Err(KclError::new_internal(KclErrorDetails::new(
1240 message.to_owned(),
1241 vec![args.source_range],
1242 )));
1243 }
1244 };
1245
1246 Ok(Solid {
1247 id,
1248 value_id: extrude_cmd_id.into(),
1249 artifact_id: extrude_cmd_id,
1250 value: new_value,
1251 faces: Default::default(),
1252 meta,
1253 units,
1254 sectional,
1255 creator,
1256 start_cap_id,
1257 end_cap_id,
1258 edge_cuts: vec![],
1259 pending_edge_cut_ids: vec![],
1260 })
1261}
1262
1263#[derive(Debug, Default)]
1264struct Faces {
1265 sides: HashMap<Uuid, Option<Uuid>>,
1267 end_cap_id: Option<Uuid>,
1269 start_cap_id: Option<Uuid>,
1271}
1272
1273async fn analyze_faces(exec_state: &mut ExecState, args: &Args, face_infos: Vec<ExtrusionFaceInfo>) -> Faces {
1274 let mut faces = Faces {
1275 sides: HashMap::with_capacity(face_infos.len()),
1276 ..Default::default()
1277 };
1278 if args.ctx.no_engine_commands().await {
1279 faces.start_cap_id = Some(exec_state.next_uuid());
1281 faces.end_cap_id = Some(exec_state.next_uuid());
1282 }
1283 for face_info in face_infos {
1284 match face_info.cap {
1285 ExtrusionFaceCapType::Bottom => faces.start_cap_id = face_info.face_id,
1286 ExtrusionFaceCapType::Top => faces.end_cap_id = face_info.face_id,
1287 ExtrusionFaceCapType::Both => {
1288 faces.end_cap_id = face_info.face_id;
1289 faces.start_cap_id = face_info.face_id;
1290 }
1291 ExtrusionFaceCapType::None => {
1292 if let Some(curve_id) = face_info.curve_id {
1293 faces.sides.insert(curve_id, face_info.face_id);
1294 }
1295 }
1296 other => {
1297 exec_state.warn(
1298 crate::CompilationIssue {
1299 source_range: args.source_range,
1300 message: format!("unknown extrusion face type {other:?}"),
1301 suggestion: None,
1302 severity: crate::errors::Severity::Warning,
1303 tag: crate::errors::Tag::Unnecessary,
1304 },
1305 annotations::WARN_NOT_YET_SUPPORTED,
1306 );
1307 }
1308 }
1309 }
1310 faces
1311}
1312fn surface_of(path: &Path, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1313 match path {
1314 Path::Arc { .. }
1315 | Path::TangentialArc { .. }
1316 | Path::TangentialArcTo { .. }
1317 | Path::Ellipse { .. }
1319 | Path::Conic {.. }
1320 | Path::Circle { .. }
1321 | Path::CircleThreePoint { .. } => {
1322 let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1323 face_id: actual_face_id,
1324 tag: path.get_base().tag.clone(),
1325 geo_meta: GeoMeta {
1326 id: path.get_base().geo_meta.id,
1327 metadata: path.get_base().geo_meta.metadata,
1328 },
1329 });
1330 Some(extrude_surface)
1331 }
1332 Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1333 let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1334 face_id: actual_face_id,
1335 tag: path.get_base().tag.clone(),
1336 geo_meta: GeoMeta {
1337 id: path.get_base().geo_meta.id,
1338 metadata: path.get_base().geo_meta.metadata,
1339 },
1340 });
1341 Some(extrude_surface)
1342 }
1343 Path::ArcThreePoint { .. } => {
1344 let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1345 face_id: actual_face_id,
1346 tag: path.get_base().tag.clone(),
1347 geo_meta: GeoMeta {
1348 id: path.get_base().geo_meta.id,
1349 metadata: path.get_base().geo_meta.metadata,
1350 },
1351 });
1352 Some(extrude_surface)
1353 }
1354 }
1355}
1356
1357fn clone_surface_of(path: &Path, clone_path_id: Uuid, actual_face_id: Uuid) -> Option<ExtrudeSurface> {
1358 match path {
1359 Path::Arc { .. }
1360 | Path::TangentialArc { .. }
1361 | Path::TangentialArcTo { .. }
1362 | Path::Ellipse { .. }
1364 | Path::Conic {.. }
1365 | Path::Circle { .. }
1366 | Path::CircleThreePoint { .. } => {
1367 let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1368 face_id: actual_face_id,
1369 tag: path.get_base().tag.clone(),
1370 geo_meta: GeoMeta {
1371 id: clone_path_id,
1372 metadata: path.get_base().geo_meta.metadata,
1373 },
1374 });
1375 Some(extrude_surface)
1376 }
1377 Path::Base { .. } | Path::ToPoint { .. } | Path::Horizontal { .. } | Path::AngledLineTo { .. } | Path::Bezier { .. } => {
1378 let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1379 face_id: actual_face_id,
1380 tag: path.get_base().tag.clone(),
1381 geo_meta: GeoMeta {
1382 id: clone_path_id,
1383 metadata: path.get_base().geo_meta.metadata,
1384 },
1385 });
1386 Some(extrude_surface)
1387 }
1388 Path::ArcThreePoint { .. } => {
1389 let extrude_surface = ExtrudeSurface::ExtrudeArc(crate::execution::ExtrudeArc {
1390 face_id: actual_face_id,
1391 tag: path.get_base().tag.clone(),
1392 geo_meta: GeoMeta {
1393 id: clone_path_id,
1394 metadata: path.get_base().geo_meta.metadata,
1395 },
1396 });
1397 Some(extrude_surface)
1398 }
1399 }
1400}
1401
1402fn fake_extrude_surface(exec_state: &mut ExecState, path: &Path) -> Option<ExtrudeSurface> {
1404 let extrude_surface = ExtrudeSurface::ExtrudePlane(crate::execution::ExtrudePlane {
1405 face_id: exec_state.next_uuid(),
1407 tag: path.get_base().tag.clone(),
1408 geo_meta: GeoMeta {
1409 id: path.get_base().geo_meta.id,
1410 metadata: path.get_base().geo_meta.metadata,
1411 },
1412 });
1413 Some(extrude_surface)
1414}
1415
1416#[cfg(test)]
1417mod tests {
1418 use kcl_api::UnitLength;
1419
1420 use super::*;
1421 use crate::execution::AbstractSegment;
1422 use crate::execution::Plane;
1423 use crate::execution::SegmentRepr;
1424 use crate::execution::parse_execute;
1425 use crate::execution::types::NumericType;
1426 use crate::execution::types::NumericTypeExt;
1427 use crate::front::Expr;
1428 use crate::front::Number;
1429 use crate::front::ObjectId;
1430 use crate::front::Point2d;
1431 use crate::front::PointCtor;
1432 use crate::std::sketch::PlaneData;
1433
1434 fn point_expr(x: f64, y: f64) -> Point2d<Expr> {
1435 Point2d {
1436 x: Expr::Var(Number::from((x, UnitLength::Millimeters))),
1437 y: Expr::Var(Number::from((y, UnitLength::Millimeters))),
1438 }
1439 }
1440
1441 fn segment_value(exec_state: &mut ExecState) -> KclValue {
1442 let plane = Plane::from_plane_data_skipping_engine(PlaneData::XY, exec_state).unwrap();
1443 let segment = Segment {
1444 id: exec_state.next_uuid(),
1445 object_id: ObjectId(1),
1446 kind: SegmentKind::Point {
1447 position: [TyF64::new(0.0, NumericType::mm()), TyF64::new(0.0, NumericType::mm())],
1448 ctor: Box::new(PointCtor {
1449 position: point_expr(0.0, 0.0),
1450 }),
1451 freedom: None,
1452 },
1453 surface: SketchSurface::Plane(Box::new(plane)),
1454 sketch_id: exec_state.next_uuid(),
1455 sketch: None,
1456 tag: None,
1457 node_path: None,
1458 meta: vec![],
1459 };
1460 KclValue::Segment {
1461 value: Box::new(AbstractSegment {
1462 repr: SegmentRepr::Solved {
1463 segment: Box::new(segment),
1464 },
1465 meta: vec![],
1466 }),
1467 }
1468 }
1469
1470 #[tokio::test(flavor = "multi_thread")]
1471 async fn extrude_rejects_negative_bidirectional_length_in_mock_exec() {
1472 let code = r#"
1473profile001 = startSketchOn(XY)
1474 |> startProfile(at = [0, 0])
1475 |> line(end = [1, 0])
1476 |> line(end = [0, 1])
1477 |> close()
1478
1479extrude(profile001, length = 1, bidirectionalLength = -1)
1480"#;
1481
1482 let err = parse_execute(code).await.unwrap_err();
1483
1484 assert!(matches!(err, KclError::Semantic { .. }), "{err:?}");
1485 assert!(
1486 err.message()
1487 .contains("`bidirectionalLength` must be greater than or equal to 0"),
1488 "{err:?}"
1489 );
1490 }
1491
1492 #[tokio::test(flavor = "multi_thread")]
1493 async fn segment_extrude_rejects_cap_tags() {
1494 let ctx = ExecutorContext::new_mock(None).await;
1495 let mut exec_state = ExecState::new(&ctx);
1496 let err = coerce_extrude_targets(
1497 vec![segment_value(&mut exec_state)],
1498 BodyType::Surface,
1499 Some(&TagDeclarator::new("cap_start")),
1500 None,
1501 &mut exec_state,
1502 &ctx,
1503 crate::SourceRange::default(),
1504 )
1505 .await
1506 .unwrap_err();
1507
1508 assert!(
1509 err.message()
1510 .contains("`tagStart` and `tagEnd` are not supported when extruding sketch segments"),
1511 "{err:?}"
1512 );
1513 ctx.close().await;
1514 }
1515
1516 fn edge_value(exec_state: &mut ExecState) -> KclValue {
1519 KclValue::Uuid {
1520 value: exec_state.next_uuid(),
1521 meta: vec![],
1522 }
1523 }
1524
1525 #[tokio::test(flavor = "multi_thread")]
1526 async fn edge_extrude_rejects_solid_body_type() {
1527 let ctx = ExecutorContext::new_mock(None).await;
1528 let mut exec_state = ExecState::new(&ctx);
1529 let edge = edge_value(&mut exec_state);
1530 let err = coerce_extrude_targets(
1531 vec![edge],
1532 BodyType::Solid,
1533 None,
1534 None,
1535 &mut exec_state,
1536 &ctx,
1537 crate::SourceRange::default(),
1538 )
1539 .await
1540 .unwrap_err();
1541
1542 assert!(
1543 err.message()
1544 .contains("edges can only be extruded with surface extrudes"),
1545 "{err:?}"
1546 );
1547 ctx.close().await;
1548 }
1549
1550 #[tokio::test(flavor = "multi_thread")]
1551 async fn edge_extrude_rejects_cap_tags() {
1552 let ctx = ExecutorContext::new_mock(None).await;
1553 let mut exec_state = ExecState::new(&ctx);
1554 let edge = edge_value(&mut exec_state);
1555 let err = coerce_extrude_targets(
1556 vec![edge],
1557 BodyType::Surface,
1558 Some(&TagDeclarator::new("cap_start")),
1559 None,
1560 &mut exec_state,
1561 &ctx,
1562 crate::SourceRange::default(),
1563 )
1564 .await
1565 .unwrap_err();
1566
1567 assert!(
1568 err.message()
1569 .contains("`tagStart` and `tagEnd` are not supported when extruding edges"),
1570 "{err:?}"
1571 );
1572 ctx.close().await;
1573 }
1574
1575 #[tokio::test(flavor = "multi_thread")]
1576 async fn edge_extrude_rejects_mixing_with_face() {
1577 let ctx = ExecutorContext::new_mock(None).await;
1578 let mut exec_state = ExecState::new(&ctx);
1579 let edge = edge_value(&mut exec_state);
1580 let face = KclValue::String {
1582 value: "START".to_owned(),
1583 meta: vec![],
1584 };
1585 let err = coerce_extrude_targets(
1586 vec![edge, face],
1587 BodyType::Surface,
1588 None,
1589 None,
1590 &mut exec_state,
1591 &ctx,
1592 crate::SourceRange::default(),
1593 )
1594 .await
1595 .unwrap_err();
1596
1597 assert!(
1598 err.message()
1599 .contains("Cannot extrude edges together with sketches or faces"),
1600 "{err:?}"
1601 );
1602 ctx.close().await;
1603 }
1604}