Frames: profile library, members along frame sketch lines, and the Frame Member dialog (#4003) (#4004)

* claim: #4003

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames: the profile library (#4003)

The first slice of frames and weldments: the cross-sections structural members
will be made of, each SolidCraft's own parametric definition built in code
(no vendor or standard size tables are shipped).

- solidcraft_doc::frame: bar, round bar, rectangular and round tube, angle,
  channel, I-beam and a generic T-slot extrusion as exact line/arc regions,
  with defaults worked out from the profile's size, refusals that name the
  dimension that does not fit, anchors and placement, and exact section
  properties (area, centroid, Ixx/Iyy/Ixy by Green's theorem).
- frame.profile.list, frame.profile.properties (with mass per metre for a
  density) and frame.profile.insert (draws a profile into a sketch, locked by
  default, at a point, anchor and angle).
- Tests against hand-computed values (rectangles, circles, composite
  rectangles by the parallel-axis theorem, fillet spandrels), hostile input,
  extrusion volume, undo; catalog entries in every locale; docs/frames.md;
  ROADMAP M15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames: drop the built-in T-slot profile (#4003)

Aluminium extrusions and other vendor sections come from the user's own
sketch (drawn or inserted from the vendor's DXF), so the library keeps the
plain steel shapes only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames: members along frame sketch lines (#4003)

frame.member lays one body per straight line of a frame sketch (2D lines or
3D sketch lines), its cross-section square to the line from end to end:

- profile: a built-in profile, or profile_sketch, a sketch whose material
  (nested loops alternating, so two circles make a tube) is the section in
  its own x and y around its origin; profiles picks override it.
- anchor (origin, centre, centroid or a bounding-box corner or edge middle),
  angle (an angle expression, so a parameter), mirror.
- Orientation: the profile's y as near world up as the line allows, x
  square to both; a vertical member's x is world X (frame::member_axes).
- Members follow sketch and parameter edits, undo as one step, save and
  reopen (format: pending/frame-members.rs), and are named after the profile
  (Rect Tube 40x40x3, (2)…), numbering on past names already taken.

Tests against hand-computed volumes and bounding boxes (rectangle, 3D
tower lines, parameter edit, sketch tube profile and picks, anchor/angle/
mirror), refusals, undo/redo and reopen; walk fixtures and goldens; docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames: fixes from the adversarial review (#4003)

- Default member lines are what was drawn: projected and other linked curves
  and 3D wires (a face sketch's edges) and lines of no length are left out.
- A profile sketch's material starts from its drawn profiles, as
  solid.extrude's "all" does, so a section sketched on a face works; the
  even-odd test uses outlines and boxes worked out once, capped at 256.
- Member names are pinned to their lines (`names`, by line id; `body_name`
  is the base): deleting or adding a line, or deleting another feature, no
  longer renames other members, and frame.member stores every name it gives.
  body.rename renames a member on its line (also for later member features);
  a copy whose body_names were set still names its members by position.
- Built-in profile dimensions are expressions (ProfileSpec): they follow
  parameters, bare numbers take the design's units, and they are feature
  inputs. frame.profile.properties/insert read them the same way.
- Default root/toe radii shrink to the room a thick section leaves; radii
  given are checked by name; a radius must be 0 or at least 0.01 mm; error
  messages report the wall or flange value given, not twice it.
- A line within 1e-6 rad of vertical orients as vertical, so rounding never
  turns a post a quarter turn.
- A 2D frame sketch in a differently placed component is mapped into the
  member's frame, and member features recompute when placements change.
- Caps before lookups for a design's `lines`; a line listed twice is
  refused; a 3D wire that runs back on itself is not a line.

Regression tests for each, from the review's scenarios.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Frames: the Frame Member dialog on the ribbon (#4003)

- Frame Member (MODEL > Create) opens a dialog: the frame sketch's lines
  picked in the view (or All Lines), a built-in profile and its dimensions or
  a section picked in another sketch, anchor, angle, mirror and name, with a
  live preview. Edit Feature reopens it filled in.
- Lines picked in the view keep their sketch (a SKETCH_LINES input picks
  ExternalSketchCurve): line ids are each sketch's own, so two 3D sketches
  both have a `w2`, and the members went on the newer sketch's lines.
- timeline.redefine takes frame.member. Members keep their names through an
  edit unless it gives them a new body_name; frame.member takes `names`.
- A member whose section is a whole profile sketch keeps it when edited
  (the dialog shows the sketch instead of picking every region, which would
  fill a tube's hole).
- An original frame_member icon, open for review, on the ribbon, timeline
  and browser.
- The angle profile is listed as L-Angle, and web and flange as Web/Flange
  thickness, so they translate apart from the existing Angle, Web and Flange;
  the dialog's labels are in en, ja and zh. en-GB no longer repeats the frame
  command labels it spells the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Karl Von Richter
2026-10-23 14:22:41 +00:00
committed by GitHub
parent 6fb72c7401
commit 27d2fe6ec0
57 changed files with 3222 additions and 19 deletions
+1
View File
@@ -343,6 +343,7 @@ Editable drawing code, native projects and shipped exports are collected under `
| assets/icons/ui/design/svg/flat/stop.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/flat/shield.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/status_recovery.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/frame_member.svg | SolidCraft contributors | original icon master (64 grid) | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/placeholder.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/plane.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 |
| assets/icons/ui/design/svg/model/plane_angle.svg | SolidCraft contributors | two-tone modelling icon master (64 grid), original SolidCraft artwork | MIT OR Apache-2.0 |
+1
View File
@@ -64,6 +64,7 @@ PCB / Package, Render, Animation, Simulation, Manufacture/CAM, Drawings.
| M12 | Release: cross-platform packages, verification and deliberate publication implemented; original current-UI demo refreshed. Trusted distribution signing and broader performance work remain | in progress | 16 |
| M14 | Configurations: a table of rows (parameter expressions and feature suppressions per row) switched with config.activate (undoable, all or nothing), kept through parameter renames and feature deletes (config.configure, config.table, config.column/row/activate). Per-row body materials and appearances (library looks, custom colour/opacity and clearing overrides), undoable activation and save/reopen: done. Ordered typed configuration rules, atomic validation and structured rule editing: done. Component appearance and certified semantic face style columns, atomic preview/apply and independent-copy remapping: done. Exact constructed sketch-side and immutable imported-face lineage now preserve legacy names and reject retargeting. Left: ambiguous shifted/two-sided caps | in progress | 4 |
| M13 | Never lose work: atomic saves (temporary file, flush, rename; a crash at any moment leaves the old file or the new one) with the replaced version kept as `<file>.bak`; autosave of unsaved changes to the recovery folder every 5 minutes (preference) and after big operations, only when something changed; "Recover unsaved design?" on the next launch (`doc.recovery_list`, `doc.recover`, `doc.recovery_discard`); a kill-mid-save test (process killed while saving a 0.5 MB design 25 times). File format: `"format": "solidcraft/12"`, older formats upgraded step by step (`doc::format`), newer ones refused with a message, out-of-range numbers and broken placements refused; a corpus of designs saved by M0, components-era, joints-era and current builds (apps/solidcraft-cli/tests/corpus) that must open and evaluate as saved; damaged and hostile variants (truncation, bit flips, hostile values, removed keys, repeated features, deep nesting) never panic | done | 6 |
| M15 | Frames and weldments (#4003): structural members along 2D and 3D sketch lines, butt and mitre corners, trim to faces and bodies, end caps, gussets, cosmetic welds and a cut list. Done: the profile library (`frame.profile.list`, `frame.profile.properties`, `frame.profile.insert`): bar, round bar, rectangular and round tube, angle, channel and I-beam, each SolidCraft's own parametric definition with exact fillet arcs and exact section properties (area, centroid, second moments), tested against hand-computed values; members (`frame.member`): one body per straight line of a 2D or 3D frame sketch, following parameter edits, with a built-in profile (its dimensions parameter expressions) or a profile sketch (its drawn material by alternating nested loops), anchor, angle and mirror; each member's name kept with its line. Left: corners, trims, end caps, gussets, welds, cut list, FRAME tab and dialogs | in progress | 60 |
M6 navigation preferences include **Touchpad**: Shift + pointer movement pans, Alt/Option +
pointer movement orbits without a mouse button, and vertical scrolling zooms. Other presets
@@ -104,6 +104,7 @@ flange false
flat false
fold false
folder false
frame_member false
gear false
graph false
ground false
@@ -0,0 +1,22 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
<title>Frame Member</title>
<path d="M9.25 18.86L17.63 23.7" fill="none" stroke="#ffffff" stroke-width="4.4" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M9.25 18.86L17.63 23.7" fill="none" stroke="#236ead" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round"/>
<circle cx="9.25" cy="18.86" r="3" fill="#236ead"/>
<path d="M11.88 20.39L40.62 36.98L40.62 50.25L11.88 33.66Z" fill="#328bd3"/>
<path d="M23.38 13.75L52.12 30.34L40.62 36.98L11.88 20.39Z" fill="#b9ddf8"/>
<path d="M52.12 30.34L40.62 36.98L40.62 50.25L52.12 43.61ZM49.8 34.35L42.94 38.31L42.94 46.24L49.8 42.28Z" fill="#8e9faf" fill-rule="evenodd"/>
<defs><clipPath id="fm_hole"><path d="M49.8 34.35L42.94 38.31L42.94 46.24L49.8 42.28Z" fill="none"/></clipPath></defs>
<g clip-path="url(#fm_hole)">
<path d="M49.8 34.35L42.94 38.31L42.94 46.24L49.8 42.28Z" fill="#236ead"/>
<path d="M49.8 34.35L49.8 42.28L42.86 38.27L42.86 30.34Z" fill="#328bd3"/>
<path d="M49.8 42.28L42.94 46.24L35.99 42.23L42.86 38.27Z" fill="#b9ddf8"/>
</g>
<path d="M49.8 34.35L42.94 38.31L42.94 46.24L49.8 42.28Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M23.38 13.75L52.12 30.34L52.12 43.61L40.62 50.25L11.88 33.66L11.88 20.39Z" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M11.88 20.39L40.62 36.98L52.12 30.34" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M40.62 36.98L40.62 50.25" fill="none" stroke="#34465b" stroke-width="2.55" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M41.74 37.62L54.75 45.14" fill="none" stroke="#ffffff" stroke-width="4.4" stroke-linejoin="round" stroke-linecap="round"/>
<path d="M41.74 37.62L54.75 45.14" fill="none" stroke="#236ead" stroke-width="2.2" stroke-linejoin="round" stroke-linecap="round"/>
<circle cx="54.75" cy="45.14" r="3" fill="#236ead"/>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Vložit STEP",
"cmd.file_save_mesh": "Uložit jako síť",
"cmd.file_slicers": "Nainstalované slicery",
"cmd.frame_member": "Prvek rámu",
"cmd.frame_profile_insert": "Vložit profil",
"cmd.frame_profile_list": "Knihovna profilů",
"cmd.frame_profile_properties": "Vlastnosti profilu",
"cmd.inspect_accessibility": "Analýza přístupnosti",
"cmd.inspect_center_of_mass": "Těžiště",
"cmd.inspect_clearance": "Vůle",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Indsæt STEP",
"cmd.file_save_mesh": "Gem som mesh",
"cmd.file_slicers": "Installerede slicere",
"cmd.frame_member": "Rammeelement",
"cmd.frame_profile_insert": "Indsæt profil",
"cmd.frame_profile_list": "Profilbibliotek",
"cmd.frame_profile_properties": "Profilegenskaber",
"cmd.inspect_accessibility": "Tilgængelighedsanalyse",
"cmd.inspect_center_of_mass": "Massecentrum",
"cmd.inspect_clearance": "Frigangskontrol",
+4
View File
@@ -641,6 +641,10 @@
"cmd.file_insert_step": "STEP einfügen",
"cmd.file_save_mesh": "Als Netz speichern",
"cmd.file_slicers": "Installierte Slicer",
"cmd.frame_member": "Rahmenelement",
"cmd.frame_profile_insert": "Profil einfügen",
"cmd.frame_profile_list": "Profilbibliothek",
"cmd.frame_profile_properties": "Profileigenschaften",
"cmd.inspect_accessibility": "Zugänglichkeitsanalyse",
"cmd.inspect_center_of_mass": "Massenschwerpunkt",
"cmd.inspect_clearance": "Freiraum",
+31
View File
@@ -25,11 +25,13 @@
"Advanced": "Advanced",
"Against": "Against",
"Alignment": "Alignment",
"All Lines": "All Lines",
"All Sketch Points": "All Sketch Points",
"All components": "All components",
"All open designs": "All open designs",
"Allowed expressions, separated by semicolons": "Allowed expressions, separated by semicolons",
"Also deletes": "Also deletes",
"Anchor": "Anchor",
"Angle 2": "Angle 2",
"Animate": "Animate",
"App/system information and command settings are included. Review private details before sharing.": "App/system information and command settings are included. Review private details before sharing.",
@@ -47,6 +49,7 @@
"BLEND SURFACE": "BLEND SURFACE",
"BOUNDARY SURFACE": "BOUNDARY SURFACE",
"BROWSER": "BROWSER",
"Bar": "Bar",
"Bend Edges": "Bend Edges",
"Bend Line Position": "Bend Line Position",
"Bend Position": "Bend Position",
@@ -59,6 +62,9 @@
"Body (last if none)": "Body (last if none)",
"Body to split": "Body to split",
"Body, or faces to take out": "Body, or faces to take out",
"Bottom Left": "Bottom Left",
"Bottom Middle": "Bottom Middle",
"Bottom Right": "Bottom Right",
"Boundary": "Boundary",
"Bounding box": "Bounding box",
"CHECK": "CHECK",
@@ -78,7 +84,9 @@
"Center Y": "Center Y",
"Center of mass": "Center of mass",
"Centre to centre": "Centre to centre",
"Centroid": "Centroid",
"Chamfer Type": "Chamfer Type",
"Channel": "Channel",
"Check collisions": "Check collisions",
"Checked": "Checked",
"Choose Variable radius or Spline in Type.": "Choose Variable radius or Spline in Type.",
@@ -113,6 +121,7 @@
"Copy screenshot": "Copy screenshot",
"Corner Relief": "Corner Relief",
"Corner Relief Shape": "Corner Relief Shape",
"Corner radius": "Corner radius",
"Counterbore depth": "Counterbore depth",
"Counterbore Ø": "Counterbore Ø",
"Countersink angle": "Countersink angle",
@@ -200,6 +209,7 @@
"First plane": "First plane",
"Fit and G2 corners require Constant radius.": "Fit and G2 corners require Constant radius.",
"Fixed Face": "Fixed Face",
"Flange thickness": "Flange thickness",
"Flat Pattern": "Flat Pattern",
"Flat size": "Flat size",
"Follow camera (Look At sketches)": "Follow camera (Look At sketches)",
@@ -222,6 +232,7 @@
"Holes (edges on them)": "Holes (edges on them)",
"Home view": "Home view",
"Horiz./Vert.": "Horiz./Vert.",
"I-Beam": "I-Beam",
"IMAGES": "IMAGES",
"Import…": "Import…",
"In This Design": "In This Design",
@@ -242,10 +253,12 @@
"Keep of the other surface": "Keep of the other surface",
"Key a joint's value at this step": "Key a joint's value at this step",
"Keys": "Keys",
"L-Angle": "L-Angle",
"LIBRARY": "LIBRARY",
"LINKS": "LINKS",
"Later": "Later",
"Leave it": "Leave it",
"Left Middle": "Left Middle",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "Legacy face attachment. Rebinding to a certified face creates an exact attachment.",
"Length": "Length",
"Length units": "Length units",
@@ -255,6 +268,7 @@
"Limits": "Limits",
"Line Spacing": "Line Spacing",
"Line Type": "Line Type",
"Lines": "Lines",
"Listing the installed fonts…": "Listing the installed fonts…",
"Load library": "Load library",
"Local library": "Local library",
@@ -319,6 +333,7 @@
"Orbit (right drag)": "Orbit (right drag)",
"Other side": "Other side",
"Other surface (mutual trim)": "Other surface (mutual trim)",
"Outer radius": "Outer radius",
"Outside": "Outside",
"Overall length": "Overall length",
"Param. Graph": "Param. Graph",
@@ -361,6 +376,7 @@
"Recover": "Recover",
"Recover unsaved design?": "Recover unsaved design?",
"Rectangular": "Rectangular",
"Rectangular Tube": "Rectangular Tube",
"Reference face": "Reference face",
"Remove Tools": "Remove Tools",
"Remove condition": "Remove condition",
@@ -398,11 +414,15 @@
"Rib Offset": "Rib Offset",
"Rib Thickness": "Rib Thickness",
"Ribs": "Ribs",
"Right Middle": "Right Middle",
"Rim Edge": "Rim Edge",
"Ring of tools on the right button": "Ring of tools on the right button",
"Roll Back Here": "Roll Back Here",
"Roll History Marker Here": "Roll History Marker Here",
"Root radius": "Root radius",
"Round": "Round",
"Round Bar": "Round Bar",
"Round Tube": "Round Tube",
"Rule": "Rule",
"Rule name": "Rule name",
"Rules run from top to bottom. Matched drives change effective values.": "Rules run from top to bottom. Matched drives change effective values.",
@@ -421,6 +441,7 @@
"Search this library": "Search this library",
"Second plane": "Second plane",
"Section": "Section",
"Section (optional)": "Section (optional)",
"Sections (one sketch each)": "Sections (one sketch each)",
"Select Other": "Select Other",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).",
@@ -492,11 +513,15 @@
"To": "To",
"To Offset": "To Offset",
"To edges": "To edges",
"Toe radius": "Toe radius",
"Tolerance": "Tolerance",
"Too close": "Too close",
"Tool Bodies": "Tool Bodies",
"Tools": "Tools",
"Tools, clockwise from the top": "Tools, clockwise from the top",
"Top Left": "Top Left",
"Top Middle": "Top Middle",
"Top Right": "Top Right",
"Trimming tool (plane, face or curves)": "Trimming tool (plane, face or curves)",
"Turn off section analysis before exporting the view.": "Turn off section analysis before exporting the view.",
"Type": "Type",
@@ -521,6 +546,7 @@
"Wall": "Wall",
"Wall Location": "Wall Location",
"Wall Thickness": "Wall Thickness",
"Web thickness": "Web thickness",
"What did you do just before the problem? A short list is enough": "What did you do just before the problem? A short list is enough",
"What did you expect to see?": "What did you expect to see?",
"What happened?": "What happened?",
@@ -689,6 +715,10 @@
"cmd.file_insert_step": "Insert STEP",
"cmd.file_save_mesh": "Save As Mesh",
"cmd.file_slicers": "Installed Slicers",
"cmd.frame_member": "Frame Member",
"cmd.frame_profile_insert": "Insert Profile",
"cmd.frame_profile_list": "Profile Library",
"cmd.frame_profile_properties": "Profile Properties",
"cmd.inspect_accessibility": "Accessibility Analysis",
"cmd.inspect_center_of_mass": "Center of Mass",
"cmd.inspect_clearance": "Clearance",
@@ -1008,6 +1038,7 @@
"file_load.stopping": "Waiting for the previous operation to stop...",
"file_load.waiting": "Waiting for file operation",
"fits the face, e.g. M8": "fits the face, e.g. M8",
"from the profile": "from the profile",
"from the rule": "from the rule",
"help.apache": "Apache licence 2.0",
"help.attributions": "Attributions (ATTRIBUTION.md)",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Insertar STEP",
"cmd.file_save_mesh": "Guardar como malla",
"cmd.file_slicers": "Laminadores instalados",
"cmd.frame_member": "Miembro estructural",
"cmd.frame_profile_insert": "Insertar perfil",
"cmd.frame_profile_list": "Biblioteca de perfiles",
"cmd.frame_profile_properties": "Propiedades del perfil",
"cmd.inspect_accessibility": "Análisis de accesibilidad",
"cmd.inspect_center_of_mass": "Centro de masas",
"cmd.inspect_clearance": "Holgura",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Insérer un STEP",
"cmd.file_save_mesh": "Enregistrer comme maillage",
"cmd.file_slicers": "Slicers installés",
"cmd.frame_member": "Élément de structure",
"cmd.frame_profile_insert": "Insérer un profilé",
"cmd.frame_profile_list": "Bibliothèque de profilés",
"cmd.frame_profile_properties": "Propriétés du profilé",
"cmd.inspect_accessibility": "Analyse d'accessibilité",
"cmd.inspect_center_of_mass": "Centre de gravité",
"cmd.inspect_clearance": "Jeu",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Inserir STEP",
"cmd.file_save_mesh": "Gardar como malla",
"cmd.file_slicers": "Laminadores instalados",
"cmd.frame_member": "Membro estrutural",
"cmd.frame_profile_insert": "Inserir perfil",
"cmd.frame_profile_list": "Biblioteca de perfís",
"cmd.frame_profile_properties": "Propiedades do perfil",
"cmd.inspect_accessibility": "Análise de accesibilidade",
"cmd.inspect_center_of_mass": "Centro de masas",
"cmd.inspect_clearance": "Folga",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "STEP beszúrása",
"cmd.file_save_mesh": "Mentés hálóként",
"cmd.file_slicers": "Telepített szeletelők",
"cmd.frame_member": "Szerkezeti elem",
"cmd.frame_profile_insert": "Profil beszúrása",
"cmd.frame_profile_list": "Profilkönyvtár",
"cmd.frame_profile_properties": "Profil tulajdonságai",
"cmd.inspect_accessibility": "Hozzáférhetőség-elemzés",
"cmd.inspect_center_of_mass": "Tömegközéppont",
"cmd.inspect_clearance": "Hézag",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "Sisipkan STEP",
"cmd.file_save_mesh": "Simpan Sebagai Mesh",
"cmd.file_slicers": "Slicer Terpasang",
"cmd.frame_member": "Batang Rangka",
"cmd.frame_profile_insert": "Sisipkan Profil",
"cmd.frame_profile_list": "Pustaka Profil",
"cmd.frame_profile_properties": "Properti Profil",
"cmd.inspect_accessibility": "Analisis Aksesibilitas",
"cmd.inspect_center_of_mass": "Pusat Massa",
"cmd.inspect_clearance": "Kelonggaran",
+4
View File
@@ -533,6 +533,10 @@
"cmd.file_insert_step": "Inserisci STEP",
"cmd.file_save_mesh": "Salva come mesh",
"cmd.file_slicers": "Slicer installati",
"cmd.frame_member": "Membro strutturale",
"cmd.frame_profile_insert": "Inserisci profilo",
"cmd.frame_profile_list": "Libreria profili",
"cmd.frame_profile_properties": "Proprietà del profilo",
"cmd.inspect_accessibility": "Analisi di accessibilità",
"cmd.inspect_center_of_mass": "Centro di massa",
"cmd.inspect_clearance": "Distanza libera",
+31
View File
@@ -25,11 +25,13 @@
"Advanced": "詳細",
"Against": "相手",
"Alignment": "配置",
"All Lines": "すべての線分",
"All Sketch Points": "すべてのスケッチ点",
"All components": "すべてのコンポーネント",
"All open designs": "すべての開いているデザイン",
"Allowed expressions, separated by semicolons": "使用可能な式(セミコロンで区切る)",
"Also deletes": "同時に削除される要素:",
"Anchor": "基準点",
"Angle 2": "角度 2",
"Animate": "アニメーション",
"App/system information and command settings are included. Review private details before sharing.": "アプリ・システム情報とコマンド設定が含まれます。共有前に非公開の情報を確認してください。",
@@ -47,6 +49,7 @@
"BLEND SURFACE": "ブレンドサーフェス",
"BOUNDARY SURFACE": "境界サーフェス",
"BROWSER": "ブラウザ",
"Bar": "平鋼",
"Bend Edges": "曲げエッジ",
"Bend Line Position": "曲げ線位置",
"Bend Position": "曲げ位置",
@@ -59,6 +62,9 @@
"Body (last if none)": "ボディ (未指定時は最後)",
"Body to split": "分割するボディ",
"Body, or faces to take out": "ボディ、または取り除く面",
"Bottom Left": "左下",
"Bottom Middle": "下中央",
"Bottom Right": "右下",
"Boundary": "境界",
"Bounding box": "境界ボックス",
"CHECK": "チェック",
@@ -78,7 +84,9 @@
"Center Y": "中心 Y",
"Center of mass": "重心",
"Centre to centre": "中心間",
"Centroid": "図心",
"Chamfer Type": "面取りタイプ",
"Channel": "溝形鋼",
"Check collisions": "衝突チェック",
"Checked": "チェック済み",
"Choose Variable radius or Spline in Type.": "タイプで Variable radius またはスプラインを選択してください。",
@@ -113,6 +121,7 @@
"Copy screenshot": "スクリーンショットをコピー",
"Corner Relief": "コーナーリリーフ",
"Corner Relief Shape": "コーナーリリーフ形状",
"Corner radius": "コーナー半径",
"Counterbore depth": "座ぐり深さ",
"Counterbore Ø": "座ぐり Ø",
"Countersink angle": "皿穴角度",
@@ -200,6 +209,7 @@
"First plane": "第1平面",
"Fit and G2 corners require Constant radius.": "フィットと G2 コーナーには Constant radius が必要です。",
"Fixed Face": "固定面",
"Flange thickness": "フランジ厚",
"Flat Pattern": "フラットパターン",
"Flat size": "展開サイズ",
"Follow camera (Look At sketches)": "カメラ追従(スケッチを正面視)",
@@ -222,6 +232,7 @@
"Holes (edges on them)": "穴(そのエッジ)",
"Home view": "ホームビュー",
"Horiz./Vert.": "水平 / 垂直",
"I-Beam": "I形鋼",
"IMAGES": "画像",
"Import…": "読み込み…",
"In This Design": "このデザイン内",
@@ -242,10 +253,12 @@
"Keep of the other surface": "相手のサーフェスで残す部分",
"Key a joint's value at this step": "このステップでジョイントの値をキー設定",
"Keys": "キー",
"L-Angle": "山形鋼",
"LIBRARY": "ライブラリ",
"LINKS": "リンク",
"Later": "後で",
"Leave it": "そのままにする",
"Left Middle": "左中央",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "従来の面アタッチメントです。確定された面に再バインドすると正確なアタッチメントが作成されます。",
"Length": "長さ",
"Length units": "長さの単位",
@@ -255,6 +268,7 @@
"Limits": "制限",
"Line Spacing": "行間",
"Line Type": "線種",
"Lines": "線分",
"Listing the installed fonts…": "インストール済みフォントを一覧表示中…",
"Load library": "ライブラリを読み込む",
"Local library": "ローカルライブラリ",
@@ -319,6 +333,7 @@
"Orbit (right drag)": "回転(右ドラッグ)",
"Other side": "反対側",
"Other surface (mutual trim)": "相手のサーフェス(相互トリム)",
"Outer radius": "外側コーナー半径",
"Outside": "外側",
"Overall length": "全長",
"Param. Graph": "パラメータ図",
@@ -361,6 +376,7 @@
"Recover": "復元",
"Recover unsaved design?": "未保存のデザインを復元しますか?",
"Rectangular": "長方形",
"Rectangular Tube": "角形鋼管",
"Reference face": "参照面",
"Remove Tools": "ツールボディを削除",
"Remove condition": "条件を削除",
@@ -398,11 +414,15 @@
"Rib Offset": "リブのオフセット",
"Rib Thickness": "リブの厚さ",
"Ribs": "リブ",
"Right Middle": "右中央",
"Rim Edge": "リムエッジ",
"Ring of tools on the right button": "右ボタンのツールリング",
"Roll Back Here": "ここまでロールバック",
"Roll History Marker Here": "履歴マーカーをここに移動",
"Root radius": "付け根半径",
"Round": "丸め",
"Round Bar": "丸鋼",
"Round Tube": "丸形鋼管",
"Rule": "ルール",
"Rule name": "ルール名",
"Rules run from top to bottom. Matched drives change effective values.": "ルールは上から順に実行されます。条件に一致する駆動ルールが有効値を変更します。",
@@ -421,6 +441,7 @@
"Search this library": "このライブラリを検索",
"Second plane": "第2平面",
"Section": "断面",
"Section (optional)": "断面(任意)",
"Sections (one sketch each)": "セクション (各1スケッチ)",
"Select Other": "その他を選択",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "その他を選択: モデル上で左ボタンを長押し(または右クリック › その他を選択…)するとカーソル下の要素が一覧表示されます。同じ場所を再度クリックすると次の要素が選択されます。中ボタンをダブルクリックするとホームビューに戻ります(環境設定 › ナビゲーション)。",
@@ -492,11 +513,15 @@
"To": "終了",
"To Offset": "オフセットまで",
"To edges": "終了側エッジ",
"Toe radius": "先端半径",
"Tolerance": "公差",
"Too close": "近すぎる",
"Tool Bodies": "ツールボディ",
"Tools": "ツール",
"Tools, clockwise from the top": "上から時計回りにツール",
"Top Left": "左上",
"Top Middle": "上中央",
"Top Right": "右上",
"Trimming tool (plane, face or curves)": "トリムツール(平面、面、または曲線)",
"Turn off section analysis before exporting the view.": "断面解析をオフにしてからエクスポートしてください。",
"Type": "タイプ",
@@ -521,6 +546,7 @@
"Wall": "肉厚",
"Wall Location": "壁の位置",
"Wall Thickness": "壁の厚さ",
"Web thickness": "ウェブ厚",
"What did you do just before the problem? A short list is enough": "問題の直前に行った操作を簡単に記入してください",
"What did you expect to see?": "どのような結果を期待していましたか?",
"What happened?": "何が起きましたか?",
@@ -689,6 +715,10 @@
"cmd.file_insert_step": "STEP を挿入",
"cmd.file_save_mesh": "メッシュとして保存",
"cmd.file_slicers": "インストール済みのスライサー",
"cmd.frame_member": "フレーム部材",
"cmd.frame_profile_insert": "形材を挿入",
"cmd.frame_profile_list": "形材ライブラリ",
"cmd.frame_profile_properties": "形材のプロパティ",
"cmd.inspect_accessibility": "アクセシビリティ解析",
"cmd.inspect_center_of_mass": "重心",
"cmd.inspect_clearance": "クリアランス",
@@ -1008,6 +1038,7 @@
"file_load.stopping": "前の操作の停止を待っています...",
"file_load.waiting": "ファイル操作を待っています",
"fits the face, e.g. M8": "面に適合するサイズ (例: M8)",
"from the profile": "形材から",
"from the rule": "ルールから",
"help.apache": "Apacheライセンス2.0",
"help.attributions": "帰属表示 (ATTRIBUTION.md)",
+4
View File
@@ -531,6 +531,10 @@
"cmd.file_insert_step": "STEP 삽입",
"cmd.file_save_mesh": "메쉬로 저장",
"cmd.file_slicers": "설치된 슬라이서",
"cmd.frame_member": "프레임 부재",
"cmd.frame_profile_insert": "프로파일 삽입",
"cmd.frame_profile_list": "프로파일 라이브러리",
"cmd.frame_profile_properties": "프로파일 속성",
"cmd.inspect_accessibility": "접근성 분석",
"cmd.inspect_center_of_mass": "무게중심",
"cmd.inspect_clearance": "여유 간격",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Sisip STEP",
"cmd.file_save_mesh": "Simpan sebagai Mesh",
"cmd.file_slicers": "Penghiris Terpasang",
"cmd.frame_member": "Anggota Rangka",
"cmd.frame_profile_insert": "Sisipkan Profil",
"cmd.frame_profile_list": "Pustaka Profil",
"cmd.frame_profile_properties": "Sifat Profil",
"cmd.inspect_accessibility": "Analisis Kebolehcapaian",
"cmd.inspect_center_of_mass": "Pusat Jisim",
"cmd.inspect_clearance": "Kelegaan",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "STEP invoegen",
"cmd.file_save_mesh": "Opslaan als mesh",
"cmd.file_slicers": "Geïnstalleerde slicers",
"cmd.frame_member": "Constructiedeel",
"cmd.frame_profile_insert": "Profiel invoegen",
"cmd.frame_profile_list": "Profielbibliotheek",
"cmd.frame_profile_properties": "Profieleigenschappen",
"cmd.inspect_accessibility": "Toegankelijkheidsanalyse",
"cmd.inspect_center_of_mass": "Zwaartepunt",
"cmd.inspect_clearance": "Speling",
+4
View File
@@ -578,6 +578,10 @@
"cmd.file_insert_step": "Wstaw STEP",
"cmd.file_save_mesh": "Zapisz jako siatkę",
"cmd.file_slicers": "Zainstalowane slicery",
"cmd.frame_member": "Element ramy",
"cmd.frame_profile_insert": "Wstaw profil",
"cmd.frame_profile_list": "Biblioteka profili",
"cmd.frame_profile_properties": "Właściwości profilu",
"cmd.inspect_accessibility": "Analiza dostępności",
"cmd.inspect_center_of_mass": "Środek masy",
"cmd.inspect_clearance": "Prześwit",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Inserir STEP",
"cmd.file_save_mesh": "Salvar como malha",
"cmd.file_slicers": "Fatiadores instalados",
"cmd.frame_member": "Membro estrutural",
"cmd.frame_profile_insert": "Inserir perfil",
"cmd.frame_profile_list": "Biblioteca de perfis",
"cmd.frame_profile_properties": "Propriedades do perfil",
"cmd.inspect_accessibility": "Análise de acessibilidade",
"cmd.inspect_center_of_mass": "Centro de massa",
"cmd.inspect_clearance": "Folga",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "Inserează STEP",
"cmd.file_save_mesh": "Salvează ca plasă",
"cmd.file_slicers": "Slicere instalate",
"cmd.frame_member": "Element de cadru",
"cmd.frame_profile_insert": "Inserare profil",
"cmd.frame_profile_list": "Bibliotecă de profile",
"cmd.frame_profile_properties": "Proprietăți profil",
"cmd.inspect_accessibility": "Analiza accesibilității",
"cmd.inspect_center_of_mass": "Centru de masă",
"cmd.inspect_clearance": "Joc",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "Вставить STEP",
"cmd.file_save_mesh": "Сохранить как меш",
"cmd.file_slicers": "Установленные слайсеры",
"cmd.frame_member": "Элемент рамы",
"cmd.frame_profile_insert": "Вставить профиль",
"cmd.frame_profile_list": "Библиотека профилей",
"cmd.frame_profile_properties": "Свойства профиля",
"cmd.inspect_accessibility": "Анализ доступности",
"cmd.inspect_center_of_mass": "Центр масс",
"cmd.inspect_clearance": "Зазор",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "Infoga STEP",
"cmd.file_save_mesh": "Spara som mesh",
"cmd.file_slicers": "Installerade slicers",
"cmd.frame_member": "Ramdel",
"cmd.frame_profile_insert": "Infoga profil",
"cmd.frame_profile_list": "Profilbibliotek",
"cmd.frame_profile_properties": "Profilegenskaper",
"cmd.inspect_accessibility": "Tillgänglighetsanalys",
"cmd.inspect_center_of_mass": "Masscentrum",
"cmd.inspect_clearance": "Frigång",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "STEP ekle",
"cmd.file_save_mesh": "Ağ olarak kaydet",
"cmd.file_slicers": "Yüklü dilimleyiciler",
"cmd.frame_member": "Çerçeve Elemanı",
"cmd.frame_profile_insert": "Profil Ekle",
"cmd.frame_profile_list": "Profil Kitaplığı",
"cmd.frame_profile_properties": "Profil Özellikleri",
"cmd.inspect_accessibility": "Erişilebilirlik analizi",
"cmd.inspect_center_of_mass": "Kütle merkezi",
"cmd.inspect_clearance": "Açıklık",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Вставити STEP",
"cmd.file_save_mesh": "Зберегти як сітку",
"cmd.file_slicers": "Встановлені слайсери",
"cmd.frame_member": "Елемент рами",
"cmd.frame_profile_insert": "Вставити профіль",
"cmd.frame_profile_list": "Бібліотека профілів",
"cmd.frame_profile_properties": "Властивості профілю",
"cmd.inspect_accessibility": "Аналіз доступності",
"cmd.inspect_center_of_mass": "Центр мас",
"cmd.inspect_clearance": "Зазор",
+4
View File
@@ -530,6 +530,10 @@
"cmd.file_insert_step": "Chèn tệp STEP",
"cmd.file_save_mesh": "Lưu dưới dạng lưới đa giác",
"cmd.file_slicers": "Phần mềm cắt lớp đã cài đặt",
"cmd.frame_member": "Thanh khung",
"cmd.frame_profile_insert": "Chèn tiết diện",
"cmd.frame_profile_list": "Thư viện tiết diện",
"cmd.frame_profile_properties": "Thuộc tính tiết diện",
"cmd.inspect_accessibility": "Phân tích khả năng gia công tiếp cận",
"cmd.inspect_center_of_mass": "Trọng tâm",
"cmd.inspect_clearance": "Khoảng cách an toàn",
+4
View File
@@ -529,6 +529,10 @@
"cmd.file_insert_step": "插入 STEP",
"cmd.file_save_mesh": "另存為網格",
"cmd.file_slicers": "已安裝的切片軟體",
"cmd.frame_member": "框架構件",
"cmd.frame_profile_insert": "插入型材",
"cmd.frame_profile_list": "型材庫",
"cmd.frame_profile_properties": "型材屬性",
"cmd.inspect_accessibility": "可達性分析",
"cmd.inspect_center_of_mass": "質心",
"cmd.inspect_clearance": "間隙",
+31
View File
@@ -25,11 +25,13 @@
"Advanced": "高级",
"Against": "对照",
"Alignment": "对齐",
"All Lines": "所有直线",
"All Sketch Points": "所有草图点",
"All components": "所有零部件",
"All open designs": "所有打开的设计",
"Allowed expressions, separated by semicolons": "允许的表达式,以分号分隔",
"Also deletes": "同时删除",
"Anchor": "基准点",
"Angle 2": "角度 2",
"Animate": "动画",
"App/system information and command settings are included. Review private details before sharing.": "报告包含应用和系统信息以及命令设置。共享前请检查私人信息。",
@@ -47,6 +49,7 @@
"BLEND SURFACE": "混合曲面",
"BOUNDARY SURFACE": "边界曲面",
"BROWSER": "浏览器",
"Bar": "扁钢",
"Bend Edges": "折弯边",
"Bend Line Position": "弯折线位置",
"Bend Position": "折弯位置",
@@ -59,6 +62,9 @@
"Body (last if none)": "实体(未指定时为最后一个)",
"Body to split": "要分割的实体",
"Body, or faces to take out": "实体,或要移除的面",
"Bottom Left": "左下",
"Bottom Middle": "下中",
"Bottom Right": "右下",
"Boundary": "边界",
"Bounding box": "边界框",
"CHECK": "检查",
@@ -78,7 +84,9 @@
"Center Y": "中心 Y",
"Center of mass": "质心",
"Centre to centre": "中心距",
"Centroid": "形心",
"Chamfer Type": "倒角类型",
"Channel": "槽钢",
"Check collisions": "检查碰撞",
"Checked": "已检查",
"Choose Variable radius or Spline in Type.": "请在“类型”中选择 Variable radius 或样条曲线。",
@@ -113,6 +121,7 @@
"Copy screenshot": "复制截图",
"Corner Relief": "拐角释放",
"Corner Relief Shape": "拐角释放形状",
"Corner radius": "圆角半径",
"Counterbore depth": "沉孔深度",
"Counterbore Ø": "柱形沉孔 Ø",
"Countersink angle": "沉头角度",
@@ -200,6 +209,7 @@
"First plane": "第一个平面",
"Fit and G2 corners require Constant radius.": "拟合和 G2 拐角需要 Constant radius。",
"Fixed Face": "固定面",
"Flange thickness": "翼缘厚度",
"Flat Pattern": "展开图",
"Flat size": "平板尺寸",
"Follow camera (Look At sketches)": "跟随相机(注视草图)",
@@ -222,6 +232,7 @@
"Holes (edges on them)": "孔(孔上的边)",
"Home view": "主视图",
"Horiz./Vert.": "水平 / 垂直",
"I-Beam": "工字钢",
"IMAGES": "图像",
"Import…": "导入…",
"In This Design": "在此设计中",
@@ -242,10 +253,12 @@
"Keep of the other surface": "另一曲面保留的部分",
"Key a joint's value at this step": "在此步骤为接头值设置关键帧",
"Keys": "关键帧",
"L-Angle": "角钢",
"LIBRARY": "库",
"LINKS": "链接",
"Later": "稍后",
"Leave it": "保持原样",
"Left Middle": "左中",
"Legacy face attachment. Rebinding to a certified face creates an exact attachment.": "旧版面附着。重新绑定到经验证的面可创建精确附着。",
"Length": "长度",
"Length units": "长度单位",
@@ -255,6 +268,7 @@
"Limits": "限制",
"Line Spacing": "行间距",
"Line Type": "线型",
"Lines": "直线",
"Listing the installed fonts…": "正在列出已安装字体…",
"Load library": "加载库",
"Local library": "本地库",
@@ -319,6 +333,7 @@
"Orbit (right drag)": "旋转(右键拖动)",
"Other side": "另一侧",
"Other surface (mutual trim)": "另一曲面(相互修剪)",
"Outer radius": "外圆角半径",
"Outside": "外侧",
"Overall length": "总长",
"Param. Graph": "参数图",
@@ -361,6 +376,7 @@
"Recover": "恢复",
"Recover unsaved design?": "恢复未保存的设计?",
"Rectangular": "矩形",
"Rectangular Tube": "矩形管",
"Reference face": "参考面",
"Remove Tools": "移除工具",
"Remove condition": "删除条件",
@@ -398,11 +414,15 @@
"Rib Offset": "筋板偏移",
"Rib Thickness": "筋板厚度",
"Ribs": "筋板",
"Right Middle": "右中",
"Rim Edge": "轮缘边",
"Ring of tools on the right button": "右键工具环",
"Roll Back Here": "回滚到此处",
"Roll History Marker Here": "将历史标记滚动到此处",
"Root radius": "根部圆角半径",
"Round": "圆角",
"Round Bar": "圆钢",
"Round Tube": "圆管",
"Rule": "规则",
"Rule name": "规则名称",
"Rules run from top to bottom. Matched drives change effective values.": "规则从上到下依次运行。满足条件的驱动规则更改有效值。",
@@ -421,6 +441,7 @@
"Search this library": "搜索此库",
"Second plane": "第二个平面",
"Section": "剖面",
"Section (optional)": "截面(可选)",
"Sections (one sketch each)": "截面(每个一个草图)",
"Select Other": "选择其他",
"Select Other: hold the left button still on the model (or right-click › Select Other…) to list everything under the cursor; click again on the same spot to select the next thing there. Double-click the middle button to go Home (Preferences › Navigation).": "“选择其他”:在模型上按住左键(或右键单击 › 选择其他…)列出光标下的所有对象;在同一位置再次单击可选择该处的下一个对象。双击中键转到主视图(首选项 › 导航)。",
@@ -492,11 +513,15 @@
"To": "终点",
"To Offset": "偏移",
"To edges": "终止边",
"Toe radius": "肢端圆角半径",
"Tolerance": "公差",
"Too close": "过近",
"Tool Bodies": "工具实体",
"Tools": "工具",
"Tools, clockwise from the top": "工具,从顶部顺时针排列",
"Top Left": "左上",
"Top Middle": "上中",
"Top Right": "右上",
"Trimming tool (plane, face or curves)": "修剪工具(平面、面或曲线)",
"Turn off section analysis before exporting the view.": "请关闭截面分析后再导出视图。",
"Type": "类型",
@@ -521,6 +546,7 @@
"Wall": "壁厚",
"Wall Location": "壁位置",
"Wall Thickness": "壁厚度",
"Web thickness": "腹板厚度",
"What did you do just before the problem? A short list is enough": "问题发生前您进行了哪些操作?简要列出即可",
"What did you expect to see?": "您期望看到什么结果?",
"What happened?": "发生了什么?",
@@ -689,6 +715,10 @@
"cmd.file_insert_step": "插入 STEP",
"cmd.file_save_mesh": "另存为网格",
"cmd.file_slicers": "已安装的切片软件",
"cmd.frame_member": "框架构件",
"cmd.frame_profile_insert": "插入型材",
"cmd.frame_profile_list": "型材库",
"cmd.frame_profile_properties": "型材属性",
"cmd.inspect_accessibility": "可达性分析",
"cmd.inspect_center_of_mass": "质心",
"cmd.inspect_clearance": "间隙",
@@ -1008,6 +1038,7 @@
"file_load.stopping": "正在等待上一次操作停止...",
"file_load.waiting": "正在等待文件操作",
"fits the face, e.g. M8": "适配该面,例如 M8",
"from the profile": "取自型材",
"from the rule": "来自规则",
"help.apache": "Apache 许可证 2.0",
"help.attributions": "署名信息 (ATTRIBUTION.md)",
+31 -1
View File
@@ -898,6 +898,34 @@ pub enum FeatureKind {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
targets: Vec<BodyName>,
},
/// Structural members (#4003): one body per straight line of a frame sketch (2D sketch lines
/// and 3D sketch lines), its cross-section the profile, square to the line from end to end.
FrameMember {
path_sketch: SketchId,
/// The lines, by curve id; none: every straight line drawn in the sketch (not
/// construction, not projected or otherwise linked, not of no length).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
lines: Vec<String>,
profile: crate::frame::MemberProfile,
/// The profile point that sits on the line.
#[serde(default, skip_serializing_if = "crate::frame::Anchor::is_origin")]
anchor: crate::frame::Anchor,
/// How far the profile turns about the line (see `frame::member_axes`).
#[serde(default, skip_serializing_if = "Option::is_none")]
#[walk(angle = "Rotation")]
angle: Option<Expr>,
/// The profile mirrored across its y axis (before it turns).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
mirror: bool,
/// What members without a name of their own are named after (`Rail`, `Rail (2)`...); none:
/// the profile's description (`Rect Tube 40x40x3`) or the profile sketch's name.
#[serde(default, skip_serializing_if = "Option::is_none")]
body_name: Option<String>,
/// Each member's body name, by its line's id, so a member keeps its name when other lines
/// come and go (`frame::member_names`).
#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
names: std::collections::BTreeMap<String, String>,
},
/// Raise or sink profiles on a planar face, or wrap them on a selected cylindrical wall.
Emboss {
sketch: SketchId,
@@ -2176,6 +2204,7 @@ impl FeatureKind {
FeatureKind::SurfaceOffset { .. } => "OffsetSurfaceFeature",
FeatureKind::BoundingSolid { .. } => "BoundingSolidFeature",
FeatureKind::Pipe { .. } => "PipeFeature",
FeatureKind::FrameMember { .. } => "FrameMemberFeature",
FeatureKind::Emboss { .. } => "EmbossFeature",
FeatureKind::Boss { .. } => "BossFeature",
FeatureKind::Lip { groove: false, .. } => "LipFeature",
@@ -2256,6 +2285,7 @@ impl FeatureKind {
FeatureKind::SurfaceOffset { .. } => "OffsetSurface",
FeatureKind::BoundingSolid { .. } => "BoundingSolid",
FeatureKind::Pipe { .. } => "Pipe",
FeatureKind::FrameMember { .. } => "Member",
FeatureKind::Emboss { .. } => "Emboss",
FeatureKind::Boss { .. } => "Boss",
FeatureKind::Lip { groove: false, .. } => "Lip",
@@ -2353,7 +2383,7 @@ fn inside_str() -> String {
"inside".into()
}
fn all_profiles() -> ProfileSel {
pub(crate) fn all_profiles() -> ProfileSel {
ProfileSel::All
}
+7 -1
View File
@@ -1476,6 +1476,7 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64
FeatureKind::Sweep { path_sketch, .. }
| FeatureKind::SurfaceSweep { path_sketch, .. }
| FeatureKind::Pipe { path_sketch, .. }
| FeatureKind::FrameMember { path_sketch, .. }
| FeatureKind::Pattern { pattern: crate::PatternKind::Path { path_sketch, .. }, .. } => Some(*path_sketch),
_ => None,
};
@@ -1487,7 +1488,9 @@ fn placement_digest(doc: &Document, f: &Feature, st: Option<&ModelState>) -> u64
| FeatureKind::SurfaceLoft { rails, .. } => rails,
_ => &[],
};
if path.as_ref().is_some_and(wired) || rails.iter().any(|r| wired(&r.sketch)) {
// Members map their frame sketch into their own component's frame, 2D lines included.
let member = matches!(f.kind, FeatureKind::FrameMember { .. });
if path.as_ref().is_some_and(|p| member || wired(p)) || rails.iter().any(|r| wired(&r.sketch)) {
if let Some(path) = path {
reads.sketch(doc, path.0);
}
@@ -5515,6 +5518,8 @@ mod model_cache;
#[path = "eval_more.rs"]
mod more;
pub use model_cache::SavedModel;
#[path = "eval_frame.rs"]
pub(crate) mod frame_member;
#[path = "eval_surface.rs"]
mod surface;
@@ -6583,6 +6588,7 @@ fn eval_feature(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st:
}
Ok(())
}
FeatureKind::FrameMember { .. } => frame_member::evaluate(doc, vals, f, st),
FeatureKind::BoundingSolid { bodies, margin } => {
let m = val(vals, margin, Kind::Length)?;
let mut bb = solidcraft_geom::Aabb3::EMPTY;
+243
View File
@@ -0,0 +1,243 @@
//! Frame members (#4003): one body per straight line of a frame sketch, its cross-section a
//! profile laid square to the line (`frame::member_axes`) and run from one end to the other.
use std::borrow::Cow;
use std::collections::{BTreeMap, HashSet};
use solidcraft_geom::{Aabb2, Plane, Region2, Ring, Vec2, Vec3};
use solidcraft_kernel as kernel;
use solidcraft_sketch::CurveKind;
use super::{ModelBody, ModelState, SolvedSketch, new_name, path_in_frame, select_profiles, sketch_in_feature_frame, val};
use crate::expr::{Kind, Value};
use crate::frame::{self, MAX_MEMBERS, MemberProfile};
use crate::{DocError, Document, Feature, FeatureKind, ProfileSel, Result};
/// Most profiles a profile sketch may have for its material to be worked out.
const MAX_PROFILE_PIECES: usize = 256;
/// Shortest member (mm).
const MIN_LENGTH: f64 = 1e-6;
/// How far (mm) a 3D sketch curve may stray from the line between its ends and still be a line.
const STRAIGHT_TOL: f64 = 1e-3;
/// Evaluate a `FrameMember` feature: one new body per line, each named
/// ([`member_names`], or by position for a copy whose `body_names` were set).
pub(super) fn evaluate(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature, st: &mut ModelState) -> Result<()> {
let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, body_name, names } = &f.kind else {
return Err(DocError::Invalid("not a frame member feature".into()));
};
let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch} (it must come earlier in the timeline)")))?;
// The frame sketch in this feature's component frame: its plane, and its 3D lines.
let mapped =
if ps.sketch.wires.is_empty() { Cow::Owned(sketch_in_feature_frame(doc, ps, f.component)?) } else { path_in_frame(doc, ps, f.component)? };
let segments = member_lines(mapped.as_ref(), lines)?;
let (mut regions, description) = profile_regions(vals, st, profile)?;
if *mirror {
regions = regions.iter().map(frame::mirrored).collect();
}
let at = frame::anchor_point(&regions, *anchor);
let turn = match angle {
Some(e) => val(vals, e, Kind::Angle)?,
None => 0.0,
};
let mut made = Vec::with_capacity(segments.len());
for (id, a, b) in &segments {
let (x, y) = frame::member_axes(*b - *a, turn).ok_or_else(|| DocError::Invalid(format!("line `{id}` has no length")))?;
let plane = Plane::new(*a - x * at.x - y * at.y, x, y).ok_or_else(|| DocError::Invalid(format!("line `{id}`: no plane square to it")))?;
let mut bodies = kernel::extrude(&plane, &regions, 0.0, a.dist(*b))?;
let body = match (bodies.pop(), bodies.is_empty()) {
(Some(body), true) => body,
_ => return Err(DocError::Invalid(format!("the member on line `{id}` is not one solid"))),
};
made.push(crate::lineage::numbered_tool(body));
}
if !f.body_names.is_empty() {
// A copy (pasted, or in a copied component) names its members by position, as any
// feature's bodies.
for (k, t) in made.into_iter().enumerate() {
let name = new_name(st, f, k);
st.bodies.push(ModelBody::traced_new(name, t, f.id));
}
return Ok(());
}
let base = body_name.as_deref().map(str::trim).filter(|n| !n.is_empty()).map_or(description, str::to_string);
let ids: Vec<String> = segments.into_iter().map(|(id, _, _)| id).collect();
for (name, t) in member_names(st, &ids, names, &base).into_iter().zip(made) {
st.bodies.push(ModelBody::traced_new(name, t, f.id));
}
Ok(())
}
/// The body name of the member on each of `lines`: its own name from `pinned` (by line id) when no
/// other body has it, else the first free one of `base`, `base (2)`, `base (3)`… that no line has
/// pinned. A member therefore keeps its name when other lines are added, deleted or reordered.
pub fn member_names(st: &ModelState, lines: &[String], pinned: &BTreeMap<String, String>, base: &str) -> Vec<String> {
let reserved: HashSet<&str> = pinned.values().map(String::as_str).collect();
let mut used: HashSet<String> = HashSet::new();
let mut out: Vec<Option<String>> = lines
.iter()
.map(|line| {
let n = pinned.get(line).map(|n| n.trim()).filter(|n| !n.is_empty() && st.body(n).is_none())?;
used.insert(n.to_string()).then(|| n.to_string())
})
.collect();
let base = if base.trim().is_empty() { "Member" } else { base.trim() };
// Each candidate is refused at most once per body, used or reserved name: past that many,
// a free one has been found for every member.
let limit = st.bodies.len() + reserved.len() + lines.len() + 2;
let mut next = 1usize;
for slot in out.iter_mut().filter(|n| n.is_none()) {
while next <= limit {
let candidate = if next == 1 { base.to_string() } else { format!("{base} ({next})") };
next += 1;
if st.body(&candidate).is_none() && !used.contains(&candidate) && !reserved.contains(candidate.as_str()) {
used.insert(candidate.clone());
*slot = Some(candidate);
break;
}
}
}
out.into_iter().map(|n| n.unwrap_or_else(|| base.to_string())).collect()
}
/// The ids of a `FrameMember` feature's lines in `st`, in the order its members are made.
pub fn member_line_ids(st: &ModelState, kind: &FeatureKind) -> Result<Vec<String>> {
let FeatureKind::FrameMember { path_sketch, lines, .. } = kind else {
return Err(DocError::Invalid("not a frame member feature".into()));
};
let ps = st.sketch(path_sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {path_sketch}")))?;
Ok(member_lines(ps, lines)?.into_iter().map(|(id, _, _)| id).collect())
}
/// The member lines of the frame sketch, each as (curve id, start, end) in its frame: the lines
/// asked for, or every straight line drawn in it (not construction, not projected or otherwise
/// linked, and with a length).
fn member_lines(ss: &SolvedSketch, ids: &[String]) -> Result<Vec<(String, Vec3, Vec3)>> {
let sk = &ss.sketch;
let mut out = Vec::new();
if ids.is_empty() {
for (ci, c) in sk.curves.iter().enumerate() {
if !c.construction
&& !c.centerline
&& c.link.is_none()
&& matches!(c.kind, CurveKind::Line { .. })
&& let Some((a, b)) = planar_line(ss, ci)
&& a.dist(b) > MIN_LENGTH
{
out.push((c.id.clone(), a, b));
}
}
for w in sk.wires.iter().filter(|w| w.link.is_none()) {
if let Some((a, b)) = straight(&w.pts)
&& a.dist(b) > MIN_LENGTH
{
out.push((w.id.clone(), a, b));
}
}
if out.is_empty() {
return Err(DocError::Invalid(format!("{} has no lines for members", ss.name)));
}
if out.len() > MAX_MEMBERS {
return Err(DocError::Invalid(format!("at most {MAX_MEMBERS} members in one feature (pick the lines)")));
}
return Ok(out);
}
if ids.len() > MAX_MEMBERS {
return Err(DocError::Invalid(format!("at most {MAX_MEMBERS} members in one feature")));
}
let mut seen = HashSet::new();
for id in ids {
if !seen.insert(id.as_str()) {
return Err(DocError::Invalid(format!("line `{id}` is listed twice")));
}
let line = if let Some(wi) = sk.wire_index(id) {
sk.wires.get(wi).and_then(|w| straight(&w.pts))
} else {
let ci = sk.curve_index(id).ok_or_else(|| DocError::Unknown(format!("line `{id}` in {}", ss.name)))?;
planar_line(ss, ci)
};
let (a, b) = line.ok_or_else(|| DocError::Invalid(format!("`{id}` is not a straight line (members run along lines)")))?;
if !(a.dist(b) > MIN_LENGTH) {
return Err(DocError::Invalid(format!("line `{id}` has no length")));
}
out.push((id.clone(), a, b));
}
Ok(out)
}
/// A sketch line's ends in the sketch's frame.
fn planar_line(ss: &SolvedSketch, ci: usize) -> Option<(Vec3, Vec3)> {
let CurveKind::Line { a, b } = ss.sketch.curves.get(ci)?.kind else { return None };
let (pa, pb) = (ss.sketch.points.get(a)?.pos, ss.sketch.points.get(b)?.pos);
Some((ss.plane.to_world(pa), ss.plane.to_world(pb)))
}
/// The ends of a 3D polyline that runs straight from its first point to its last: every point
/// within [`STRAIGHT_TOL`] of the line between them, none behind the start, past the end or back
/// from a point before it.
fn straight(pts: &[Vec3]) -> Option<(Vec3, Vec3)> {
let (a, b) = (*pts.first()?, *pts.last()?);
let (len, d) = (a.dist(b), (b - a).normalized()?);
let mut reached = 0.0_f64;
for p in pts {
let q = *p - a;
let t = q.dot(d);
if (q - d * t).len() > STRAIGHT_TOL || t < reached - STRAIGHT_TOL || t > len + STRAIGHT_TOL {
return None;
}
reached = reached.max(t);
}
Some((a, b))
}
/// The regions of a member's profile, in the profile's own coordinates: one piece of material,
/// holes and all; and what its members are named after when they have no name of their own.
fn profile_regions(vals: &BTreeMap<String, Value>, st: &ModelState, profile: &MemberProfile) -> Result<(Vec<Region2>, String)> {
let (regions, description) = match profile {
MemberProfile::Library { profile } => {
let p = profile.resolve(|name, e| val(vals, e, Kind::Length).map_err(|err| DocError::Invalid(format!("profile `{name}`: {err}"))))?;
(vec![p.region()?], p.description())
}
MemberProfile::Sketch { sketch, profiles } => {
let ss = st.sketch(sketch.0).ok_or_else(|| DocError::Unknown(format!("sketch {sketch} (it must come earlier in the timeline)")))?;
let picked = match profiles {
ProfileSel::All => material(ss)?,
sel => select_profiles(ss, sel)?,
};
(solidcraft_sketch::merge_regions(&picked), ss.name.clone())
}
};
match regions.len() {
1 => Ok((regions, description)),
0 => Err(DocError::Invalid("the member profile has no area".into())),
n => Err(DocError::Invalid(format!("the member profile is {n} separate pieces (pick one with `profiles`)"))),
}
}
/// The material of a profile sketch: of what was drawn (as `solid.extrude` takes all profiles:
/// projected reference geometry only when the drawn curves make no profile, letters without
/// their counters filled in), each profile inside an even number of other profiles' outlines,
/// so nested loops alternate between material and hole.
fn material(ss: &SolvedSketch) -> Result<Vec<Region2>> {
let drawn = solidcraft_sketch::find_drawn_profiles(&ss.sketch);
let ps = solidcraft_sketch::without_text_counters(&ss.sketch, if drawn.is_empty() { ss.profiles.clone() } else { drawn });
if ps.is_empty() {
return Err(DocError::Invalid(format!("{} has no closed profiles", ss.name)));
}
if ps.len() > MAX_PROFILE_PIECES {
return Err(DocError::Invalid(format!("{} has more than {MAX_PROFILE_PIECES} profiles (pick the member's with `profiles`)", ss.name)));
}
// Outer polylines and their boxes, once.
let polys: Vec<Ring<Vec2>> = ps.iter().map(|p| p.region.outer.polyline(1e-3)).collect();
let boxes: Vec<Aabb2> = polys.iter().map(|poly| poly.bounds()).collect();
Ok(ps
.iter()
.enumerate()
.filter(|(i, p)| {
let at = p.region.interior_point();
let depth = polys.iter().zip(&boxes).enumerate().filter(|(j, (poly, bb))| j != i && bb.contains(at) && poly.contains(at)).count();
depth % 2 == 0
})
.map(|(_, p)| p.region.clone())
.collect())
}
@@ -103,6 +103,16 @@ pub(super) fn fixtures() -> Vec<(&'static str, Value)> {
("delete_face", json!({"type": "delete_face", "faces": [o]})),
("bounding_solid", json!({"type": "bounding_solid", "bodies": ["B"], "margin": "bounding.margin"})),
("pipe", json!({"type": "pipe", "path_sketch": 1, "path": ["l1"], "diameter": "pipe.diameter", "wall": "pipe.wall"})),
(
"frame_member",
json!({"type": "frame_member", "path_sketch": 1, "lines": ["l1"],
"profile": {"source": "library", "profile": {"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}}, "angle": "frame_member.angle"}),
),
(
"frame_member_sketch",
json!({"type": "frame_member", "path_sketch": 1, "profile": {"source": "sketch", "sketch": 2, "profiles": {"type": "all"}},
"anchor": "bottom_left", "mirror": true}),
),
("emboss", json!({"type": "emboss", "sketch": 1, "profiles": {"type": "all"}, "depth": "emboss.depth"})),
("rib", json!({"type": "rib", "sketch": 1, "curves": ["l1"], "thickness": "rib.thickness", "depth": "rib.depth"})),
("replace_face", json!({"type": "replace_face", "faces": [o], "target": plane("replace_face")})),
@@ -212,6 +212,14 @@ pipe
Diameter = pipe.diameter (Length)
Wall = pipe.wall (Length)
expressions: pipe.diameter, pipe.wall
frame_member
inputs:
Height = 40 (Length)
Wall = 3 (Length)
Width = 40 (Length)
Rotation = frame_member.angle (Angle)
expressions: 40, 3, 40, frame_member.angle
frame_member_sketch
emboss
inputs:
Depth = emboss.depth (Length)
@@ -97,6 +97,9 @@ delete_face
face points: [0, 0, 0]
bounding_solid
pipe
frame_member
frame_member_sketch
profiles: 2 all
emboss
face points: [5, 5.5, 5.25]
profiles: 1 all
@@ -104,6 +104,12 @@ pipe
sketches: [1]
remap_refs: path_sketch
remap_bodies: targets[0]
frame_member
sketches: [1]
remap_refs: path_sketch
frame_member_sketch
sketches: [1, 2]
remap_refs: path_sketch, profile.sketch
emboss
sketches: [1]
remap_refs: sketch
@@ -0,0 +1,7 @@
//! A design can hold frame members (#4003): a `frame_member` feature with its frame sketch
//! (`path_sketch`), the `lines` it runs along (none: every straight line drawn in it), its
//! `profile` (a built-in profile by `source: library`, its dimensions saved as expressions, or a
//! profile sketch by `source: sketch`), the profile's `anchor`, `angle` and `mirror`, and its
//! members' names: `body_name` and `names` (each member's body name by its line's id). Older
//! designs need no transformation: they have no such feature. The last release refuses a design
//! saved with this (the newer format number).
+760
View File
@@ -0,0 +1,760 @@
//! Frames: the profile library structural members are made of (#4003).
//!
//! A profile is a closed cross-section, an outline and its holes, built in code from a few
//! dimensions ([`Profile`]). Every built-in profile is SolidCraft's own parametric definition:
//! no vendor's or standard's size table is shipped. A dimension left out takes a default worked
//! out from the others, so `{"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}` is a
//! complete profile. Any other section (a vendor's extrusion, say) comes from a sketch.
//!
//! Features and commands hold a profile as a [`ProfileSpec`]: each dimension an expression over
//! the design's parameters, worked out into a [`Profile`] when the feature is evaluated.
//!
//! Coordinates are millimetres in the profile's own plane, x across and y up, with the centre
//! of the profile's bounding box at the origin. The outline runs counter-clockwise and holes
//! clockwise, as [`Region2`] expects.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use solidcraft_geom::{Loop2, Region2, Seg2, Vec2, Vec3};
use crate::expr::Kind;
use crate::{DocError, Expr, Result};
#[cfg(test)]
#[path = "frame_tests.rs"]
mod tests;
/// Most members one frame member feature makes.
pub const MAX_MEMBERS: usize = 1000;
/// The largest profile dimension (mm).
pub const MAX_PROFILE_SIZE: f64 = 10_000.0;
/// The smallest profile dimension (mm): walls and sides thinner than this are refused, and so
/// are radii smaller than this but not 0.
pub const MIN_PROFILE_DIMENSION: f64 = 0.01;
/// How far from vertical (radians) a member's line may lean and still count as vertical for its
/// orientation ([`member_axes`]).
pub const VERTICAL_TOLERANCE: f64 = 1e-6;
/// A built-in profile and its dimensions (mm). `Option` dimensions take a default worked out from
/// the profile's size ([`Profile::filled`] says which).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Profile {
/// A solid rectangle (flat bar, square bar), its corners optionally rounded.
Bar {
width: f64,
height: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
corner_radius: Option<f64>,
},
/// A solid circle.
RoundBar { diameter: f64 },
/// A rectangular or square hollow section. The outer corner radius defaults to twice the
/// wall; the inner radius is the outer one less the wall.
RectTube {
width: f64,
height: f64,
wall: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
outer_radius: Option<f64>,
},
/// A round hollow section (pipe or tube).
RoundTube { diameter: f64, wall: f64 },
/// An L angle: one leg `width` along x, the other `height` along y, both `thickness` thick,
/// the heel at the bottom left. The root radius defaults to the thickness, the toe radius to
/// half of it, both made smaller where the legs leave less room.
Angle {
width: f64,
height: f64,
thickness: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
root_radius: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
toe_radius: Option<f64>,
},
/// A channel with parallel flanges, open towards +x: the web `web` thick along the left side,
/// flanges `width` long and `flange` thick. The root radius defaults to the web thickness (less
/// where the flanges or the web leave less room), the toe radius to none.
Channel {
height: f64,
width: f64,
web: f64,
flange: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
root_radius: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
toe_radius: Option<f64>,
},
/// An I or H beam with parallel flanges. The root radius defaults to the web thickness (less
/// where the flanges or the web leave less room).
IBeam {
height: f64,
width: f64,
web: f64,
flange: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
root_radius: Option<f64>,
},
}
/// One built-in profile kind, for listing.
#[derive(Clone, Debug, Serialize)]
pub struct ProfileKind {
pub kind: &'static str,
pub label: &'static str,
/// The dimensions it needs.
pub required: &'static [&'static str],
/// The dimensions that default when left out.
pub optional: &'static [&'static str],
/// A complete example, as JSON.
pub example: Profile,
}
/// Every built-in profile kind.
pub fn profile_kinds() -> Vec<ProfileKind> {
vec![
ProfileKind {
kind: "bar",
label: "Bar",
required: &["width", "height"],
optional: &["corner_radius"],
example: Profile::Bar { width: 40.0, height: 10.0, corner_radius: None },
},
ProfileKind { kind: "round_bar", label: "Round Bar", required: &["diameter"], optional: &[], example: Profile::RoundBar { diameter: 20.0 } },
ProfileKind {
kind: "rect_tube",
label: "Rectangular Tube",
required: &["width", "height", "wall"],
optional: &["outer_radius"],
example: Profile::RectTube { width: 40.0, height: 40.0, wall: 3.0, outer_radius: None },
},
ProfileKind {
kind: "round_tube",
label: "Round Tube",
required: &["diameter", "wall"],
optional: &[],
example: Profile::RoundTube { diameter: 42.4, wall: 3.2 },
},
ProfileKind {
kind: "angle",
label: "L-Angle",
required: &["width", "height", "thickness"],
optional: &["root_radius", "toe_radius"],
example: Profile::Angle { width: 50.0, height: 50.0, thickness: 5.0, root_radius: None, toe_radius: None },
},
ProfileKind {
kind: "channel",
label: "Channel",
required: &["height", "width", "web", "flange"],
optional: &["root_radius", "toe_radius"],
example: Profile::Channel { height: 100.0, width: 50.0, web: 6.0, flange: 8.0, root_radius: None, toe_radius: None },
},
ProfileKind {
kind: "i_beam",
label: "I-Beam",
required: &["height", "width", "web", "flange"],
optional: &["root_radius"],
example: Profile::IBeam { height: 100.0, width: 50.0, web: 4.5, flange: 7.0, root_radius: None },
},
]
}
/// The label of a profile dimension, as the feature's inputs show it.
pub fn dimension_label(name: &str) -> &'static str {
match name {
"width" => "Width",
"height" => "Height",
"wall" => "Wall",
"diameter" => "Diameter",
"thickness" => "Thickness",
"web" => "Web thickness",
"flange" => "Flange thickness",
"corner_radius" => "Corner radius",
"outer_radius" => "Outer radius",
"root_radius" => "Root radius",
"toe_radius" => "Toe radius",
_ => "Dimension",
}
}
/// A built-in profile as a feature saves it and a command takes it: its kind and each dimension
/// as an expression over the design's parameters (`"tube_wall"`, `"2 in"`, a number). Saved as
/// one JSON object, `{"kind": "rect_tube", "width": "40", ...}`; numbers read as their text. A
/// length without a unit is millimetres here: commands give bare numbers the design's unit first.
#[derive(Clone, Debug, PartialEq)]
pub struct ProfileSpec {
pub kind: String,
pub dims: BTreeMap<String, Expr>,
}
impl ProfileSpec {
/// The profile, each dimension worked out by `eval` (given the dimension's name and its
/// expression, returning millimetres).
pub fn resolve(&self, mut eval: impl FnMut(&str, &Expr) -> Result<f64>) -> Result<Profile> {
let mut o = serde_json::Map::new();
o.insert("kind".into(), serde_json::Value::String(self.kind.clone()));
for (name, e) in &self.dims {
let v = eval(name, e)?;
let n = serde_json::Number::from_f64(v).ok_or_else(|| invalid(format!("profile `{name}` is not a finite length")))?;
o.insert(name.clone(), serde_json::Value::Number(n));
}
serde_json::from_value(serde_json::Value::Object(o)).map_err(|e| invalid(format!("profile: {e}")))
}
}
impl Serialize for ProfileSpec {
fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let mut m = s.serialize_map(Some(self.dims.len() + 1))?;
m.serialize_entry("kind", &self.kind)?;
for (k, v) in &self.dims {
m.serialize_entry(k, v)?;
}
m.end()
}
}
impl<'de> Deserialize<'de> for ProfileSpec {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
use serde::de::Error;
let mut m = BTreeMap::<String, serde_json::Value>::deserialize(d)?;
let kind = match m.remove("kind") {
Some(serde_json::Value::String(k)) => k,
_ => return Err(D::Error::custom("a profile needs `kind` (bar, round_bar, rect_tube, round_tube, angle, channel or i_beam)")),
};
let kinds = profile_kinds();
let info = kinds.iter().find(|k| k.kind == kind).ok_or_else(|| {
D::Error::custom(format!("unknown profile kind `{kind}` (bar, round_bar, rect_tube, round_tube, angle, channel or i_beam)"))
})?;
let mut dims = BTreeMap::new();
for (name, v) in m {
if !info.required.contains(&name.as_str()) && !info.optional.contains(&name.as_str()) {
return Err(D::Error::custom(format!("a {kind} profile has no dimension `{name}`")));
}
let text = match v {
serde_json::Value::Number(n) => n.to_string(),
serde_json::Value::String(t) if !t.trim().is_empty() && t.len() <= 4096 => t,
_ => return Err(D::Error::custom(format!("profile `{name}` must be a number or an expression"))),
};
dims.insert(name, Expr::new(text));
}
if let Some(missing) = info.required.iter().find(|r| !dims.contains_key(**r)) {
return Err(D::Error::custom(format!("a {kind} profile needs `{missing}`")));
}
Ok(ProfileSpec { kind, dims })
}
}
impl crate::walk::Walk for ProfileSpec {
fn walk_exprs<'a>(&'a self, f: &mut dyn FnMut(crate::walk::ExprItem<'a>)) {
for (name, e) in &self.dims {
f((dimension_label(name), e, Kind::Length, crate::walk::ExprRole::Input));
}
}
fn walk_exprs_mut<'a>(&'a mut self, f: &mut dyn FnMut(crate::walk::ExprItemMut<'a>)) {
for (name, e) in self.dims.iter_mut() {
f((dimension_label(name), e, Kind::Length, crate::walk::ExprRole::Input));
}
}
}
pub use crate::eval::frame_member::{member_line_ids, member_names};
/// Where a frame member's cross-section comes from.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, solidcraft_derive::Walk)]
#[serde(tag = "source", rename_all = "snake_case")]
pub enum MemberProfile {
/// A built-in profile, from its dimensions.
Library { profile: ProfileSpec },
/// The profiles of a sketch, in the sketch's own x and y, its origin the profile's origin.
/// Every profile (the default) means the material as nested loops alternate: an outline is
/// material, a loop inside it a hole, a loop inside that material again, so a tube drawn as
/// two circles is its wall.
Sketch {
sketch: crate::SketchId,
#[serde(default = "crate::document::all_profiles")]
#[walk(profiles_of = sketch)]
profiles: crate::ProfileSel,
},
}
impl Anchor {
pub fn is_origin(&self) -> bool {
*self == Anchor::Origin
}
}
/// The point of a profile that sits on a member's line (or on `at` when a profile is inserted):
/// the profile's own origin (a built-in profile's bounding-box centre, a sketch profile's sketch
/// origin), its centroid, or a corner or edge middle of its bounding box.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Anchor {
#[default]
Origin,
Center,
Centroid,
TopLeft,
Top,
TopRight,
Left,
Right,
BottomLeft,
Bottom,
BottomRight,
}
/// A profile's section properties (mm², mm, mm⁴). Second moments are about axes through the
/// centroid, parallel to the profile's x and y.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct Section {
pub area: f64,
pub centroid: [f64; 2],
/// ∫ y² dA about the centroid: bending about the x axis.
pub ixx: f64,
/// ∫ x² dA about the centroid: bending about the y axis.
pub iyy: f64,
pub ixy: f64,
/// The bounding box's size.
pub width: f64,
pub height: f64,
}
fn invalid(msg: impl Into<String>) -> DocError {
DocError::Invalid(msg.into())
}
/// `v` as a dimension: finite, at least [`MIN_PROFILE_DIMENSION`] and at most
/// [`MAX_PROFILE_SIZE`].
fn dim(name: &str, v: f64) -> Result<f64> {
if v.is_finite() && (MIN_PROFILE_DIMENSION..=MAX_PROFILE_SIZE).contains(&v) {
Ok(v)
} else {
Err(invalid(format!("profile `{name}` must be between {MIN_PROFILE_DIMENSION} and {MAX_PROFILE_SIZE} mm (got {v})")))
}
}
/// `v` as a radius: 0 (a sharp corner), or from [`MIN_PROFILE_DIMENSION`] up to
/// [`MAX_PROFILE_SIZE`].
fn radius(name: &str, v: f64) -> Result<f64> {
if v == 0.0 || (v.is_finite() && (MIN_PROFILE_DIMENSION..=MAX_PROFILE_SIZE).contains(&v)) {
Ok(v)
} else {
Err(invalid(format!("profile `{name}` must be 0 or between {MIN_PROFILE_DIMENSION} and {MAX_PROFILE_SIZE} mm (got {v})")))
}
}
/// `a` less than `b`.
fn less(a_name: &str, a: f64, b_name: &str, b: f64) -> Result<()> {
if a < b { Ok(()) } else { Err(invalid(format!("profile `{a_name}` ({a}) must be less than {b_name} ({b})"))) }
}
/// `a` less than half of `b`.
fn less_half(a_name: &str, a: f64, b_name: &str, b: f64) -> Result<()> {
if 2.0 * a < b { Ok(()) } else { Err(invalid(format!("profile `{a_name}` ({a}) must be less than half {b_name} ({})", b / 2.0))) }
}
/// Radius `r` at most `room` (with a little slack for rounding).
fn at_most(what: &str, r: f64, room: f64, why: &str) -> Result<()> {
if r <= room + 1e-9 * (1.0 + room.abs()) {
Ok(())
} else {
Err(invalid(format!("profile {what} ({r}) must be at most {} mm: {why}", room.max(0.0))))
}
}
/// A number for a name: up to four decimals, without trailing zeros.
fn short(x: f64) -> String {
let t = format!("{x:.4}");
let t = if t.contains('.') { t.trim_end_matches('0').trim_end_matches('.') } else { &t };
if t == "-0" { "0".into() } else { t.to_string() }
}
impl Profile {
/// The kind's id (`rect_tube`, `angle`…).
pub fn kind(&self) -> &'static str {
match self {
Profile::Bar { .. } => "bar",
Profile::RoundBar { .. } => "round_bar",
Profile::RectTube { .. } => "rect_tube",
Profile::RoundTube { .. } => "round_tube",
Profile::Angle { .. } => "angle",
Profile::Channel { .. } => "channel",
Profile::IBeam { .. } => "i_beam",
}
}
/// A short description from the kind and its main sizes, such as `Rect Tube 40x40x3`: what a
/// member body is named after.
pub fn description(&self) -> String {
let d = |v: &[f64]| v.iter().map(|x| short(*x)).collect::<Vec<_>>().join("x");
match *self {
Profile::Bar { width, height, .. } => format!("Bar {}", d(&[width, height])),
Profile::RoundBar { diameter } => format!("Round Bar {}", short(diameter)),
Profile::RectTube { width, height, wall, .. } => format!("Rect Tube {}", d(&[width, height, wall])),
Profile::RoundTube { diameter, wall } => format!("Round Tube {}", d(&[diameter, wall])),
Profile::Angle { width, height, thickness, .. } => format!("Angle {}", d(&[width, height, thickness])),
Profile::Channel { height, width, web, .. } => format!("Channel {}", d(&[height, width, web])),
Profile::IBeam { height, width, web, .. } => format!("I-Beam {}", d(&[height, width, web])),
}
}
/// The profile with every defaulted dimension written out. A default radius is made smaller
/// where the profile leaves less room for it than its usual size (a short leg, a narrow
/// flange), so leaving radii out never makes a profile that does not fit.
pub fn filled(&self) -> Profile {
let room = |x: f64| if x.is_finite() { x.max(0.0) } else { 0.0 };
match *self {
Profile::Bar { width, height, corner_radius } => Profile::Bar { width, height, corner_radius: Some(corner_radius.unwrap_or(0.0)) },
Profile::RectTube { width, height, wall, outer_radius } => {
let r = outer_radius.unwrap_or_else(|| (2.0 * wall).min(width.min(height) / 2.0));
Profile::RectTube { width, height, wall, outer_radius: Some(r) }
}
Profile::Angle { width, height, thickness: t, root_radius, toe_radius } => {
// Root and toe share the inside length of the shorter leg.
let leg = room(width.min(height) - t);
let (r1, r2) = match (root_radius, toe_radius) {
(Some(r1), Some(r2)) => (r1, r2),
(Some(r1), None) => (r1, (t / 2.0).min(room(leg - r1))),
(None, Some(r2)) => (t.min(room(leg - r2)), r2),
(None, None) => {
let k = if 1.5 * t > leg { leg / (1.5 * t) } else { 1.0 };
(t * k, t / 2.0 * k)
}
};
Profile::Angle { width, height, thickness: t, root_radius: Some(r1), toe_radius: Some(r2) }
}
Profile::Channel { height, width, web, flange, root_radius, toe_radius } => {
let r2 = toe_radius.unwrap_or(0.0);
// The root shares a flange's inside length with the toe, and the web's inside
// height with the other root.
let r1 = root_radius.unwrap_or_else(|| web.min(room(width - web - r2)).min(room(height - 2.0 * flange) / 2.0));
Profile::Channel { height, width, web, flange, root_radius: Some(r1), toe_radius: Some(r2) }
}
Profile::IBeam { height, width, web, flange, root_radius } => {
let r = root_radius.unwrap_or_else(|| web.min(room(width - web) / 2.0).min(room(height - 2.0 * flange) / 2.0));
Profile::IBeam { height, width, web, flange, root_radius: Some(r) }
}
Profile::RoundBar { .. } | Profile::RoundTube { .. } => self.clone(),
}
}
/// The bounding box's width and height (mm), before validation.
pub fn size(&self) -> (f64, f64) {
match *self {
Profile::Bar { width, height, .. }
| Profile::RectTube { width, height, .. }
| Profile::Angle { width, height, .. }
| Profile::Channel { width, height, .. }
| Profile::IBeam { width, height, .. } => (width, height),
Profile::RoundBar { diameter } | Profile::RoundTube { diameter, .. } => (diameter, diameter),
}
}
/// The profile's cross-section, the bounding box centred on the origin. An error names the
/// dimension that is out of range or does not fit.
pub fn region(&self) -> Result<Region2> {
let f = self.filled();
match f {
Profile::Bar { width, height, corner_radius } => {
let (w, h) = (dim("width", width)?, dim("height", height)?);
let r = radius("corner_radius", corner_radius.unwrap_or(0.0))?;
if r > w.min(h) / 2.0 {
return Err(invalid(format!("profile `corner_radius` ({r}) must be at most half the smaller side ({})", w.min(h) / 2.0)));
}
Ok(Region2 { outer: rounded_rect(w, h, r)?, holes: Vec::new() })
}
Profile::RoundBar { diameter } => Ok(Region2 { outer: Loop2::circle(Vec2::ZERO, dim("diameter", diameter)? / 2.0), holes: Vec::new() }),
Profile::RectTube { width, height, wall, outer_radius } => {
let (w, h, t) = (dim("width", width)?, dim("height", height)?, dim("wall", wall)?);
less_half("wall", t, "the smaller side", w.min(h))?;
let ro = radius("outer_radius", outer_radius.unwrap_or(0.0))?;
if ro > w.min(h) / 2.0 {
return Err(invalid(format!("profile `outer_radius` ({ro}) must be at most half the smaller side ({})", w.min(h) / 2.0)));
}
let ri = (ro - t).max(0.0);
Ok(Region2 { outer: rounded_rect(w, h, ro)?, holes: vec![rounded_rect(w - 2.0 * t, h - 2.0 * t, ri)?.reversed()] })
}
Profile::RoundTube { diameter, wall } => {
let (d, t) = (dim("diameter", diameter)?, dim("wall", wall)?);
less_half("wall", t, "the diameter", d)?;
Ok(Region2 { outer: Loop2::circle(Vec2::ZERO, d / 2.0), holes: vec![Loop2::circle(Vec2::ZERO, d / 2.0 - t).reversed()] })
}
Profile::Angle { width, height, thickness, root_radius, toe_radius } => {
let (a, b, t) = (dim("width", width)?, dim("height", height)?, dim("thickness", thickness)?);
less("thickness", t, "the shorter leg", a.min(b))?;
let r1 = radius("root_radius", root_radius.unwrap_or(0.0))?;
let r2 = radius("toe_radius", toe_radius.unwrap_or(0.0))?;
at_most("`toe_radius`", r2, t, "the thickness")?;
at_most("`root_radius` + `toe_radius`", r1 + r2, a.min(b) - t, "the inside length of the shorter leg")?;
let pts = [(0.0, 0.0), (a, 0.0), (a, t), (t, t), (t, b), (0.0, b)];
let radii = [0.0, 0.0, r2, r1, r2, 0.0];
Ok(Region2 { outer: rounded_polygon(&shifted(&pts, a, b), &radii)?, holes: Vec::new() })
}
Profile::Channel { height, width, web, flange, root_radius, toe_radius } => {
let (h, b, tw, tf) = (dim("height", height)?, dim("width", width)?, dim("web", web)?, dim("flange", flange)?);
less("web", tw, "width", b)?;
less_half("flange", tf, "the height", h)?;
let r1 = radius("root_radius", root_radius.unwrap_or(0.0))?;
let r2 = radius("toe_radius", toe_radius.unwrap_or(0.0))?;
at_most("`toe_radius`", r2, tf, "the flange thickness")?;
at_most("`root_radius` + `toe_radius`", r1 + r2, b - tw, "the inside length of a flange")?;
at_most("`root_radius`", r1, (h - 2.0 * tf) / 2.0, "half the web's inside height")?;
let pts = [(0.0, 0.0), (b, 0.0), (b, tf), (tw, tf), (tw, h - tf), (b, h - tf), (b, h), (0.0, h)];
let radii = [0.0, 0.0, r2, r1, r1, r2, 0.0, 0.0];
Ok(Region2 { outer: rounded_polygon(&shifted(&pts, b, h), &radii)?, holes: Vec::new() })
}
Profile::IBeam { height, width, web, flange, root_radius } => {
let (h, b, tw, tf) = (dim("height", height)?, dim("width", width)?, dim("web", web)?, dim("flange", flange)?);
less("web", tw, "width", b)?;
less_half("flange", tf, "the height", h)?;
let r = radius("root_radius", root_radius.unwrap_or(0.0))?;
at_most("`root_radius`", r, (b - tw) / 2.0, "the inside length of a flange")?;
at_most("`root_radius`", r, (h - 2.0 * tf) / 2.0, "half the web's inside height")?;
let (x, y, w, f) = (b / 2.0, h / 2.0, tw / 2.0, h / 2.0 - tf);
let pts = [(-x, -y), (x, -y), (x, -f), (w, -f), (w, f), (x, f), (x, y), (-x, y), (-x, f), (-w, f), (-w, -f), (-x, -f)];
let radii = [0.0, 0.0, 0.0, r, r, 0.0, 0.0, 0.0, 0.0, r, r, 0.0];
let pts: Vec<Vec2> = pts.iter().map(|&(x, y)| Vec2::new(x, y)).collect();
Ok(Region2 { outer: rounded_polygon(&pts, &radii)?, holes: Vec::new() })
}
}
}
}
/// Points given with the heel at the origin, moved so a `w` × `h` bounding box is centred on it.
fn shifted(pts: &[(f64, f64)], w: f64, h: f64) -> Vec<Vec2> {
pts.iter().map(|&(x, y)| Vec2::new(x - w / 2.0, y - h / 2.0)).collect()
}
fn rounded_rect(w: f64, h: f64, r: f64) -> Result<Loop2> {
let (x, y) = (w / 2.0, h / 2.0);
rounded_polygon(&[Vec2::new(-x, -y), Vec2::new(x, -y), Vec2::new(x, y), Vec2::new(-x, y)], &[r; 4])
}
/// The counter-clockwise polygon `pts` with each corner rounded by its radius in `radii` (0: a
/// sharp corner). Convex and concave corners alike: the arc is tangent to both edges. An error
/// when the arcs at the two ends of an edge need more than its length.
pub fn rounded_polygon(pts: &[Vec2], radii: &[f64]) -> Result<Loop2> {
let n = pts.len();
if n < 3 || radii.len() != n {
return Err(invalid("a profile polygon needs 3 or more corners, each with a radius"));
}
// Each corner as (where its arc starts, where it ends, the arc).
let mut corners: Vec<(Vec2, Vec2, Option<Seg2>)> = Vec::with_capacity(n);
for i in 0..n {
let (Some(&prev), Some(&v), Some(&next), Some(&r)) = (pts.get((i + n - 1) % n), pts.get(i), pts.get((i + 1) % n), radii.get(i)) else {
return Err(invalid("a profile polygon corner is missing"));
};
let (Some(d1), Some(d2)) = ((v - prev).normalized(), (next - v).normalized()) else {
return Err(invalid("a profile polygon has two corners in one place"));
};
let turn = d1.cross(d2).atan2(d1.dot(d2));
if r <= 0.0 || turn.abs() < 1e-12 {
corners.push((v, v, None));
continue;
}
if turn.abs() > std::f64::consts::PI - 1e-9 {
return Err(invalid("a profile polygon turns back on itself"));
}
let l = r * (turn.abs() / 2.0).tan();
let (t1, t2) = (v - d1 * l, v + d2 * l);
let side = if turn > 0.0 { d1.perp() } else { d1.perp() * -1.0 };
let center = t1 + side * r;
corners.push((t1, t2, Some(Seg2::Arc { center, radius: r, start: (t1 - center).angle(), sweep: turn })));
}
let mut segs = Vec::with_capacity(2 * n);
for i in 0..n {
let (Some(&(_, out, arc)), Some(&(inn, _, _)), Some(&a), Some(&b)) =
(corners.get(i), corners.get((i + 1) % n), pts.get(i), pts.get((i + 1) % n))
else {
return Err(invalid("a profile polygon corner is missing"));
};
if let Some(arc) = arc {
segs.push(arc);
}
// The edge left between the two arcs must run the edge's way (or be empty).
let along = (inn - out).dot(b - a);
if along < -1e-9 * (1.0 + a.dist(b)) {
return Err(invalid(format!("profile corner radii do not fit along an edge {:.4} mm long", a.dist(b))));
}
if out.dist(inn) > 1e-9 {
segs.push(Seg2::Line { a: out, b: inn });
}
}
Ok(Loop2 { segs })
}
/// Gauss–Legendre nodes and weights on [0, 1] (5 points).
const GL5: [(f64, f64); 5] = [
(0.046_910_077_030_668, 0.118_463_442_528_094_5),
(0.230_765_344_947_158_5, 0.239_314_335_249_683_2),
(0.5, 0.284_444_444_444_444_4),
(0.769_234_655_052_841_5, 0.239_314_335_249_683_2),
(0.953_089_922_969_332, 0.118_463_442_528_094_5),
];
/// The boundary integrals of one loop, as it runs (counter-clockwise positive): area, ∫x dA,
/// ∫y dA, ∫x² dA, ∫y² dA, ∫xy dA, by Green's theorem.
fn loop_moments(l: &Loop2) -> [f64; 6] {
let mut m = [0.0; 6];
for seg in &l.segs {
let pieces = match seg {
Seg2::Line { .. } => 1,
_ => 16,
};
for k in 0..pieces {
let h = 1.0 / pieces as f64;
for (x, wt) in GL5 {
let t = (k as f64 + x) * h;
let (p, dp) = (seg.point_at(t), seg.derivative(t));
let w = wt * h;
let terms = [
p.x * dp.y,
0.5 * p.x * p.x * dp.y,
-0.5 * p.y * p.y * dp.x,
p.x * p.x * p.x * dp.y / 3.0,
-p.y * p.y * p.y * dp.x / 3.0,
0.5 * p.x * p.x * p.y * dp.y,
];
for (acc, v) in m.iter_mut().zip(terms) {
*acc += w * v;
}
}
}
}
m
}
/// Points of `l` that include its extremes along x and y: every segment's ends, and where an arc
/// passes a quarter turn. Free-form segments add the polyline points within 1 µm.
fn extreme_points(l: &Loop2) -> Vec<Vec2> {
let mut out = Vec::new();
for seg in &l.segs {
match *seg {
Seg2::Line { a, b } => out.extend([a, b]),
Seg2::Arc { center, radius, start, sweep } => {
out.extend([seg.start(), seg.end()]);
let (lo, hi) = if sweep >= 0.0 { (start, start + sweep) } else { (start + sweep, start) };
let quarter = std::f64::consts::FRAC_PI_2;
let mut k = (lo / quarter).ceil();
// An arc turns at most once around: five quarter turns at most.
for _ in 0..5 {
let t = k * quarter;
if t > hi {
break;
}
out.push(center + Vec2::from_angle(t) * radius);
k += 1.0;
}
}
_ => out.extend(seg.polyline(1e-3)),
}
}
out
}
/// The section properties of `region` (outer loop and holes, whichever way each runs).
pub fn section(region: &Region2) -> Section {
let mut m = loop_moments(&region.outer.ccw());
for hole in &region.holes {
for (acc, v) in m.iter_mut().zip(loop_moments(&hole.ccw())) {
*acc -= v;
}
}
let [a, sx, sy, jyy, jxx, jxy] = m;
let (cx, cy) = if a.abs() > 1e-300 { (sx / a, sy / a) } else { (0.0, 0.0) };
let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY));
for p in extreme_points(&region.outer) {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
let (width, height) = if lo.x <= hi.x { (hi.x - lo.x, hi.y - lo.y) } else { (0.0, 0.0) };
Section { area: a, centroid: [cx, cy], ixx: jxx - a * cy * cy, iyy: jyy - a * cx * cx, ixy: jxy - a * cx * cy, width, height }
}
/// Where `anchor` is on the profile made of `regions`, in the profile's own coordinates.
pub fn anchor_point(regions: &[Region2], anchor: Anchor) -> Vec2 {
let (mut lo, mut hi) = (Vec2::new(f64::INFINITY, f64::INFINITY), Vec2::new(f64::NEG_INFINITY, f64::NEG_INFINITY));
for p in regions.iter().flat_map(|r| extreme_points(&r.outer)) {
lo = Vec2::new(lo.x.min(p.x), lo.y.min(p.y));
hi = Vec2::new(hi.x.max(p.x), hi.y.max(p.y));
}
if !(lo.x <= hi.x && lo.y <= hi.y) {
return Vec2::ZERO;
}
let mid = Vec2::new((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0);
match anchor {
Anchor::Origin => Vec2::ZERO,
Anchor::Center => mid,
Anchor::Centroid => {
let (mut a, mut c) = (0.0, Vec2::ZERO);
for r in regions {
let s = section(r);
a += s.area;
c += Vec2::new(s.centroid[0], s.centroid[1]) * s.area;
}
if a > 1e-300 { c / a } else { mid }
}
Anchor::TopLeft => Vec2::new(lo.x, hi.y),
Anchor::Top => Vec2::new(mid.x, hi.y),
Anchor::TopRight => hi,
Anchor::Left => Vec2::new(lo.x, mid.y),
Anchor::Right => Vec2::new(hi.x, mid.y),
Anchor::BottomLeft => lo,
Anchor::Bottom => Vec2::new(mid.x, lo.y),
Anchor::BottomRight => Vec2::new(hi.x, lo.y),
}
}
/// `region` mirrored across its y axis (x → −x), its loops still running the way [`Region2`]
/// expects.
pub fn mirrored(region: &Region2) -> Region2 {
let m = |p: Vec2| Vec2::new(-p.x, p.y);
let seg = |g: &Seg2| match *g {
Seg2::Line { a, b } => Seg2::Line { a: m(a), b: m(b) },
Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center: m(center), radius, start: std::f64::consts::PI - start, sweep: -sweep },
Seg2::Cubic { p0, p1, p2, p3 } => Seg2::Cubic { p0: m(p0), p1: m(p1), p2: m(p2), p3: m(p3) },
Seg2::Conic { a, apex, b, w } => Seg2::Conic { a: m(a), apex: m(apex), b: m(b), w },
Seg2::Bezier { n, p } => Seg2::Bezier { n, p: p.map(m) },
};
let lp = |l: &Loop2| Loop2 { segs: l.segs.iter().map(seg).collect() }.reversed();
Region2 { outer: lp(&region.outer), holes: region.holes.iter().map(lp).collect() }
}
/// The directions a member's profile x and y take in the world, for a member running along `d`
/// (any length): the profile's y points up (world +Z) as far as the line allows and x = y × d, so
/// x × y runs along the line; a vertical member's x is world +X (a line leaning less than
/// [`VERTICAL_TOLERANCE`] counts as vertical, so rounding never turns a post). `angle` (radians) then turns the
/// profile counter-clockwise about the line, seen looking back from its end. `None` for a
/// direction of no length.
pub fn member_axes(d: Vec3, angle: f64) -> Option<(Vec3, Vec3)> {
let d = d.normalized()?;
let up = Vec3::Z - d * Vec3::Z.dot(d);
// `up` is as long as the sine of the line's lean from vertical.
let (x, y) = match up.normalized().filter(|_| up.len() > VERTICAL_TOLERANCE) {
Some(y) => (y.cross(d), y),
None => (Vec3::X, d.cross(Vec3::X)),
};
let (c, s) = (angle.cos(), angle.sin());
Some((x * c + y * s, y * c - x * s))
}
/// `region` turned by `angle` (radians, counter-clockwise) about its `anchor` point and moved so
/// that point lands on `at`.
pub fn placed(region: &Region2, anchor: Vec2, at: Vec2, angle: f64) -> Region2 {
let (c, s) = (angle.cos(), angle.sin());
let map = |p: Vec2| {
let q = p - anchor;
at + Vec2::new(c * q.x - s * q.y, s * q.x + c * q.y)
};
let seg = |g: &Seg2| match *g {
Seg2::Line { a, b } => Seg2::Line { a: map(a), b: map(b) },
Seg2::Arc { center, radius, start, sweep } => Seg2::Arc { center: map(center), radius, start: start + angle, sweep },
Seg2::Cubic { p0, p1, p2, p3 } => Seg2::Cubic { p0: map(p0), p1: map(p1), p2: map(p2), p3: map(p3) },
Seg2::Conic { a, apex, b, w } => Seg2::Conic { a: map(a), apex: map(apex), b: map(b), w },
Seg2::Bezier { n, p } => Seg2::Bezier { n, p: p.map(map) },
};
let lp = |l: &Loop2| Loop2 { segs: l.segs.iter().map(seg).collect() };
Region2 { outer: lp(&region.outer), holes: region.holes.iter().map(lp).collect() }
}
+413
View File
@@ -0,0 +1,413 @@
//! Profile library tests. Expected values are worked out by hand: rectangles and circles, and
//! composite rectangles by the parallel-axis theorem; each fillet adds or removes a spandrel of
//! (1 − π/4) r².
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::f64::consts::PI;
const SPANDREL: f64 = 1.0 - PI / 4.0;
fn close(got: f64, want: f64, what: &str) {
let tol = 1e-9 * (1.0 + want.abs());
assert!((got - want).abs() <= tol, "{what}: got {got}, want {want}");
}
fn profile(json: serde_json::Value) -> Profile {
serde_json::from_value(json).unwrap()
}
fn sec(p: &Profile) -> Section {
let r = p.region().unwrap();
assert!(r.outer.is_closed(1e-9), "{} outline is closed", p.kind());
assert!(r.outer.is_ccw(), "{} outline runs counter-clockwise", p.kind());
for h in &r.holes {
assert!(h.is_closed(1e-9) && !h.is_ccw(), "{} holes are closed and clockwise", p.kind());
}
// The exact boundary integral agrees with the region's own area.
let s = section(&r);
close(s.area, r.area(), "area against Region2::area");
s
}
/// Area, centroid (in the profile's centred frame) and centroidal Ixx, Iyy of rectangles
/// given as (x0, y0, x1, y1), combined.
fn rects(parts: &[(f64, f64, f64, f64)]) -> (f64, f64, f64, f64, f64) {
let a: f64 = parts.iter().map(|&(x0, y0, x1, y1)| (x1 - x0) * (y1 - y0)).sum();
let cx = parts.iter().map(|&(x0, y0, x1, y1)| (x1 - x0) * (y1 - y0) * (x0 + x1) / 2.0).sum::<f64>() / a;
let cy = parts.iter().map(|&(x0, y0, x1, y1)| (x1 - x0) * (y1 - y0) * (y0 + y1) / 2.0).sum::<f64>() / a;
let ixx = parts
.iter()
.map(|&(x0, y0, x1, y1)| {
let (b, h) = (x1 - x0, y1 - y0);
b * h * h * h / 12.0 + b * h * ((y0 + y1) / 2.0 - cy).powi(2)
})
.sum();
let iyy = parts
.iter()
.map(|&(x0, y0, x1, y1)| {
let (b, h) = (x1 - x0, y1 - y0);
h * b * b * b / 12.0 + b * h * ((x0 + x1) / 2.0 - cx).powi(2)
})
.sum();
(a, cx, cy, ixx, iyy)
}
fn check_rects(s: &Section, parts: &[(f64, f64, f64, f64)], what: &str) {
let (a, cx, cy, ixx, iyy) = rects(parts);
close(s.area, a, &format!("{what} area"));
close(s.centroid[0], cx, &format!("{what} centroid x"));
close(s.centroid[1], cy, &format!("{what} centroid y"));
close(s.ixx, ixx, &format!("{what} Ixx"));
close(s.iyy, iyy, &format!("{what} Iyy"));
}
#[test]
fn bar_is_a_rectangle() {
let s = sec(&profile(serde_json::json!({"kind": "bar", "width": 40, "height": 10})));
close(s.area, 400.0, "area");
close(s.ixx, 40.0 * 1000.0 / 12.0, "Ixx = b h³ / 12");
close(s.iyy, 10.0 * 64_000.0 / 12.0, "Iyy = h b³ / 12");
close(s.ixy, 0.0, "Ixy");
close(s.width, 40.0, "width");
close(s.height, 10.0, "height");
}
#[test]
fn rounded_bar_loses_four_spandrels() {
let s = sec(&profile(serde_json::json!({"kind": "bar", "width": 30, "height": 20, "corner_radius": 4})));
close(s.area, 600.0 - 4.0 * SPANDREL * 16.0, "area");
// Fully rounded: a 20 × 20 bar with radius 10 is a circle.
let s = sec(&profile(serde_json::json!({"kind": "bar", "width": 20, "height": 20, "corner_radius": 10})));
close(s.area, PI * 100.0, "fully rounded area");
close(s.ixx, PI * 10f64.powi(4) / 4.0, "fully rounded Ixx");
}
#[test]
fn round_bar_and_tube() {
let s = sec(&Profile::RoundBar { diameter: 20.0 });
close(s.area, PI * 100.0, "bar area");
close(s.ixx, PI * 20f64.powi(4) / 64.0, "bar Ixx = π d⁴ / 64");
close(s.iyy, s.ixx, "bar Iyy");
let s = sec(&Profile::RoundTube { diameter: 42.4, wall: 3.2 });
let d = 42.4 - 6.4;
close(s.area, PI / 4.0 * (42.4f64.powi(2) - d * d), "tube area");
close(s.ixx, PI / 64.0 * (42.4f64.powi(4) - d.powi(4)), "tube Ixx = π (D⁴ − d⁴) / 64");
}
#[test]
fn rect_tube_sharp_and_rounded() {
let s = sec(&profile(serde_json::json!({"kind": "rect_tube", "width": 60, "height": 40, "wall": 3, "outer_radius": 0})));
close(s.area, 60.0 * 40.0 - 54.0 * 34.0, "sharp area");
close(s.ixx, (60.0 * 40f64.powi(3) - 54.0 * 34f64.powi(3)) / 12.0, "sharp Ixx");
close(s.iyy, (40.0 * 60f64.powi(3) - 34.0 * 54f64.powi(3)) / 12.0, "sharp Iyy");
// Defaults: outer radius 2 t = 6, inner radius 3.
let p = profile(serde_json::json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}));
assert_eq!(p.filled(), Profile::RectTube { width: 40.0, height: 40.0, wall: 3.0, outer_radius: Some(6.0) });
let s = sec(&p);
let outer = 1600.0 - 4.0 * SPANDREL * 36.0;
let inner = 34.0 * 34.0 - 4.0 * SPANDREL * 9.0;
close(s.area, outer - inner, "rounded area");
close(s.centroid[0], 0.0, "centroid x");
close(s.ixy, 0.0, "Ixy");
}
#[test]
fn angle_sharp_matches_two_rectangles() {
let (a, b, t) = (60.0, 40.0, 5.0);
let s = sec(&profile(serde_json::json!({"kind": "angle", "width": a, "height": b, "thickness": t, "root_radius": 0, "toe_radius": 0})));
let (x0, y0) = (-a / 2.0, -b / 2.0);
check_rects(&s, &[(x0, y0, x0 + a, y0 + t), (x0, y0 + t, x0 + t, y0 + b)], "angle");
assert!(s.ixy.abs() > 1.0, "an unequal angle has a product of inertia");
}
#[test]
fn angle_root_adds_and_toes_remove_spandrels() {
let (a, b, t) = (50.0, 50.0, 5.0);
let p = profile(serde_json::json!({"kind": "angle", "width": a, "height": b, "thickness": t}));
let s = sec(&p);
// Defaults: root radius t, toe radius t / 2.
close(s.area, t * (a + b - t) + SPANDREL * t * t - 2.0 * SPANDREL * (t / 2.0).powi(2), "area");
// An equal angle is symmetric about its diagonal.
close(s.centroid[0], s.centroid[1], "centroid on the diagonal");
close(s.ixx, s.iyy, "Ixx = Iyy");
}
#[test]
fn channel_and_i_beam_sharp_match_rectangles() {
let (h, b, tw, tf) = (100.0, 50.0, 6.0, 8.0);
let s = sec(&profile(serde_json::json!({"kind": "channel", "height": h, "width": b, "web": tw, "flange": tf, "root_radius": 0})));
let (x0, y0) = (-b / 2.0, -h / 2.0);
let parts = [(x0, y0, x0 + b, y0 + tf), (x0, y0 + tf, x0 + tw, y0 + h - tf), (x0, y0 + h - tf, x0 + b, y0 + h)];
check_rects(&s, &parts, "channel");
close(s.ixy, 0.0, "channel Ixy");
let (h, b, tw, tf) = (100.0, 50.0, 4.5, 7.0);
let s = sec(&profile(serde_json::json!({"kind": "i_beam", "height": h, "width": b, "web": tw, "flange": tf, "root_radius": 0})));
close(s.area, 2.0 * b * tf + (h - 2.0 * tf) * tw, "I area");
close(s.ixx, (b * h.powi(3) - (b - tw) * (h - 2.0 * tf).powi(3)) / 12.0, "I Ixx");
close(s.iyy, (2.0 * tf * b.powi(3) + (h - 2.0 * tf) * tw.powi(3)) / 12.0, "I Iyy");
}
#[test]
fn i_beam_root_radii_add_four_spandrels() {
let (h, b, tw, tf, r) = (100.0, 50.0, 4.5, 7.0, 7.0);
let s = sec(&profile(serde_json::json!({"kind": "i_beam", "height": h, "width": b, "web": tw, "flange": tf, "root_radius": r})));
close(s.area, 2.0 * b * tf + (h - 2.0 * tf) * tw + 4.0 * SPANDREL * r * r, "area");
close(s.centroid[0], 0.0, "centroid x");
close(s.centroid[1], 0.0, "centroid y");
}
#[test]
fn every_kind_example_builds() {
for k in profile_kinds() {
assert_eq!(k.example.kind(), k.kind);
let s = sec(&k.example);
assert!(s.area > 0.0 && s.ixx > 0.0 && s.iyy > 0.0, "{}: {s:?}", k.kind);
let (w, h) = k.example.size();
close(s.width, w, &format!("{} width", k.kind));
close(s.height, h, &format!("{} height", k.kind));
}
}
#[test]
fn dimensions_that_do_not_fit_are_refused() {
let bad = [
serde_json::json!({"kind": "bar", "width": f64::MAX, "height": 1}),
serde_json::json!({"kind": "bar", "width": -1, "height": 1}),
serde_json::json!({"kind": "bar", "width": 0, "height": 1}),
serde_json::json!({"kind": "bar", "width": 10, "height": 10, "corner_radius": 6}),
serde_json::json!({"kind": "round_bar", "diameter": 1e300}),
serde_json::json!({"kind": "rect_tube", "width": 10, "height": 10, "wall": 5}),
serde_json::json!({"kind": "rect_tube", "width": 10, "height": 10, "wall": 1, "outer_radius": -1}),
serde_json::json!({"kind": "round_tube", "diameter": 10, "wall": 5}),
serde_json::json!({"kind": "angle", "width": 10, "height": 10, "thickness": 10}),
serde_json::json!({"kind": "angle", "width": 10, "height": 10, "thickness": 2, "root_radius": 9}),
serde_json::json!({"kind": "angle", "width": 10, "height": 10, "thickness": 2, "toe_radius": 3}),
serde_json::json!({"kind": "channel", "height": 10, "width": 10, "web": 2, "flange": 5}),
serde_json::json!({"kind": "channel", "height": 10, "width": 10, "web": 10, "flange": 2}),
serde_json::json!({"kind": "i_beam", "height": 100, "width": 50, "web": 5, "flange": 7, "root_radius": 30}),
];
for j in bad {
let p: Profile = serde_json::from_value(j.clone()).unwrap();
assert!(p.region().is_err(), "{j} is refused");
}
for j in [
serde_json::json!({"kind": "bar", "width": 1}),
serde_json::json!({"kind": "bar", "width": 1, "height": 1, "colour": 2}),
serde_json::json!({"kind": "hexagon"}),
] {
assert!(serde_json::from_value::<Profile>(j.clone()).is_err(), "{j} is not a profile");
}
}
#[test]
fn non_finite_dimensions_are_refused() {
for v in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert!(Profile::RoundBar { diameter: v }.region().is_err());
assert!(Profile::RectTube { width: 40.0, height: 40.0, wall: 3.0, outer_radius: Some(v) }.region().is_err());
}
}
#[test]
fn placing_moves_the_anchor_onto_the_point() {
let p = profile(serde_json::json!({"kind": "angle", "width": 60, "height": 40, "thickness": 5}));
let r = p.region().unwrap();
let s0 = section(&r);
let anchor = anchor_point(std::slice::from_ref(&r), Anchor::BottomLeft);
close(anchor.x, -30.0, "bottom left x");
close(anchor.y, -20.0, "bottom left y");
let at = Vec2::new(100.0, 50.0);
let moved = placed(&r, anchor, at, PI / 2.0);
let s1 = section(&moved);
close(s1.area, s0.area, "area is kept");
// Turned a quarter: the heel stays on `at`, the 60 mm leg now runs up and the 40 mm one left.
close(s1.width, 40.0, "turned width");
close(s1.height, 60.0, "turned height");
let c = at + Vec2::new(-(s0.centroid[1] + 20.0), s0.centroid[0] + 30.0);
close(s1.centroid[0], c.x, "centroid x");
close(s1.centroid[1], c.y, "centroid y");
close(s1.ixx, s0.iyy, "Ixx after a quarter turn");
let centre = anchor_point(std::slice::from_ref(&r), Anchor::Centroid);
let s2 = section(&placed(&r, centre, Vec2::ZERO, 0.0));
close(s2.centroid[0], 0.0, "centroid anchor x");
close(s2.centroid[1], 0.0, "centroid anchor y");
}
#[test]
fn member_axes_are_square_to_the_line_and_keep_up() {
for d in [Vec3::X, Vec3::new(0.0, -3.0, 0.0), Vec3::new(1.0, 2.0, 3.0), Vec3::Z, Vec3::new(0.0, 0.0, -2.0), Vec3::new(1e-12, 0.0, 1.0)] {
for angle in [0.0, 0.3, -PI / 2.0] {
let (x, y) = member_axes(d, angle).unwrap();
let n = d.normalized().unwrap();
close(x.len(), 1.0, "|x|");
close(y.len(), 1.0, "|y|");
close(x.dot(y), 0.0, "x ⟂ y");
close(x.cross(y).dist(n), 0.0, "x × y runs along the line");
}
}
// Unturned: a horizontal member's y is world up; a vertical one's x is world X.
let (_, y) = member_axes(Vec3::new(1.0, 1.0, 0.0), 0.0).unwrap();
close(y.dist(Vec3::Z), 0.0, "horizontal y");
let (x, _) = member_axes(Vec3::Z, 0.0).unwrap();
close(x.dist(Vec3::X), 0.0, "vertical x");
let (x, _) = member_axes(Vec3::new(0.0, 0.0, -1.0), 0.0).unwrap();
close(x.dist(Vec3::X), 0.0, "downward x");
// A quarter turn takes x to where y was.
let (_, y0) = member_axes(Vec3::X, 0.0).unwrap();
let (x1, _) = member_axes(Vec3::X, PI / 2.0).unwrap();
close(x1.dist(y0), 0.0, "quarter turn");
assert!(member_axes(Vec3::ZERO, 0.0).is_none());
}
#[test]
fn mirroring_keeps_the_section_and_flips_x() {
let p = profile(serde_json::json!({"kind": "angle", "width": 60, "height": 40, "thickness": 5}));
let r = p.region().unwrap();
let m = mirrored(&r);
assert!(m.outer.is_ccw() && m.outer.is_closed(1e-9), "the outline still runs counter-clockwise");
let (a, b) = (section(&r), section(&m));
close(b.area, a.area, "area");
close(b.centroid[0], -a.centroid[0], "centroid x");
close(b.centroid[1], a.centroid[1], "centroid y");
close(b.ixy, -a.ixy, "Ixy changes sign");
let tube = mirrored(&profile(serde_json::json!({"kind": "rect_tube", "width": 40, "height": 20, "wall": 2})).region().unwrap());
assert!(tube.holes.iter().all(|h| !h.is_ccw()), "holes still run clockwise");
}
#[test]
fn anchors_of_an_off_centre_region() {
// A sketch profile need not be centred: a 10 × 20 box from (5, 5).
let r = Region2 {
outer: Loop2::polygon(&[Vec2::new(5.0, 5.0), Vec2::new(15.0, 5.0), Vec2::new(15.0, 25.0), Vec2::new(5.0, 25.0)]),
holes: Vec::new(),
};
let at = |a| anchor_point(std::slice::from_ref(&r), a);
assert_eq!(at(Anchor::Origin), Vec2::ZERO);
assert_eq!(at(Anchor::Center), Vec2::new(10.0, 15.0));
assert_eq!(at(Anchor::BottomLeft), Vec2::new(5.0, 5.0));
assert_eq!(at(Anchor::TopRight), Vec2::new(15.0, 25.0));
assert_eq!(at(Anchor::Left), Vec2::new(5.0, 15.0));
let c = at(Anchor::Centroid);
close(c.x, 10.0, "centroid x");
close(c.y, 15.0, "centroid y");
}
#[test]
fn default_radii_shrink_to_fit_thick_sections() {
// Each of these failed with the defaults at their usual size (#4003 review).
for j in [
serde_json::json!({"kind": "angle", "width": 20, "height": 20, "thickness": 10}),
serde_json::json!({"kind": "channel", "height": 50, "width": 10, "web": 6, "flange": 2}),
serde_json::json!({"kind": "channel", "height": 20, "width": 40, "web": 5, "flange": 8}),
serde_json::json!({"kind": "i_beam", "height": 100, "width": 10, "web": 6, "flange": 5}),
] {
let p = profile(j.clone());
let s = sec(&p);
assert!(s.area > 0.0, "{j}");
}
// A 20 × 20 × 10 angle has 10 mm of leg inside: root and toe keep their 2 : 1 ratio.
let Profile::Angle { root_radius: Some(r1), toe_radius: Some(r2), .. } =
profile(serde_json::json!({"kind": "angle", "width": 20, "height": 20, "thickness": 10})).filled()
else {
panic!("an angle")
};
close(r1, 20.0 / 3.0, "root");
close(r2, 10.0 / 3.0, "toe");
// One given, the other default takes what is left.
let Profile::Angle { toe_radius: Some(r2), .. } =
profile(serde_json::json!({"kind": "angle", "width": 20, "height": 20, "thickness": 10, "root_radius": 8})).filled()
else {
panic!("an angle")
};
close(r2, 2.0, "toe after an 8 mm root");
// A channel 20 tall with 8 mm flanges has 4 mm of web inside: two roots of 2.
let Profile::Channel { root_radius: Some(r1), .. } =
profile(serde_json::json!({"kind": "channel", "height": 20, "width": 40, "web": 5, "flange": 8})).filled()
else {
panic!("a channel")
};
close(r1, 2.0, "channel root");
// Defaults that fit are left as they are.
assert_eq!(
profile(serde_json::json!({"kind": "angle", "width": 50, "height": 50, "thickness": 5})).filled(),
Profile::Angle { width: 50.0, height: 50.0, thickness: 5.0, root_radius: Some(5.0), toe_radius: Some(2.5) }
);
}
#[test]
fn radii_given_too_large_or_too_small_are_refused_by_name() {
for (j, name) in [
(serde_json::json!({"kind": "angle", "width": 20, "height": 20, "thickness": 10, "toe_radius": 11}), "toe_radius"),
(serde_json::json!({"kind": "angle", "width": 20, "height": 20, "thickness": 10, "root_radius": 9, "toe_radius": 2}), "root_radius"),
(serde_json::json!({"kind": "channel", "height": 20, "width": 40, "web": 5, "flange": 8, "root_radius": 3}), "root_radius"),
(serde_json::json!({"kind": "i_beam", "height": 100, "width": 10, "web": 6, "flange": 5, "root_radius": 3}), "root_radius"),
(serde_json::json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3, "outer_radius": 1e-12}), "outer_radius"),
(serde_json::json!({"kind": "bar", "width": 40, "height": 10, "corner_radius": 0.001}), "corner_radius"),
] {
let err = profile(j.clone()).region().unwrap_err().to_string();
assert!(err.contains(name), "{j}: {err}");
}
// The value named is the one given, not twice it.
let err = profile(serde_json::json!({"kind": "rect_tube", "width": 10, "height": 10, "wall": 5})).region().unwrap_err().to_string();
assert!(err.contains("`wall` (5)") && err.contains("half the smaller side (5)"), "{err}");
let err = profile(serde_json::json!({"kind": "channel", "height": 10, "width": 10, "web": 2, "flange": 5})).region().unwrap_err().to_string();
assert!(err.contains("`flange` (5)"), "{err}");
}
#[test]
fn a_spec_holds_expressions_and_resolves_them() {
let spec: ProfileSpec = serde_json::from_value(serde_json::json!({"kind": "rect_tube", "width": 40, "height": "H", "wall": "2 * t"})).unwrap();
assert_eq!(spec.dims.get("width").map(|e| e.as_str()), Some("40"));
// Saved as one object of text.
assert_eq!(serde_json::to_value(&spec).unwrap(), serde_json::json!({"kind": "rect_tube", "width": "40", "height": "H", "wall": "2 * t"}));
let p = spec
.resolve(|_, e| match e.as_str() {
"40" => Ok(40.0),
"H" => Ok(60.0),
"2 * t" => Ok(3.0),
other => Err(crate::DocError::Invalid(other.into())),
})
.unwrap();
assert_eq!(p, Profile::RectTube { width: 40.0, height: 60.0, wall: 3.0, outer_radius: None });
// A value that is not a finite length is refused, naming the dimension.
let err = spec.resolve(|name, _| Ok(if name == "wall" { f64::NAN } else { 40.0 })).unwrap_err().to_string();
assert!(err.contains("wall"), "{err}");
let mut labels = Vec::new();
crate::walk::Walk::walk_exprs(&spec, &mut |(label, e, kind, _)| labels.push((label, e.as_str().to_string(), kind)));
assert_eq!(labels, [("Height", "H".into(), Kind::Length), ("Wall", "2 * t".into(), Kind::Length), ("Width", "40".into(), Kind::Length)]);
for (j, why) in [
(serde_json::json!({"width": 40}), "kind"),
(serde_json::json!({"kind": "hexagon", "width": 40}), "unknown profile kind"),
(serde_json::json!({"kind": "round_bar"}), "needs `diameter`"),
(serde_json::json!({"kind": "round_bar", "diameter": 10, "colour": 2}), "no dimension `colour`"),
(serde_json::json!({"kind": "round_bar", "diameter": true}), "number or an expression"),
(serde_json::json!({"kind": "round_bar", "diameter": " "}), "number or an expression"),
(serde_json::json!({"kind": "round_bar", "diameter": "x".repeat(5000)}), "number or an expression"),
] {
let err = serde_json::from_value::<ProfileSpec>(j.clone()).unwrap_err().to_string();
assert!(err.contains(why), "{j}: {err}");
}
}
#[test]
fn descriptions_round_to_a_tenth_of_a_micron() {
let p = Profile::RectTube { width: 25.4, height: 25.4, wall: 0.125 * 25.4, outer_radius: None };
assert_eq!(p.description(), "Rect Tube 25.4x25.4x3.175");
assert_eq!(Profile::RoundBar { diameter: 1.0 / 3.0 }.description(), "Round Bar 0.3333");
}
#[test]
fn a_line_a_hair_off_vertical_is_vertical() {
// Rounding noise must not turn a post a quarter turn (#4003 review).
let (x0, _) = member_axes(Vec3::Z, 0.0).unwrap();
for lean in [1e-8, -1e-8, 1e-12] {
let (x, _) = member_axes(Vec3::new(lean, 0.0, 1.0), 0.0).unwrap();
close(x.dist(x0), 0.0, "near-vertical x");
let (x, _) = member_axes(Vec3::new(0.0, lean, 1.0), 0.0).unwrap();
close(x.dist(x0), 0.0, "near-vertical x");
}
// A lean you can see is a lean: its y tips toward up.
let (_, y) = member_axes(Vec3::new(1e-3, 0.0, 1.0), 0.0).unwrap();
assert!(y.z > 0.0 && y.x < 0.0, "{y:?}");
}
+1
View File
@@ -27,6 +27,7 @@ mod feature_refs;
pub use face_anchor::{FaceAnchor, FaceAttachmentStatus};
pub mod format;
mod format_offsets;
pub mod frame;
mod history_names;
pub use format_offsets::whole_profile_selection_from_value;
pub mod joints;
+2
View File
@@ -43,6 +43,8 @@ impl Walk for f64 {}
impl Walk for usize {}
impl Walk for u32 {}
impl Walk for ProfileSel {}
impl Walk for std::collections::BTreeMap<String, String> {}
impl Walk for crate::frame::Anchor {}
impl Walk for solidcraft_sketch::Sketch {}
impl Walk for solidcraft_sketch::PatternAlignment {}
impl Walk for solidcraft_kernel::StepNode {}
+41 -11
View File
@@ -4,6 +4,8 @@
//! Browser items are keyed per component folder (`bodies`, `sketches`, `construction`): a body
//! by name, a sketch or construction plane by feature id.
use std::collections::BTreeMap;
use serde_json::{Value, json};
use solidcraft_doc::FeatureKind;
@@ -539,6 +541,16 @@ fn replace_body_name(v: &mut Value, old: &str, new: &str, names_body: bool, dept
}
}
/// A frame member feature's bodies by line id, as its own result made them: what pins each
/// member's name to its line. `None` for any other feature, or when they don't pair up.
fn member_pins(s: &Session, fid: u64) -> Option<BTreeMap<String, String>> {
let f = s.doc.feature(fid)?;
let result = s.model.result(fid)?;
let lines = solidcraft_doc::frame::member_line_ids(&result.state, &f.kind).ok()?;
let made: Vec<String> = result.state.bodies.iter().filter(|b| b.feature == fid).map(|b| b.name.clone()).collect();
(lines.len() == made.len()).then(|| lines.into_iter().zip(made).collect())
}
fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "body.rename";
let old = str_(p, "body").ok_or_else(|| bad(cmd, "`body` must be a body name"))?.to_string();
@@ -589,22 +601,40 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
.collect(),
None => Vec::new(),
};
// Frame members are named by their lines (#4003): each keeps the name it has now on its
// line, whichever lines come and go later, and the renamed one takes its new name.
let later_pins: Vec<Option<BTreeMap<String, String>>> = later.iter().map(|(id, _)| member_pins(s, *id)).collect();
let own_pins = member_pins(s, fid).and_then(|mut pins| {
let line = pins.iter().find(|(_, n)| **n == old).map(|(line, _)| line.clone())?;
pins.insert(line, name.to_string());
Some(pins)
});
let d = s.doc_mut();
for (id, made) in &later {
for ((id, made), pins) in later.iter().zip(later_pins) {
if let Some(f) = d.feature_mut(*id) {
f.body_names.clone_from(made);
if let (Some(pins), FeatureKind::FrameMember { names, .. }) = (pins, &mut f.kind) {
*names = pins;
f.body_names.clear();
} else {
f.body_names.clone_from(made);
}
}
}
let f = d.feature_mut(fid).ok_or_else(|| bad(cmd, "the body's feature is gone"))?;
while f.body_names.len() < siblings.len().max(k + 1) {
let i = f.body_names.len();
f.body_names.push(siblings.get(i).cloned().unwrap_or_default());
}
for (slot, current) in f.body_names.iter_mut().zip(&siblings) {
slot.clone_from(current);
}
if let Some(slot) = f.body_names.get_mut(k) {
*slot = name.to_string();
if let (Some(pins), FeatureKind::FrameMember { names, .. }) = (own_pins, &mut f.kind) {
*names = pins;
f.body_names.clear();
} else {
while f.body_names.len() < siblings.len().max(k + 1) {
let i = f.body_names.len();
f.body_names.push(siblings.get(i).cloned().unwrap_or_default());
}
for (slot, current) in f.body_names.iter_mut().zip(&siblings) {
slot.clone_from(current);
}
if let Some(slot) = f.body_names.get_mut(k) {
*slot = name.to_string();
}
}
// Later features refer to bodies by name.
let mut failed = None;
+9
View File
@@ -1238,6 +1238,7 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
| "plastic.lip"
| "plastic.snap_fit"
| "plastic.rest"
| "frame.member"
);
if !constructor {
return Err(bad(cmd, format!("`{cid}` does not make a feature")));
@@ -1262,6 +1263,14 @@ fn redefine(s: &mut Session, p: &Value) -> Result<Value> {
{
parameters.entry("convention").or_insert_with(|| json!(convention));
}
// Members keep their names through an edit, unless it gives them another name.
if let FeatureKind::FrameMember { names, body_name, .. } = &old.kind
&& cid == "frame.member"
&& let Some(parameters) = params.as_object_mut()
&& parameters.get("body_name").and_then(Value::as_str) == body_name.as_deref()
{
parameters.entry("names").or_insert_with(|| json!(names));
}
if !old.participants.is_empty()
&& let Some(parameters) = params.as_object_mut()
{
+276
View File
@@ -0,0 +1,276 @@
//! Frames and weldments (#4003). `frame.member` lays structural members along the lines of a frame
//! sketch, their cross-section a built-in profile or a profile sketch. `frame.profile.list` lists
//! the built-in profiles, `frame.profile.properties` works out a profile's section, and
//! `frame.profile.insert` draws one into a sketch.
use std::collections::BTreeMap;
use serde_json::{Value, json};
use solidcraft_doc::expr::Kind;
use solidcraft_doc::frame::{self, Anchor, MemberProfile, Profile, ProfileSpec};
use solidcraft_doc::{FeatureKind, SketchId};
use solidcraft_geom::{Loop2, Seg2, Vec2};
use solidcraft_sketch::Sketch;
use super::features::{add_feature, check_expr, sketch_id};
use super::sketch::edit;
use super::{CommandSpec, in_sketch, not_in_sketch};
use crate::params::{bad, bool_, expr, num, str_, string_list, vec2};
use crate::{Result, Session};
#[cfg(test)]
#[path = "frame_tests.rs"]
mod tests;
/// The profile parameter, as every frame command documents it.
macro_rules! profile_doc {
() => {
"profile: {kind: bar|round_bar|rect_tube|round_tube|angle|channel|i_beam, …its dimensions: each a number in the design's units or a length expression over its parameters (\"tube_wall\", \"2 in\")} (frame.profile.list gives each kind's dimensions and an example; dimensions left out take defaults from the profile's size)"
};
}
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("frame.member", "Frame Member", member).at("SOLID", "CREATE").icon("frame_member").enabled(not_in_sketch).params(concat!(
"sketch: the frame sketch (id or name; 2D or 3D); lines?: [curve ids] (one member each; default: every straight line drawn in the sketch: not construction, not projected or otherwise linked, not of no length); ",
profile_doc!(),
" | profile_sketch: a sketch whose profile is the section, in its own x and y around its origin, with profiles?: picks as solid.extrude takes them (default: its material, nested loops alternating, so two circles make a tube); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point that sits on each line, default origin); angle?: angle expr (the profile turned about the line; default 0: its y as near world up as the line allows, a vertical member's x along world X); mirror?: bool (the profile mirrored across its y axis); name?; body_name? (what the members are named after, then numbered: `Rail`, `Rail (2)`…; default the profile's description, `Rect Tube 40x40x3`, or the profile sketch's name); names?: {line id: name} (names to keep, as Edit Feature keeps them). One body per line, from its start to its end; each member keeps its name when other lines are added or deleted. Returns the feature and the bodies it made"
)),
CommandSpec::new("frame.profile.list", "Profile Library", list).icon("library")
.noundo()
.doc_only()
.params("Returns kinds: [{kind, label, required, optional, example}]: the built-in profiles, each SolidCraft's own parametric definition"),
CommandSpec::new("frame.profile.properties", "Profile Properties", properties).icon("measure").noundo().doc_only().params(concat!(
profile_doc!(),
"; density?: kg/m³ (adds mass_per_m, kg/m). Returns profile (every default filled in), area (mm²), centroid [x,y] (mm, from the bounding box centre), ixx, iyy, ixy (mm⁴ about the centroid), width, height"
)),
CommandSpec::new("frame.profile.insert", "Insert Profile", insert).icon("import").enabled(in_sketch).params(concat!(
profile_doc!(),
"; at?: [x,y] (sketch mm, default the origin); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point placed on `at`: its origin, the default and a built-in profile's centre, its bounding box's centre, its centroid, or a corner or edge middle of its bounding box); angle?: radians, counter-clockwise; fixed?: bool (default true: the curves are locked, so solving the sketch keeps the shape); sketch?: id|name (default: the sketch being edited). Returns the section as frame.profile.properties does",
created_doc!()
)),
];
/// The `profile` parameter: its kind and each dimension as given, a number or an expression.
fn profile_spec(cmd: &str, p: &Value) -> Result<ProfileSpec> {
let v = p.get("profile").ok_or_else(|| bad(cmd, "`profile` is required (frame.profile.list gives the kinds)"))?;
serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("`profile`: {e}")))
}
/// The profile a spec makes in this design: a bare number in the design's units, an expression
/// over its parameters.
fn resolve(s: &Session, cmd: &str, spec: &ProfileSpec) -> Result<Profile> {
let doc = &s.doc;
spec.resolve(|name, e| {
doc.eval(&doc.with_design_unit(e, Kind::Length), Kind::Length)
.map_err(|err| solidcraft_doc::DocError::Invalid(format!("profile `{name}`: {err}")))
})
.map_err(|e| bad(cmd, e.to_string()))
}
/// The profile of `p`, worked out in this design.
fn profile(s: &Session, cmd: &str, p: &Value) -> Result<Profile> {
resolve(s, cmd, &profile_spec(cmd, p)?)
}
fn list(_: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({"kinds": frame::profile_kinds()}))
}
/// The profile's section as the commands report it.
fn section_json(cmd: &str, profile: &Profile, density: Option<f64>) -> Result<Value> {
let region = profile.region().map_err(|e| bad(cmd, e.to_string()))?;
let s = frame::section(&region);
let mut out = json!({
"profile": profile.filled(),
"area": s.area,
"centroid": s.centroid,
"ixx": s.ixx,
"iyy": s.iyy,
"ixy": s.ixy,
"width": s.width,
"height": s.height,
});
if let (Some(rho), Some(o)) = (density, out.as_object_mut()) {
// mm² × 1e-6 m²/mm² × kg/m³ = kg/m.
o.insert("mass_per_m".into(), json!(s.area * 1e-6 * rho));
}
Ok(out)
}
fn properties(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "frame.profile.properties";
let profile = profile(s, cmd, p)?;
let density = match p.get("density") {
None | Some(Value::Null) => None,
Some(_) => Some(
num(p, "density")
.filter(|d| *d > 0.0 && *d <= 1e6)
.ok_or_else(|| bad(cmd, "`density` must be a positive number of kg/m³ (at most 1e6)"))?,
),
};
section_json(cmd, &profile, density)
}
fn insert(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "frame.profile.insert";
let profile = profile(s, cmd, p)?;
let at = match p.get("at") {
None | Some(Value::Null) => Vec2::ZERO,
Some(v) => vec2(v).ok_or_else(|| bad(cmd, "`at` must be [x, y] in sketch millimetres"))?,
};
let anchor: Anchor = match p.get("anchor") {
None | Some(Value::Null) => Anchor::default(),
Some(v) => serde_json::from_value(v.clone()).map_err(|_| {
bad(cmd, "`anchor` must be origin, center, centroid, top_left, top, top_right, left, right, bottom_left, bottom or bottom_right")
})?,
};
let angle = match p.get("angle") {
None | Some(Value::Null) => 0.0,
Some(_) => num(p, "angle").filter(|a| a.abs() <= 1e6).ok_or_else(|| bad(cmd, "`angle` must be a number of radians"))?,
};
let fixed = match p.get("fixed") {
None | Some(Value::Null) => true,
Some(_) => bool_(p, "fixed").ok_or_else(|| bad(cmd, "`fixed` must be true or false"))?,
};
let region = profile.region().map_err(|e| bad(cmd, e.to_string()))?;
let placed = frame::placed(&region, frame::anchor_point(std::slice::from_ref(&region), anchor), at, angle);
let section = section_json(cmd, &profile, None)?;
let (created, info) = edit(s, p, cmd, false, |sk, _| {
let before = sk.clone();
for l in std::iter::once(&placed.outer).chain(&placed.holes) {
add_loop(sk, l, fixed, cmd)?;
}
Ok(super::sketch_created(Some(&before), sk))
})?;
Ok(json!({"created": created, "section": section, "sketch": info}))
}
/// Draw the closed loop `l` (lines and arcs) into the sketch, each segment sharing its end
/// points with its neighbours; a loop of two half arcs of one circle becomes a circle.
fn add_loop(sk: &mut Sketch, l: &Loop2, fixed: bool, cmd: &str) -> Result<()> {
let mut curves = Vec::new();
if let [Seg2::Arc { center: c0, radius: r0, sweep: s0, .. }, Seg2::Arc { center: c1, radius: r1, sweep: s1, .. }] = l.segs.as_slice()
&& c0.dist(*c1) <= 1e-9
&& (r0 - r1).abs() <= 1e-9
&& ((s0 + s1).abs() - std::f64::consts::TAU).abs() <= 1e-9
{
curves.push(sk.add_circle(*c0, *r0, None, None)?);
} else {
let pts = l.segs.iter().map(|g| sk.add_point(g.start(), None)).collect::<std::result::Result<Vec<_>, _>>()?;
let n = pts.len();
for (i, g) in l.segs.iter().enumerate() {
let (Some(&a), Some(&b)) = (pts.get(i), pts.get((i + 1) % n)) else {
return Err(bad(cmd, "a profile segment is missing its end"));
};
let c = match *g {
Seg2::Line { .. } => sk.add_line_pts(a, b, None)?,
// The sketch's arcs run counter-clockwise: a clockwise one is drawn from its end.
Seg2::Arc { center, sweep, .. } if sweep >= 0.0 => sk.add_arc(center, g.start(), g.end(), [None, Some(a), Some(b)], None)?,
Seg2::Arc { center, .. } => sk.add_arc(center, g.end(), g.start(), [None, Some(b), Some(a)], None)?,
_ => return Err(bad(cmd, "not supported yet: profiles with free-form edges")),
};
curves.push(c);
}
}
if fixed {
for c in curves {
if let Some(cu) = sk.curves.get_mut(c) {
cu.fixed = true;
}
}
}
Ok(())
}
fn member(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "frame.member";
let path_sketch = sketch_id(s, p.get("sketch"), cmd, "sketch")?;
let lines = match p.get("lines") {
None | Some(Value::Null) => Vec::new(),
Some(Value::Array(a)) if !a.is_empty() && a.len() <= frame::MAX_MEMBERS && a.iter().all(Value::is_string) => {
let lines = string_list(p, "lines");
let mut seen = std::collections::HashSet::new();
if let Some(twice) = lines.iter().find(|l| !seen.insert(l.as_str())) {
return Err(bad(cmd, format!("line `{twice}` is listed twice")));
}
lines
}
Some(_) => Err(bad(cmd, format!("`lines` must list 1…{} curve ids", frame::MAX_MEMBERS)))?,
};
let body_name = match p.get("body_name") {
None | Some(Value::Null) => None,
Some(_) => Some(
str_(p, "body_name")
.map(str::trim)
.filter(|n| !n.is_empty() && n.len() <= 128)
.ok_or_else(|| bad(cmd, "`body_name` must be 1…128 characters"))?
.to_string(),
),
};
let (profile, default_name) = match (p.get("profile"), p.get("profile_sketch")) {
(Some(_), None) => {
let spec = profile_spec(cmd, p)?;
let pr = resolve(s, cmd, &spec)?;
pr.region().map_err(|e| bad(cmd, e.to_string()))?;
(MemberProfile::Library { profile: spec }, pr.description())
}
(None, Some(v)) => {
let id = sketch_id(s, Some(v), cmd, "profile_sketch")?;
if id == path_sketch {
return Err(bad(cmd, "the profile sketch must not be the frame sketch"));
}
let name = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_else(|| "Member".into());
(MemberProfile::Sketch { sketch: SketchId(id), profiles: super::feature_profiles(p, cmd)? }, name)
}
_ => return Err(bad(cmd, "give `profile` (a built-in profile) or `profile_sketch` (a sketch), one of them")),
};
let anchor: Anchor = match p.get("anchor") {
None | Some(Value::Null) => Anchor::default(),
Some(v) => serde_json::from_value(v.clone()).map_err(|_| {
bad(cmd, "`anchor` must be origin, center, centroid, top_left, top, top_right, left, right, bottom_left, bottom or bottom_right")
})?,
};
let angle = match p.get("angle") {
None | Some(Value::Null) => None,
Some(_) => {
let e = expr(p, "angle").ok_or_else(|| bad(cmd, "`angle` must be an angle expression"))?;
check_expr(s, &e, solidcraft_doc::expr::Kind::Angle, cmd, "angle")?;
Some(e)
}
};
let mirror = match p.get("mirror") {
None | Some(Value::Null) => false,
Some(_) => bool_(p, "mirror").ok_or_else(|| bad(cmd, "`mirror` must be true or false"))?,
};
let kept: BTreeMap<String, String> = match p.get("names") {
None | Some(Value::Null) => BTreeMap::new(),
Some(Value::Object(m)) if m.len() <= frame::MAX_MEMBERS => m
.iter()
.map(|(line, v)| {
let name = v.as_str().map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128);
name.map(|n| (line.clone(), n.to_string()))
.ok_or_else(|| bad(cmd, format!("`names`: the name of line `{line}` must be 1…128 characters")))
})
.collect::<Result<_>>()?,
Some(_) => return Err(bad(cmd, format!("`names` must map up to {} line ids to names", frame::MAX_MEMBERS))),
};
let base = body_name.clone().unwrap_or(default_name);
let mut kind =
FeatureKind::FrameMember { path_sketch: SketchId(path_sketch), lines, profile, anchor, angle, mirror, body_name, names: BTreeMap::new() };
// Each member's name is pinned to its line as the feature is made, so deleting or adding a
// line later leaves the other members' names alone.
let st = s.model.state();
let ids = frame::member_line_ids(&st, &kind).map_err(|e| bad(cmd, e.to_string()))?;
let pinned: BTreeMap<String, String> = ids.iter().cloned().zip(frame::member_names(&st, &ids, &kept, &base)).collect();
if let FeatureKind::FrameMember { names, .. } = &mut kind {
*names = pinned;
}
// The feature names its own members (`body_name`, `names`), not by position.
let mut p = p.clone();
if let Some(o) = p.as_object_mut() {
o.remove("body_name");
o.remove("body_names");
o.remove("names");
}
add_feature(s, &p, kind)
}
+640
View File
@@ -0,0 +1,640 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use serde_json::{Value, json};
use std::f64::consts::PI;
use crate::Session;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
match s.execute(id, &p) {
Ok(v) => v,
Err(e) => panic!("{id} {p}: {e}"),
}
}
fn f(v: &Value) -> f64 {
v.as_f64().unwrap_or_else(|| panic!("not a number: {v}"))
}
fn rel(a: f64, b: f64) -> f64 {
(a - b).abs() / b.abs().max(1e-12)
}
fn new_sketch() -> Session {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY"}));
s
}
/// The areas of the active sketch's profiles, largest first.
fn profile_areas(s: &Session) -> Vec<f64> {
let id = s.active_sketch.unwrap();
let mut a: Vec<f64> = s.model.state().sketch(id).unwrap().profiles.iter().map(|p| p.area).collect();
a.sort_by(|x, y| y.total_cmp(x));
a
}
#[test]
fn list_gives_every_kind_with_a_working_example() {
let mut s = Session::default();
let out = run(&mut s, "frame.profile.list", json!({}));
let kinds = out["kinds"].as_array().unwrap();
let ids: Vec<&str> = kinds.iter().filter_map(|k| k["kind"].as_str()).collect();
assert_eq!(ids, ["bar", "round_bar", "rect_tube", "round_tube", "angle", "channel", "i_beam"]);
for k in kinds {
let r = run(&mut s, "frame.profile.properties", json!({"profile": k["example"]}));
assert!(f(&r["area"]) > 0.0, "{}", k["kind"]);
}
}
#[test]
fn properties_fill_defaults_and_give_mass_per_metre() {
let mut s = Session::default();
let r = run(
&mut s,
"frame.profile.properties",
json!({"profile": {"kind": "rect_tube", "width": 40, "height": 40, "wall": 3, "outer_radius": 0}, "density": 7850}),
);
let area = 40.0 * 40.0 - 34.0 * 34.0;
assert!(rel(f(&r["area"]), area) < 1e-12, "{r}");
assert!(rel(f(&r["mass_per_m"]), area * 1e-6 * 7850.0) < 1e-12, "{r}");
assert!(rel(f(&r["ixx"]), (40f64.powi(4) - 34f64.powi(4)) / 12.0) < 1e-12, "{r}");
let r = run(&mut s, "frame.profile.properties", json!({"profile": {"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}}));
assert_eq!(r["profile"]["outer_radius"], json!(6.0), "{r}");
assert!(r.get("mass_per_m").is_none(), "{r}");
}
#[test]
fn bad_profiles_are_refused_with_the_reason() {
let mut s = new_sketch();
for (p, why) in [
(json!({}), "`profile` is required"),
(json!({"profile": {"kind": "hexagon"}}), "`profile`"),
(json!({"profile": {"kind": "rect_tube", "width": 10, "height": 10, "wall": 5}}), "wall"),
(json!({"profile": {"kind": "round_bar", "diameter": -1}}), "diameter"),
(json!({"profile": {"kind": "round_bar", "diameter": 10}, "density": -1}), "density"),
(json!({"profile": {"kind": "round_bar", "diameter": 10}, "density": "steel"}), "density"),
] {
let err = s.execute("frame.profile.properties", &p).unwrap_err().to_string();
assert!(err.contains(why), "{p}: {err}");
}
for p in [
json!({"profile": {"kind": "round_bar", "diameter": 10}, "at": [1e300, 0]}),
json!({"profile": {"kind": "round_bar", "diameter": 10}, "at": "here"}),
json!({"profile": {"kind": "round_bar", "diameter": 10}, "anchor": "middle"}),
json!({"profile": {"kind": "round_bar", "diameter": 10}, "angle": "a lot"}),
json!({"profile": {"kind": "round_bar", "diameter": 10}, "fixed": 3}),
] {
assert!(s.execute("frame.profile.insert", &p).is_err(), "{p} is refused");
}
// Nothing was drawn.
assert!(profile_areas(&s).is_empty());
}
#[test]
fn insert_needs_a_sketch() {
let mut s = Session::default();
assert!(s.execute("frame.profile.insert", &json!({"profile": {"kind": "round_bar", "diameter": 10}})).is_err());
}
#[test]
fn inserted_tube_is_one_profile_with_its_hole() {
let mut s = new_sketch();
let r = run(&mut s, "frame.profile.insert", json!({"profile": {"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}}));
let area = f(&r["section"]["area"]);
// Outer radius 6, inner radius 3.
let want = (1600.0 - (4.0 - PI) * 36.0) - (34.0 * 34.0 - (4.0 - PI) * 9.0);
assert!(rel(area, want) < 1e-12, "{r}");
// Four lines and four arcs outside, the same inside.
assert_eq!(r["created"]["curves"].as_array().unwrap().len(), 16, "{r}");
// The sketch has the wall and, as a region of its own, the inside.
let areas = profile_areas(&s);
assert_eq!(areas.len(), 2, "{areas:?}");
assert!(areas.iter().any(|a| rel(*a, want) < 1e-9), "the wall is the tube's section: {areas:?}");
}
#[test]
fn inserted_channel_extrudes_to_its_area_times_length() {
let mut s = new_sketch();
let r = run(
&mut s,
"frame.profile.insert",
json!({"profile": {"kind": "channel", "height": 60, "width": 45, "web": 5, "flange": 6}, "at": [100, 50], "anchor": "bottom_left"}),
);
let area = f(&r["section"]["area"]);
let areas = profile_areas(&s);
assert!(areas.iter().any(|a| rel(*a, area) < 1e-9), "{areas:?} vs {area}");
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "solid.extrude", json!({"distance": 500, "profiles": [{"point": [101.5, 51.5]}]}));
let m = run(&mut s, "inspect.measure", json!({}));
let v = f(&m["total"]["volume_mm3"]);
// The kernel measures arcs through their facets: within 1e-4.
assert!(rel(v, area * 500.0) < 1e-4, "volume {v} vs {}", area * 500.0);
// The bottom-left corner sits on (100, 50): the body spans 100…145 and 50…110.
let bb = &m["bodies"][0]["bbox"];
let near = |v: &Value, want: f64| (f(v) - want).abs() < 1e-6;
assert!(near(&bb["min"][0], 100.0) && near(&bb["min"][1], 50.0) && near(&bb["max"][0], 145.0) && near(&bb["max"][1], 110.0), "{bb}");
}
#[test]
fn inserted_profile_turns_about_its_anchor_and_stays_fixed() {
let mut s = new_sketch();
let r = run(
&mut s,
"frame.profile.insert",
json!({"profile": {"kind": "angle", "width": 60, "height": 40, "thickness": 5}, "anchor": "bottom_left", "angle": PI / 2.0}),
);
let id = s.active_sketch.unwrap();
let sk = s.model.state().sketch(id).unwrap().sketch.clone();
let created: Vec<&str> = r["created"]["curves"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
assert!(!created.is_empty());
for c in sk.curves.iter().filter(|c| created.contains(&c.id.as_str())) {
assert!(c.fixed, "{} is locked", c.id);
}
// Turned a quarter about the heel at the origin: the 60 mm leg runs up the y axis, the 40 mm
// one along −x.
let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
for p in &sk.points {
lo = [lo[0].min(p.pos.x), lo[1].min(p.pos.y)];
hi = [hi[0].max(p.pos.x), hi[1].max(p.pos.y)];
}
assert!((lo[0] + 40.0).abs() < 1e-9 && hi[0].abs() < 1e-9 && lo[1].abs() < 1e-9 && (hi[1] - 60.0).abs() < 1e-9, "{lo:?} {hi:?}");
// Unlocked on request.
let r =
run(&mut s, "frame.profile.insert", json!({"profile": {"kind": "round_tube", "diameter": 20, "wall": 2}, "at": [200, 0], "fixed": false}));
assert_eq!(r["created"]["curves"].as_array().unwrap().len(), 2, "two circles: {r}");
let sk = s.model.state().sketch(id).unwrap().sketch.clone();
assert!(sk.curves.iter().filter(|c| r["created"]["curves"].as_array().unwrap().contains(&json!(c.id))).all(|c| !c.fixed));
}
#[test]
fn insert_is_one_undo_step() {
let mut s = new_sketch();
run(&mut s, "frame.profile.insert", json!({"profile": {"kind": "i_beam", "height": 100, "width": 50, "web": 4.5, "flange": 7}}));
assert_eq!(profile_areas(&s).len(), 1);
run(&mut s, "edit.undo", json!({}));
assert!(profile_areas(&s).is_empty());
}
// ---------------------------------------------------------------------------------------------
// Members
/// How close a measured volume comes: the kernel measures curved faces through their facets.
const MEASURED: f64 = 1e-3;
/// The section area of a 40 × 40 × 3 rectangular tube (outer radius 6, inner 3).
fn tube_area() -> f64 {
(1600.0 - (4.0 - PI) * 36.0) - (34.0 * 34.0 - (4.0 - PI) * 9.0)
}
fn tube() -> Value {
json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3})
}
/// A body's name, volume, bounding box and centre of mass.
type Measured = (String, f64, [f64; 3], [f64; 3], [f64; 3]);
fn bodies(s: &mut Session) -> Vec<Measured> {
let m = run(s, "inspect.measure", json!({}));
let v3 = |v: &Value| [f(&v[0]), f(&v[1]), f(&v[2])];
m["bodies"]
.as_array()
.unwrap()
.iter()
.map(|b| {
(b["name"].as_str().unwrap().to_string(), f(&b["volume_mm3"]), v3(&b["bbox"]["min"]), v3(&b["bbox"]["max"]), v3(&b["center_of_mass"]))
})
.collect()
}
fn total_volume(s: &mut Session) -> f64 {
bodies(s).iter().map(|b| b.1).sum()
}
fn near3(got: [f64; 3], want: [f64; 3]) -> bool {
got.iter().zip(want).all(|(g, w)| (g - w).abs() < 1e-6)
}
/// A 600 × 400 rectangle on XY, as the frame sketch `Frame`.
fn rectangle_frame(s: &mut Session) {
run(s, "sketch.create", json!({"plane": "XY", "name": "Frame"}));
run(s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [600, 400]}));
run(s, "sketch.finish", json!({}));
}
#[test]
fn members_follow_every_line_of_a_rectangle() {
let mut s = Session::default();
rectangle_frame(&mut s);
let r = run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()}));
let bs = bodies(&mut s);
assert_eq!(bs.len(), 4, "{r}");
let names: Vec<&str> = bs.iter().map(|b| b.0.as_str()).collect();
assert_eq!(names, ["Rect Tube 40x40x3", "Rect Tube 40x40x3 (2)", "Rect Tube 40x40x3 (3)", "Rect Tube 40x40x3 (4)"]);
// Each member is the section run the length of its line: 2 × 600 + 2 × 400.
let v = total_volume(&mut s);
assert!(rel(v, tube_area() * 2000.0) < MEASURED, "{v} vs {}", tube_area() * 2000.0);
// The bottom line runs along +X: the profile is centred on it, square to it.
assert!(bs.iter().any(|b| near3(b.2, [0.0, -20.0, -20.0]) && near3(b.3, [600.0, 20.0, 20.0])), "{bs:?}");
// The right line runs along Y at x = 600.
assert!(bs.iter().any(|b| near3(b.2, [580.0, 0.0, -20.0]) && near3(b.3, [620.0, 400.0, 20.0])), "{bs:?}");
}
#[test]
fn members_follow_a_parameter_edit() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "W", "expression": "600 mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Frame"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], ["W", 0], ["W", 400], [0, 400]], "closed": true}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()}));
assert!(rel(total_volume(&mut s), tube_area() * 2000.0) < MEASURED);
run(&mut s, "parameters.change", json!({"name": "W", "expression": "800 mm"}));
// The two 600 mm members are 800 mm now.
let v = total_volume(&mut s);
assert!(rel(v, tube_area() * 2400.0) < MEASURED, "{v} vs {}", tube_area() * 2400.0);
}
#[test]
fn members_along_3d_sketch_lines() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Tower"}));
run(&mut s, "sketch.options", json!({"sketch_3d": true}));
run(&mut s, "sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1500], [600, 0, 1500]]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "frame.member", json!({"sketch": "Tower", "profile": tube()}));
let bs = bodies(&mut s);
assert_eq!(bs.len(), 2, "{bs:?}");
// The upright: square to Z, the profile's x along world X.
assert!(bs.iter().any(|b| near3(b.2, [-20.0, -20.0, 0.0]) && near3(b.3, [20.0, 20.0, 1500.0])), "{bs:?}");
// The rail along X at the top.
assert!(bs.iter().any(|b| near3(b.2, [0.0, -20.0, 1480.0]) && near3(b.3, [600.0, 20.0, 1520.0])), "{bs:?}");
let v = total_volume(&mut s);
assert!(rel(v, tube_area() * 2100.0) < MEASURED, "{v} vs {} {bs:?}", tube_area() * 2100.0);
}
#[test]
fn a_profile_sketch_is_the_section() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Tube section"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 20}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 17}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Post"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [1000, 0]]}));
run(&mut s, "sketch.finish", json!({}));
// The material: the ring between the circles (nested loops alternate).
run(&mut s, "frame.member", json!({"sketch": "Post", "profile_sketch": "Tube section"}));
let bs = bodies(&mut s);
assert_eq!(bs.len(), 1);
assert_eq!(bs[0].0, "Tube section");
let ring = PI * (400.0 - 289.0) * 1000.0;
assert!(rel(bs[0].1, ring) < MEASURED, "{} vs {ring}", bs[0].1);
// Picked: the inner disc alone.
run(&mut s, "frame.member", json!({"sketch": "Post", "profile_sketch": "Tube section", "profiles": [{"point": [0, 0]}]}));
// A second feature of the same profile numbers on from the first.
let disc = bodies(&mut s).into_iter().find(|b| b.0 != "Tube section").unwrap();
assert_eq!(disc.0, "Tube section (2)");
assert!(rel(disc.1, PI * 289.0 * 1000.0) < MEASURED, "{disc:?}");
}
#[test]
fn anchor_angle_and_mirror_place_the_profile() {
let place = |extra: Value| {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Rail"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [1000, 0]]}));
run(&mut s, "sketch.finish", json!({}));
let mut p = json!({"sketch": "Rail", "profile": {"kind": "angle", "width": 60, "height": 40, "thickness": 5}, "anchor": "bottom_left"});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
run(&mut s, "frame.member", p);
bodies(&mut s).remove(0)
};
// Along +X the profile's x is world +Y and its y world +Z: the heel on the line, the legs
// running +Y (60) and +Z (40).
let plain = place(json!({}));
assert!(near3(plain.2, [0.0, 0.0, 0.0]) && near3(plain.3, [1000.0, 60.0, 40.0]), "{plain:?}");
// Turned a quarter: the 60 mm leg up, the 40 mm one toward −Y.
let b = place(json!({"angle": "90 deg"}));
assert!(near3(b.2, [0.0, -40.0, 0.0]) && near3(b.3, [1000.0, 0.0, 60.0]), "{b:?}");
// Mirrored: the same box, the heel at the far side (the mass sits past the middle).
let m = place(json!({"mirror": true}));
assert!(near3(m.2, [0.0, 0.0, 0.0]) && near3(m.3, [1000.0, 60.0, 40.0]), "{m:?}");
assert!(plain.4[1] < 30.0 && m.4[1] > 30.0, "{plain:?} {m:?}");
}
#[test]
fn bad_members_are_refused() {
let mut s = Session::default();
rectangle_frame(&mut s);
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Arc"}));
let arc = run(&mut s, "sketch.arc.three_point", json!({"start": [0, 0], "end": [100, 0], "through": [50, 30]}));
let arc_id = arc["created"]["curves"][0].as_str().unwrap().to_string();
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Empty"}));
run(&mut s, "sketch.finish", json!({}));
for (p, why) in [
(json!({"sketch": "Frame"}), "`profile`"),
(json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Frame"}), "one of them"),
(json!({"sketch": "Frame", "profile_sketch": "Frame"}), "must not be the frame sketch"),
(json!({"sketch": "Nowhere", "profile": tube()}), "no sketch"),
(json!({"sketch": "Frame", "profile": {"kind": "rect_tube", "width": 10, "height": 10, "wall": 5}}), "wall"),
(json!({"sketch": "Frame", "profile": tube(), "lines": []}), "`lines`"),
(json!({"sketch": "Frame", "profile": tube(), "lines": ["nope"]}), "nope"),
(json!({"sketch": "Arc", "profile": tube(), "lines": [arc_id]}), "not a straight line"),
(json!({"sketch": "Arc", "profile": tube()}), "no lines"),
(json!({"sketch": "Empty", "profile": tube()}), "no lines"),
(json!({"sketch": "Frame", "profile": tube(), "anchor": "middle"}), "`anchor`"),
(json!({"sketch": "Frame", "profile": tube(), "angle": "a lot"}), "angle"),
(json!({"sketch": "Frame", "profile": tube(), "mirror": 3}), "`mirror`"),
(json!({"sketch": "Frame", "profile": tube(), "names": ["Rail"]}), "`names`"),
(json!({"sketch": "Frame", "profile": tube(), "names": {"l1": " "}}), "`names`"),
] {
let err = s.execute("frame.member", &p).unwrap_err().to_string();
assert!(err.contains(why), "{p}: {err}");
}
assert!(bodies(&mut s).is_empty(), "nothing was made");
// Not while a sketch is open.
run(&mut s, "sketch.create", json!({"plane": "XY"}));
assert!(s.execute("frame.member", &json!({"sketch": "Frame", "profile": tube()})).is_err());
}
#[test]
fn members_undo_and_survive_save_and_reopen() {
let mut s = Session::default();
rectangle_frame(&mut s);
run(
&mut s,
"frame.member",
json!({"sketch": "Frame", "profile": tube(), "anchor": "bottom", "angle": "15 deg", "mirror": true, "body_name": "Rail"}),
);
let before = bodies(&mut s);
assert_eq!(before.len(), 4);
assert_eq!(before[0].0, "Rail");
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
let after = bodies(&mut reopened);
assert_eq!(before.len(), after.len());
for (b, a) in before.iter().zip(&after) {
assert_eq!(b.0, a.0);
assert!(rel(a.1, b.1) < 1e-9 && near3(a.2, b.2) && near3(a.3, b.3), "{b:?} vs {a:?}");
}
run(&mut s, "edit.undo", json!({}));
assert!(bodies(&mut s).is_empty());
run(&mut s, "edit.redo", json!({}));
assert_eq!(bodies(&mut s).len(), 4);
}
// ---------------------------------------------------------------------------------------------
// Regressions from the adversarial review of #4003
/// The lines of sketch `name`, as (id, start, end) in sketch coordinates.
fn sketch_lines(s: &Session, name: &str) -> Vec<(String, [f64; 2], [f64; 2])> {
let id = s.doc.find_feature(name).unwrap().id;
let sk = s.doc.sketch(id).unwrap();
sk.curves
.iter()
.filter_map(|c| match c.kind {
solidcraft_sketch::CurveKind::Line { a, b } => {
let (p, q) = (sk.points[a].pos, sk.points[b].pos);
Some((c.id.clone(), [p.x, p.y], [q.x, q.y]))
}
_ => None,
})
.collect()
}
/// The id of the line of sketch `name` with both ends at x = `x`.
fn line_at_x(s: &Session, name: &str, x: f64) -> String {
sketch_lines(s, name).into_iter().find(|(_, a, b)| (a[0] - x).abs() < 1e-9 && (b[0] - x).abs() < 1e-9).unwrap().0
}
/// The id of the line of sketch `name` with both ends at y = `y`.
fn line_at_y(s: &Session, name: &str, y: f64) -> String {
sketch_lines(s, name).into_iter().find(|(_, a, b)| (a[1] - y).abs() < 1e-9 && (b[1] - y).abs() < 1e-9).unwrap().0
}
fn delete_line(s: &mut Session, sketch: &str, line: &str) {
run(s, "sketch.edit", json!({"sketch": sketch}));
run(s, "sketch.delete", json!({"entities": [line]}));
run(s, "sketch.finish", json!({}));
}
/// Each body's bounding box by name.
fn boxes(s: &mut Session) -> std::collections::BTreeMap<String, ([f64; 3], [f64; 3])> {
bodies(s).into_iter().map(|b| (b.0, (b.2, b.3))).collect()
}
#[test]
fn projected_edges_are_not_member_lines() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 10, "body_name": "Plate"}));
// A sketch on the plate's top face projects its edges; the one line drawn is the only member.
run(&mut s, "sketch.create", json!({"plane": {"face": [50, 50, 10]}, "name": "On plate"}));
run(&mut s, "sketch.line", json!({"points": [[10, 10], [90, 10]]}));
run(&mut s, "sketch.finish", json!({}));
// The plate's four edges are in the sketch, projected.
assert_eq!(sketch_lines(&s, "On plate").len(), 5);
run(&mut s, "frame.member", json!({"sketch": "On plate", "profile": tube()}));
let members: Vec<Measured> = bodies(&mut s).into_iter().filter(|b| b.0 != "Plate").collect();
assert_eq!(members.len(), 1, "{members:?}");
assert!(rel(members[0].1, tube_area() * 80.0) < MEASURED, "{members:?}");
}
#[test]
fn a_profile_sketch_on_a_face_is_its_drawn_section() {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 100, "width": 100, "height": 10, "body_name": "Plate"}));
run(&mut s, "sketch.create", json!({"plane": {"face": [50, 50, 10]}, "name": "Section on plate"}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 20}));
run(&mut s, "sketch.circle.center", json!({"center": [0, 0], "radius": 17}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "sketch.create", json!({"plane": "XZ", "name": "Post"}));
run(&mut s, "sketch.line", json!({"points": [[200, 0], [200, 1000]]}));
run(&mut s, "sketch.finish", json!({}));
assert_eq!(sketch_lines(&s, "Section on plate").len(), 4, "the plate's edges, projected");
run(&mut s, "frame.member", json!({"sketch": "Post", "profile_sketch": "Section on plate"}));
let member = bodies(&mut s).into_iter().find(|b| b.0 != "Plate").unwrap();
assert!(rel(member.1, PI * (400.0 - 289.0) * 1000.0) < MEASURED, "{member:?}");
}
#[test]
fn members_keep_their_names_when_a_line_is_deleted() {
let mut s = Session::default();
rectangle_frame(&mut s);
run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()}));
let before = boxes(&mut s);
assert_eq!(before.len(), 4);
let right = line_at_x(&s, "Frame", 600.0);
delete_line(&mut s, "Frame", &right);
let after = boxes(&mut s);
assert_eq!(after.len(), 3, "{after:?}");
// Each member left is still called what it was, and is where it was.
for (name, bb) in &after {
assert_eq!(before.get(name), Some(bb), "{name} moved: {before:?} → {after:?}");
}
}
#[test]
fn a_renamed_member_keeps_its_name_through_line_edits() {
let mut s = Session::default();
rectangle_frame(&mut s);
run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()}));
let top = boxes(&mut s).into_iter().find(|(_, (lo, _))| (lo[1] - 380.0).abs() < 1e-6).unwrap();
run(&mut s, "body.rename", json!({"body": top.0, "name": "Top rail"}));
let before = boxes(&mut s);
assert_eq!(before.get("Top rail"), Some(&top.1));
let left = line_at_x(&s, "Frame", 0.0);
delete_line(&mut s, "Frame", &left);
let after = boxes(&mut s);
assert_eq!(after.len(), 3);
for (name, bb) in &after {
assert_eq!(before.get(name), Some(bb), "{name}: {before:?} → {after:?}");
}
// It survives saving and reopening.
let mut reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());
assert_eq!(boxes(&mut reopened), after);
}
#[test]
fn a_numbered_member_name_is_kept_when_the_first_feature_goes() {
let mut s = Session::default();
rectangle_frame(&mut s);
let (bottom, top) = (line_at_y(&s, "Frame", 0.0), line_at_y(&s, "Frame", 400.0));
run(&mut s, "frame.member", json!({"sketch": "Frame", "lines": [bottom], "profile": tube(), "name": "First"}));
run(&mut s, "frame.member", json!({"sketch": "Frame", "lines": [top], "profile": tube(), "name": "Second"}));
assert_eq!(boxes(&mut s).keys().collect::<Vec<_>>(), ["Rect Tube 40x40x3", "Rect Tube 40x40x3 (2)"]);
run(&mut s, "timeline.delete", json!({"feature": "First"}));
assert_eq!(boxes(&mut s).keys().collect::<Vec<_>>(), ["Rect Tube 40x40x3 (2)"]);
}
#[test]
fn an_asymmetric_profile_turns_with_its_3d_line() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Tower"}));
run(&mut s, "sketch.options", json!({"sketch_3d": true}));
run(&mut s, "sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 1500], [600, 0, 1500]]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "frame.member", json!({"sketch": "Tower", "profile": {"kind": "bar", "width": 60, "height": 10}}));
let bs = bodies(&mut s);
// The post: the bar's width (its x) along world X, its height along Y.
assert!(bs.iter().any(|b| near3(b.2, [-30.0, -5.0, 0.0]) && near3(b.3, [30.0, 5.0, 1500.0])), "{bs:?}");
// The rail along +X: width along +Y, height up.
assert!(bs.iter().any(|b| near3(b.2, [0.0, -30.0, 1495.0]) && near3(b.3, [600.0, 30.0, 1505.0])), "{bs:?}");
}
#[test]
fn a_post_a_hair_off_vertical_is_oriented_as_a_vertical_one() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Posts"}));
run(&mut s, "sketch.options", json!({"sketch_3d": true}));
run(&mut s, "sketch.line3d", json!({"points": [[0, 0, 0], [1e-5, 0, 1000]]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "frame.member", json!({"sketch": "Posts", "profile": {"kind": "bar", "width": 60, "height": 10}}));
let b = bodies(&mut s).remove(0);
// Width along X as for a true vertical, not along Y.
assert!((b.3[0] - b.2[0] - 60.0).abs() < 1e-3 && (b.3[1] - b.2[1] - 10.0).abs() < 1e-3, "{b:?}");
}
#[test]
fn thick_sections_build_with_their_default_radii() {
let mut s = Session::default();
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Rail"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [500, 0]]}));
run(&mut s, "sketch.finish", json!({}));
for profile in [
json!({"kind": "angle", "width": 20, "height": 20, "thickness": 10}),
json!({"kind": "channel", "height": 50, "width": 10, "web": 6, "flange": 2}),
json!({"kind": "channel", "height": 20, "width": 40, "web": 5, "flange": 8}),
json!({"kind": "i_beam", "height": 100, "width": 10, "web": 6, "flange": 5}),
] {
run(&mut s, "frame.member", json!({"sketch": "Rail", "profile": profile}));
}
assert_eq!(bodies(&mut s).len(), 4);
}
#[test]
fn profile_dimensions_follow_parameters() {
let mut s = Session::default();
run(&mut s, "parameters.add", json!({"name": "T", "expression": "3 mm"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Rail"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [1000, 0]]}));
run(&mut s, "sketch.finish", json!({}));
let square = |t: f64| (1600.0 - (40.0 - 2.0 * t).powi(2)) * 1000.0;
let sharp = json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": "T", "outer_radius": 0});
let props = run(&mut s, "frame.profile.properties", json!({"profile": sharp}));
assert!(rel(f(&props["area"]), square(3.0) / 1000.0) < 1e-12, "{props}");
run(&mut s, "frame.member", json!({"sketch": "Rail", "profile": sharp}));
assert!(rel(total_volume(&mut s), square(3.0)) < 1e-9);
run(&mut s, "parameters.change", json!({"name": "T", "expression": "2 mm"}));
assert!(rel(total_volume(&mut s), square(2.0)) < 1e-9, "{}", total_volume(&mut s));
// A parameter that makes the profile not fit fails the feature, naming the dimension.
let err = s.execute("parameters.change", &json!({"name": "T", "expression": "25 mm"})).err().map(|e| e.to_string()).unwrap_or_default();
let fid = s.doc.features.iter().find(|f| matches!(f.kind, solidcraft_doc::FeatureKind::FrameMember { .. })).unwrap().id;
let failing = s.model.result(fid).and_then(|r| r.error.clone()).unwrap_or_default();
assert!(err.contains("wall") || failing.contains("wall"), "{err} / {failing}");
}
#[test]
fn bare_profile_numbers_are_in_the_design_units() {
let mut s = Session::default();
run(&mut s, "document.units", json!({"units": "in"}));
run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Rail"}));
run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]]}));
run(&mut s, "sketch.finish", json!({}));
run(&mut s, "frame.member", json!({"sketch": "Rail", "profile": {"kind": "bar", "width": 2, "height": 1}}));
let b = bodies(&mut s).remove(0);
// 2 in across (world Y) and 1 in up (world Z).
assert!((b.3[1] - b.2[1] - 50.8).abs() < 1e-6 && (b.3[2] - b.2[2] - 25.4).abs() < 1e-6, "{b:?}");
let props = run(&mut s, "frame.profile.properties", json!({"profile": {"kind": "round_bar", "diameter": 1}}));
assert!((f(&props["width"]) - 25.4).abs() < 1e-9, "{props}");
}
#[test]
fn members_follow_a_frame_sketch_in_another_component() {
let mut s = Session::default();
rectangle_frame(&mut s);
let c = run(&mut s, "component.create", json!({"name": "Frame parts"}))["component"].as_u64().unwrap();
let o = s.doc.occurrence_of(c).unwrap().id;
run(&mut s, "occurrence.move", json!({"occurrence": o, "translate": [0, 0, 100], "capture": true}));
// Made in the moved component, the members still lie on the root's frame sketch.
run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()}));
let bs = bodies(&mut s);
assert_eq!(bs.len(), 4);
for b in &bs {
assert!((b.2[2] + 20.0).abs() < 1e-6 && (b.3[2] - 20.0).abs() < 1e-6, "{b:?}");
}
}
#[test]
fn listing_a_line_twice_is_refused() {
let mut s = Session::default();
rectangle_frame(&mut s);
let bottom = line_at_y(&s, "Frame", 0.0);
let err = s.execute("frame.member", &json!({"sketch": "Frame", "profile": tube(), "lines": [bottom, bottom]})).unwrap_err().to_string();
assert!(err.contains("listed twice"), "{err}");
}
/// Edit Feature keeps each member's name, a renamed one too, through a change of profile; giving
/// the members a name renames them all.
#[test]
fn editing_the_feature_keeps_member_names_until_it_names_them() {
let mut s = Session::default();
rectangle_frame(&mut s);
let fid = run(&mut s, "frame.member", json!({"sketch": "Frame", "profile": tube()}))["feature"].clone();
let top = boxes(&mut s).into_iter().find(|(_, (lo, _))| (lo[1] - 380.0).abs() < 1e-6).unwrap().0;
run(&mut s, "body.rename", json!({"body": top, "name": "Top rail"}));
let names: Vec<String> = boxes(&mut s).into_keys().collect();
let bigger = json!({"kind": "rect_tube", "width": 50, "height": 50, "wall": 3});
run(&mut s, "timeline.redefine", json!({"feature": fid, "command": "frame.member", "params": {"sketch": "Frame", "profile": bigger}}));
let after = boxes(&mut s);
assert_eq!(after.keys().cloned().collect::<Vec<_>>(), names);
// The top rail is the 50 mm tube now, centred on the line at y = 400.
assert!(near3(after["Top rail"].0, [0.0, 375.0, -25.0]) && near3(after["Top rail"].1, [600.0, 425.0, 25.0]), "{after:?}");
let params = json!({"sketch": "Frame", "profile": bigger, "body_name": "Rail"});
run(&mut s, "timeline.redefine", json!({"feature": fid, "command": "frame.member", "params": params}));
assert_eq!(boxes(&mut s).into_keys().collect::<Vec<_>>(), ["Rail", "Rail (2)", "Rail (3)", "Rail (4)"]);
run(&mut s, "edit.undo", json!({}));
assert_eq!(boxes(&mut s).into_keys().collect::<Vec<_>>(), names);
}
+2
View File
@@ -44,6 +44,7 @@ pub use view_dxf::sketch::exportable as view_dxf_exportable;
mod component_link;
mod config;
mod file;
mod frame;
mod inspect;
mod interference;
pub(crate) mod joints;
@@ -277,6 +278,7 @@ pub fn command_specs() -> Vec<&'static CommandSpec> {
v.extend(construct::COMMANDS.iter());
v.extend(sheet::COMMANDS.iter());
v.extend(plastic::COMMANDS.iter());
v.extend(frame::COMMANDS.iter());
v.extend(component::COMMANDS.iter());
v.extend(component_link::COMMANDS.iter());
v.extend(joints::COMMANDS.iter());
+4
View File
@@ -822,6 +822,10 @@ fn hostile_params_never_panic() {
"keep_with",
"stitch",
"extend",
"profile",
"anchor",
"density",
"names",
];
// Commands are independent; worker threads take them one at a time (their costs vary a lot).
let ids: Vec<&str> = command_specs()
+12 -2
View File
@@ -353,6 +353,8 @@ crate::dialog_descriptor::dialog_descriptors! {
},
/// Plastic features (`dialogs_plastic`).
Plastic(crate::dialogs_plastic::Pl),
/// Frame members (`dialogs_frame`).
Frame(crate::dialogs_frame::Member),
/// Appearance (`dialogs_appearance`).
Appearance(crate::dialogs_appearance::Ap),
/// Contact sets, motion studies, exploded views, configurations (`dialogs_motion`).
@@ -570,13 +572,14 @@ fn fits(a: Accept, s: &Sel) -> bool {
Sel::Body { .. } => a & BODIES != 0,
Sel::Plane { .. } => a & PLANES != 0,
Sel::Axis { .. } => a & AXES != 0,
Sel::SketchCurve { .. } => a & (AXES | CURVES) != 0,
Sel::SketchCurve { .. } => a & (AXES | CURVES | selection::SKETCH_LINES) != 0,
Sel::ExternalSketchCurve { .. } => a & selection::SKETCH_LINES != 0,
Sel::Vertex { .. } => a & selection::VERTICES != 0,
Sel::Feature { .. } => a & selection::FEATURES != 0,
// Sketch points go into a sketch command's own inputs (Entities, a base point), so a
// box selection and a pre-selection reach them the way a click already does.
Sel::SketchPoint { .. } => a & (selection::POINTS | selection::SKETCH_POINTS) != 0,
Sel::SketchConstraint { .. } | Sel::Occurrence { .. } | Sel::ExternalSketchCurve { .. } | Sel::ExternalSketchPoint { .. } => false,
Sel::SketchConstraint { .. } | Sel::Occurrence { .. } | Sel::ExternalSketchPoint { .. } => false,
}
}
@@ -793,6 +796,7 @@ impl Dialog {
.or_else(|| crate::dialogs_save_mesh::start(app, id))
.or_else(|| crate::dialogs_view_dxf::start(app, id))
.or_else(|| crate::dialogs_plastic::start(app, id))
.or_else(|| crate::dialogs_frame::start(app, id))
.or_else(|| crate::dialogs_appearance::start(app, id))
.or_else(|| crate::dialogs_motion::start(app, id))
.or_else(|| crate::dialogs_parts::start(app, id))
@@ -934,6 +938,7 @@ impl Dialog {
Kind::Surface(_) => return true,
Kind::SketchModify(k) => return k.previews(),
Kind::Plastic(k) => return k.previews(),
Kind::Frame(_) => return true,
Kind::Part(_) | Kind::PartSize(_) => return true,
// Web previews run synchronously; a modelled thread can take seconds.
Kind::Thread { .. } => return !cfg!(target_arch = "wasm32") && self.extra.get("modeled").and_then(Value::as_bool).unwrap_or(false),
@@ -1708,6 +1713,7 @@ fn title(k: &Kind) -> &'static str {
Kind::SaveMesh(_) => "SAVE AS MESH",
Kind::ViewDxf { .. } => "Export Current View as DXF",
Kind::Plastic(k) => k.title(),
Kind::Frame(_) => "FRAME MEMBER",
Kind::Appearance(_) => "APPEARANCE",
Kind::Motion(k) => k.title(),
Kind::Part(_) => "INSERT PART",
@@ -1729,6 +1735,8 @@ fn hint(inp: &SelInput) -> &'static str {
"click a plane or planar face"
} else if a & AXES != 0 {
"click an axis or sketch line"
} else if a & selection::SKETCH_LINES != 0 {
"click sketch lines"
} else if a & CURVES != 0 {
"click sketch curves"
} else if a & (selection::POINTS | selection::SKETCH_POINTS) != 0 {
@@ -3760,6 +3768,7 @@ fn dialog_commands(app: &SolveApp, d: &Dialog) -> Result<Vec<(String, Value)>, S
Kind::SaveMesh(k) => return crate::dialogs_save_mesh::commands(k, &d.inputs),
Kind::ViewDxf { .. } => return Ok(Vec::new()),
Kind::Plastic(k) => return crate::dialogs_plastic::commands(app, k, &d.inputs, &d.extra),
Kind::Frame(k) => return crate::dialogs_frame::commands(app, k, &d.inputs, &d.extra),
Kind::Appearance(k) => return Ok(crate::dialogs_appearance::commands(k, &d.inputs)),
Kind::Motion(k) => return crate::dialogs_motion::commands(app, k, &d.inputs),
Kind::Part(k) => return crate::dialogs_parts::commands(app, k, &d.inputs),
@@ -4933,6 +4942,7 @@ pub fn for_feature(app: &SolveApp, id: u64, marker: Option<usize>) -> Option<Dia
other => {
let (kind, inputs, extra) = crate::dialogs_sheet::for_feature(app, other)
.or_else(|| crate::dialogs_plastic::for_feature(app, other))
.or_else(|| crate::dialogs_frame::for_feature(app, other))
.or_else(|| crate::dialogs_surface::for_feature(app, other, &feature_frame(s, f.component)))?;
let mut d = Dialog::new(kind, inputs);
d.extra = extra;
+6 -2
View File
@@ -55,6 +55,8 @@ fn representative(h: &Harness, command: &str) -> Dialog {
}
} else if input.accept & PLANES != 0 {
vec![Sel::Plane { name: if index == 1 { "XZ" } else { "XY" }.into() }]
} else if input.accept & crate::selection::SKETCH_LINES != 0 {
vec![Sel::ExternalSketchCurve { sketch: s.world_state().sketches.last().unwrap().feature, id: path.clone() }]
} else if input.accept & CURVES != 0 || command == "sheet.fold" && index == 0 {
vec![Sel::SketchCurve { id: path.clone() }]
} else if input.accept & AXES != 0 {
@@ -148,6 +150,7 @@ fn check_form(command: &str, labels: &[&str]) {
"joint.gear" => &["Reverse", "Internal gear"],
"joint.rack_pinion" | "joint.screw" => &["Reverse"],
"joint.cam" => &["Other side"],
"frame.member" => &["All Lines", "Mirror"],
_ => &[],
};
for label in checks {
@@ -192,10 +195,10 @@ fn control_role(command: &str, label: &str) -> Option<egui::accesskit::Role> {
"Operation" if command == "solid.mirror" => return None,
"Operation" | "Type" | "Orientation" | "Move Type" | "Object Type" | "Rule" | "Rim Edge" | "Catch Direction" | "Shape" | "Holes" | "Size"
| "Bend Line Position" | "From Snap" | "To Snap" | "Joint" | "Joint 1" | "Joint 2" | "Gear 1" | "Gear 2" | "Pinion" | "Rack" | "Screw"
| "Nut" | "Cam" | "Follower" => Role::ComboBox,
| "Nut" | "Cam" | "Follower" | "Anchor" => Role::ComboBox,
"Radius" if command == "joint.rack_pinion" => Role::Label,
"Pitch" if command == "solid.thread" => Role::ComboBox,
"Automatic size" | "Reverse" | "Other side" => Role::CheckBox,
"Automatic size" | "Reverse" | "Other side" | "All Lines" | "Mirror" => Role::CheckBox,
"Animate" => Role::Button,
"Ratio" if command.starts_with("joint.") && command != "joint.motion_link" => return None,
_ => Role::TextInput,
@@ -235,6 +238,7 @@ form_case!(remove, "solid.remove", []);
form_case!(path_pattern, "solid.pattern.path", ["Type", "Object Type", "Quantity", "Spacing"]);
form_case!(pipe, "solid.pipe", ["Diameter", "Wall"]);
form_case!(stock, "solid.bounding_solid", ["Margin"]);
form_case!(frame_member, "frame.member", ["All Lines", "Anchor", "Angle", "Mirror", "Name"]);
form_case!(thread, "solid.thread", ["Profile", "Size", "Pitch", "Designation"]);
form_case!(primitive_box, "solid.box", ["length", "width", "height", "Operation"]);
form_case!(cylinder, "solid.cylinder", ["diameter", "height", "Operation"]);
+2
View File
@@ -75,6 +75,7 @@ pub(super) fn command(kind: &Kind) -> Option<&'static str> {
crate::dialogs_sheet::Sm::FlatPattern { .. } => Some("sheet.flat_pattern"),
_ => k.simple_metadata().map(|(command, _)| command),
},
Kind::Frame(_) => Some("frame.member"),
Kind::Plastic(k) => match k {
crate::dialogs_plastic::Pl::SnapFit { .. } => Some("plastic.snap_fit"),
crate::dialogs_plastic::Pl::Assign { .. } => Some("plastic.assign_rule"),
@@ -784,6 +785,7 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
Kind::Surface(k) => enter |= crate::dialogs_surface::rows(ui, k),
Kind::Sheet(k) => enter |= crate::dialogs_sheet::rows(app, ui, k, &mut d.inputs),
Kind::Plastic(k) => enter |= crate::dialogs_plastic::rows(app, ui, k, &d.inputs),
Kind::Frame(k) => enter |= crate::dialogs_frame::rows(app, ui, k, &d.inputs),
Kind::Assembly(k) => enter |= crate::dialogs_assembly::rows(app, ui, k, &mut d.inputs, &mut d.active),
Kind::Measure { result, show, .. } => measure_rows(app, ui, result.as_ref(), show),
Kind::Section { offset, flip, hatch } => {
+215
View File
@@ -0,0 +1,215 @@
//! Frame Member (`frame.member`): structural members along the lines of a frame sketch. The lines
//! are picked in the view; the section is a built-in profile with its dimensions, or the profiles
//! picked in another sketch. Anchor, angle and mirror place the section on each line.
use serde_json::{Map, Value, json};
use solidcraft_engine::Sel;
use solidcraft_engine::doc::expr::Kind as ValueKind;
use solidcraft_engine::doc::frame::{self, MemberProfile};
use solidcraft_engine::doc::{FeatureKind, ProfileSel};
use crate::SolveApp;
use crate::dialogs::{Kind, check, curves_sketch, form_row, profile_indices, put, shown_expr};
use crate::selection::{PROFILES, SKETCH_LINES, SelInput, SelectionExt as _};
use crate::ui_kit::{choice_row, expr_row, hint_row, text_row};
/// The anchors as `frame.member` names them, and their labels.
const ANCHORS: [(&str, &str); 11] = [
("origin", "Origin"),
("center", "Center"),
("centroid", "Centroid"),
("top_left", "Top Left"),
("top", "Top Middle"),
("top_right", "Top Right"),
("left", "Left Middle"),
("right", "Right Middle"),
("bottom_left", "Bottom Left"),
("bottom", "Bottom Middle"),
("bottom_right", "Bottom Right"),
];
/// The Frame Member dialog's values (the picks are its selection inputs).
#[derive(Clone, Debug)]
pub struct Member {
/// Every line of the frame sketch, now and as lines are added, not only the lines picked.
pub all: bool,
/// The built-in profile (an index into `frame::profile_kinds`), used when no section is picked.
pub kind: usize,
/// Each built-in profile's dimensions, its required ones then its optional ones; kept per
/// profile so switching back finds them again. An empty optional one takes its default.
pub dims: Vec<Vec<String>>,
/// A profile sketch whose whole drawn section is the member's (nested loops alternating), as
/// a feature made that way keeps it while no section is picked.
pub whole: Option<u64>,
pub anchor: usize,
pub angle: String,
pub mirror: bool,
pub name: String,
}
impl Member {
fn new() -> Member {
let dims = frame::profile_kinds()
.iter()
.map(|k| {
let example = serde_json::to_value(&k.example).unwrap_or(Value::Null);
let given = k.required.iter().map(|d| example.get(*d).and_then(Value::as_f64).map(|v| format!("{v} mm")).unwrap_or_default());
given.chain(k.optional.iter().map(|_| String::new())).collect()
})
.collect();
// A rectangular tube is the most common member.
let kind = frame::profile_kinds().iter().position(|k| k.kind == "rect_tube").unwrap_or(0);
Member { all: false, kind, dims, whole: None, anchor: 0, angle: String::new(), mirror: false, name: String::new() }
}
}
/// The dialog for Frame Member.
pub fn start(_app: &SolveApp, id: &str) -> Option<(Kind, Vec<SelInput>)> {
(id == "frame.member")
.then(|| (Kind::Frame(Member::new()), vec![SelInput::new("Lines", SKETCH_LINES, true), SelInput::new("Section (optional)", PROFILES, true)]))
}
fn tr(text: &str) -> &str {
crate::i18n::tr_label(text)
}
/// The dialog's own rows (after the selection inputs); true when Enter was pressed in a value.
pub fn rows(app: &SolveApp, ui: &mut egui::Ui, m: &mut Member, inputs: &[SelInput]) -> bool {
let mut enter = false;
form_row(ui, "All Lines", |ui| check(ui, &mut m.all));
let picked = !crate::selection::items(inputs, 1).is_empty();
if let Some(sketch) = m.whole.filter(|_| !picked) {
let name = app.session.doc.feature(sketch).map(|f| f.name.clone()).unwrap_or_default();
let mut on = true;
form_row(ui, "Section", |ui| crate::ui_kit::checkbox(ui, &name, &mut on));
if !on {
m.whole = None;
}
} else if !picked {
let kinds = frame::profile_kinds();
let labels: Vec<&str> = kinds.iter().map(|k| k.label).collect();
choice_row(ui, "Profile", "frame_profile", &mut m.kind, &labels);
if let (Some(k), Some(values)) = (kinds.get(m.kind), m.dims.get_mut(m.kind)) {
for (i, (name, v)) in k.required.iter().chain(k.optional).zip(values.iter_mut()).enumerate() {
let label = frame::dimension_label(name);
enter |= if i < k.required.len() { expr_row(ui, label, v) } else { hint_row(ui, label, v, tr("default")) };
}
}
}
let anchors: Vec<&str> = ANCHORS.iter().map(|a| a.1).collect();
choice_row(ui, "Anchor", "frame_anchor", &mut m.anchor, &anchors);
enter |= hint_row(ui, "Angle", &mut m.angle, "0 deg");
form_row(ui, "Mirror", |ui| check(ui, &mut m.mirror));
enter |= text_row(ui, "Name", &mut m.name, tr("from the profile")).0;
enter
}
/// The command the dialog's OK runs (`extra`: parameters kept from the feature being edited).
pub fn commands(app: &SolveApp, m: &Member, inputs: &[SelInput], extra: &Map<String, Value>) -> Result<Vec<(String, Value)>, String> {
let section = crate::selection::items(inputs, 1).profiles();
let section_sketch = section.first().map(|x| x.0).or(m.whole);
if section.iter().any(|x| Some(x.0) != section_sketch) {
return Err("the section's profiles must be in one sketch".into());
}
// A line picked in the view comes with its sketch (line ids are a sketch's own); a line
// selected before the dialog opened is looked for in the newest sketch with it, not the
// section's.
let picks = crate::selection::items(inputs, 0);
let mut lines = Vec::new();
let mut known = None;
for pick in picks {
match pick {
Sel::ExternalSketchCurve { sketch, id } => {
if known.is_some_and(|k| k != *sketch) {
return Err("the lines must be in one sketch".into());
}
known = Some(*sketch);
lines.push(id.clone());
}
Sel::SketchCurve { id } => lines.push(id.clone()),
_ => {}
}
}
if lines.is_empty() {
return Err("select the frame sketch's lines first".into());
}
let sketch = known.or_else(|| curves_sketch(app, &lines, section_sketch)).ok_or("the lines must be in one sketch, not the section's")?;
let mut p = json!({"sketch": sketch});
if !m.all {
p["lines"] = json!(lines);
}
if let Some(ps) = section_sketch {
p["profile_sketch"] = json!(ps);
if !section.is_empty() {
p["profiles"] = json!(section.iter().map(|x| x.1).collect::<Vec<_>>());
}
} else {
let kinds = frame::profile_kinds();
let (k, values) = kinds.get(m.kind).zip(m.dims.get(m.kind)).ok_or("choose a profile")?;
let mut profile = json!({"kind": k.kind});
for (name, v) in k.required.iter().chain(k.optional).zip(values) {
if !v.trim().is_empty() {
profile[*name] = json!(v);
}
}
p["profile"] = profile;
}
if m.anchor != 0
&& let Some((anchor, _)) = ANCHORS.get(m.anchor)
{
p["anchor"] = json!(anchor);
}
put(&mut p, &[("angle", &m.angle), ("body_name", m.name.trim())]);
if m.mirror {
p["mirror"] = json!(true);
}
if let Value::Object(o) = &mut p {
for (key, v) in extra {
o.entry(key.clone()).or_insert_with(|| v.clone());
}
}
Ok(vec![("frame.member".to_string(), p)])
}
/// The dialog editing a frame member feature, filled from it.
pub fn for_feature(app: &SolveApp, kind: &FeatureKind) -> Option<(Kind, Vec<SelInput>, Map<String, Value>)> {
let FeatureKind::FrameMember { path_sketch, lines, profile, anchor, angle, mirror, body_name, .. } = kind else { return None };
let (_, mut inputs) = start(app, "frame.member")?;
let st = app.session.model.state();
let mut m = Member::new();
m.all = lines.is_empty();
let ids = if m.all { frame::member_line_ids(&st, kind).unwrap_or_default() } else { lines.clone() };
if let Some(i) = inputs.get_mut(0) {
i.items = ids.into_iter().map(|id| Sel::ExternalSketchCurve { sketch: path_sketch.0, id }).collect();
}
match profile {
MemberProfile::Library { profile } => {
let kinds = frame::profile_kinds();
if let Some((index, k)) = kinds.iter().enumerate().find(|(_, k)| k.kind == profile.kind)
&& let Some(values) = m.dims.get_mut(index)
{
m.kind = index;
for (name, v) in k.required.iter().chain(k.optional).zip(values.iter_mut()) {
*v = profile.dims.get(*name).map(|e| shown_expr(e, ValueKind::Length)).unwrap_or_default();
}
}
}
MemberProfile::Sketch { sketch, profiles: ProfileSel::All } => m.whole = Some(sketch.0),
MemberProfile::Sketch { sketch, profiles } => {
let picks = st.sketch(sketch.0).map(|ss| profile_indices(ss, profiles)).unwrap_or_default();
if let Some(i) = inputs.get_mut(1) {
i.items = picks.into_iter().map(|index| Sel::Profile { sketch: sketch.0, index }).collect();
}
}
}
let anchor = serde_json::to_value(anchor).ok();
m.anchor = ANCHORS.iter().position(|(a, _)| anchor.as_ref().and_then(Value::as_str) == Some(*a)).unwrap_or(0);
m.angle = angle.as_deref().map(|a| shown_expr(a, ValueKind::Angle)).unwrap_or_default();
m.mirror = *mirror;
m.name = body_name.clone().unwrap_or_default();
Some((Kind::Frame(m), inputs, Map::new()))
}
#[cfg(test)]
#[path = "dialogs_frame_tests.rs"]
mod tests;
+197
View File
@@ -0,0 +1,197 @@
use crate::test_support::run_all;
use serde_json::json;
use solidcraft_engine::Session;
use super::*;
use crate::Services;
use crate::dialogs::{Dialog, apply_commands, for_feature as edit_dialog};
fn app_with(cmds: &[(&str, Value)]) -> SolveApp {
let mut s = Session::default();
for (id, p) in cmds {
s.execute(id, p).unwrap();
}
SolveApp::new(s, Services::default())
}
/// A 600 × 400 rectangle on XY as the frame sketch `Frame`, and, drawn after it on YZ, a ring of
/// two circles as the section sketch `Ring` (its circles' ids are not the frame's line ids).
fn frame_app() -> SolveApp {
app_with(&[
("sketch.create", json!({"plane": "XY", "name": "Frame"})),
("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [600, 400]})),
("sketch.finish", json!({})),
("sketch.create", json!({"plane": "YZ", "name": "Ring"})),
("sketch.circle.center", json!({"center": [0, 0], "radius": 20})),
("sketch.circle.center", json!({"center": [0, 0], "radius": 17})),
("sketch.finish", json!({})),
])
}
fn sketch_id(app: &SolveApp, name: &str) -> u64 {
app.session.doc.find_feature(name).unwrap().id
}
fn frame_lines(app: &SolveApp) -> Vec<String> {
app.session.doc.sketch(sketch_id(app, "Frame")).unwrap().curves.iter().map(|c| c.id.clone()).collect()
}
fn body_names(app: &SolveApp) -> Vec<String> {
app.session.world_state().bodies.iter().map(|b| b.name.clone()).collect()
}
/// The dialog started with the given lines picked.
fn dialog_on(app: &mut SolveApp, lines: &[String]) -> Dialog {
app.session.selection = lines.iter().map(|id| Sel::SketchCurve { id: id.clone() }).collect();
app.start("frame.member");
app.dialog.clone().unwrap()
}
fn member(d: &mut Dialog) -> &mut Member {
match &mut d.kind {
Kind::Frame(m) => m,
k => panic!("{k:?}"),
}
}
/// Picked lines and the default built-in profile make one member a line; Edit Feature refills
/// the dialog and runs `timeline.redefine`, and the members keep their names.
#[test]
fn members_from_picked_lines_and_a_built_in_profile() {
let mut app = frame_app();
let lines = frame_lines(&app);
let mut d = dialog_on(&mut app, &lines[..2]);
let c = apply_commands(&app, &d).unwrap();
assert_eq!(c[0].0, "frame.member");
let p = &c[0].1;
assert_eq!(p["sketch"], json!(sketch_id(&app, "Frame")), "the frame sketch, not the newer section sketch: {p}");
assert_eq!(p["lines"], json!(lines[..2]));
assert_eq!(p["profile"], json!({"kind": "rect_tube", "width": "40 mm", "height": "40 mm", "wall": "3 mm"}));
assert!(p.get("anchor").is_none() && p.get("angle").is_none() && p.get("mirror").is_none() && p.get("body_name").is_none(), "{p}");
// Another built-in profile and its dimensions; an optional one left empty takes its default.
let m = member(&mut d);
m.kind = frame::profile_kinds().iter().position(|k| k.kind == "angle").unwrap();
m.dims[m.kind][2] = "4 mm".into();
let c = apply_commands(&app, &d).unwrap();
assert_eq!(c[0].1["profile"], json!({"kind": "angle", "width": "50 mm", "height": "50 mm", "thickness": "4 mm"}));
run_all(&mut app, c);
assert_eq!(body_names(&app), ["Angle 50x50x4", "Angle 50x50x4 (2)"]);
app.run("body.rename", json!({"body": "Angle 50x50x4 (2)", "name": "Rail"})).unwrap();
let f = app.session.doc.features.last().unwrap().id;
let mut e = edit_dialog(&app, f, None).unwrap();
assert_eq!(e.inputs[0].items.len(), 2);
let m = member(&mut e);
assert_eq!((frame::profile_kinds()[m.kind].kind, m.dims[m.kind][2].as_str()), ("angle", "4 mm"));
m.dims[m.kind][2] = "5 mm".into();
let c = apply_commands(&app, &e).unwrap();
assert_eq!(c[0].0, "timeline.redefine");
run_all(&mut app, c);
assert_eq!(body_names(&app), ["Angle 50x50x4", "Rail"], "the members keep their names through the edit");
}
/// A section picked in another sketch is the profile, the picks naming its regions; All Lines,
/// anchor, angle, mirror and name reach the command and come back when editing.
#[test]
fn a_picked_section_and_the_placement() {
let mut app = frame_app();
let lines = frame_lines(&app);
let ring = sketch_id(&app, "Ring");
let mut d = dialog_on(&mut app, &lines[..1]);
// The ring between the circles: the region whose interior point lies between radii 17 and 20.
let ss = app.session.world_state().sketch(ring).unwrap().clone();
let index = ss.profiles.iter().position(|p| (p.region.interior_point().len() - 18.5).abs() < 1.5).unwrap();
d.inputs[1].items = vec![Sel::Profile { sketch: ring, index }];
let m = member(&mut d);
m.all = true;
m.anchor = ANCHORS.iter().position(|a| a.0 == "bottom").unwrap();
m.angle = "15 deg".into();
m.mirror = true;
m.name = " Rail ".into();
let c = apply_commands(&app, &d).unwrap();
let p = &c[0].1;
assert_eq!(p["sketch"], json!(sketch_id(&app, "Frame")));
assert!(p.get("lines").is_none() && p.get("profile").is_none(), "{p}");
assert_eq!((&p["profile_sketch"], &p["profiles"]), (&json!(ring), &json!([index])));
assert_eq!((&p["anchor"], &p["angle"], &p["mirror"], &p["body_name"]), (&json!("bottom"), &json!("15 deg"), &json!(true), &json!("Rail")));
run_all(&mut app, c);
assert_eq!(body_names(&app), ["Rail", "Rail (2)", "Rail (3)", "Rail (4)"]);
let f = app.session.doc.features.last().unwrap().id;
let mut e = edit_dialog(&app, f, None).unwrap();
assert_eq!(e.inputs[0].items.len(), 4, "every line of the sketch shows as picked");
assert_eq!(e.inputs[1].items, [Sel::Profile { sketch: ring, index }]);
let m = member(&mut e);
assert!(m.all && m.mirror && m.name == "Rail" && m.angle == "15 deg" && ANCHORS[m.anchor].0 == "bottom", "{m:?}");
}
/// A member whose section is a whole profile sketch keeps it when edited: the dialog shows the
/// sketch rather than picking every region of it, which would fill the tube's hole.
#[test]
fn a_whole_sketch_section_stays_whole_through_an_edit() {
let mut app = frame_app();
app.run("frame.member", json!({"sketch": "Frame", "profile_sketch": "Ring"})).unwrap();
let volume = |app: &mut SolveApp| app.session.execute("inspect.measure", &json!({})).unwrap()["bodies"][0]["volume_mm3"].as_f64().unwrap();
let before = volume(&mut app);
let f = app.session.doc.features.last().unwrap().id;
let mut e = edit_dialog(&app, f, None).unwrap();
assert!(e.inputs[1].items.is_empty());
assert_eq!(member(&mut e).whole, Some(sketch_id(&app, "Ring")));
member(&mut e).angle = "30 deg".into();
let c = apply_commands(&app, &e).unwrap();
assert!(c[0].1["params"].get("profiles").is_none(), "{}", c[0].1);
run_all(&mut app, c);
assert!((volume(&mut app) - before).abs() < 1e-6 * before, "still the ring, not the filled circle");
// Unticked, the section is a built-in profile again.
let mut e = edit_dialog(&app, f, None).unwrap();
member(&mut e).whole = None;
assert_eq!(apply_commands(&app, &e).unwrap()[0].1["params"]["profile"]["kind"], "rect_tube");
}
/// Without lines there is nothing to place; lines and the section in one sketch are refused.
#[test]
fn missing_or_mixed_picks_are_refused() {
let mut app = frame_app();
let d = dialog_on(&mut app, &[]);
assert!(apply_commands(&app, &d).unwrap_err().contains("lines"));
let ring = sketch_id(&app, "Ring");
let circles: Vec<String> = app.session.doc.sketch(ring).unwrap().curves.iter().map(|c| c.id.clone()).collect();
let mut d = dialog_on(&mut app, &circles[..1]);
d.inputs[1].items = vec![Sel::Profile { sketch: ring, index: 0 }];
assert!(apply_commands(&app, &d).is_err());
}
/// Lines picked in the view keep their sketch: two 3D sketches both number their lines `w1`…, and
/// the members go on the lines that were clicked, not on the newer sketch's lines of those ids.
#[test]
fn picked_lines_stay_in_the_sketch_they_were_picked_in() {
let mut app = app_with(&[
("sketch.create", json!({"plane": "XY", "name": "Uprights"})),
("sketch.options", json!({"sketch_3d": true})),
("sketch.line3d", json!({"points": [[0, 0, 0], [0, 0, 500]]})),
("sketch.line3d", json!({"points": [[300, 0, 0], [300, 0, 500]]})),
("sketch.finish", json!({})),
("sketch.create", json!({"plane": "XY", "name": "Rails"})),
("sketch.options", json!({"sketch_3d": true})),
("sketch.line3d", json!({"points": [[0, 0, 250], [300, 0, 250]]})),
("sketch.line3d", json!({"points": [[0, 0, 480], [300, 0, 480]]})),
("sketch.finish", json!({})),
]);
let (uprights, rails) = (sketch_id(&app, "Uprights"), sketch_id(&app, "Rails"));
let wires = |id: u64| -> Vec<String> { app.session.doc.sketch(id).unwrap().wires.iter().map(|w| w.id.clone()).collect() };
let ids = wires(uprights);
assert_eq!(ids, wires(rails), "the two sketches share their line ids");
app.start("frame.member");
let mut d = app.dialog.clone().unwrap();
d.inputs[0].items = ids.iter().map(|id| Sel::ExternalSketchCurve { sketch: uprights, id: id.clone() }).collect();
let c = apply_commands(&app, &d).unwrap();
assert_eq!(c[0].1["sketch"], json!(uprights));
run_all(&mut app, c.clone());
// Two posts the height of the uprights, not two rails.
let m = app.session.execute("inspect.measure", &json!({})).unwrap();
for b in m["bodies"].as_array().unwrap() {
let (lo, hi) = (b["bbox"]["min"][2].as_f64().unwrap(), b["bbox"]["max"][2].as_f64().unwrap());
assert!(lo.abs() < 1e-6 && (hi - 500.0).abs() < 1e-6, "{b}");
}
// Lines picked in two sketches are refused.
d.inputs[0].items.push(Sel::ExternalSketchCurve { sketch: rails, id: ids[0].clone() });
assert!(apply_commands(&app, &d).unwrap_err().contains("one sketch"));
}
+1
View File
@@ -34,6 +34,7 @@ pub mod dialogs;
pub mod dialogs_appearance;
pub mod dialogs_assembly;
pub mod dialogs_coupling;
pub mod dialogs_frame;
pub mod dialogs_library;
pub mod dialogs_motion;
pub mod dialogs_move;
+4
View File
@@ -40,6 +40,9 @@ pub const FEATURES: Accept = 1024;
pub const SKETCH_POINTS: Accept = 2048;
/// The origin point, picked as a vertex of no body (in the viewport or the browser's Origin).
pub const ORIGIN: Accept = 4096;
/// Curves of any sketch, picked with their sketch (`ExternalSketchCurve`): curve ids are a
/// sketch's own, so two sketches can both have a `w2` (frame member lines).
pub const SKETCH_LINES: Accept = 8192;
/// One selection input of a command dialog ("Profiles", "Edges", "Plane", ...).
#[derive(Clone, Debug, PartialEq)]
@@ -78,6 +81,7 @@ impl SelInput {
Hit::Plane { name, .. } if a & PLANES != 0 => Some(Sel::Plane { name: name.clone() }),
Hit::Axis { name } if a & AXES != 0 => Some(Sel::Axis { name: name.clone() }),
Hit::SketchCurve { id, straight: true, .. } if a & AXES != 0 => Some(Sel::SketchCurve { id: id.clone() }),
Hit::SketchCurve { sketch, id, .. } if a & SKETCH_LINES != 0 => Some(Sel::ExternalSketchCurve { sketch: *sketch, id: id.clone() }),
Hit::SketchCurve { id, .. } if a & CURVES != 0 => Some(Sel::SketchCurve { id: id.clone() }),
Hit::SketchPoint { id, .. } if a & SKETCH_POINTS != 0 => Some(Sel::SketchPoint { id: id.clone() }),
Hit::SketchPoint { sketch, id, .. } if a & POINTS != 0 => Some(Sel::SketchPoint { id: format!("{sketch}:{id}") }),
+1
View File
@@ -114,6 +114,7 @@ pub(crate) fn icon_of(k: &FeatureKind) -> &'static str {
FeatureKind::Remove { .. } => "delete",
FeatureKind::BoundingSolid { .. } => "bounding_solid",
FeatureKind::Pipe { .. } => "pipe",
FeatureKind::FrameMember { .. } => "frame_member",
FeatureKind::Emboss { .. } => "emboss",
FeatureKind::ReplaceFace { .. } => "replace_face",
FeatureKind::Align { .. } => "align",
+5
View File
@@ -2496,6 +2496,11 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
feedback.line(a.to_f32(), b.to_f32(), c4(t.sel_edge), 3.5, true);
}
}
} else if let Some(w) = st.sketch(*sketch).and_then(|ss| ss.sketch.wire_index(id).and_then(|i| ss.sketch.wires.get(i))) {
// A 3D sketch curve of that sketch.
for q in w.pts.windows(2) {
feedback.line(q[0].to_f32(), q[1].to_f32(), c4(t.sel_edge), 3.5, true);
}
}
}
// A 3D sketch curve, in whichever sketch has it.
+112
View File
@@ -0,0 +1,112 @@
# Frames and weldments
Frames and weldments (#4003) are structural members (tube, angle, channel, beam, an aluminium
extrusion of your own) laid along the lines of a frame sketch. This page covers what has landed:
members and their profiles. Corners, trims, end caps, gussets, welds and the cut list follow.
## The workflow
1. **Sketch the frame**: lines in a sketch, or a 3D sketch for a frame that leaves one plane
(`sketch.options sketch_3d: true`, then `sketch.line3d`). Drive the sizes with parameters as
usual; members follow.
2. **Choose a profile**: a built-in one from its dimensions (below), or your own drawn in a sketch
(a vendor's extrusion: insert their DXF with `sketch.insert_dxf`). A profile sketch's origin is
the point that sits on each line, and its x and y are the profile's.
3. **Add members**: **Frame Member** (MODEL › CREATE, `frame.member`) makes one body per line,
square to it, from its start to its end. Repeat with another profile for the next group of
lines.
```json
{"command": "frame.member", "params": {"sketch": "Frame", "profile": {"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}}}
{"command": "frame.member", "params": {"sketch": "Frame", "lines": ["l5", "l6"], "profile_sketch": "45x45 section", "anchor": "bottom_left", "angle": "90 deg"}}
```
Members are ordinary bodies: mirror, pattern, move, drill and combine them with the usual
commands. Where members meet they overlap until corner treatments land.
## The Frame Member dialog
- **Lines**: pick the frame sketch's lines in the view (2D or 3D sketch lines). **All Lines**
makes a member on every line of that sketch instead, including lines drawn later.
- **Section (optional)**: pick the section's region in another sketch (the ring between two
circles makes a tube). With nothing picked, **Profile** chooses a built-in profile and its
dimensions follow; optional ones left empty take their defaults.
- **Anchor**, **Angle** and **Mirror** place the section on each line, as below. **Name** names
the members (default: after the profile).
- The preview shows the members as you change the values. **Edit Feature** reopens the dialog with
the feature's values; the members keep their names through the edit, and a new **Name**
renames them all. A member made with a whole profile sketch keeps it (the **Section** row shows
the sketch; untick it for a built-in profile).
## frame.member
- `sketch`: the frame sketch. `lines`: the curve ids to lay members on (2D lines or 3D sketch
lines), each once; left out, every straight line drawn in the sketch: not construction, not
projected or otherwise linked (a sketch on a face projects the face's edges; they are
references, not members), and with a length.
- `profile` (a built-in profile) or `profile_sketch` (a sketch), one of them. A profile sketch's
section is its material as nested loops alternate (an outline is material, a loop inside it a
hole, a loop inside that material again), so two circles make a tube; pick other regions with
`profiles` as `solid.extrude` takes them. Like `solid.extrude`, only what was drawn counts:
projected edges are left out unless the drawn curves make no profile. It must be one piece.
- `anchor`: the profile point on the line: `origin` (the default: a built-in profile's centre, a
profile sketch's origin), `center` (of its bounding box), `centroid`, or a corner or edge middle
of its bounding box (`bottom_left`, `top`…).
- **Orientation**: the profile's y points up (world +Z) as far as the line allows and its x is
square to the line and to y (x × y runs along the line, so on a line along +X the profile's x is
world +Y); a vertical member's x is world +X. `angle` (an angle expression) turns the profile
about the line, counter-clockwise looking back from the line's end; `mirror` mirrors it across
its y axis first. A line leaning less than 10⁻⁶ rad from vertical counts as vertical, so
rounding in a 3D sketch never turns a post a quarter turn.
- Bodies are named after `body_name`, or the profile (`Rect Tube 40x40x3`) or the profile
sketch, then numbered on past names already taken (`(2)`, `(3)`…). Each member's name is kept
with its line (the feature's `names`), so deleting or adding a line, or deleting another
feature, leaves the other members' names alone; `body.rename` renames a member on its line.
`names` (`{line id: name}`) gives names to keep, as Edit Feature (`timeline.redefine`) passes
them unless the edit changes `body_name`.
Every built-in profile is SolidCraft's own parametric definition, built in code
(`solidcraft_doc::frame`). SolidCraft ships no vendor's or standard's size table: you give the
dimensions of the stock you buy. Any other section, a vendor's aluminium extrusion for example, comes
from a sketch: draw it or insert the vendor's DXF.
## Built-in profiles
A profile is JSON with a `kind` and its dimensions, each a number in the design's units or a
length expression over its parameters (`"tube_wall"`, `"2 in"`): a member follows a parameter
change like any feature. Dimensions marked *optional* default from the profile's size when left
out, made smaller where a thick section leaves less room for a radius;
`frame.profile.properties` returns the profile in millimetres with every default written out.
| Kind | Required | Optional (default) |
|---|---|---|
| `bar` | `width`, `height` | `corner_radius` (0) |
| `round_bar` | `diameter` | |
| `rect_tube` | `width`, `height`, `wall` | `outer_radius` (2 × wall; inner radius is outer − wall) |
| `round_tube` | `diameter`, `wall` | |
| `angle` | `width` (leg along x), `height` (leg along y), `thickness` | `root_radius` (thickness), `toe_radius` (thickness / 2); together at most the shorter leg's inside length |
| `channel` | `height`, `width` (flange length), `web`, `flange` (thicknesses) | `root_radius` (web, at most the room in a flange and half the web's inside height), `toe_radius` (0) |
| `i_beam` | `height`, `width`, `web`, `flange` | `root_radius` (web, at most the room in a flange and half the web's inside height) |
The profile's bounding box is centred on its origin, x across and y up. Angles have their heel at
the bottom left; channels open towards +x.
Dimensions are refused, with the dimension named, when they are not finite, are outside
0.01 mm–10 m (radii: 0, or 0.01 mm–10 m), or do not fit: a wall of half the tube or more, a radius
given larger than the room for it.
## Commands
- `frame.profile.list`: every kind, its dimensions and a working example.
- `frame.profile.properties` `{profile, density?}`: the section, worked out exactly from its lines
and arcs: `area` (mm²), `centroid` (mm from the bounding box centre), `ixx`, `iyy`, `ixy` (mm⁴
about the centroid), `width`, `height`; with `density` (kg/m³), `mass_per_m` (kg/m).
- `frame.profile.insert` `{profile, at?, anchor?, angle?, fixed?, sketch?}`: draws the profile into
the sketch being edited, its `anchor` point (`center`, `centroid`, or a corner or edge middle of
the bounding box such as `bottom_left`) on `at`, turned by `angle` radians. The curves are locked
(`fixed`, default true) so solving the sketch keeps the shape. The outline and each hole are
separate sketch regions: extrude the material region (pick it with `profiles: [{point}]`).
```json
{"command": "frame.profile.insert", "params": {"profile": {"kind": "rect_tube", "width": 40, "height": 40, "wall": 3}, "at": [0, 0], "anchor": "bottom_left"}}
```
+2 -2
View File
@@ -9,7 +9,7 @@ Always shown, in order: MODEL, SURFACE, ASSEMBLE, INSERT, INSPECT, MANAGE, VIEW,
| Tab | Section | Command ids, in menu order |
|---|---|---|
| MODEL | SKETCH | **`sketch.create`**, `sketch.edit`, `sketch.line3d`, `sketch.spline3d`, `sketch.point3d`, `sketch.move3d` |
| MODEL | CREATE | **`solid.extrude`**, **`solid.revolve`**, **`solid.hole`**, `solid.sweep`, `solid.loft`, `solid.box`, `solid.cylinder`, `solid.sphere`, `solid.torus`, `solid.pipe`, `solid.bounding_solid`, `solid.thread`, `solid.boundary_fill`, `solid.coil`, `solid.rib`, `solid.web`, `solid.emboss`, `plastic.boss`, `plastic.lip`, `plastic.snap_fit`, `plastic.rest` |
| MODEL | CREATE | **`solid.extrude`**, **`solid.revolve`**, **`solid.hole`**, `solid.sweep`, `solid.loft`, `solid.box`, `solid.cylinder`, `solid.sphere`, `solid.torus`, `solid.pipe`, `solid.bounding_solid`, `solid.thread`, `solid.boundary_fill`, `solid.coil`, `solid.rib`, `solid.web`, `solid.emboss`, `plastic.boss`, `plastic.lip`, `plastic.snap_fit`, `plastic.rest`, `frame.member` |
| MODEL | MODIFY | **`solid.fillet`**, **`solid.chamfer`**, **`solid.shell`**, **`solid.press_pull`**, `sheet.convert`, `solid.combine`, `solid.scale`, `solid.offset_face`, `solid.draft`, `solid.split_face`, `solid.split_body`, `solid.replace_face`, `solid.remove`, `timeline.delete`, `face.delete` |
| MODEL | ARRANGE | **`solid.move`**, **`solid.mirror`**, **`solid.pattern.rectangular`**, `solid.align`, `solid.pattern.circular`, `solid.pattern.path` |
| MODEL | CONFIGURE | **`parameters.change`**, **`config.table`**, `config.configure` |
@@ -93,7 +93,7 @@ Explicit command-id lists override the default placement mapping. Shared command
| SOLID / CONSTRUCT | MODEL / CONSTRUCT | `construct.plane.offset`, `construct.plane.at_angle`, `construct.axis.through_cylinder`, `construct.axis.normal_to_face`, `construct.axis.two_planes`, `construct.axis.two_points`, `construct.axis.edge`, `construct.point.vertex`, `construct.point.two_edges`, `construct.point.three_planes`, `construct.point.center`, `construct.point.edge_plane`, `construct.point.along_path`, `construct.plane.midplane`, `construct.plane.two_edges`, `construct.plane.three_points`, `construct.plane.tangent`, `construct.plane.along_path`, `construct.plane.perpendicular` |
| SOLID / CREATE | ASSEMBLE / JOINTS | `joint.origin` |
| SOLID / CREATE | MODEL / ARRANGE | `solid.pattern.rectangular`, `solid.pattern.circular`, `solid.pattern.path`, `solid.mirror` |
| SOLID / CREATE | MODEL / CREATE | `solid.extrude`, `solid.revolve`, `solid.sweep`, `solid.loft`, `solid.box`, `solid.cylinder`, `solid.sphere`, `solid.torus`, `solid.hole`, `solid.pipe`, `solid.bounding_solid`, `solid.thread`, `solid.boundary_fill`, `solid.coil`, `solid.rib`, `solid.web`, `solid.emboss` |
| SOLID / CREATE | MODEL / CREATE | `solid.extrude`, `solid.revolve`, `solid.sweep`, `solid.loft`, `solid.box`, `solid.cylinder`, `solid.sphere`, `solid.torus`, `solid.hole`, `solid.pipe`, `solid.bounding_solid`, `solid.thread`, `solid.boundary_fill`, `solid.coil`, `solid.rib`, `solid.web`, `solid.emboss`, `frame.member` |
| SOLID / CREATE | MODEL / SKETCH | `sketch.create` |
| SOLID / INSERT | INSERT / FILES | `file.insert_step`, `file.insert_mesh` |
| SOLID / INSERT | INSERT / LIBRARY | `parts.fastener` |