SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Sketch: dimension new shapes as drawn (squashed onto current main) (#5987)
Herperlerpicus3a951bc8c3da
diff --git a/assets/locales/pending/sketch-auto-dimensions.json b/assets/locales/pending/sketch-auto-dimensions.jsonnew file mode 100644index 0000000000..553d3867f9--- /dev/null+++ b/assets/locales/pending/sketch-auto-dimensions.json@@ -0,0 +1,164 @@+{+ "en": {+ "Dimension new shapes": "Dimension new shapes",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.",+ "Also place them from the origin (fully constrained)": "Also place them from the origin (fully constrained)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none."+ },+ "ar": {+ "Dimension new shapes": "إضافة أبعاد للأشكال الجديدة",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "يحصل كل شكل ترسمه على جميع أبعاده بالمقاسات التي رسمتها (القيم المكتوبة لها الأولوية). يُستبعد المقاس الذي يحدده الرسم مسبقًا.",+ "Also place them from the origin (fully constrained)": "وضعها أيضًا انطلاقًا من نقطة الأصل (مقيّدة بالكامل)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "يحصل كل شكل جديد أيضًا على أبعاد من نقطة أصل الرسم حتى لا يبقى فيه شيء حر. لا يحصل الشكل المتصل مسبقًا بنقطة الأصل أو بهندسة موضوعة على أي منها."+ },+ "cs": {+ "Dimension new shapes": "Kótovat nové tvary",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Každý nakreslený tvar dostane všechny své kóty v nakreslených velikostech (zadané hodnoty mají přednost). Velikost, kterou už skica určuje, se vynechá.",+ "Also place them from the origin (fully constrained)": "Také je umístit od počátku (plně zavazbené)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Každý nový tvar se také okótuje od počátku skici, dokud v něm nic nezůstane volné. Tvar již připojený k počátku nebo k umístěné geometrii nedostane nic."+ },+ "da": {+ "Dimension new shapes": "Mål nye figurer",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Hver figur, du tegner, får alle sine mål i de størrelser, du tegnede (indtastede værdier vinder). En størrelse, som skitsen allerede fastlægger, udelades.",+ "Also place them from the origin (fully constrained)": "Placer dem også fra origo (fuldt fastlåst)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Hver ny figur får også mål fra skitsens origo, indtil intet af den er frit. En figur, der allerede er knyttet til origo eller til placeret geometri, får ingen."+ },+ "de": {+ "Dimension new shapes": "Neue Formen bemaßen",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Jede gezeichnete Form erhält alle ihre Bemaßungen in den gezeichneten Größen (eingegebene Werte haben Vorrang). Eine Größe, die die Skizze bereits festlegt, wird ausgelassen.",+ "Also place them from the origin (fully constrained)": "Auch vom Ursprung aus platzieren (vollständig bestimmt)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Jede neue Form wird zusätzlich vom Skizzenursprung aus bemaßt, bis nichts mehr frei ist. Eine Form, die schon am Ursprung oder an platzierter Geometrie hängt, erhält keine."+ },+ "es": {+ "Dimension new shapes": "Acotar las formas nuevas",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Cada forma que dibujas recibe todas sus cotas con los tamaños dibujados (los valores escritos tienen prioridad). Se omite un tamaño que el croquis ya fija.",+ "Also place them from the origin (fully constrained)": "Situarlas también desde el origen (totalmente restringidas)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Cada forma nueva también se acota desde el origen del croquis hasta que no quede nada libre. Una forma ya unida al origen o a geometría situada no recibe ninguna."+ },+ "fr": {+ "Dimension new shapes": "Coter les nouvelles formes",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Chaque forme dessinée reçoit toutes ses cotes aux tailles dessinées (les valeurs saisies l'emportent). Une taille déjà fixée par l'esquisse est omise.",+ "Also place them from the origin (fully constrained)": "Les placer aussi depuis l'origine (entièrement contraintes)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Chaque nouvelle forme est aussi cotée depuis l'origine de l'esquisse jusqu'à ce que rien ne reste libre. Une forme déjà liée à l'origine ou à une géométrie placée n'en reçoit aucune."+ },+ "gl": {+ "Dimension new shapes": "Cotar as formas novas",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Cada forma que debuxas recibe todas as súas cotas cos tamaños debuxados (os valores escritos teñen prioridade). Omítese un tamaño que o esbozo xa fixa.",+ "Also place them from the origin (fully constrained)": "Situalas tamén desde a orixe (totalmente restrinxidas)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Cada forma nova tamén se cota desde a orixe do esbozo ata que non quede nada libre. Unha forma xa unida á orixe ou a xeometría situada non recibe ningunha."+ },+ "he": {+ "Dimension new shapes": "הוספת מידות לצורות חדשות",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "כל צורה שתשרטט תקבל את כל המידות שלה בגדלים ששרטטת (ערכים שהוקלדו קודמים). גודל שהסקיצה כבר קובעת מושמט.",+ "Also place them from the origin (fully constrained)": "מיקום גם ביחס לראשית (מוגבל לחלוטין)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "כל צורה חדשה מקבלת גם מידות מראשית הסקיצה עד שלא נשאר בה דבר חופשי. צורה שכבר מחוברת לראשית או לגאומטריה ממוקמת לא מקבלת אף אחת."+ },+ "hu": {+ "Dimension new shapes": "Új alakzatok méretezése",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Minden megrajzolt alakzat megkapja az összes méretét a rajzolt méretekkel (a beírt értékek elsőbbséget élveznek). A vázlat által már meghatározott méret kimarad.",+ "Also place them from the origin (fully constrained)": "Elhelyezés az origótól is (teljesen kényszerezve)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Minden új alakzat méretet kap a vázlat origójától is, amíg semmi sem marad szabadon. Az origóhoz vagy elhelyezett geometriához már kötött alakzat nem kap."+ },+ "id": {+ "Dimension new shapes": "Beri dimensi bentuk baru",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Setiap bentuk yang Anda gambar mendapat semua dimensinya sesuai ukuran yang digambar (nilai yang diketik diutamakan). Ukuran yang sudah ditetapkan sketsa dilewati.",+ "Also place them from the origin (fully constrained)": "Tempatkan juga dari titik asal (terkunci penuh)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Setiap bentuk baru juga diberi dimensi dari titik asal sketsa hingga tidak ada yang bebas. Bentuk yang sudah terhubung ke titik asal atau geometri yang ditempatkan tidak mendapat apa pun."+ },+ "it": {+ "Dimension new shapes": "Quota le nuove forme",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Ogni forma disegnata riceve tutte le sue quote alle dimensioni disegnate (i valori digitati hanno la precedenza). Una dimensione già fissata dallo schizzo viene omessa.",+ "Also place them from the origin (fully constrained)": "Posizionale anche dall'origine (completamente vincolate)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Ogni nuova forma viene quotata anche dall'origine dello schizzo finché nulla resta libero. Una forma già collegata all'origine o a geometria posizionata non ne riceve."+ },+ "ja": {+ "Dimension new shapes": "新しい図形に寸法を付ける",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "描いた図形に、描いたサイズですべての寸法が付きます(入力した値が優先されます)。スケッチですでに決まっているサイズは省かれます。",+ "Also place them from the origin (fully constrained)": "原点からの位置も付ける(完全拘束)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "新しい図形には、自由な部分がなくなるまでスケッチの原点からの寸法も付きます。原点や配置済みの形状にすでにつながっている図形には付きません。"+ },+ "ko": {+ "Dimension new shapes": "새 도형에 치수 지정",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "그린 도형마다 그린 크기로 모든 치수가 지정됩니다(입력한 값이 우선). 스케치에서 이미 정해진 크기는 생략됩니다.",+ "Also place them from the origin (fully constrained)": "원점 기준 위치도 지정(완전 구속)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "새 도형마다 자유로운 부분이 없어질 때까지 스케치 원점 기준 치수도 지정됩니다. 원점이나 배치된 형상에 이미 연결된 도형은 지정되지 않습니다."+ },+ "ms": {+ "Dimension new shapes": "Dimensikan bentuk baharu",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Setiap bentuk yang anda lukis mendapat semua dimensinya pada saiz yang dilukis (nilai yang ditaip diutamakan). Saiz yang sudah ditetapkan oleh lakaran ditinggalkan.",+ "Also place them from the origin (fully constrained)": "Letakkan juga dari asalan (terkekang penuh)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Setiap bentuk baharu juga didimensikan dari asalan lakaran sehingga tiada yang bebas. Bentuk yang sudah terikat pada asalan atau geometri yang diletakkan tidak mendapat apa-apa."+ },+ "nb": {+ "Dimension new shapes": "Sett mål på nye figurer",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Hver figur du tegner får alle målene sine i størrelsene du tegnet (inntastede verdier går foran). En størrelse skissen allerede bestemmer, utelates.",+ "Also place them from the origin (fully constrained)": "Plasser dem også fra origo (fullt bestemt)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Hver ny figur får også mål fra skissens origo til ingenting av den er fritt. En figur som allerede er festet til origo eller til plassert geometri, får ingen."+ },+ "nl": {+ "Dimension new shapes": "Nieuwe vormen maatvoeren",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Elke vorm die je tekent krijgt al zijn maten op de getekende grootte (getypte waarden gaan voor). Een maat die de schets al vastlegt, wordt weggelaten.",+ "Also place them from the origin (fully constrained)": "Ook vanaf de oorsprong plaatsen (volledig bepaald)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Elke nieuwe vorm krijgt ook maten vanaf de schetsoorsprong tot er niets meer vrij is. Een vorm die al aan de oorsprong of aan geplaatste geometrie vastzit, krijgt er geen."+ },+ "pl": {+ "Dimension new shapes": "Wymiaruj nowe kształty",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Każdy narysowany kształt otrzymuje wszystkie swoje wymiary w narysowanych rozmiarach (wpisane wartości mają pierwszeństwo). Rozmiar, który szkic już określa, jest pomijany.",+ "Also place them from the origin (fully constrained)": "Umieść je też względem początku (w pełni związane)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Każdy nowy kształt otrzymuje też wymiary od początku szkicu, aż nic nie pozostanie swobodne. Kształt już połączony z początkiem lub z umieszczoną geometrią nie otrzymuje żadnych."+ },+ "pt-BR": {+ "Dimension new shapes": "Cotar novas formas",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Cada forma que você desenha recebe todas as suas cotas nos tamanhos desenhados (valores digitados têm prioridade). Um tamanho que o esboço já define é omitido.",+ "Also place them from the origin (fully constrained)": "Posicioná-las também a partir da origem (totalmente restritas)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Cada nova forma também recebe cotas a partir da origem do esboço até nada ficar livre. Uma forma já ligada à origem ou a uma geometria posicionada não recebe nenhuma."+ },+ "ro": {+ "Dimension new shapes": "Cotează formele noi",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Fiecare formă desenată primește toate cotele sale la dimensiunile desenate (valorile tastate au prioritate). O dimensiune pe care schița o fixează deja este omisă.",+ "Also place them from the origin (fully constrained)": "Plasează-le și față de origine (complet constrânse)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Fiecare formă nouă primește și cote față de originea schiței până nu mai rămâne nimic liber. O formă deja legată de origine sau de geometrie plasată nu primește niciuna."+ },+ "ru": {+ "Dimension new shapes": "Проставлять размеры новых фигур",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Каждая нарисованная фигура получает все свои размеры по нарисованным величинам (введённые значения важнее). Размер, который эскиз уже задаёт, пропускается.",+ "Also place them from the origin (fully constrained)": "Также привязывать к началу координат (полностью определено)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Каждая новая фигура также получает размеры от начала координат эскиза, пока в ней не останется ничего свободного. Фигура, уже привязанная к началу или к размещённой геометрии, их не получает."+ },+ "sv": {+ "Dimension new shapes": "Måttsätt nya former",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Varje form du ritar får alla sina mått i de ritade storlekarna (inskrivna värden har företräde). En storlek som skissen redan bestämmer utelämnas.",+ "Also place them from the origin (fully constrained)": "Placera dem också från origo (helt bestämda)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Varje ny form får också mått från skissens origo tills inget av den är fritt. En form som redan sitter i origo eller i placerad geometri får inga."+ },+ "tr": {+ "Dimension new shapes": "Yeni şekillere ölçü ver",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Çizdiğiniz her şekil, çizdiğiniz boyutlarda tüm ölçülerini alır (yazılan değerler önceliklidir). Çizimin zaten belirlediği bir boyut atlanır.",+ "Also place them from the origin (fully constrained)": "Orijinden de konumlandır (tam kısıtlı)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Her yeni şekle, serbest bir şey kalmayana kadar çizim orijininden de ölçü verilir. Orijine veya yerleştirilmiş geometriye zaten bağlı bir şekle verilmez."+ },+ "uk": {+ "Dimension new shapes": "Проставляти розміри нових фігур",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Кожна намальована фігура отримує всі свої розміри за намальованими величинами (введені значення важливіші). Розмір, який ескіз уже задає, пропускається.",+ "Also place them from the origin (fully constrained)": "Також прив'язувати до початку координат (повністю визначено)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Кожна нова фігура також отримує розміри від початку координат ескізу, доки в ній не залишиться нічого вільного. Фігура, уже прив'язана до початку чи до розміщеної геометрії, їх не отримує."+ },+ "vi": {+ "Dimension new shapes": "Ghi kích thước cho hình mới",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "Mỗi hình bạn vẽ nhận đủ các kích thước theo cỡ đã vẽ (giá trị nhập tay được ưu tiên). Kích thước mà bản phác thảo đã xác định sẽ được bỏ qua.",+ "Also place them from the origin (fully constrained)": "Đồng thời định vị từ gốc tọa độ (ràng buộc hoàn toàn)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "Mỗi hình mới cũng được ghi kích thước từ gốc phác thảo cho đến khi không còn phần nào tự do. Hình đã gắn với gốc hoặc với hình học đã đặt sẽ không nhận thêm."+ },+ "zh": {+ "Dimension new shapes": "为新图形标注尺寸",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "您绘制的每个图形都会按绘制的大小获得所有尺寸(输入的值优先)。草图已确定的尺寸会被跳过。",+ "Also place them from the origin (fully constrained)": "同时从原点定位(完全约束)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "每个新图形也会从草图原点标注尺寸,直到没有任何自由度。已连接到原点或已放置几何的图形不会再加。"+ },+ "zh-TW": {+ "Dimension new shapes": "為新圖形標註尺寸",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out.": "您繪製的每個圖形都會依繪製的大小取得所有尺寸(輸入的值優先)。草圖已決定的尺寸會略過。",+ "Also place them from the origin (fully constrained)": "同時從原點定位(完全約束)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none.": "每個新圖形也會從草圖原點標註尺寸,直到沒有任何自由度。已連接到原點或已放置幾何的圖形不會再加。"+ }+}diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 9fb28e4288..6f9ebee769 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -39,6 +39,7 @@ pub(crate) use face::{FaceRefForm, face_ref_form};pub(crate) use features::profiles as feature_profiles;pub(crate) use features::{EdgeRefForm, axis_dir_form, edge_ref_form, sketch_key};pub use features::{auto_operation, extrude_reach};+pub use sketch::dimension_roles;pub use sketch_import::drawing_import_command;pub use sketch_modify::{extend_arc_preview, extend_preview, trim_piece};pub use view_dxf::sketch::exportable as view_dxf_exportable;diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 444b4c3954..495c78d18b 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -15,6 +15,7 @@ mod dimensioned;mod drag;#[path = "sketch_face.rs"]pub(super) mod face;+pub use dimensioned::dimension_roles;use dimensioned::draw as draw_dimensioned;use drag::drag_entity;@@ -51,7 +52,7 @@ pub static COMMANDS: &[CommandSpec] = &[.params(concat!("points: [[x,y] | \"l1.end\" | {at, ref}…] (x and y each a number or an expression over the design's parameters, \"W / 2\": such a point is fixed where it comes to and follows the parameters; likewise wherever a point argument also takes a point id), closed?: bool, construction?: bool, ids?: [..], infer?: bool (add horizontal/vertical)", connect_doc!(), created_doc!())),CommandSpec::new("sketch.draw.dimensioned", "Draw Dimensioned Sketch Geometry", draw_dimensioned).icon("dimension").enabled(in_sketch)- .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value, or `name = expression` (also `#name = expression`), which defines the user parameter `name` as sketch.dimension does (the reply's `defined` lists the names); creates geometry and all driving dimensions atomically in one undo step", created_doc!())),+ .params(concat!("command: sketch creation command, params: object, dimensions: object of role to numeric or expression value, or `name = expression` (also `#name = expression`), which defines the user parameter `name` as sketch.dimension does (the reply's `defined` lists the names) (optional with as_drawn or locate), as_drawn?: bool (also dimension every other role of the shape at its size as drawn; a radius or diameter given takes the place of the other, a circle otherwise takes its diameter, and a size the sketch already determines, such as the angle of a line inferred horizontal, is left out), locate?: bool (then place the shape from the sketch origin until nothing of it is left free: horizontal and vertical distances from the origin to its points, centres first, each kept only where it removes freedom, so a shape anchored to the origin or to placed geometry gets none; a point on an axis goes onto that axis instead of a 0 distance; the reply's located lists them); creates geometry and all driving dimensions atomically in one undo step", created_doc!())),CommandSpec::new("sketch.rectangle.two_point", "2-Point Rectangle", rect_two_point).at("SKETCH", "CREATE").icon("rect")diff --git a/crates/engine/src/cmd/sketch_dimensioned.rs b/crates/engine/src/cmd/sketch_dimensioned.rsindex 3d563b37bd..466d6d2478 100644--- a/crates/engine/src/cmd/sketch_dimensioned.rs+++ b/crates/engine/src/cmd/sketch_dimensioned.rs@@ -1,30 +1,75 @@-//! Shape creation and its typed driving dimensions form one command and one undo step.-use serde_json::{Value, json};+//! Shape creation and its driving dimensions form one command and one undo step: the typed+//! values, with `as_drawn` every other size of the shape at its size as drawn, and with `locate`+//! its place from the sketch origin until nothing of it is left free.+//!+//! [`dimension_roles`] is the one list of the sizes each creator has. The UI asks it which+//! creators can be dimensioned on creation, so a creator added here (with its entities in+//! `draw`) needs nothing else to take part. `locate` needs nothing per creator: it works on the+//! points any creator reports, along the directions of an [`OriginFrame`].+//!+//! 3D sketches: their curves (`sketch.line3d`…) take no constraints yet. Once they do, a 3D+//! creator joins [`dimension_roles`] with its roles and entities, and `locate` gets a frame with a+//! Z direction; the UI routes the 3D tools through `tools::draw`, which asks `dimension_roles`.+use serde_json::{Map, Value, json};use solidcraft_doc::expr::{Kind, definition};+use solidcraft_geom::Vec3;use crate::{Result, Session,- params::{bad, expr, str_},+ params::{bad, bool_, expr, str_},};-pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {- let cmd = "sketch.draw.dimensioned";- let create = str_(p, "command").ok_or_else(|| bad(cmd, "`command` must name a supported sketch creator"))?;- let roles: &[&str] = match create {+/// The dimension roles of a sketch creator, in the order `as_drawn` adds them, or None when+/// `sketch.draw.dimensioned` cannot dimension it. Roles of one [`ALTERNATIVES`] pair are two+/// readings of one size: only the first given (or listed) of them is placed.+pub fn dimension_roles(creator: &str) -> Option<&'static [&'static str]> {+ Some(match creator {"sketch.line" | "sketch.line.midpoint" => &["length", "angle"],"sketch.rectangle.two_point" | "sketch.rectangle.center" | "sketch.rectangle.three_point" | "sketch.rectangle.rounded" => {&["width", "height"]}- "sketch.circle.center" | "sketch.circle.two_point" | "sketch.circle.three_point" => &["radius", "diameter"],+ // A circle is dimensioned by its diameter unless a radius is given.+ "sketch.circle.center" | "sketch.circle.two_point" | "sketch.circle.three_point" => &["diameter", "radius"],"sketch.arc.center_point" => &["radius", "sweep"],"sketch.slot.center_to_center" | "sketch.slot.overall" | "sketch.slot.center_point" => &["length", "width"],"sketch.slot.arc_center" => &["radius", "sweep", "width"],"sketch.slot.arc_three_point" => &["width"],"sketch.polygon.inscribed" | "sketch.polygon.circumscribed" | "sketch.polygon.edge" => &["radius"],- _ => return Err(bad(cmd, "unsupported sketch creator")),- };+ _ => return None,+ })+}++/// Roles that measure the same size two ways: a shape takes one of each pair.+const ALTERNATIVES: &[[&str; 2]] = &[["radius", "diameter"]];++/// The roles to place: the given ones, then (`as_drawn`) each other role of `roles` that is not+/// an alternative of one already placed. None stands for the size as drawn.+fn wanted<'a>(roles: &[&'a str], given: &'a Map<String, Value>, as_drawn: bool) -> Vec<(&'a str, Option<&'a Value>)> {+ let mut wanted: Vec<(&str, Option<&Value>)> = given.iter().map(|(role, value)| (role.as_str(), Some(value))).collect();+ if as_drawn {+ for role in roles {+ let placed = |r: &str| wanted.iter().any(|(w, _)| *w == r);+ let alternative_placed = ALTERNATIVES.iter().any(|pair| pair.contains(role) && pair.iter().any(|other| other != role && placed(other)));+ if !placed(role) && !alternative_placed {+ wanted.push((role, None));+ }+ }+ }+ wanted+}++pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "sketch.draw.dimensioned";+ let create = str_(p, "command").ok_or_else(|| bad(cmd, "`command` must name a supported sketch creator"))?;+ let roles = dimension_roles(create).ok_or_else(|| bad(cmd, "unsupported sketch creator"))?;+ let as_drawn = bool_(p, "as_drawn").unwrap_or(false);+ let locate = bool_(p, "locate").unwrap_or(false);let mut params = p.get("params").filter(|v| v.is_object()).cloned().ok_or_else(|| bad(cmd, "`params` must be an object"))?;- let dimensions = p.get("dimensions").and_then(Value::as_object).ok_or_else(|| bad(cmd, "`dimensions` must be an object"))?;+ let none = Map::new();+ let dimensions = match p.get("dimensions") {+ None if as_drawn || locate => &none,+ given => given.and_then(Value::as_object).ok_or_else(|| bad(cmd, "`dimensions` must be an object"))?,+ };if dimensions.len() > roles.len() || dimensions.keys().any(|key| !roles.contains(&key.as_str())) {return Err(bad(cmd, "unsupported dimension role for this creator"));}@@ -93,8 +138,8 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {};let mut added = serde_json::Map::new();let mut defined = Vec::new();- for (role, value) in dimensions {- let (entities, ty) = match (create, role.as_str()) {+ for (role, value) in wanted(roles, dimensions, as_drawn) {+ let (entities, ty) = match (create, role) {("sketch.line" | "sketch.line.midpoint", "length") => (vec![curve(0)?], "length"),("sketch.line" | "sketch.line.midpoint", "angle") => (vec![curve(0)?], "angle"),// A rounded rectangle's sides stop at the arcs: its size is between opposite sides.@@ -105,14 +150,14 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {(vec![side(a)?, side(b)?], "distance")}(c, "width" | "height") if c.starts_with("sketch.rectangle.") => (vec![curve(usize::from(role == "height"))?], "length"),- (c, "radius" | "diameter") if c.starts_with("sketch.circle.") => (vec![curve(0)?], role.as_str()),- ("sketch.arc.center_point", "radius" | "sweep") => (vec![curve(0)?], role.as_str()),+ (c, "radius" | "diameter") if c.starts_with("sketch.circle.") => (vec![curve(0)?], role),+ ("sketch.arc.center_point", "radius" | "sweep") => (vec![curve(0)?], role),("sketch.slot.center_to_center" | "sketch.slot.center_point", "length") => (vec![curve(0)?], "length"),("sketch.slot.overall", "length") => (vec![curve(1)?, curve(3)?], "overall_length"),(c, "width") if c.starts_with("sketch.slot.") => (vec![curve(1)?], "diameter"),("sketch.slot.arc_center", "radius" | "sweep") => {let centre = out.get("centre_arc").filter(|v| v.is_string()).cloned().ok_or_else(|| bad(cmd, "slot centre arc missing"))?;- (vec![centre], role.as_str())+ (vec![centre], role)}(c, "radius") if c.starts_with("sketch.polygon.") => {let support =@@ -121,18 +166,40 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {}_ => return Err(bad(cmd, "unsupported dimension role")),};- // A typed size the sketch already has (a rectangle drawn onto another's side, the same- // height) is placed as a driven (reference) dimension rather than refused.- let mut dimension = json!({"entities": entities, "type": ty, "value": value, "if_redundant": "driven"});+ let mut dimension = json!({"entities": entities, "type": ty});if let Some(sketch) = params.get("sketch") {dimension["sketch"] = sketch.clone();}- let result = scratch.execute("sketch.dimension", &dimension)?;- if let Some(name) = result.get("defined").filter(|v| v.is_string()) {- defined.push(name.clone());+ match value {+ // A typed size the sketch already has (a rectangle drawn onto another's side, the+ // same height) is placed as a driven (reference) dimension rather than refused. A+ // typed `name = expression` defines the parameter `name` (the reply's `defined`).+ Some(value) => {+ dimension["value"] = value.clone();+ dimension["if_redundant"] = json!("driven");+ let result = scratch.execute("sketch.dimension", &dimension)?;+ if let Some(name) = result.get("defined").filter(|v| v.is_string()) {+ defined.push(name.clone());+ }+ added.insert(role.to_string(), result);+ }+ // A size as drawn (no value: the current one) that the sketch already determines, such+ // as the angle of a line that snapped horizontal, is left out; a failed command leaves+ // the sketch as it was.+ None => {+ if let Ok(result) = scratch.execute("sketch.dimension", &dimension) {+ added.insert(role.to_string(), result);+ }+ }}- added.insert(role.clone(), result);}+ let located = if locate {+ // The freedom left once the shape and its sizes are in: the last reply that reports it.+ let dof = added.values().rev().chain([&out]).find_map(dof_of);+ place_from_origin(&mut scratch, &out, ¶ms, dof)+ } else {+ Vec::new()+ };// Session::execute records the wrapper's before snapshot. Nested history must not leak.scratch.undo.clear();s.accept_computed(scratch);@@ -140,9 +207,111 @@ pub(super) fn draw(s: &mut Session, p: &Value) -> Result<Value> {if !defined.is_empty() {out["defined"] = Value::Array(defined);}+ if locate {+ out["located"] = Value::Array(located);+ }Ok(out)}+/// The sketch's degrees of freedom as a command reported them.+fn dof_of(reply: &Value) -> Option<u64> {+ reply.get("sketch").and_then(|s| s.get("dof")).and_then(Value::as_u64)+}++/// More points than any creator makes: a cap on the work `locate` does.+const MAX_LOCATED_POINTS: usize = 64;++/// What `locate` places a shape with: the directions it measures from the origin, and the+/// commands that fix a distance along one of them or put a point on one of its axes. The loop in+/// [`place_from_origin`] only reads this, so a 3D sketch joins with a frame of its own (a third+/// direction, Z, and its 3D commands) once its geometry can take constraints.+struct OriginFrame {+ directions: &'static [OriginDirection],+ /// Fixes a point's distance from the origin along a direction: `{entities: ["origin", point], type}`.+ distance_command: &'static str,+ /// Puts a point on an axis: `{a: point, b: axis}`.+ onto_command: &'static str,+}++/// One direction of an [`OriginFrame`].+struct OriginDirection {+ /// The point's coordinate along this direction.+ along: fn(Vec3) -> f64,+ /// The distance dimension's `type` along it.+ distance: &'static str,+ /// The axis a point at 0 along this direction lies on (a distance of 0 keeps no side).+ onto: &'static str,+}++fn x_of(p: Vec3) -> f64 {+ p.x+}+fn y_of(p: Vec3) -> f64 {+ p.y+}++/// A sketch on a plane: horizontal and vertical from its origin; x = 0 is its own y axis, y = 0 its+/// x axis.+const PLANE: OriginFrame = OriginFrame {+ directions: &[+ OriginDirection { along: x_of, distance: "horizontal", onto: "y" },+ OriginDirection { along: y_of, distance: "vertical", onto: "x" },+ ],+ distance_command: "sketch.dimension",+ onto_command: "sketch.constraint.coincident",+};++/// `locate`: distances from the sketch origin to the shape's points along each direction of the+/// frame, centres first (a circle, arc or polygon is placed by its centre), each kept only where it+/// takes freedom away, so a shape anchored to the origin or to placed geometry gets none and the+/// rest end fully constrained. A point at 0 along a direction goes onto that axis instead. Nothing+/// here is per creator (it reads the points the creator reports) or per number of directions (it+/// reads the frame).+fn place_from_origin(scratch: &mut Session, out: &Value, params: &Value, mut dof: Option<u64>) -> Vec<Value> {+ let frame = &PLANE;+ let mut points: Vec<String> = out["created"]["points"].as_array().into_iter().flatten().filter_map(|p| p.as_str().map(str::to_string)).collect();+ points.sort_by_key(|p| !p.ends_with(".center"));+ let mut placed = Vec::new();+ for point in points.iter().take(MAX_LOCATED_POINTS) {+ for direction in frame.directions {+ if dof == Some(0) {+ return placed;+ }+ let Some(at) = coordinate(scratch, params, point) else { break };+ let (command, mut request) = if (direction.along)(at).abs() < 1e-6 {+ (frame.onto_command, json!({"a": point, "b": direction.onto}))+ } else {+ (frame.distance_command, json!({"entities": ["origin", point], "type": direction.distance}))+ };+ if let Some(sketch) = params.get("sketch") {+ request["sketch"] = sketch.clone();+ }+ // Refused (the sketch already determines it): nothing changed.+ let Ok(result) = scratch.execute(command, &request) else { continue };+ match (dof, dof_of(&result)) {+ (Some(before), Some(after)) if after >= before => {+ // Accepted but redundant (a constraint the sketch already implies): take it back.+ let _ = scratch.execute("edit.undo", &json!({}));+ }+ (_, after) => {+ dof = after.or(dof);+ placed.push(result);+ }+ }+ }+ }+ placed+}++/// Where a point of the target sketch is now, in the frame's coordinates: a plane sketch's+/// points have z = 0 (a 3D frame would read its points' own z).+fn coordinate(s: &Session, params: &Value, point: &str) -> Option<Vec3> {+ let id = super::target_sketch(s, params, "sketch.draw.dimensioned").ok()?;+ let sketch = s.doc.sketch(id).ok()?;+ let at = sketch.point(sketch.resolve_point(point)?)?;+ Some(Vec3::new(at.x, at.y, 0.0))+}+#[cfg(test)]#[path = "sketch_dimensioned_tests.rs"]mod tests;diff --git a/crates/engine/src/cmd/sketch_dimensioned_tests.rs b/crates/engine/src/cmd/sketch_dimensioned_tests.rsindex a3728e9bda..6436eb0849 100644--- a/crates/engine/src/cmd/sketch_dimensioned_tests.rs+++ b/crates/engine/src/cmd/sketch_dimensioned_tests.rs@@ -305,3 +305,189 @@ fn a_refused_typed_definition_changes_nothing() {assert_eq!(s.undo.len(), undo);}}++/// A drawing for each creator `dimension_roles` accepts. A creator added there needs one here,+/// or `as_drawn_dimensions_every_size_of_every_creator_where_it_was_drawn` fails.+fn sample(creator: &str) -> Option<Value> {+ Some(match creator {+ "sketch.line" => json!({"points":[[0,0],[6,8]]}),+ "sketch.line.midpoint" => json!({"mid":[3,4],"end":[9,12]}),+ "sketch.rectangle.two_point" => json!({"p0":[0,0],"p1":[30,20]}),+ "sketch.rectangle.center" => json!({"center":[0,0],"corner":[15,10]}),+ "sketch.rectangle.three_point" => json!({"p0":[0,0],"p1":[30,10],"p2":[25,25]}),+ "sketch.rectangle.rounded" => json!({"p0":[0,0],"p1":[30,20],"radius":3}),+ "sketch.circle.center" => json!({"center":[0,0],"radius":5}),+ "sketch.circle.two_point" => json!({"p0":[0,0],"p1":[10,0]}),+ "sketch.circle.three_point" => json!({"p0":[0,0],"p1":[10,0],"p2":[5,5]}),+ "sketch.arc.center_point" => json!({"center":[0,0],"start":[10,0],"end":[0,10]}),+ "sketch.slot.center_to_center" | "sketch.slot.overall" => json!({"p0":[2,3],"p1":[22,3],"width":4}),+ "sketch.slot.center_point" => json!({"center":[12,3],"end":[22,3],"width":4}),+ "sketch.slot.arc_center" => json!({"center":[0,0],"start":[20,0],"end":[0,20],"width":6}),+ "sketch.slot.arc_three_point" => json!({"start":[20,0],"through":[14.142136,14.142136],"end":[0,20],"width":6}),+ "sketch.polygon.inscribed" | "sketch.polygon.circumscribed" => json!({"center":[4,5],"radius":10,"sides":6}),+ "sketch.polygon.edge" => json!({"p0":[0,0],"p1":[10,0],"sides":6}),+ _ => return None,+ })+}++fn points(s: &Session) -> Vec<(f64, f64)> {+ sketch(s).points.iter().map(|p| (p.pos.x, p.pos.y)).collect()+}++/// With `as_drawn`, every creator gets every size it has (one of radius and diameter) as driving+/// dimensions, in one undo step, and the shape stays exactly where it was drawn.+#[test]+fn as_drawn_dimensions_every_size_of_every_creator_where_it_was_drawn() {+ let creators: Vec<&str> = crate::command_specs().iter().map(|c| c.id).filter(|id| super::dimension_roles(id).is_some()).collect();+ assert!(creators.len() >= 17, "{creators:?}");+ for creator in creators {+ let params = sample(creator).unwrap_or_else(|| panic!("{creator}: add a sample drawing for it"));+ let mut plain = session();+ run(&mut plain, creator, params.clone());+ let mut s = session();+ let undo = s.undo.len();+ let out = run(&mut s, "sketch.draw.dimensioned", json!({"command":creator,"params":params,"as_drawn":true}));+ assert_eq!(s.undo.len(), undo + 1, "{creator}: one undo step");+ let placed = out["dimensions"].as_object().unwrap();+ for role in super::dimension_roles(creator).unwrap() {+ let alternative = super::ALTERNATIVES.iter().find(|pair| pair.contains(role)).and_then(|pair| pair.iter().find(|r| r != &role));+ assert!(+ placed.contains_key(*role) || alternative.is_some_and(|other| placed.contains_key(*other)),+ "{creator}: no {role} dimension in {placed:?}"+ );+ if let Some(other) = alternative {+ assert!(!(placed.contains_key(*role) && placed.contains_key(*other)), "{creator}: both {role} and {other}");+ }+ }+ for (role, result) in placed {+ assert_ne!(result["driven"], json!(true), "{creator}: {role} is driven");+ }+ for ((x, y), (px, py)) in points(&s).into_iter().zip(points(&plain)) {+ assert!((x - px).abs() < 1e-5 && (y - py).abs() < 1e-5, "{creator}: moved from ({px}, {py}) to ({x}, {y})");+ }+ run(&mut s, "edit.undo", json!({}));+ assert!(sketch(&s).curves.is_empty(), "{creator}: undo left geometry");+ assert!(s.doc.params.iter().all(|p| !p.model), "{creator}: undo left a dimension parameter");+ }+}++/// Typed values win over the size as drawn; a typed radius stands in for the diameter; a size the+/// sketch already determines (a line inferred horizontal has no angle to give) is left out.+#[test]+fn as_drawn_keeps_typed_values_alternatives_and_leaves_out_determined_sizes() {+ let mut s = session();+ let out = run(+ &mut s,+ "sketch.draw.dimensioned",+ json!({"command":"sketch.rectangle.two_point","params":{"p0":[0,0],"p1":[30,20]},"dimensions":{"width":40},"as_drawn":true}),+ );+ let mut placed: Vec<&String> = out["dimensions"].as_object().unwrap().keys().collect();+ placed.sort();+ assert_eq!(placed, ["height", "width"]);+ let lengths: Vec<f64> = sketch(&s)+ .constraints+ .iter()+ .filter(|c| matches!(c.kind, ConstraintKind::Length { .. }))+ .map(|c| solidcraft_sketch::measure_dimension(&sketch(&s), &c.kind).unwrap())+ .collect();+ assert_eq!(lengths.len(), 2);+ assert!(lengths.iter().any(|l| (l - 40.0).abs() < 1e-6) && lengths.iter().any(|l| (l - 20.0).abs() < 1e-6), "{lengths:?}");++ let mut s = session();+ let out = run(+ &mut s,+ "sketch.draw.dimensioned",+ json!({"command":"sketch.circle.center","params":{"center":[0,0],"radius":5},"dimensions":{"radius":"4 mm"},"as_drawn":true}),+ );+ assert_eq!(out["dimensions"].as_object().unwrap().keys().collect::<Vec<_>>(), ["radius"]);+ close(measure(&s, |k| matches!(k, ConstraintKind::Radius { .. })), 4.0);++ let mut s = session();+ let out =+ run(&mut s, "sketch.draw.dimensioned", json!({"command":"sketch.line","params":{"points":[[0,0],[10,0]],"infer":true},"as_drawn":true}));+ assert_eq!(out["dimensions"].as_object().unwrap().keys().collect::<Vec<_>>(), ["length"]);+ assert!(sketch(&s).constraints.iter().any(|c| matches!(c.kind, ConstraintKind::Horizontal { .. })), "the inferred horizontal stays");+ close(measure(&s, |k| matches!(k, ConstraintKind::Length { .. })), 10.0);++ // Without as_drawn the call is unchanged: only what is typed.+ let mut s = session();+ let out = draw(&mut s, "sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[30,20]}), json!({"width":40}));+ assert_eq!(out["dimensions"].as_object().unwrap().keys().collect::<Vec<_>>(), ["width"]);+}++/// Every `[x, y]` point of a sample moved by `(dx, dy)`; sizes and counts stay.+fn shifted(v: &Value, dx: f64, dy: f64) -> Value {+ match v {+ Value::Array(xy) if xy.len() == 2 && xy.iter().all(Value::is_number) => {+ json!([xy[0].as_f64().unwrap() + dx, xy[1].as_f64().unwrap() + dy])+ }+ Value::Array(items) => Value::Array(items.iter().map(|item| shifted(item, dx, dy)).collect()),+ Value::Object(fields) => Value::Object(fields.iter().map(|(k, item)| (k.clone(), shifted(item, dx, dy))).collect()),+ other => other.clone(),+ }+}++fn dof(s: &mut Session) -> u64 {+ run(s, "sketch.solve", json!({}))["dof"].as_u64().unwrap()+}++/// With `as_drawn` and `locate`, every creator ends fully constrained wherever it is drawn: at its+/// sample place (several touch the origin, which anchors them) and moved away from the origin.+/// Nothing moves, and it is one undo step.+#[test]+fn locate_fully_constrains_every_creator_where_it_was_drawn() {+ let creators: Vec<&str> = crate::command_specs().iter().map(|c| c.id).filter(|id| super::dimension_roles(id).is_some()).collect();+ for creator in creators {+ let sample = sample(creator).unwrap_or_else(|| panic!("{creator}: add a sample drawing for it"));+ for params in [sample.clone(), shifted(&sample, 13.0, 7.0)] {+ let mut plain = session();+ run(&mut plain, creator, params.clone());+ let mut s = session();+ let undo = s.undo.len();+ let out = run(&mut s, "sketch.draw.dimensioned", json!({"command":creator,"params":params,"as_drawn":true,"locate":true}));+ assert_eq!(dof(&mut s), 0, "{creator} {params}: not fully constrained; located {}", out["located"]);+ assert_eq!(s.undo.len(), undo + 1, "{creator}: one undo step");+ for ((x, y), (px, py)) in points(&s).into_iter().zip(points(&plain)) {+ assert!((x - px).abs() < 1e-5 && (y - py).abs() < 1e-5, "{creator} {params}: moved from ({px}, {py}) to ({x}, {y})");+ }+ for placed in out["located"].as_array().unwrap() {+ assert_ne!(placed["driven"], json!(true), "{creator}: a driven position {placed}");+ }+ run(&mut s, "edit.undo", json!({}));+ assert!(sketch(&s).curves.is_empty() && sketch(&s).constraints.is_empty(), "{creator}: undo left something");+ }+ }+}++/// A shape anchored to the origin gets no position; a point on an axis goes onto the axis rather+/// than taking a 0 distance; one off both axes gets a horizontal and a vertical distance.+#[test]+fn locate_adds_only_what_the_shape_lacks() {+ let located = |center: [f64; 2]| -> (Value, Session) {+ let mut s = session();+ let out = run(+ &mut s,+ "sketch.draw.dimensioned",+ json!({"command":"sketch.circle.center","params":{"center":center,"radius":5},"as_drawn":true,"locate":true}),+ );+ (out["located"].clone(), s)+ };+ let (anchored, mut s) = located([0.0, 0.0]);+ assert_eq!(anchored, json!([]), "a circle on the origin is already placed");+ assert_eq!(dof(&mut s), 0);++ let (on_axis, mut s) = located([20.0, 0.0]);+ assert_eq!(on_axis.as_array().unwrap().len(), 2, "{on_axis}");+ assert_eq!(dof(&mut s), 0);+ let zero_distance = sketch(&s).constraints.iter().any(|c| match &c.kind {+ ConstraintKind::DistanceX { value, .. } | ConstraintKind::DistanceY { value, .. } => value.abs() < 1e-9,+ _ => false,+ });+ assert!(!zero_distance, "a 0 distance was placed instead of the axis");++ let (free, mut s) = located([20.0, 12.0]);+ assert_eq!(free.as_array().unwrap().len(), 2, "{free}");+ assert_eq!(dof(&mut s), 0);+ close(measure(&s, |k| matches!(k, ConstraintKind::DistanceX { .. })), 20.0);+ close(measure(&s, |k| matches!(k, ConstraintKind::DistanceY { .. })), 12.0);+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex e48da67560..157310622f 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -42,7 +42,9 @@ use serde_json::Value;use solidcraft_doc::{Document, Model, ModelState};use solidcraft_geom::Vec3;-pub use cmd::{CommandInfo, CommandSpec, auto_operation, command_specs, extrude_reach, find_command, resolve_design_links, standard_view};+pub use cmd::{+ CommandInfo, CommandSpec, auto_operation, command_specs, dimension_roles, extrude_reach, find_command, resolve_design_links, standard_view,+};pub use solidcraft_doc as doc;pub use solidcraft_doc::Visibility;pub use solidcraft_geom as geom;diff --git a/crates/ui-egui/src/prefs.rs b/crates/ui-egui/src/prefs.rsindex ea5756d473..78705119c6 100644--- a/crates/ui-egui/src/prefs.rs+++ b/crates/ui-egui/src/prefs.rs@@ -1030,6 +1030,20 @@ preference_settings! {shortcut_cycles_modes: bool = false, PAGE_SKETCH;/// Where the view goes when a sketch ends (#7038). Keep (the default) leaves it as it is.sketch_exit_view: SketchExitView = SketchExitView::default(), PAGE_SKETCH;+ /// A shape drawn in a sketch gets all its dimensions at once: the typed values, and every+ /// other size the shape has at its size as drawn (`sketch.draw.dimensioned` with `as_drawn`).+ /// Shapes `solidcraft_engine::dimension_roles` doesn't list are drawn as before.+ sketch_auto_dimensions: bool = false, PAGE_SKETCH => check(+ "Dimension new shapes",+ "Each shape you draw gets all its dimensions, at the sizes you drew (typed values win). A size the sketch already sets is left out."+ );+ /// With `sketch_auto_dimensions`: new shapes are also placed from the sketch origin until they+ /// are fully constrained (`sketch.draw.dimensioned` with `locate`). A shape already anchored to+ /// the origin or to placed geometry gets nothing more.+ sketch_auto_locate: bool = false, PAGE_SKETCH => check(+ "Also place them from the origin (fully constrained)",+ "Each new shape is also dimensioned from the sketch origin until nothing of it is left free. A shape already attached to the origin or to placed geometry gets none."+ );/// When true: Shift+click adds without removing; Primary toggles./// When false (default): Shift and Primary both toggle.selection_shift_add_only: bool = false, PAGE_SKETCH;diff --git a/crates/ui-egui/src/prefs/sketch.rs b/crates/ui-egui/src/prefs/sketch.rsindex 2f70e426fb..f7a676c9ce 100644--- a/crates/ui-egui/src/prefs/sketch.rs+++ b/crates/ui-egui/src/prefs/sketch.rs@@ -13,6 +13,12 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {.on_hover_text(crate::i18n::tr_label("Before the first point, pressing a sketch tool's shortcut again steps through its creation modes. Off: it starts the tool again.",));+ let dimension = setting::sketch_auto_dimensions(app, ui);+ crate::scenario::publish_handle("prefs:sketch_auto_dimensions", dimension.rect.center());+ ui.add_enabled_ui(app.preferences.sketch_auto_dimensions, |ui| {+ let locate = setting::sketch_auto_locate(app, ui);+ crate::scenario::publish_handle("prefs:sketch_auto_locate", locate.rect.center());+ });ui_kit::settings_block_hint(ui, app.tr("prefs.hold_stop_snapping"), app.tr("prefs.snap_drawing_note"), t.space_24 * 8.0 + t.space_8, |ui| {let combo = &mut app.preferences.suppress_sketch_snap;ui_kit::settings_control_width(ui, t.space_24 * 7.0 + t.space_12, |ui| {diff --git a/crates/ui-egui/src/sketch_dims_tests.rs b/crates/ui-egui/src/sketch_dims_tests.rsindex 4f4c10ac8a..4aaaa672c2 100644--- a/crates/ui-egui/src/sketch_dims_tests.rs+++ b/crates/ui-egui/src/sketch_dims_tests.rs@@ -298,6 +298,69 @@ fn rounded_rectangle_clicks_use_a_default_radius() {assert!((sketch.profiles[0].area - want).abs() < 0.05 * want, "area {} want about {want}", sketch.profiles[0].area);}+/// "Dimension new shapes" (Preferences › Sketch) is off by default: shapes drawn by clicks get no+/// dimensions. On, every size of the shape is dimensioned at its size as drawn, in the same undo+/// step as the shape.+#[test]+fn dimension_new_shapes_dimensions_every_size_only_when_on() {+ use solidcraft_engine::doc::expr::Kind;+ let dimensions = |h: &Harness| -> Vec<f64> {+ let doc = &h.app.session.doc;+ let mut values: Vec<f64> = doc.params.iter().filter(|p| p.model).filter_map(|p| doc.eval(&p.name, Kind::Length).ok()).collect();+ values.sort_by(f64::total_cmp);+ values+ };+ let rectangle = |h: &mut Harness| {+ h.step(&json!({"start": "sketch.rectangle.two_point"})).unwrap();+ h.step(&json!({"click": {"sketch": [0, 0]}})).unwrap();+ h.step(&json!({"click": {"sketch": [40, 20]}})).unwrap();+ };++ let mut h = Harness::new();+ assert!(!h.app.preferences.sketch_auto_dimensions, "Dimension new shapes is on by default");+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ rectangle(&mut h);+ assert!(dimensions(&h).is_empty(), "off, yet the rectangle has dimensions {:?}", dimensions(&h));++ let mut h = Harness::new();+ h.app.preferences.sketch_auto_dimensions = true;+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ rectangle(&mut h);+ let sizes = dimensions(&h);+ assert_eq!(sizes.len(), 2, "width and height: {sizes:?} {:?}", h.app.status);+ assert!((sizes[0] - 20.0).abs() < 0.5 && (sizes[1] - 40.0).abs() < 0.5, "{sizes:?}");+ h.step(&json!({"key": "Escape"})).unwrap();+ h.step(&json!({"start": "sketch.circle.center"})).unwrap();+ h.step(&json!({"click": {"sketch": [70, 10]}})).unwrap();+ h.step(&json!({"click": {"sketch": [80, 10]}})).unwrap();+ assert_eq!(dimensions(&h).len(), 3, "the circle's diameter joins: {:?} {:?}", dimensions(&h), h.app.status);+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(dimensions(&h).len(), 2, "one undo removes the circle with its dimension");+}++/// "Also place them from the origin" finishes the job: a rectangle drawn away from the origin+/// gets its width, height and place, and the sketch is fully constrained. On its own (without+/// "Dimension new shapes") it does nothing.+#[test]+fn place_from_the_origin_fully_constrains_new_shapes() {+ let draw = |dimension: bool, locate: bool| -> (usize, u64) {+ let mut h = Harness::new();+ assert!(!h.app.preferences.sketch_auto_locate, "Also place them from the origin is on by default");+ h.app.preferences.sketch_auto_dimensions = dimension;+ h.app.preferences.sketch_auto_locate = locate;+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();+ h.step(&json!({"start": "sketch.rectangle.two_point"})).unwrap();+ h.step(&json!({"click": {"sketch": [10, 10]}})).unwrap();+ h.step(&json!({"click": {"sketch": [50, 30]}})).unwrap();+ let dimensions = h.app.session.doc.params.iter().filter(|p| p.model).count();+ let dof = h.app.run("sketch.solve", json!({})).unwrap()["dof"].as_u64().unwrap();+ (dimensions, dof)+ };+ assert_eq!(draw(true, true), (4, 0), "width, height and two distances from the origin");+ assert_eq!(draw(true, false), (2, 2), "sizes only: the rectangle can still move");+ assert_eq!(draw(false, true), (0, 4), "placing needs Dimension new shapes");+}+/// A line from a circle's centre to the circle, ending a little off the quadrant: the preview/// snaps to horizontal or vertical, so the click must place exactly that line, on the circle.#[test]diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rsindex 9938f76311..783ddab8c3 100644--- a/crates/ui-egui/src/tools.rs+++ b/crates/ui-egui/src/tools.rs@@ -496,13 +496,21 @@ pub fn place(app: &mut SolveApp, p: (Vec2, Option<String>)) {app.tool = Some(tool);}-/// Geometry and typed constraints are committed atomically, as one undo step.+/// Geometry and typed constraints are committed atomically, as one undo step. With "Dimension+/// new shapes" on (Preferences › Sketch), every other size of a shape the engine can dimension+/// joins them at its size as drawn, and with "Also place them from the origin" the shape is then+/// placed until fully constrained; the engine's `dimension_roles` decides which shapes those are.+/// This is the one place drawing tools commit through: the 3D tools (`sketch3d`) take part by+/// committing here once their creators are listed there.pub(crate) fn draw(app: &mut SolveApp, t: &Tool, params: Value) -> Result<Value, String> {let dimensions = crate::sketch_dims::dimensions(t);- if dimensions.as_object().is_none_or(|values| values.is_empty()) {+ let as_drawn = app.preferences.sketch_auto_dimensions && solidcraft_engine::dimension_roles(t.cmd).is_some();+ let locate = as_drawn && app.preferences.sketch_auto_locate;+ if !as_drawn && dimensions.as_object().is_none_or(|values| values.is_empty()) {app.run(t.cmd, params)} else {- let result = app.run("sketch.draw.dimensioned", json!({"command": t.cmd, "params": params, "dimensions": dimensions}))?;+ let request = json!({"command": t.cmd, "params": params, "dimensions": dimensions, "as_drawn": as_drawn, "locate": locate});+ let result = app.run("sketch.draw.dimensioned", request)?;// The internal wrapper has no toolbar category; apply the original creator's line// type while retaining the draw's undo history, including at the history limit.let history = std::mem::take(&mut app.session.undo);diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.mdindex 85ddde37f3..118b574bcc 100644--- a/docs/book/src/guide/sketching.md+++ b/docs/book/src/guide/sketching.md@@ -244,6 +244,20 @@ nothing picked yet, click it once: its value box opens with the value selected,and the tool stays on for the next dimension. The dimension's text always takes the click; itslines take it only away from sketch points and curves, which still start a new dimension.+To have shapes dimensioned as you draw them, turn on **Dimension new shapes** in Preferences ›+Sketch (it is off by default). Each line, rectangle, circle, arc, slot or polygon you draw then+gets all its dimensions at the sizes you drew: a line its length and angle, a rectangle its width+and height, a circle its diameter, and so on. Values you type in the drawing boxes win, and a size+the sketch already sets (the angle of a line that snapped horizontal) is left out. The shape and+its dimensions are one undo step. In scripts, `sketch.draw.dimensioned` takes `"as_drawn": true`.++Tick **Also place them from the origin (fully constrained)** as well, and each new shape is also+dimensioned from the sketch origin until nothing of it is left free: a horizontal and a vertical+distance to its centre or first point, and one more where the shape could still turn (a polygon,+a rectangle drawn at an angle). A shape already attached to the origin or to geometry that is+placed gets none, and a point on an axis is put on that axis rather than given a 0 distance.+In scripts: `"locate": true`.+Between two points, or on a line, that don't line up with an axis, where you place thedimension picks what it measures: across from them, the distance between them; above or belowthem, the horizontal distance; beside them, the vertical distance.diff --git a/docs/control-protocol.md b/docs/control-protocol.mdindex c6bb0ac293..9477ba867e 100644--- a/docs/control-protocol.md+++ b/docs/control-protocol.md@@ -349,6 +349,8 @@ One setting per line, sorted by name. A change that adds a setting adds its own- `pan_reverse_y` (default false: vertical scrolling pans the other way)- `placement_handles` (default false: handles on the preview of a Rest, Boss or Snap Fit that move it across the model and turn it)- `show_frame_rate` (default false: frames per second in the view's bottom-right corner, counting the frames the view draws anyway; it reads 0 FPS once the view is idle)+- `sketch_auto_dimensions` (default false: each shape drawn in a sketch gets all its dimensions at the sizes drawn, as `sketch.draw.dimensioned` with `as_drawn`; typed values win)+- `sketch_auto_locate` (default false; with `sketch_auto_dimensions`, new shapes are also placed from the sketch origin until fully constrained, as `sketch.draw.dimensioned` with `locate`)- `sketch_exit_view` (`keep` (default: the view stays where it is when a sketch ends), `previous` (back to the view from before the sketch), `unless_rotated` (back unless the sketch view was turned))- `sketch_tab_always` (default false: the SKETCH tab stays in the ribbon right after MODEL while no sketch is open; a tool in its CREATE or REFERENCE section then opens Create Sketch, on the selected plane or planar face or else on the plane picked next, and starts in the new sketch, #7904)- `smooth_wheel_zoom` (default true)