Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions assets/locales/pending/sketch-create3d.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"ar": {
"cmd.sketch_create3d": "رسم ثلاثي الأبعاد",
"help.sketch.create3d": "يبدأ رسمًا ثلاثي الأبعاد جديدًا مباشرةً دون اختيار مستوى، ويبدأ فيه أداة خط ثلاثي الأبعاد. استخدمه للمسارات والإطارات الممتدة في الفراغ.",
"sketch.hint.create3d": "رسم ثلاثي الأبعاد: انقر نقاطًا لرسم خط ثلاثي الأبعاد؛ انقر بالزر الأيمن أو اضغط Esc للإنهاء. النقر في مكان فارغ يقع على المستوى XY. للخروج منه، التقط نقطة على النموذج، أو انقر بعد ذلك نقطة مرسومة واسحب أسهمها"
},
"de": {
"cmd.sketch_create3d": "3D-Skizze",
"help.sketch.create3d": "Beginnt sofort eine neue 3D-Skizze, ohne dass eine Ebene gewählt wird, und startet darin die 3D-Linie. Für Pfade und Rahmen, die durch den Raum verlaufen.",
"sketch.hint.create3d": "3D-Skizze: Punkte anklicken, um eine 3D-Linie zu zeichnen; Rechtsklick oder Esc beendet. Ein Klick in den leeren Raum landet auf der XY-Ebene. Um sie zu verlassen, am Modell fangen oder danach einen gezeichneten Punkt anklicken und an seinen Pfeilen ziehen"
},
"en": {
"cmd.sketch_create3d": "3D Sketch",
"help.sketch.create3d": "Starts a new 3D sketch at once, with no plane to choose, and starts 3D Line in it. Use it for paths and frames that run through space.",
"sketch.hint.create3d": "3D Sketch: click points to draw a 3D line; right-click or Esc to finish. A click in empty space lands on the XY plane. To leave it, snap to the model, or click a drawn point afterwards and drag its arrows"
},
"he": {
"cmd.sketch_create3d": "סקיצה תלת־ממדית",
"help.sketch.create3d": "מתחיל מיד סקיצה תלת־ממדית חדשה, בלי לבחור מישור, ומפעיל בה את הכלי קו תלת־ממדי. מתאים למסלולים ולמסגרות שעוברים במרחב.",
"sketch.hint.create3d": "סקיצה תלת־ממדית: לחצו על נקודות כדי לשרטט קו תלת־ממדי; לחיצה ימנית או Esc לסיום. לחיצה במקום ריק נוחתת על מישור XY. כדי לצאת ממנו, הצמידו למודל, או לחצו אחר כך על נקודה משורטטת וגררו את החצים שלה"
},
"ja": {
"cmd.sketch_create3d": "3D スケッチ",
"help.sketch.create3d": "平面を選ばずに、新しい 3D スケッチをすぐに開始し、その中で 3D 線分を起動します。空間を通るパスやフレームに使います。",
"sketch.hint.create3d": "3D スケッチ: 点をクリックして 3D 線分を描きます。右クリックまたは Esc で終了します。何もない場所をクリックすると、点は XY 平面上に置かれます。平面から離すには、モデルにスナップするか、あとで描いた点をクリックして矢印をドラッグします"
},
"ko": {
"cmd.sketch_create3d": "3D 스케치",
"help.sketch.create3d": "평면을 선택하지 않고 새 3D 스케치를 바로 시작하고, 그 안에서 3D 선을 시작합니다. 공간을 지나는 경로와 프레임에 사용합니다.",
"sketch.hint.create3d": "3D 스케치: 점을 클릭하여 3D 선을 그립니다. 마우스 오른쪽 버튼 클릭 또는 Esc로 끝냅니다. 빈 공간을 클릭하면 점이 XY 평면에 놓입니다. 평면을 벗어나려면 모델에 스냅하거나, 나중에 그린 점을 클릭하고 화살표를 드래그합니다"
},
"vi": {
"cmd.sketch_create3d": "3D Phác thảo",
"help.sketch.create3d": "Bắt đầu ngay một phác thảo 3D mới mà không cần chọn mặt phẳng, và khởi động lệnh Đường thẳng 3D trong đó. Dùng cho đường dẫn và khung chạy trong không gian.",
"sketch.hint.create3d": "3D Phác thảo: nhấp các điểm để vẽ đường thẳng 3D; nhấp chuột phải hoặc nhấn Esc để kết thúc. Nhấp vào chỗ trống sẽ đặt điểm trên mặt phẳng XY. Để rời mặt phẳng này, hãy bắt điểm vào mô hình, hoặc sau đó nhấp một điểm đã vẽ và kéo các mũi tên của nó"
},
"zh": {
"cmd.sketch_create3d": "3D 草图",
"help.sketch.create3d": "无需选择平面,立即开始新的 3D 草图,并在其中启动三维直线。用于穿过空间的路径和框架。",
"sketch.hint.create3d": "3D 草图:单击各点以绘制三维直线;右键单击或按 Esc 结束。在空白处单击时,点落在 XY 平面上。要离开该平面,请捕捉到模型,或之后单击已绘制的点并拖动其箭头"
}
}
3 changes: 3 additions & 0 deletions attribution/pending/sketch3d-icon.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
| File | Author | Source | Licence |
| --- | --- | --- | --- |
| crates/look/icons/design/svg/model/sketch3d.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | SolidCraft Brand and Interface Licence (LICENSE-BRAND) |
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/sketch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1396,7 +1396,7 @@ pub(super) fn create_sketch_with_plane(s: &mut Session, p: &Value, plane: PlaneR
}

/// A new sketch on `plane`, as `sketch.create` replies.
fn sketch_on_plane(s: &mut Session, p: &Value, mut plane: PlaneRef, internal_body: Option<(&str, usize)>) -> Result<CreateResult> {
pub(super) fn sketch_on_plane(s: &mut Session, p: &Value, mut plane: PlaneRef, internal_body: Option<(&str, usize)>) -> Result<CreateResult> {
let sketching_view = s.requested_sketch_view(p, "sketch.create")?;
let before = entry_point(s);
if face::is_face(p) {
Expand Down
33 changes: 31 additions & 2 deletions crates/engine/src/cmd/sketch_3d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ use super::{CommandSpec, in_sketch};
use crate::params::{bad, vec3};
use crate::schema::sketch::Constrained;
use crate::schema::sketch_3d::{
AlongAxisParams, AlongAxisResult, Arc3dParams, AxisName, ControlSpline3dParams, Curves3dResult, Line3dParams, Move3dParams, Move3dResult,
OnPlaneParams, OnPlaneResult, POINT3_MUST, Point3dParams, Point3dResult, Spline3dParams, point3_coordinates,
AlongAxisParams, AlongAxisResult, Arc3dParams, AxisName, ControlSpline3dParams, Create3dParams, Create3dResult, Curves3dResult, Line3dParams,
Move3dParams, Move3dResult, OnPlaneParams, OnPlaneResult, POINT3_MUST, Point3dParams, Point3dResult, Spline3dParams, point3_coordinates,
};
use crate::schema::sketch_dimension::DimensionResult;
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};

const CREATE3D_CONTRACT: TypedContract<Create3dParams> = TypedContract::new();
const LINE3D_CONTRACT: TypedContract<Line3dParams> = TypedContract::new();
const SPLINE3D_CONTRACT: TypedContract<Spline3dParams> = TypedContract::new();
const CONTROL_SPLINE3D_CONTRACT: TypedContract<ControlSpline3dParams> = TypedContract::new();
Expand All @@ -36,6 +37,12 @@ const ALONG_AXIS_CONTRACT: TypedContract<AlongAxisParams> = TypedContract::new()
const ON_PLANE_CONTRACT: TypedContract<OnPlaneParams> = TypedContract::new();

pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.create3d", "3D Sketch", crate::checked!("sketch.create3d", create3d))
.begins_edit()
.icon("sketch3d")
.contract(&CREATE3D_CONTRACT)
.output(output_schema_for::<Create3dResult>)
.params("name?; view?: open Model view id (defaults to focused or most recent Model). Starts a 3D sketch with no plane to choose: a new sketch with 3D Sketch on, opened for editing, so sketch.line3d, sketch.spline3d, sketch.arc3d and sketch.point3d draw in it at once. It rests on the active component's XY origin plane and its curves may leave that plane. One undo step"),
CommandSpec::new("sketch.line3d", "3D Line", crate::checked!("sketch.line3d", line3d))
.icon("line")
.enabled(in_sketch_3d)
Expand Down Expand Up @@ -206,6 +213,28 @@ fn inverse_owner_frame(s: &Session, p: &Value, cmd: &str) -> Result<solidcraft_d
solidcraft_doc::mat_inverse(&frame).ok_or_else(|| bad(cmd, "the sketch owner placement is not invertible"))
}

/// `sketch.create3d`: a new sketch with 3D Sketch on, with no plane to choose. A sketch always
/// has a plane, so this one rests on the XY origin plane of the active component: a click in
/// empty space lands there, and nothing new is saved in the design.
fn create3d(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.create3d";
s.requested_sketch_view(p, cmd)?;
Comment thread
Ledzz marked this conversation as resolved.
Resolved
// Only the keys this command takes reach `sketch.create`'s builder: a stray `plane` or
// `project_edges` must not turn this into a sketch on a face.
let mut keys = serde_json::Map::new();
for key in ["name", "view"] {
if let Some(value) = p.get(key) {
keys.insert(key.into(), value.clone());
}
}
let made = super::sketch::sketch_on_plane(s, &Value::Object(keys), solidcraft_doc::PlaneRef::Origin { name: "XY".into() }, None)?;
sketch_store::update(s, made.sketch, |_, _, sk| {
sk.view.three_d = true;
Ok(())
})?;
reply(cmd, Create3dResult { sketching_view: made.sketching_view, sketch: made.sketch, name: made.name, param_warnings: Vec::new() })
}

fn line3d(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.line3d";
let inverse = inverse_owner_frame(s, p, cmd)?;
Expand Down
139 changes: 139 additions & 0 deletions crates/engine/src/cmd/sketch_3d_frame_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,145 @@ fn line3d_spline3d_point3d_need_a_3d_sketch() {
}
}

/// Is `sketch` a 3D sketch on the XY origin plane?
fn rests_on_xy_with_3d_on(s: &Session, sketch: u64) -> bool {
use solidcraft_doc::{FeatureKind, PlaneRef};
s.doc
.feature(sketch)
.is_some_and(|f| matches!(&f.kind, FeatureKind::Sketch { plane: PlaneRef::Origin { name }, sketch } if name == "XY" && sketch.view.three_d))
}

#[test]
fn create3d_starts_a_3d_sketch_with_no_plane_in_one_undo_step() {
let mut s = Session::default();
let empty = s.doc.to_json();
let undo = s.undo.len();
let made = run(&mut s, "sketch.create3d", json!({"name": "Rail"}));
let sketch = made["sketch"].as_u64().unwrap();
assert_eq!(made["name"], "Rail", "{made}");
assert_eq!(s.active_sketch, Some(sketch), "the new sketch is the one being edited");
assert_eq!(s.undo.len(), undo + 1, "the sketch and its 3D option are one undo step");
assert!(rests_on_xy_with_3d_on(&s, sketch));
// The 3D tools are offered at once: no plane to pick, no option to turn on.
for id in ["sketch.line3d", "sketch.spline3d", "sketch.arc3d", "sketch.point3d"] {
let info = crate::cmd::find_command(id).unwrap().info(&s);
assert!(info.enabled, "{id} not offered in a new 3D sketch: {:?}", info.disabled_reason);
}
let created = s.doc.to_json();

// Line, Fit Point Spline and Point all leave the plane.
let line = run(&mut s, "sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 30], [20, 10, 30]]}));
let rise = line["curves"][0].as_str().unwrap().to_string();
let run_out = line["curves"][1].as_str().unwrap().to_string();
let spline =
run(&mut s, "sketch.spline3d", json!({"points": [[40, 0, 0], [50, 5, 15], [60, 10, 30]]}))["curves"][0].as_str().unwrap().to_string();
let point = run(&mut s, "sketch.point3d", json!({"point": [5, 6, 7]}))["point"].as_str().unwrap().to_string();
near(fit(&s, &rise, 1), Vec3::new(0.0, 0.0, 30.0));
near(fit(&s, &run_out, 1), Vec3::new(20.0, 10.0, 30.0));
near(fit(&s, &spline, 1), Vec3::new(50.0, 5.0, 15.0));
near(fit(&s, &point, 0), Vec3::new(5.0, 6.0, 7.0));
let sk = s.doc.sketch(sketch).unwrap();
assert!(sk.curves.is_empty(), "nothing was flattened onto the plane");
assert_eq!(sk.wires.len(), 4, "two lines, a spline and a point");
let drawn = s.doc.to_json();

// Undo takes the drawing back step by step, then the sketch itself; redo brings it all back.
for _ in 0..3 {
run(&mut s, "edit.undo", json!({}));
}
assert_eq!(s.doc.to_json(), created);
assert!(rests_on_xy_with_3d_on(&s, sketch), "the 3D option belongs to the step that made the sketch");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.to_json(), empty);
for _ in 0..4 {
run(&mut s, "edit.redo", json!({}));
}
assert_eq!(s.doc.to_json(), drawn);
assert!(rests_on_xy_with_3d_on(&s, sketch));
}

#[test]
fn create3d_paths_carry_a_pipe_and_a_sweep_and_reopen() {
let mut s = Session::default();
let path = run(&mut s, "sketch.create3d", json!({"name": "Path"}))["sketch"].as_u64().unwrap();
// 10 mm straight up from (17, 32, 45): no point of it is on the sketch's own plane.
let wire = run(&mut s, "sketch.line3d", json!({"points": [[17, 32, 45], [17, 32, 55]]}))["curves"][0].as_str().unwrap().to_string();
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.pipe", json!({"path_sketch": path, "path": [wire], "diameter": 6}));
let profile = run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 45, "name": "Profile"}))["sketch"].as_u64().unwrap();
run(&mut s, "sketch.circle.center", json!({"center": [17, 32], "radius": 2}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.sweep", json!({"sketch": profile, "path_sketch": path, "path": [wire], "operation": "new"}));
let check = |s: &Session| {
let world = s.world_state().unwrap();
let n = world.bodies.len();
assert!(n >= 2, "a pipe and a sweep: {n} bodies");
// A cylinder along the 10 mm line: the pipe of radius 3, then the swept circle of radius 2.
for (body, radius) in world.bodies[n - 2..].iter().zip([3.0_f64, 2.0]) {
let measure = solidcraft_kernel::measure(&body.body).unwrap();
let expected = std::f64::consts::PI * radius * radius * 10.0;
assert!((measure.volume - expected).abs() < 0.05, "radius {radius}: {} != {expected}", measure.volume);
near(measure.centroid, Vec3::new(17.0, 32.0, 50.0));
}
};
check(&s);
// Saved and read back: still a 3D sketch with the same curve, and the same solids.
let saved = s.doc.to_json();
let restored = solidcraft_doc::format::read(&saved).unwrap();
assert!(restored.sketch(path).unwrap().view.three_d);
assert_eq!(restored.sketch(path).unwrap().wires, s.doc.sketch(path).unwrap().wires);
let mut reopened = Session { doc: restored.into(), ..Default::default() };
reopened.refresh();
check(&reopened);
assert!(rests_on_xy_with_3d_on(&reopened, path));
}

#[test]
fn create3d_finishes_the_open_sketch_and_belongs_to_the_active_component() {
// `second_frame` leaves a sketch open in a component placed by (x,y,z) -> (20-y,30+x,40+z).
let (mut s, component, _, _) = second_frame();
let open = s.active_sketch.unwrap();
run(&mut s, "sketch.line3d", json!({"points": [[17, 32, 45], [17, 32, 55]]}));
let made = run(&mut s, "sketch.create3d", json!({}));
let sketch = made["sketch"].as_u64().unwrap();
assert_ne!(sketch, open);
assert_eq!(s.active_sketch, Some(sketch), "starting a 3D sketch finishes the sketch that was open");
assert_eq!(s.doc.sketch(open).unwrap().wires.len(), 1, "and keeps what was drawn in it");
assert_eq!(s.doc.feature(sketch).unwrap().component, component);
assert!(rests_on_xy_with_3d_on(&s, sketch), "the XY origin plane is the active component's own");
// World points come to rest in the component's own coordinates, as in any of its sketches.
let wire = run(&mut s, "sketch.line3d", json!({"points": [[17, 32, 45], [17, 32, 55]]}))["curves"][0].as_str().unwrap().to_string();
near(fit(&s, &wire, 0), Vec3::new(2.0, 3.0, 5.0));
near(fit(&s, &wire, 1), Vec3::new(2.0, 3.0, 15.0));
}

#[test]
fn create3d_reads_no_plane_and_hostile_inputs_change_nothing() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20}));
let before = s.doc.to_json();
// A view that is no view id, or names no open view, is refused and nothing is made.
for p in [json!({"view": "front"}), json!({"view": -1}), json!({"view": 0}), json!({"view": 123456})] {
assert!(s.execute("sketch.create3d", &p).is_err(), "{p}");
assert_eq!(s.doc.to_json(), before, "{p}");
assert_eq!(s.active_sketch, None, "{p}");
}
// A plane has no meaning here. With the parameter check off the key is not read: the sketch
// does not go onto the box's top face. In strict the call is refused.
let stray = json!({"plane": {"face": [10, 10, 20]}, "project_edges": true, "offset": 5, "name": 7});
let sketch = run(&mut s, "sketch.create3d", stray.clone())["sketch"].as_u64().unwrap();
assert!(rests_on_xy_with_3d_on(&s, sketch));
assert!(s.doc.sketch(sketch).unwrap().links.is_empty(), "no face edges were projected");
run(&mut s, "edit.undo", json!({}));
assert_eq!(s.doc.to_json(), before);
s.param_check = crate::schema::ParamCheck::Strict;
let refused = s.execute("sketch.create3d", &stray).unwrap_err().to_string();
assert!(refused.contains("unknown key"), "{refused}");
let refused = s.execute("sketch.create3d", &json!({"plane": "XZ"})).unwrap_err().to_string();
assert!(refused.contains("unknown key `plane`"), "{refused}");
assert_eq!(s.doc.to_json(), before);
}

#[test]
fn wire_frame_copies_keep_component_and_legacy_coordinates() {
let (mut s, _, first, second) = second_frame();
Expand Down
36 changes: 33 additions & 3 deletions crates/engine/src/schema/sketch_3d.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Contracts and result types for the commands in `cmd/sketch_3d.rs`: `sketch.line3d`,
//! `sketch.spline3d`, `sketch.spline3d.control_point`, `sketch.arc3d`, `sketch.point3d` and
//! `sketch.move3d`.
//! Contracts and result types for the commands in `cmd/sketch_3d.rs`: `sketch.create3d`,
//! `sketch.line3d`, `sketch.spline3d`, `sketch.spline3d.control_point`, `sketch.arc3d`,
//! `sketch.point3d` and `sketch.move3d`.
//!
//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
//! reads it and fails with the handler's message. Whether the sketch has 3D Sketch on, a wire
Expand All @@ -23,6 +23,36 @@ use super::sketch_shapes::Created;
use super::types::{Point3, PointExpr3, SketchRef, present};
use crate::params;

/// Start a 3D sketch with no plane to choose: a new sketch with 3D Sketch on, opened for
/// editing, so `sketch.line3d`, `sketch.spline3d`, `sketch.arc3d` and `sketch.point3d` draw in
/// it at once. The sketch rests on the XY origin plane of the active component, and its curves
/// may leave that plane. One undo step.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct Create3dParams {
/// Open Model view to edit in; defaults to the focused or most recent Model view.
#[serde(default)]
#[schemars(range(min = 1, max = 9007199254740992_u64))]
pub view: Option<u64>,
/// The sketch's name. Default: numbered.
#[serde(default)]
pub name: Option<String>,
}

/// What `sketch.create3d` returns.
#[derive(Debug, Serialize, JsonSchema)]
pub struct Create3dResult {
/// The Model view owning this sketch edit. Runtime identity, not a design feature.
pub sketching_view: u64,
/// The new sketch's feature id.
pub sketch: u64,
/// Its name.
pub name: String,
/// In the warn parameter-check mode: what the call's parameters got wrong.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub param_warnings: Vec<String>,
}

/// Draw 3D lines through world points, one line per segment, joined end to end. Needs 3D Sketch
/// on for the sketch (`sketch.options` with `sketch_3d: true`). One undo step.
#[derive(Debug, Deserialize, JsonSchema)]
Expand Down
Loading
Loading