Compare commits
225 Commits
ui-before-wheel
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| f9bfba7322 | |||
| 6f131b2efc | |||
| 8911bf2b4a | |||
| ff84a02082 | |||
| 4477fb2033 | |||
| 41ff788485 | |||
| 266aa176db | |||
| c5afac571d | |||
| 6b796c06cf | |||
| 27eb88e5c5 | |||
| 7a9e3caadc | |||
| 7bac6e1855 | |||
| 1e282f3b1c | |||
| bce9708035 | |||
| ee568a78cb | |||
| 82ec28a307 | |||
| 4d4016b92b | |||
| 739a819efd | |||
| 64f7b67432 | |||
| 3e95ff557c | |||
| 443799d7d4 | |||
| 0fd4394bc0 | |||
| 8483f6cec2 | |||
| 47afac977c | |||
| 3e3cece7fe | |||
| 55f654073c | |||
| 69ea518b83 | |||
| 65d38e3fff | |||
| 70871f6a7e | |||
| a2cfe76a3f | |||
| d53ddeaa76 | |||
| f8cc57fe7f | |||
| 47583abb3a | |||
| fc404cc92b | |||
| e4c5095be3 | |||
| 2433833eef | |||
| 4f93cfbf83 | |||
| a305c3c859 | |||
| 8ea2cb758c | |||
| 29836a709f | |||
| 342fbd6390 | |||
| f4d3113272 | |||
| b01f0b8f2c | |||
| d0d416c736 | |||
| aece06984b | |||
| 08803ba552 | |||
| 6b1b01fc91 | |||
| 1e97d848bf | |||
| d666e27dc8 | |||
| d0b39abbc0 | |||
| 6e30ce44e0 | |||
| e7cade47ce | |||
| 2d89322a97 | |||
| 6318ec47b5 | |||
| 96650a1652 | |||
| 95bd548aaa | |||
| 3fa975596d | |||
| 4cbd0d044e | |||
| 953d939180 | |||
| ac570d06c7 | |||
| 3ed4fb89e9 | |||
| 39865e7a19 | |||
| fbcf3d977f | |||
| 768c6964fc | |||
| 2efe1a83ef | |||
| 8259fc913f | |||
| 58ce95a443 | |||
| c61e3f0734 | |||
| d3c5146220 | |||
| c6b35b30e8 | |||
| 58b8bbe8c3 | |||
| 839c6538f5 | |||
| eb4cff5eeb | |||
| bb622f4866 | |||
| 4bfee451e2 | |||
| c8de25789d | |||
| 1a82d65802 | |||
| a81d22f143 | |||
| 0b9287cbeb | |||
| 093046340f | |||
| 35c2a350b0 | |||
| 57b6ca97e0 | |||
| b0a0d7124a | |||
| 720cbe9c28 | |||
| 179383d383 | |||
| 110eb695e5 | |||
| 5246af40b9 | |||
| 3a0efa62f0 | |||
| 26aeced38b | |||
| 7b225c93ae | |||
| 98865ff7ce | |||
| a07315e65d | |||
| 537ec20e5d | |||
| fe553f0c16 | |||
| 248fc7deb7 | |||
| 51c577d2ea | |||
| 1b20de78d8 | |||
| fb1a7a5314 | |||
| 5ffd6faf65 | |||
| 54986f617d | |||
| e2711937c3 | |||
| b8e7a3a58e | |||
| bf0a7a3dd9 | |||
| 434954fb8a | |||
| 4d91f1d14a | |||
| 179c475191 | |||
| 458b004e56 | |||
| df383a1291 | |||
| fcafc90e8f | |||
| efae4f257f | |||
| e2178263ed | |||
| 3e15e3a628 | |||
| f38204bddd | |||
| c652990d49 | |||
| af13a38f9b | |||
| 183230be7c | |||
| 42008ee4f9 | |||
| 21ec16229d | |||
| c8044fe17d | |||
| 1e711dca72 | |||
| c874eca73d | |||
| e08b81d3a4 | |||
| 5f3b455b33 | |||
| 1ba9249c24 | |||
| eb417e7f11 | |||
| c5858e55db | |||
| 60a2c0e671 | |||
| 7019512295 | |||
| 90ec917363 | |||
| d729a26fa8 | |||
| a8e7ed306a | |||
| bb23043b5b | |||
| 4951ad37c2 | |||
| 2f1a7a9496 | |||
| 0c4c282297 | |||
| e3926d2405 | |||
| d826580029 | |||
| c82df43257 | |||
| a2b7ff7c58 | |||
| 068eeaf38d | |||
| 319a170c35 | |||
| 4c17d5d9f3 | |||
| 5c54a2a2cb | |||
| cb8082f363 | |||
| 264fc1c244 | |||
| 3c0ddeb9df | |||
| 67d29470a3 | |||
| 0509747792 | |||
| 621009ba46 | |||
| 5e0f7f7ce6 | |||
| 28c8b69e12 | |||
| e3c81bc114 | |||
| 844647fb22 | |||
| 4ea8c70857 | |||
| 8258fcc05d | |||
| 5478bc71c9 | |||
| 409b01bab8 | |||
| 21116bdcb3 | |||
| 9a54b500d2 | |||
| 28393ed9cc | |||
| bafa89d599 | |||
| c2f9f33b9d | |||
| 43466f5b31 | |||
| 4b00ff0eca | |||
| 857f632c95 | |||
| 6541d92040 | |||
| 1d458cee3e | |||
| 664ef5a900 | |||
| 5c2bdfbb8c | |||
| 895366f2c2 | |||
| ef29247234 | |||
| 1bd75f8ed4 | |||
| 1ba46073ee | |||
| 433ffce1f4 | |||
| bfcf43bed6 | |||
| 7d935ebf3b | |||
| 7a3e190f53 | |||
| bb34a0a807 | |||
| 17e25f76ad | |||
| fcc78e60f8 | |||
| a5f53b5555 | |||
| a036d550c4 | |||
| 5a7fd027f1 | |||
| fccdae44d6 | |||
| 6a53df0019 | |||
| 2cb65c2146 | |||
| b8de2dc60f | |||
| 221187e60c | |||
| 8de2367a0c | |||
| bb97faba29 | |||
| a5b544dd16 | |||
| e946d020cf | |||
| d55b4193f4 | |||
| 9c6818592c | |||
| 9be1e8b074 | |||
| 9ca93f03e5 | |||
| 60b0c5e287 | |||
| a41684a5ed | |||
| 6af3b1727d | |||
| d5e2d0655e | |||
| 7ac0242515 | |||
| 2e2a92c02b | |||
| 655ba0e09d | |||
| 5f756942dc | |||
| 6a6ef8753e | |||
| 150dfa2550 | |||
| 7c0279a5af | |||
| 959e28f2be | |||
| fcd4c95bbb | |||
| 39c0d3fc7a | |||
| 676a2bd1d2 | |||
| 4a68114543 | |||
| 62589ebd85 | |||
| 1b4ee841f9 | |||
| 9e1c181905 | |||
| 4001b05c0e | |||
| 3a8f5bdb56 | |||
| 252de0e420 | |||
| 9f814af551 | |||
| 136bef9419 | |||
| d48ca428bc | |||
| 63352c1916 | |||
| 5204f9d6b8 | |||
| 409f0dfd9e | |||
| be7a232a3b |
@@ -1,5 +1,5 @@
|
||||
supergeometry.app - free browser-based solid modeler
|
||||
Copyright (C) 2026 supergeometry.app contributors
|
||||
superGeometry.app - free browser-based solid modeler
|
||||
Copyright (C) 2026 superGeometry.app contributors
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# supergeometry.app
|
||||
# superGeometry.app
|
||||
|
||||
**A free 3D design (CAD) app that runs in your web browser** - on a computer,
|
||||
an iPad or Android tablet, a phone, or a VR headset like the Meta Quest 3.
|
||||
No account, no download, no subscription. Your work stays on your device.
|
||||
|
||||
👉 **Open it:** [supergeometry.app](https://supergeometry.app)
|
||||
👉 **Open it:** [superGeometry.app](https://supergeometry.app)
|
||||
|
||||
Use it to design things for 3D printing, woodworking, laser cutting or just to
|
||||
think in 3D: brackets, boxes, vases, knobs, threads, enclosures, furniture parts…
|
||||
@@ -30,7 +30,10 @@ think in 3D: brackets, boxes, vases, knobs, threads, enclosures, furniture parts
|
||||
15. [For developers](#for-developers)
|
||||
16. [License](#license)
|
||||
|
||||
Inside the app, **More → Help** shows what every button does.
|
||||
Inside the app, **More → Help** shows what every button does, and **More →
|
||||
Tutorial** builds a first part with you: an M10 bolt and the nut that fits it,
|
||||
one lit tap at a time (the first time the app is opened, it is offered once
|
||||
the welcome window is closed).
|
||||
|
||||
---
|
||||
|
||||
@@ -42,8 +45,9 @@ Almost everything follows the same rhythm:
|
||||
2. **Turn it into a solid** - pull it up (*Extrude*), spin it around an axis
|
||||
(*Revolve*), or move it along a path (*Sweep*).
|
||||
3. **Select something and change it** - tap a face, an edge or a whole body:
|
||||
only the tools that make sense for it appear on the left. Drag the arrow or
|
||||
type a number.
|
||||
it can be dragged by itself (or by its arrow or dot), or typed; the buttons
|
||||
beside it hold the next likely tools, Delete and More, and the line at the
|
||||
bottom has every tool by group.
|
||||
4. **Every step is remembered** in *History*, so you can go back and change a
|
||||
size later - everything after it updates.
|
||||
|
||||
@@ -53,21 +57,28 @@ There's no wrong order. Undo (bottom left) is always one tap away.
|
||||
|
||||
## Your first part: a box with a hole
|
||||
|
||||
1. Tap **Sketch** (left column), then tap the blue **XY** square near the
|
||||
middle of the screen. The view turns to look straight down at that plane.
|
||||
2. Tap **Rectangle**, tap one corner, tap the opposite corner. While you draw,
|
||||
type a number for an exact size (e.g. `40`, Tab, `30`).
|
||||
3. Tap **Circle**, tap a centre inside the rectangle, tap again for the size
|
||||
1. A new project opens straight in a sketch on the floor, looking down at
|
||||
it, with **Line** on. (Any other time: tap **Sketch** on the line at the
|
||||
bottom, then a plane or a flat face.)
|
||||
2. Tap **Draw**, then **Rectangle**; tap one corner, tap the opposite corner. While you draw,
|
||||
type a number for an exact size (e.g. `40`, Tab, `30`, then Enter or a
|
||||
click): with a mouse the sizes show in small tags by the pointer, the one
|
||||
a typed number goes to lit. The ways a tool can
|
||||
be used (Rectangle: Center, Diagonal, 3 Points) are on the line while it is on.
|
||||
3. Tap **Draw**, then **Circle**; tap a centre inside the rectangle, tap again for the size
|
||||
(or type `8`).
|
||||
4. Tap **Exit Sketch** (top left of the tools) - or just tap an empty spot
|
||||
while looking at it from the side.
|
||||
4. Tap **Exit** at the end of the line. The view swings round to a
|
||||
three-quarter view.
|
||||
5. Tap inside the rectangle (but outside the circle): that region turns blue
|
||||
and an **arrow** appears. Drag the arrow up, or type `20`. You now have a
|
||||
box with a round hole.
|
||||
6. Tap the top face of the box. Drag its arrow to make it taller - the hole
|
||||
follows. Tap an edge and drag the dot **outward** for a rounded edge
|
||||
(*fillet*) or **inward** for a bevel (*chamfer*).
|
||||
7. **File → Export STL** to 3D-print it.
|
||||
and an **arrow** appears. Drag the shape itself, or its arrow, up - or type
|
||||
`20`: drawn on a plane, up makes a new body (down would cut). Tap the tick.
|
||||
You now have a box with a round hole.
|
||||
6. Tap the top face of the box and drag it to make it taller - the hole
|
||||
follows. Tap an edge and drag it **outward** for a rounded edge
|
||||
(*fillet*) or **inward** for a bevel (*chamfer*). Tap the hole's wall:
|
||||
**Thread** is on a button beside it.
|
||||
7. **More → Print / Share** says whether it is fit to print and saves it as
|
||||
3MF, STL or STEP.
|
||||
|
||||
## Second part: a vase
|
||||
|
||||
@@ -86,28 +97,37 @@ There's no wrong order. Undo (bottom left) is always one tap away.
|
||||
|
||||
| | Mouse | Touch / pen | Headset controller |
|
||||
|---|---|---|---|
|
||||
| Turn the view | left-drag empty space | one-finger drag | drag with the trigger |
|
||||
| Move the view | right or middle-drag | two-finger drag | - (use the view cube) |
|
||||
| Turn the view | right-drag (or Alt + left-drag) | one-finger drag | drag with the trigger |
|
||||
| Move the view | middle-drag (or Shift + right-drag) | two-finger drag | - (use the view cube) |
|
||||
| Zoom | mouse wheel | pinch | thumbstick / pinch |
|
||||
| Select | click | tap | point and trigger |
|
||||
| Select several | left-drag a box on empty space, or Ctrl + A for everything | tap one after another | point and trigger |
|
||||
| Select a whole body | double-click | double-tap | double-trigger |
|
||||
| Deselect | Esc or click empty space | tap empty space | tap empty space |
|
||||
| Step back | right-click or Esc | - | - |
|
||||
|
||||
- **Used to another program's mouse?** Settings → Mouse makes the buttons
|
||||
turn, move and zoom the view as they do there: Onshape and Tinkercad (the
|
||||
way the app comes), Fusion / Inventor / Revit / AutoCAD, SolidWorks,
|
||||
Creo / Solid Edge / Blender / SketchUp, NX, CATIA / FreeCAD, or Rhino -
|
||||
and sets which way the wheel zooms.
|
||||
- **Right-click steps back**: first what's half done or picked, then the
|
||||
drawing tool, then out of the sketch; in other tools it backs out. With
|
||||
something selected, right-click shows its tools by the pointer.
|
||||
- On touch screens **every tap adds to the selection**; tap again to drop it.
|
||||
- **A tap picks that thing** and lets the last pick go; tap it again to drop
|
||||
it. Shift, Ctrl or the **+** beside the pick's name adds to the pick. With
|
||||
a face or an edge picked, **Whole body** beside its name picks the body (a
|
||||
double tap on the model does too).
|
||||
- **A list opened from the line stays up** while you turn, move or zoom the
|
||||
view; it goes when you choose something in it or tap the model.
|
||||
|
||||
- **Fit** (right column) zooms so everything is on screen.
|
||||
- **Fit**: double-tap the view cube to get everything on screen.
|
||||
- **View cube** (top right): tap a face for a straight-on view (Top, Front…);
|
||||
⟲ ⟳ at its top corners turn the view by 90°.
|
||||
- **Orbit centre** (the cube's bottom-left button): tap it, then tap a point -
|
||||
the view now turns around that point. Fit resets it.
|
||||
- **Views** (the cube's bottom-right button): standard and saved views, and
|
||||
how the view looks; tap again to close.
|
||||
- On touch screens, **press and hold a tool** to see its name in the middle
|
||||
of the screen; let go on it to use it, slide off to cancel.
|
||||
- **Views** (the cube's bottom-right button): standard and saved views; tap
|
||||
again to close.
|
||||
|
||||
---
|
||||
|
||||
@@ -116,28 +136,44 @@ There's no wrong order. Undo (bottom left) is always one tap away.
|
||||
**Top bar** (top centre) - the project name (tap to rename), **File** (new / open / save /
|
||||
export), **Items** (a list of everything, with eyes to hide or show and
|
||||
folders to group; each kind - Bodies, Sketches, Planes & axes, Images - folds
|
||||
away under its heading, and a plane's icon shows how it was made), **More**
|
||||
(fullscreen, Help, About, support). On tablets and computers Items runs the
|
||||
full height of the screen, like History.
|
||||
away under its heading), **History**, **More** (fullscreen, Help, About,
|
||||
support).
|
||||
|
||||
**Left column** - the tools. With nothing selected you get the ones that
|
||||
*make* things (Sketch, Freeform, Extrude, Revolve, Transform, Construct,
|
||||
Insert…). With something selected you only see what can be done with it,
|
||||
in groups (picking, moving and patterns, making, combining, construction,
|
||||
colour, delete) apart with a dim line.
|
||||
**The line at the bottom** is how every tool is reached. Tap part of the
|
||||
model: a tag over the line names what is picked, and the line shows the
|
||||
groups - Sketch, Freeform, Transform, Construct, Modify, Combine, Create -
|
||||
each a list: what can be done with that pick first, then the group's other
|
||||
tools in a quieter part (each asks for its own pick as it starts). The group
|
||||
whose list is open stays lit. **More**, at the end of the line, holds only
|
||||
what is not on the line already: Insert, BIM, Section View, Measure,
|
||||
Variables, Print / Share, and the pick's own (Delete, Colour, Isolate). Tap a
|
||||
tool and the line becomes its settings: tap a number to type it or drag it
|
||||
sideways, tap a word to change it, tap the model to fill a blank; the tick
|
||||
finishes, the cross takes it back. On a phone held upright a tool shows its
|
||||
size and what it still needs tapped, and the rest is one word, **Options**.
|
||||
In a sketch the line holds Draw, Modify and Transform.
|
||||
|
||||
**Right column** (middle of the right edge) - Fit, Snapping, Units & grid,
|
||||
Display mode, Screenshot, Numpad (on / off), History, and in a sketch,
|
||||
Constraints.
|
||||
**Looks ahead** - with a mouse, the pointer over a tool draws what it would
|
||||
do in dashed yellow on the model before anything starts: a face's outline
|
||||
lifted (Extrude, Offset Face) or sunk (Shell), the lines a Fillet or Chamfer
|
||||
runs between, a row or a ring of copies for a pattern.
|
||||
|
||||
**Bottom left** - Undo / Redo, Section View (cut the view open), Measure and
|
||||
Isolate (show only the selected bodies).
|
||||
**Quick buttons** - round buttons beside a pick with its next two likeliest
|
||||
tools (a flat face Sketch and Move, a round face Thread and Fillet, an edge
|
||||
Chamfer and Move, a body Fillet and Mirror), then **Delete**, then **More**,
|
||||
which opens every other tool that pick has. In a sketch: Construction and
|
||||
Delete.
|
||||
|
||||
**The tool card** - the values for whatever you're doing (sizes, counts,
|
||||
options), its own actions, and Cancel / Done, each apart with a dim line. It
|
||||
keeps clear of what you're drawing; drag it by its grip where you want it
|
||||
(remembered per screen type), double-tap the grip to fold it down to its
|
||||
name (and again to open it).
|
||||
**Right edge** - **Fit**, **Display** (shaded, wireframe, X-ray) and
|
||||
**Settings**: one sheet with Units & grid, Snapping, the number pad and
|
||||
Appearance, each row saying how it is set now.
|
||||
|
||||
**Bottom left** - Undo / Redo.
|
||||
|
||||
**A tool's settings** - the values for whatever you're doing (sizes, counts,
|
||||
options) are the words on the line while the tool is open, with Cancel and
|
||||
Done at its end. The size that is dragged is also in a box on the model:
|
||||
tap it to type.
|
||||
|
||||
---
|
||||
|
||||
@@ -145,12 +181,12 @@ name (and again to open it).
|
||||
|
||||
Tap **Sketch** and pick where to draw: an origin plane (tap it, or the
|
||||
**XY** floor / **XZ** front / **YZ** side buttons), a flat face of a part, or
|
||||
one of your construction planes (listed by name in the card). In a
|
||||
one of your construction planes (listed by name on the line). In a
|
||||
straight-on view (Front, Top…) Sketch goes on the face you're looking at.
|
||||
Sketches on a face measure X / Y from the model's origin.
|
||||
|
||||
**Drawing tools:** Line (keeps going from the last point; tap the first point
|
||||
to close), Arc (two ends, then the bend - or by centre), Spline (smooth curve through points;
|
||||
to close, which ends the line), Arc (two ends, then the bend - or by centre), Spline (smooth curve through points;
|
||||
*Fit* or *Control* points, or *Draw*: press and drag freehand like a pencil - the stroke
|
||||
is cleaned up into a few lines, arcs and smooth curves, corners kept, so an extrusion
|
||||
gets a handful of faces, not hundreds; end where you began to close it), Rectangle (diagonal / centre / 3 points), Circle
|
||||
@@ -160,7 +196,7 @@ a few lines, arcs and smooth curves, so extruded text has a face per side, not h
|
||||
(copies body edges or other sketches' curves here).
|
||||
|
||||
**Exact points on touch screens:** right after the first tap of a line,
|
||||
rectangle, circle, polygon or ellipse the card has **X / Y** for that point
|
||||
rectangle, circle, polygon or ellipse the line has **X / Y** for that point
|
||||
(a fingertip can't hit a 1 mm grid). A line then takes **Length and Angle**,
|
||||
or **Across and Up** for a slope ("in 10, up 12"); an arc by centre takes the
|
||||
centre, Radius and the Start and End angles. Grid snapping follows the zoom
|
||||
@@ -171,6 +207,10 @@ is placed with Enter or Done.
|
||||
perpendicular, where two cross) are kept as constraints. Dragging a point onto
|
||||
another joins them.
|
||||
|
||||
**Fill Pattern:** a closed shape filled with lines from edge to edge (straight, crossed, zigzag, waves) or with
|
||||
small shapes (dots, honeycomb, squares, diamonds), its spacing, size and angle set; the strips and cells are
|
||||
shapes to extrude or cut, for textures.
|
||||
|
||||
**Edit tools:** Offset Edge (parallel copy; whole outlines too), Fillet and
|
||||
Chamfer (round or bevel a corner where lines or arcs meet; tap the next corner
|
||||
to go on), Mirror (the selected shapes, across a line or an axis), Trim (cut
|
||||
@@ -180,8 +220,6 @@ on along their circle), Split, Move/Rotate (gimbal, or Rotate About a tapped
|
||||
centre), Scale, Pattern (linear with an arrow you drag, or circular around a
|
||||
centre), Delete. Tools with options start with the option you used last.
|
||||
Tapping empty space finishes Offset, Move, Scale, Pattern, Rotate and Mirror.
|
||||
On phones the tool column shrinks to icons once you place a point; tap the
|
||||
tool in use to see the names again.
|
||||
|
||||
**Select** (in a sketch): tap curves to select them, double-tap for a whole
|
||||
shape. Drag points or curves, or use the gimbal. Tap an arc or circle to type
|
||||
@@ -198,13 +236,13 @@ picked stays put, the others adapt to it). Constraints are strict: one that
|
||||
contradicts those already there isn't added - remove the old one first, or
|
||||
switch **Auto constrain** off; a typed value that can't be met is refused
|
||||
rather than bending the sketch. Their marks are small and faint, a colour per
|
||||
kind, and never catch a tap meant for the drawing. Toggle the column with the
|
||||
**Constraints** button on the right.
|
||||
kind, and never catch a tap meant for the drawing. Show or hide their column
|
||||
with the **Constraints** button at the right edge while sketching.
|
||||
|
||||
Any closed shape becomes a **region** (blue when selected) you can extrude,
|
||||
revolve, sweep or loft. Overlapping shapes split into separate regions.
|
||||
Tapping a region shows Extrude's arrow - drag it, or type a height - and
|
||||
Revolve, Sweep and Loft beside it in the column for the same shape. While the
|
||||
Tapping a region shows Extrude's arrow - drag it or the shape itself, or
|
||||
type a height - with Sketch and Revolve on the buttons beside it. While the
|
||||
arrow is still at 0, tapping more regions of the same sketch adds them;
|
||||
**All shapes** takes every shape at once. Double-tap a shape to open its
|
||||
sketch. A sketch stays in view until every region of it is used.
|
||||
@@ -213,9 +251,9 @@ sketch. A sketch stays in view until every region of it is used.
|
||||
|
||||
## Making and changing solids
|
||||
|
||||
- **Extrude** - pull a region or a face. Negative distances cut. In *Auto*
|
||||
mode an extrusion that runs into another body cuts through it; choose *New*
|
||||
for a separate body. **Taper end %** sizes the far end (100 none, 0 a
|
||||
- **Extrude** - pull a region or a face. **Operation** (Auto, New body, Add,
|
||||
Cut, Intersect): Auto goes by direction - on a plane + is a new body and -
|
||||
a cut, on a face out adds and in cuts. **Taper end %** sizes the far end (100 none, 0 a
|
||||
point: a spire, a pyramid or a cone in one step) - type it or drag the box
|
||||
left / right. Extrude starts at the last distance.
|
||||
- **Revolve** - spin a region around an axis (a separate line, a side of a
|
||||
@@ -229,6 +267,10 @@ sketch. A sketch stays in view until every region of it is used.
|
||||
- **Fillet / Chamfer** - tap edges, drag the dot (outward rounds, inward
|
||||
bevels) or type a size in the box on the model; variables work too. A
|
||||
fillet that can't be made leaves the edge sharp with a note in History.
|
||||
- **Direct touch** - what is picked is dragged by itself: a face pushed or
|
||||
pulled, a sketch's shape pulled up into a solid, an edge rounded, a body
|
||||
slid over the floor. On a touch screen press and hold a face, shape or edge
|
||||
and pull, in one touch.
|
||||
- **Faces** - drag the arrow to push/pull a face: its neighbours follow,
|
||||
curved ones included; fillets next to it are kept. **Move/Rotate Face**
|
||||
(a gimbal on the face) moves it every way and turns it about its normal. A
|
||||
@@ -256,17 +298,19 @@ sketch. A sketch stays in view until every region of it is used.
|
||||
- **Split Body** - by a plane (yours, by name) or a face.
|
||||
- **Thread** - tap a round face or a hole's rim: a shank at the nominal size
|
||||
gets an outside thread, a hole at the tap-drill size an inside one. The
|
||||
pitch starts at the ISO coarse pitch (the card says what it makes, e.g.
|
||||
M10 × 1.5); left-hand as an option.
|
||||
pitch starts at the ISO coarse pitch (the line says what it makes, e.g.
|
||||
M10 × 1.5); left-hand as an option; free ends get a 45° lead-in.
|
||||
- **Repair Body** - fixes an imported or broken body (gaps, bad faces,
|
||||
slivers, inside-out) without changing its shape or size.
|
||||
- **Fill to Plane** - an open freeform surface becomes a solid by filling
|
||||
the gap down (or up, or across) to a plane.
|
||||
- **Freeform** - organic shapes: start from a box, sphere, cylinder or plane
|
||||
(its size and rows in the card) and pull its cage points, edges and faces.
|
||||
(its size and rows on the line) and pull its cage points, edges and faces.
|
||||
Tap picks the closest point, edge or face (tap a face again for the one
|
||||
behind it); press on empty space and drag a box to pick the points inside.
|
||||
Move / Turn / Scale take exact X, Y, Z values in the card. Cage tools:
|
||||
behind it); press on empty space and drag a box to pick the points inside
|
||||
(on a touch screen: switch on **Pick in a box** on the line, and a finger
|
||||
draws the box - the points behind are picked too, a whole slice from a side view).
|
||||
Move / Turn / Scale take exact X, Y, Z values on the line. Cage tools:
|
||||
**Extrude faces** (Length, Bend, Taper and Steps sliders - a spout in one
|
||||
go), **Bridge faces** (two faces become a tube; two looking the same way
|
||||
arch into a handle, with Arch and Segments), **Inset**, **Add edge loop**,
|
||||
@@ -294,9 +338,26 @@ sketch. A sketch stays in view until every region of it is used.
|
||||
- **Colour** - ten soft colours or **Custom…** for any colour; and how
|
||||
see-through a body is.
|
||||
- **Section View** - cut the view (not the part) to look inside; the cut
|
||||
shows as a solid face with a thick outline. **Place Plane** in its card
|
||||
shows as a solid face with a thick outline. **Place Plane** on the line
|
||||
puts a construction plane where the cut is (to sketch on or split with).
|
||||
- **Measure** - distances and angles; pin a measurement to keep it.
|
||||
- **BIM** (under More) - **Materials**: a real material for each body, which
|
||||
gives it its mass. **Technical Sheet**: the parts list with masses and the
|
||||
materials' data. **Drawings**: sheets with views, dimensions, item numbers
|
||||
and a title block.
|
||||
- **Assemblies** (More → BIM, still being tried out) - how the parts move.
|
||||
The parts stay where you modelled them; a **joint** only says how two of
|
||||
them move against each other. **Add joint**, tap a face on each part, and
|
||||
the kind is read off the faces: two round faces on one axis, or two flat
|
||||
faces one above the other, make a **Hinge** (a **Screw** of the thread's
|
||||
pitch when one part is threaded - a thread's own faces can be tapped too);
|
||||
two flat faces side by side, a **Slide**;
|
||||
anything else, **Fixed**. Drag a part to move it by its joint, or type its
|
||||
angle or distance; **Limits** keep it between two values; **Follows** makes
|
||||
one joint go with another by a ratio (gears); **Explode** pulls the parts
|
||||
apart. The pose is kept with the project and shown after OK; **Home** puts
|
||||
every part back where it was modelled. **Stop on contact** keeps a dragged
|
||||
part from running into another. No weight or forces.
|
||||
|
||||
---
|
||||
|
||||
@@ -312,11 +373,17 @@ sketch. A sketch stays in view until every region of it is used.
|
||||
↔ a length, ∠ an angle, # a number - and follows it as the model moves.
|
||||
Tap a tag to type its value or a formula, or drag the value: the model
|
||||
follows as you go, and lines show what it's made from and what uses it.
|
||||
The card has New Variable and the whole list; tap Variables again to switch off.
|
||||
The line has New Variable and the whole list; tap Variables again to switch off.
|
||||
Type them into any field (`wall * 2`) or pick them from the **ƒx** menu
|
||||
next to a value. Change the variable later and everything using it updates.
|
||||
- The **on-screen numpad** (the keypad button in the right column - tap it
|
||||
on or off) replaces the system keyboard for value boxes. It's on by default
|
||||
A size that follows a variable says so on the line (`od / 2 = 60 mm`).
|
||||
Formulas take `+ - * / ^`, brackets, units (`2 in + 5 mm`) and `sqrt`,
|
||||
`abs`, `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `floor`, `ceil`,
|
||||
`round`, `min`, `max` - `floor(length / pitch)` is how many fit. Changing
|
||||
the project's unit changes no size: plain numbers in formulas are given
|
||||
the unit they were typed in.
|
||||
- The **on-screen numpad** (Settings at the right edge, Number pad on
|
||||
screen) replaces the system keyboard for value boxes. It's on by default
|
||||
on phones, tablets and headsets. Tapping a box selects its value, so typing
|
||||
replaces it; nothing is applied until you press ↵. After the second tap of
|
||||
a line, its length box opens right away. Drag the numpad by its grip where
|
||||
@@ -362,8 +429,12 @@ can't be rebuilt after a change, it's marked and the reason is shown.
|
||||
File → Export DXF. Construction lines go on their own layer.
|
||||
- **File → New project** starts an empty one; the open project stays in the
|
||||
gallery.
|
||||
- **Insert** brings in STEP, STL, SVG and DXF files, and images to trace over
|
||||
(on the floor, front or side, its middle at the X / Y you type).
|
||||
- **More → Insert** brings in files (STEP, STL, OBJ, 3MF, DXF, SVG), another
|
||||
project's parts (**Project**), and pictures to trace over (**Image on
|
||||
plane**: on the floor, front or side, its middle at the X / Y you type).
|
||||
- A **.super** file is the whole project: every step and sketch, variables,
|
||||
saved views, names, colours, and the BIM side - materials, drawings, joints
|
||||
and the assembly's pose.
|
||||
|
||||
---
|
||||
|
||||
@@ -373,15 +444,12 @@ can't be rebuilt after a change, it's marked and the reason is shown.
|
||||
first turns the bin red, the second deletes. It goes back by itself after 3
|
||||
seconds, or at a tap anywhere else. Delete in the tools and in a tool's
|
||||
window takes one tap (Undo brings it back).
|
||||
- Tools show as icons: press and hold one to see its name.
|
||||
- With a pen, fingers are ignored while the pen touches the screen.
|
||||
- iPad / Android: **More → Fullscreen** gives the whole screen. On phones and
|
||||
tablets the app offers to be **installed on the home screen** (or More →
|
||||
Install app); on iPhone/iPad it's *Share → Add to Home Screen*.
|
||||
- The window the app opens with has a **Full screen** button. The tool card fits the widest
|
||||
clear gap along the bottom (beside undo/redo on a phone on its side), and a
|
||||
tool's options open beside a column of tools instead of over it.
|
||||
- Fit frames the model in the part of the screen the columns and bars leave
|
||||
- The window the app opens with has a **Full screen** button.
|
||||
- Fit frames the model in the part of the screen the bars leave
|
||||
free.
|
||||
- Meta Quest: open the site in the Quest browser; buttons and pick distances
|
||||
are bigger, and the numpad is on.
|
||||
@@ -428,20 +496,21 @@ OpenCascade (via replicad) running in a Web Worker; the UI is plain DOM over a
|
||||
three.js view. Units are millimetres internally; the display unit is a setting.
|
||||
|
||||
**Interaction model.**
|
||||
- Nothing selected → the left column shows creation tools: Sketch, Freeform,
|
||||
- Nothing selected → the line at the bottom has every tool (one that needs a pick asks for it as it starts): Sketch, Freeform,
|
||||
Extrude, Revolve, Sweep, Loft, Shell, Transform ▸ (Move/Rotate, Scale,
|
||||
Translate, Mirror, Rotate Around Axis, Patterns), Boolean ▸ (Union,
|
||||
Subtract, Intersect), Construct ▸ (planes, axes), Insert ▸ (variables,
|
||||
images, files), Tools ▸ (Offset Face, Offset Edge, Split Body, Fill to Plane, Thread,
|
||||
Repair Body…).
|
||||
- Something selected → only tools valid for it are shown (unusable ones are
|
||||
hidden, not greyed). Faces get a drag arrow (offset), straight edges a
|
||||
Move/Rotate gimbal (Fillet / Chamfer in the list), bodies a gimbal
|
||||
(move/rotate, with Copy). A sketch region gets Extrude's arrow plus
|
||||
Revolve / Sweep / Loft.
|
||||
- Something selected → each group lists the tools valid for it first, then
|
||||
its other tools (those ask for their own pick). The pick is dragged by
|
||||
itself or by its handle: faces an arrow (offset), edges a dot (fillet,
|
||||
inward a chamfer), bodies a gimbal (move/rotate, with Copy; its middle dot
|
||||
moves the pivot). A sketch region gets Extrude's arrow plus Revolve /
|
||||
Sweep / Loft.
|
||||
- Every operation is a *feature* in History; editing a feature replays
|
||||
everything after it.
|
||||
- Values: type while dragging, or in the bottom panel; expressions and
|
||||
- Values: type while dragging, or tap a number on the line at the bottom (the tool's options); expressions and
|
||||
variables are accepted everywhere a number is.
|
||||
|
||||
**Project file (`.super`, JSON).**
|
||||
@@ -479,6 +548,12 @@ three.js view. Units are millimetres internally; the display unit is a setting.
|
||||
`parallel`), `axis`, `moveFace` (face / edge / vertex), `scaleFace`,
|
||||
`replaceFace`, `deleteGeom`, `freeform` (`cage`, `surface`, `thickness`,
|
||||
`symmetry {origin, normal}`), `thread`, `repair`, `import`, `image`.
|
||||
- Beside `features`, the project holds `joints` (`type`: `fixed`, `hinge`,
|
||||
`slide`, `screw`; the two bodies `a` and `b`; the joint's line `origin`,
|
||||
`axis`; `min`, `max`; a screw's `pitch`; `drive {joint, ratio}`), `ground`
|
||||
(the body that stands still) and `pose {values, exploded}` (each joint's
|
||||
value by its id: degrees, or mm for a slide). They move what is shown, not
|
||||
the model.
|
||||
- Faces and edges are referenced by geometry, not index:
|
||||
faces `{body, center, normal, area}`, edges `{body, mid, dir, length}`.
|
||||
- `exprs` maps a field path (`"distance"`, `"op.translate.2"`) to an
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Architecture
|
||||
|
||||
supergeometry.app is a static web app. There is no server: everything (geometry kernel
|
||||
superGeometry.app is a static web app. There is no server: everything (geometry kernel
|
||||
included) runs in the browser, so it can be hosted for free and works offline.
|
||||
|
||||
```
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#1f2125" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<!-- Already dark: browser dark-mode add-ons (they lighten dark fills, and washed the wheels out) leave it as it is. -->
|
||||
<meta name="darkreader-lock" />
|
||||
<!-- The first paint, before the app's stylesheet is in (a reload, More → Update):
|
||||
the app's grey, and the search engines' text hidden - not black text on white. -->
|
||||
<style>
|
||||
@@ -17,16 +19,16 @@
|
||||
<link rel="canonical" href="https://supergeometry.app/" />
|
||||
<!-- Link previews (WhatsApp, Reddit, Discord, X, Facebook...). -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="supergeometry.app" />
|
||||
<meta property="og:site_name" content="superGeometry.app" />
|
||||
<meta property="og:url" content="https://supergeometry.app/" />
|
||||
<meta property="og:title" content="supergeometry.app - Free 3D CAD and 3D modeling in your browser" />
|
||||
<meta property="og:title" content="Free 3D CAD modeling on any device" />
|
||||
<meta property="og:description" content="Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download." />
|
||||
<meta property="og:image" content="https://supergeometry.app/og-image.png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta property="og:image:alt" content="supergeometry.app - free 3D CAD in your browser" />
|
||||
<meta property="og:image:alt" content="Free 3D CAD modeling on any device" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
<meta name="twitter:title" content="supergeometry.app - Free 3D CAD and 3D modeling in your browser" />
|
||||
<meta name="twitter:title" content="Free 3D CAD modeling on any device" />
|
||||
<meta name="twitter:description" content="Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download." />
|
||||
<meta name="twitter:image" content="https://supergeometry.app/og-image.png" />
|
||||
<!-- What it is, for search engines: a free design app that runs in the browser. -->
|
||||
@@ -34,7 +36,7 @@
|
||||
{
|
||||
"@context": "https://schema.org",
|
||||
"@type": "WebApplication",
|
||||
"name": "supergeometry.app",
|
||||
"name": "superGeometry.app",
|
||||
"url": "https://supergeometry.app/",
|
||||
"description": "Free 3D CAD app in your browser, for phone, tablet, computer and VR headset. Sketch, extrude, fillet and design parts for 3D printing. Export STL, STEP and 3MF. No account, no download.",
|
||||
"applicationCategory": "DesignApplication",
|
||||
@@ -53,15 +55,15 @@
|
||||
<link rel="manifest" href="./manifest.webmanifest" />
|
||||
<link rel="icon" href="./icon.svg" type="image/svg+xml" />
|
||||
<link rel="apple-touch-icon" href="./apple-touch-icon.png" />
|
||||
<title>supergeometry.app - Free 3D CAD and 3D modeling in your browser</title>
|
||||
<title>Free 3D CAD modeling on any device</title>
|
||||
</head>
|
||||
<body>
|
||||
<!-- What the app is, as text (the app itself is a 3D canvas and buttons):
|
||||
for search engines and screen readers. Not shown on screen. -->
|
||||
<main class="sr-only" aria-label="About supergeometry.app">
|
||||
<h1>supergeometry.app - free 3D CAD in your browser</h1>
|
||||
<main class="sr-only" aria-label="About superGeometry.app">
|
||||
<h1>Free 3D CAD modeling on any device</h1>
|
||||
<p>
|
||||
supergeometry.app is a free 3D design (CAD) and 3D modeling app that runs in your web browser, on a computer
|
||||
superGeometry.app is a free 3D design (CAD) and 3D modeling app that runs in your web browser, on a computer
|
||||
(Windows, Mac, Linux, Chromebook), an iPad or Android tablet, a phone, or a VR headset like the Meta Quest 3.
|
||||
No account, no download, no subscription. Your work stays on your device.
|
||||
</p>
|
||||
@@ -86,8 +88,8 @@
|
||||
<div id="pins"></div>
|
||||
|
||||
<header id="topbar">
|
||||
<div class="brand"><img class="brand-icon" src="icon.svg" alt="supergeometry.app" width="30" height="30" /><span class="brand-name">supergeometry<span class="brand-tld">.app</span></span></div>
|
||||
<input id="project-name" class="project-name" spellcheck="false" autocomplete="off" title="Project name - click to rename" aria-label="Project name" />
|
||||
<div class="brand"><img class="brand-icon" src="icon.svg" alt="superGeometry.app" width="30" height="30" /><span class="brand-name">superGeometry<span class="brand-tld">.app</span></span></div>
|
||||
<span id="project-name" class="project-name" role="textbox" tabindex="0" spellcheck="false" title="Project name - click to rename" aria-label="Project name"></span>
|
||||
<div class="menu-wrap">
|
||||
<button id="file-btn" class="text-btn">File</button>
|
||||
<div id="file-menu" class="menu" hidden>
|
||||
@@ -100,28 +102,32 @@
|
||||
<button id="m-3mf">Export 3MF</button>
|
||||
<button id="m-glb">Export GLB</button>
|
||||
<button id="m-each">Export each body separately…</button>
|
||||
<hr />
|
||||
<button id="m-dxf">Export DXF (sketch)</button>
|
||||
<button id="m-svg">Export SVG (sketch)</button>
|
||||
</div>
|
||||
</div>
|
||||
<button id="items-btn" class="text-btn" title="Items (bodies, sketches, planes)">Items</button>
|
||||
<button id="history-btn" class="text-btn" title="History (every step in order)">History</button>
|
||||
<button id="vr-btn" class="text-btn vr-btn" title="View the model in the headset" hidden>Enter VR</button>
|
||||
<div class="menu-wrap">
|
||||
<button id="more-btn" class="text-btn">More</button>
|
||||
<div id="more-menu" class="menu" hidden>
|
||||
<button id="m-fullscreen">Fullscreen<span class="menu-soon">F11</span></button>
|
||||
<button id="m-install" hidden>Install app <span class="menu-soon">Home screen</span></button>
|
||||
<button id="m-help">Help</button>
|
||||
<button id="m-hints">Guide text <span class="menu-soon" id="m-hints-state"></span></button>
|
||||
<button id="m-offline">Offline mode <span class="menu-soon" id="m-offline-state"></span></button>
|
||||
<button id="m-tutorial">Tutorial <span class="menu-soon">soon</span></button>
|
||||
<button id="m-update">Update</button>
|
||||
<hr />
|
||||
<button id="m-offline" class="menu-toggle" role="switch">Offline mode <span class="menu-soon" id="m-offline-state"></span><span class="switch"></span></button>
|
||||
<hr />
|
||||
<button id="m-hints" class="menu-toggle" role="switch">Guide text <span class="menu-soon" id="m-hints-state"></span><span class="switch"></span></button>
|
||||
<button id="m-tutorial">Tutorial <span class="menu-soon">a bolt and nut</span></button>
|
||||
<hr />
|
||||
<button id="m-help">Help</button>
|
||||
<button id="m-feedback">Feedback <span class="menu-soon">Bug / Idea</span></button>
|
||||
<button id="m-about">About supergeometry.app</button>
|
||||
<button id="m-donate">Boost / Donate / Support <span class="menu-soon" id="m-donate-arrow">▸</span></button>
|
||||
<button id="m-about">About</button>
|
||||
<button id="m-donate">Support <span class="menu-soon" id="m-donate-arrow">▸</span></button>
|
||||
<div id="m-donate-list" class="menu-sub" hidden>
|
||||
<button id="m-support-makerworld">MakerWorld - Boost <span class="menu-soon">↗</span></button>
|
||||
<button id="m-support-bmc">Buy Me a Coffee <span class="menu-soon">↗</span></button>
|
||||
<button id="m-support-stripe">Card (Stripe) <span class="menu-soon">↗</span></button>
|
||||
</div>
|
||||
<hr />
|
||||
<div class="menu-note" id="m-version"></div>
|
||||
@@ -141,6 +147,8 @@
|
||||
|
||||
<div id="viewcube-host"></div>
|
||||
<nav id="right-col" aria-label="View settings"></nav>
|
||||
<!-- Isolate, Measure, Section: always there, at the middle of the left edge. -->
|
||||
<nav id="left-col" aria-label="Isolate, measure, section"></nav>
|
||||
<div id="popover" hidden></div>
|
||||
|
||||
<nav id="toolbar" aria-label="Tools"></nav>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "supergeometry",
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "supergeometry",
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@fontsource/bebas-neue": "^5.3.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "supergeometry",
|
||||
"private": true,
|
||||
"version": "0.3.0",
|
||||
"version": "0.6.0",
|
||||
"description": "Free, browser-based solid modeler for every device.",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"type": "module",
|
||||
|
||||
@@ -25,3 +25,14 @@
|
||||
|
||||
/version.json
|
||||
Cache-Control: no-cache
|
||||
|
||||
# Security, on every file.
|
||||
# - What the page may load and run: its own files only. No script written into the page runs (a project file from
|
||||
# someone else that got markup onto the page could do nothing with it), no script from another site, no plugins.
|
||||
# 'unsafe-eval' is for the geometry engine, which builds part of itself as it starts ('wasm-unsafe-eval': its
|
||||
# WebAssembly). Pictures and the Browser window's pages may come from anywhere: they are what the user opens.
|
||||
# - Files are what they say they are (nosniff); other sites are told only the site's address, not the page's.
|
||||
/*
|
||||
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https: http:; font-src 'self' data:; connect-src 'self' data: blob:; worker-src 'self' blob:; frame-src https: http:; media-src 'self' data: blob:; object-src 'none'; base-uri 'self'; form-action 'none'
|
||||
X-Content-Type-Options: nosniff
|
||||
Referrer-Policy: strict-origin-when-cross-origin
|
||||
|
||||
|
Before Width: | Height: | Size: 7.8 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 26 KiB |
@@ -1,5 +1,243 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<rect width="64" height="64" rx="14" fill="#1f2125"/>
|
||||
<path d="M32.00 10.00 L20.23 25.20 L43.77 25.20Z" fill="#a9cbff"/><path d="M12.95 21.00 L32.00 10.00 L20.23 25.20Z" fill="#bcd6ff"/><path d="M32.00 10.00 L51.05 21.00 L43.77 25.20Z" fill="#8bb8ff"/><path d="M20.23 25.20 L43.77 25.20 L32.00 45.60Z" fill="#5c9dff"/><path d="M51.05 21.00 L51.05 43.00 L43.77 25.20Z" fill="#3d8bff"/><path d="M51.05 43.00 L43.77 25.20 L32.00 45.60Z" fill="#3478e6"/><path d="M12.95 43.00 L12.95 21.00 L20.23 25.20Z" fill="#6aa5ff"/><path d="M12.95 43.00 L20.23 25.20 L32.00 45.60Z" fill="#4a8ff5"/><path d="M51.05 43.00 L32.00 54.00 L32.00 45.60Z" fill="#2a63c4"/><path d="M32.00 54.00 L12.95 43.00 L32.00 45.60Z" fill="#2457ad"/>
|
||||
<path d="M32.00 10.00 L51.05 21.00 L51.05 43.00 L32.00 54.00 L12.95 43.00 L12.95 21.00Z M43.77 25.20 L32.00 45.60 L20.23 25.20Z M32.00 10.00 L20.23 25.20 M32.00 10.00 L43.77 25.20 M51.05 21.00 L43.77 25.20 M51.05 43.00 L43.77 25.20 M51.05 43.00 L32.00 45.60 M32.00 54.00 L32.00 45.60 M12.95 43.00 L32.00 45.60 M12.95 43.00 L20.23 25.20 M12.95 21.00 L20.23 25.20" fill="none" stroke="#1f2125" stroke-width="1.1" stroke-linejoin="round"/>
|
||||
<rect width="64" height="64" rx="14" fill="#1f2125"/>
|
||||
<g stroke-width=".2" stroke-linejoin="round">
|
||||
<path d="M19.8 47.9L26.4 55L20.8 54.6Z" fill="#ce362d" stroke="#ce362d"/>
|
||||
<path d="M19.8 47.9L20.8 54.6L15.2 52Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M50 42.5L55.1 44.4L60 49.4Z" fill="#ac2c25" stroke="#ac2c25"/>
|
||||
<path d="M23.7 41.6L24.8 48.4L19.8 47.9Z" fill="#da3c31" stroke="#da3c31"/>
|
||||
<path d="M21.6 48L21 47.7L20.5 47.4L20.2 47.2L23.7 41.6L24.8 48.4L21.8 48.1Z" fill="#ffc442" stroke="#ffc442"/>
|
||||
<path d="M21.4 45.2L21.5 45.2L22.1 45.6L22.7 45.9L23.3 46.2L23.9 46.5L24.5 46.8L24.5 46.9L23.7 41.8L23.6 41.7Z" fill="#2d66c7" stroke="#2d66c7"/>
|
||||
<path d="M19.8 47.9L24.8 48.4L26.4 55Z" fill="#e2483d" stroke="#e2483d"/>
|
||||
<path d="M25 49.8L24.4 49.5L23.9 49.2L23.3 48.9L22.7 48.6L22.2 48.3L21.8 48.1L24.8 48.4L25.2 49.9Z" fill="#ffcc57" stroke="#ffcc57"/>
|
||||
<path d="M50 42.5L60 49.4L54.4 47.3Z" fill="#87211c" stroke="#87211c"/>
|
||||
<path d="M19.2 40.9L23.7 41.6L19.8 47.9Z" fill="#8e241e" stroke="#8e241e"/>
|
||||
<path d="M20 47.1L19.7 46.9L19.2 40.9L23.7 41.6L20.2 47.2Z" fill="#ac7a12" stroke="#ac7a12"/>
|
||||
<path d="M19.4 43.9L19.9 44.2L20.5 44.5L21 44.9L21.4 45.2L23.6 41.7L23.3 41.5L19.2 40.9Z" fill="#163d82" stroke="#163d82"/>
|
||||
<path d="M50.5 38.8L55.1 44.4L50 42.5Z" fill="#9d2821" stroke="#9d2821"/>
|
||||
<path d="M23 34.5L26.8 33.8L23.7 41.6Z" fill="#dc3f35" stroke="#dc3f35"/>
|
||||
<path d="M23 34.5L26.8 33.8L23.7 41.6Z" fill="#ffc648" stroke="#ffc648"/>
|
||||
<path d="M19.1 33.7L23 34.5L23.7 41.6Z" fill="#7f1f1a" stroke="#7f1f1a"/>
|
||||
<path d="M19.1 33.7L23 34.5L23.7 41.6Z" fill="#9c6b09" stroke="#9c6b09"/>
|
||||
<path d="M21.2 37.3L21.1 37L21 36.4L20.9 35.9L20.7 35.3L20.6 34.8L20.5 34.2L20.5 34L19.1 33.7Z" fill="#123675" stroke="#123675"/>
|
||||
<path d="M19.1 33.7L23.7 41.6L19.2 40.9Z" fill="#8b231d" stroke="#8b231d"/>
|
||||
<path d="M19.1 33.7L23.7 41.6L19.2 40.9Z" fill="#a87710" stroke="#a87710"/>
|
||||
<path d="M19.2 40.9L23.3 41.5L23.2 41.5L22.6 41.1L22.1 40.7L21.6 40.4L21.5 39.8L21.4 39.3L21.4 38.7L21.3 38.1L21.2 37.6L21.2 37.3L19.1 33.7Z" fill="#153c7f" stroke="#153c7f"/>
|
||||
<path d="M14.7 45.6L19.8 47.9L15.2 52Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M23.7 41.6L29.8 46.2L24.8 48.4Z" fill="#e0453b" stroke="#e0453b"/>
|
||||
<path d="M23.7 41.6L29.8 46.2L24.8 48.4Z" fill="#ffca52" stroke="#ffca52"/>
|
||||
<path d="M24.5 46.9L25 46.9L25.6 47L26.2 47L26.7 47L27.3 47.1L27.8 47.1L29.8 46.2L23.9 41.8L23.7 41.8L23.7 41.8Z" fill="#3871d0" stroke="#3871d0"/>
|
||||
<path d="M24.8 48.4L29.8 46.2L26.4 55Z" fill="#e44b3f" stroke="#e44b3f"/>
|
||||
<path d="M28.2 50.1L27.7 50.1L27.2 50L26.6 50L26.1 49.9L25.5 49.9L25.2 49.9L24.8 48.4L29.8 46.2L28.3 50.1Z" fill="#ffce5b" stroke="#ffce5b"/>
|
||||
<path d="M28.4 47.2L29 47.2L29.4 47.2L29.8 46.2L27.8 47.1L27.9 47.1Z" fill="#3e76d6" stroke="#3e76d6"/>
|
||||
<path d="M22.8 27.3L26.8 33.8L23 34.5Z" fill="#d93a30" stroke="#d93a30"/>
|
||||
<path d="M22.8 27.3L26.8 33.8L23 34.5Z" fill="#ffc33f" stroke="#ffc33f"/>
|
||||
<path d="M22.9 32.1L23.1 31.9L23.6 31.5L24.1 31.1L24.6 30.7L24.8 30.6L22.8 27.3Z" fill="#2b64c5" stroke="#2b64c5"/>
|
||||
<path d="M22.8 27.3L23 34.5L19.1 33.7Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M22.8 27.3L23 34.5L19.1 33.7Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M19.1 33.7L20.5 34L20.4 33.6L20.3 33L20.8 32.9L21.2 32.7L21.7 32.5L22.2 32.3L22.6 32.2L22.9 32.1L22.8 27.3Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M26.8 33.8L28.1 40.1L23.7 41.6Z" fill="#eb564a" stroke="#eb564a"/>
|
||||
<path d="M23.7 41.6L26.8 33.8L28.1 40.1Z" fill="#ffd56e" stroke="#ffd56e"/>
|
||||
<path d="M46 37.1L50.5 38.8L50 42.5Z" fill="#7f1f1a" stroke="#7f1f1a"/>
|
||||
<path d="M14.7 38.9L19.2 40.9L19.8 47.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M19.5 46.7L19 46.2L18.6 45.9L14.7 38.9L19.2 40.9L19.7 46.9Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M16.9 40.7L17.1 41.3L17.2 41.8L17.8 42.3L18.3 42.8L18.9 43.3L19.4 43.8L19.4 43.9L19.2 40.9L16.7 39.8L16.8 40.1Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M22.8 27.3L26 27.1L26.8 33.8Z" fill="#dd4035" stroke="#dd4035"/>
|
||||
<path d="M22.8 27.3L26 27.1L26.8 33.8Z" fill="#ffc749" stroke="#ffc749"/>
|
||||
<path d="M22.8 27.3L24.8 30.6L25.1 30.4L25.5 30.1L25.9 29.8L26.3 29.5L26.3 29.5L26 27.1Z" fill="#326bcb" stroke="#326bcb"/>
|
||||
<path d="M42.3 31.2L46.2 32.7L50.5 38.8Z" fill="#80201a" stroke="#80201a"/>
|
||||
<path d="M50 42.5L54.4 47.3L48.8 44.9Z" fill="#82201b" stroke="#82201b"/>
|
||||
<path d="M25.6 20L26 27.1L22.8 27.3Z" fill="#cf362d" stroke="#cf362d"/>
|
||||
<path d="M22.8 27.3L25.2 21.2L25.7 20.9L25.7 20.9L26 27.1Z" fill="#f4b937" stroke="#f4b937"/>
|
||||
<path d="M25.3 24.5L24.8 24.8L24.3 25.1L23.8 25.4L23.4 25.7L22.8 27.3L26 27.1L25.9 24.2L25.9 24.2Z" fill="#275ebc" stroke="#275ebc"/>
|
||||
<path d="M23.7 41.6L28.1 40.1L29.8 46.2Z" fill="#ef5b4f" stroke="#ef5b4f"/>
|
||||
<path d="M23.7 41.6L28.1 40.1L29.8 46.2Z" fill="#ffd978" stroke="#ffd978"/>
|
||||
<path d="M29.8 46.2L28.8 42.4L28.8 42.4L28.2 42.4L27.7 42.3L27.1 42.2L26.6 42.1L26 42.1L25.5 42L24.9 41.9L24.3 41.8L23.9 41.8Z" fill="#5189e6" stroke="#5189e6"/>
|
||||
<path d="M14.7 38.9L19.8 47.9L14.7 45.6Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M17.9 45.2L17.4 44.7L16.8 44.2L16.2 43.7L15.7 43.2L15.1 42.7L14.7 42.4L14.7 38.9L18.6 45.9L18.4 45.7Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M23.1 19.9L25.6 20L22.8 27.3Z" fill="#9e2821" stroke="#9e2821"/>
|
||||
<path d="M23 22.5L23.3 22.3L23.7 22L24.2 21.7L24.6 21.5L25.1 21.2L25.2 21.2L22.8 27.3Z" fill="#be891b" stroke="#be891b"/>
|
||||
<path d="M23.4 25.7L23 26L22.8 26.1L22.8 27.3L23.4 25.7Z" fill="#1b4590" stroke="#1b4590"/>
|
||||
<path d="M19.6 26.5L22.8 27.3L19.1 33.7Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M19.6 26.5L22.8 27.3L19.1 33.7Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M20.8 26.8L20.6 26.9L20.2 27L19.7 27.2L19.5 27.3L19.1 33.7L22.8 27.3Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M19.1 33.7L19.2 40.9L14.7 38.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M19.1 33.7L19.2 40.9L14.7 38.9Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M16.2 37.2L16.3 37.6L16.4 38.3L16.5 38.9L16.6 39.5L16.7 39.8L19.2 40.9L19.1 33.7Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M42.3 31.2L50.5 38.8L46 37.1Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M26 27.1L29.2 25.9L26.8 33.8Z" fill="#e64d42" stroke="#e64d42"/>
|
||||
<path d="M26 27.1L29.2 25.9L26.8 33.8Z" fill="#ffd060" stroke="#ffd060"/>
|
||||
<path d="M26 27.1L26.3 29.5L26.3 29.5L26.8 29.6L27.3 29.7L27.7 29.8L28 29.9L29.2 25.9Z" fill="#427ad8" stroke="#427ad8"/>
|
||||
<path d="M42.1 26.2L46.2 32.7L42.3 31.2Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M25.6 20L29.2 25.9L26 27.1Z" fill="#e1473c" stroke="#e1473c"/>
|
||||
<path d="M26 27.1L25.7 20.9L25.7 20.9L26.2 20.9L29.2 25.9Z" fill="#ffcb55" stroke="#ffcb55"/>
|
||||
<path d="M27.9 24.5L27.4 24.4L26.9 24.3L26.4 24.3L25.9 24.2L25.9 24.2L26 27.1L29.2 25.9L28.4 24.6L28.4 24.6Z" fill="#3a72d2" stroke="#3a72d2"/>
|
||||
<path d="M20.6 19.3L23.1 19.9L22.8 27.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M21.6 23.1L22 22.9L22.4 22.7L22.9 22.5L23 22.5L22.8 27.3Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M22.6 26.2L22.5 26.3L22.8 27.3L22.8 26.1Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M20.6 19.3L22.8 27.3L19.6 26.5Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M20 23.5L20 23.5L20.6 23.4L21.1 23.2L21.6 23.1L21.6 23.1L22.8 27.3L19.6 26.5Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M21.6 26.5L21.1 26.7L20.8 26.8L22.8 27.3L22.5 26.3L22.1 26.4Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M24.1 12.3L25.6 20L23.1 19.9Z" fill="#992720" stroke="#992720"/>
|
||||
<path d="M29.8 46.2L32 52.3L26.4 55Z" fill="#e75045" stroke="#e75045"/>
|
||||
<path d="M31.2 50L30.6 50L30 50.1L29.4 50.1L28.8 50.1L28.3 50.1L29.8 46.2L31.2 50Z" fill="#ffd165" stroke="#ffd165"/>
|
||||
<path d="M29.4 47.2L29.6 47.2L30.2 47.2L30.2 47.2L29.8 46.2Z" fill="#457cdb" stroke="#457cdb"/>
|
||||
<path d="M25.6 20L28.1 19.5L29.2 25.9Z" fill="#eb564a" stroke="#eb564a"/>
|
||||
<path d="M27.2 21.2L27.7 21.4L28.1 21.6L28.5 21.7L29.2 25.9L26.2 20.9L26.2 20.9L26.7 21.1Z" fill="#ffd56f" stroke="#ffd56f"/>
|
||||
<path d="M28.8 24.8L28.4 24.6L29.2 25.9L29.1 24.9Z" fill="#4b83e1" stroke="#4b83e1"/>
|
||||
<path d="M27.2 12.3L28.1 19.5L25.6 20Z" fill="#de4338" stroke="#de4338"/>
|
||||
<path d="M24.1 12.3L25.7 12.3L25.6 20Z" fill="#a52a23" stroke="#a52a23"/>
|
||||
<path d="M25.7 12.3L27.2 12.3L25.6 20Z" fill="#a52a23" stroke="#a52a23"/>
|
||||
<path d="M26.8 33.8L32.6 37.4L28.1 40.1Z" fill="#e64e42" stroke="#e64e42"/>
|
||||
<path d="M26.8 33.8L32.6 37.4L28.1 40.1Z" fill="#ffd061" stroke="#ffd061"/>
|
||||
<path d="M28.1 40.1L32.6 37.4L27.6 34.2L27.7 34.7L27.8 35.3L27.9 35.8L28 36.3L28.1 36.9L28.2 37.4L28.3 38L28.9 37.6L29.5 37.2L30.1 36.8L30.8 36.5L30.9 36.4L32.6 37.4L28.1 40.1Z" fill="#427ad9" stroke="#427ad9"/>
|
||||
<path d="M29.2 25.9L30.7 31.8L26.8 33.8Z" fill="#e95347" stroke="#e95347"/>
|
||||
<path d="M29.2 25.9L30.7 31.8L26.8 33.8Z" fill="#ffd36a" stroke="#ffd36a"/>
|
||||
<path d="M28 29.9L28.2 29.9L28.8 29.9L29.3 29.8L29.8 29.8L30.2 29.8L29.2 25.9Z" fill="#487fde" stroke="#487fde"/>
|
||||
<path d="M24.1 12.3L23.1 19.9L20.6 19.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M16.3 25.3L19.6 26.5L19.1 33.7Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M16.3 25.3L19.6 26.5L19.1 33.7Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M19.3 27.3L18.8 27.5L18.4 27.6L18 27.8L17.5 27.9L17.2 28L19.1 33.7L19.5 27.3Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M41.5 35.4L46 37.1L50 42.5Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M42.8 36.3L42.9 36.5L41.5 35.4L42.5 35.8L42.6 35.9Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M35.7 18.7L38.2 19.3L42.1 26.2Z" fill="#88221c" stroke="#88221c"/>
|
||||
<path d="M9.7 44L14.7 45.6L15.2 52Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M15.2 32.1L19.1 33.7L14.7 38.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M15.2 32.1L19.1 33.7L14.7 38.9Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M15.6 33L15.7 33.6L15.8 34.2L15.9 34.7L15.9 35.3L16 35.9L16.1 36.5L16.2 37L16.2 37.2L19.1 33.7L15.5 32.2L15.5 32.4Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M38.9 25L42.1 26.2L42.3 31.2Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M39.5 26.2L39.9 26.5L40.4 26.8L40.5 27.2L40.6 27.6L40.6 28.1L40.7 28.3Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M45 40.4L50 42.5L48.8 44.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M20.9 12.3L22.5 12.3L20.6 19.3Z" fill="#d6382e" stroke="#d6382e"/>
|
||||
<path d="M22.5 12.3L24.1 12.3L20.6 19.3Z" fill="#d6382e" stroke="#d6382e"/>
|
||||
<path d="M28.1 19.5L30.7 18.7L29.2 25.9Z" fill="#ea5448" stroke="#ea5448"/>
|
||||
<path d="M28.5 21.7L28.6 21.7L29 21.8L29.4 22L29.9 22.1L30 22.1L29.2 25.9Z" fill="#ffd46c" stroke="#ffd46c"/>
|
||||
<path d="M29.2 24.9L29.1 24.9L29.2 25.9L29.4 25Z" fill="#4981df" stroke="#4981df"/>
|
||||
<path d="M35.7 18.7L42.1 26.2L38.9 25Z" fill="#83201b" stroke="#83201b"/>
|
||||
<path d="M28.1 40.1L32.6 37.4L29.8 46.2Z" fill="#e85145" stroke="#e85145"/>
|
||||
<path d="M28.1 40.1L32.6 37.4L29.8 46.2Z" fill="#ffd266" stroke="#ffd266"/>
|
||||
<path d="M29.8 46.2L32.5 37.8L32.2 38.2L31.7 38.7L31.3 39.3L30.9 39.8L30.4 40.3L30 40.9L29.6 41.4L29.2 41.9L28.8 42.4L28.8 42.4Z" fill="#457ddc" stroke="#457ddc"/>
|
||||
<path d="M27.2 12.3L30.7 18.7L28.1 19.5Z" fill="#df4439" stroke="#df4439"/>
|
||||
<path d="M33.6 12.3L38.2 19.3L35.7 18.7Z" fill="#982620" stroke="#982620"/>
|
||||
<path d="M20.6 19.3L19.6 26.5L16.3 25.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M17.1 24.2L17.5 24.1L18 24L18.5 23.9L19 23.8L19.5 23.6L20 23.5L19.6 26.5L16.3 25.3Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M16.3 25.3L19.1 33.7L15.2 32.1Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M16.3 25.3L19.1 33.7L15.2 32.1Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M16.6 28.1L16.1 28.2L15.9 28.2L15.4 31.2L15.4 31.3L15.5 31.8L15.5 32.2L19.1 33.7L17.2 28L17.1 28Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M27.2 12.3L28.8 12.3L30.7 18.7Z" fill="#e3493e" stroke="#e3493e"/>
|
||||
<path d="M28.8 12.3L30.4 12.3L30.7 18.7Z" fill="#e3493e" stroke="#e3493e"/>
|
||||
<path d="M30.4 12.3L32 12.3L35.7 18.7Z" fill="#e34a3f" stroke="#e34a3f"/>
|
||||
<path d="M32 12.3L33.6 12.3L35.7 18.7Z" fill="#e34a3f" stroke="#e34a3f"/>
|
||||
<path d="M26.8 33.8L30.7 31.8L32.6 37.4Z" fill="#e95348" stroke="#e95348"/>
|
||||
<path d="M26.8 33.8L30.7 31.8L32.6 37.4Z" fill="#ffd36b" stroke="#ffd36b"/>
|
||||
<path d="M32.6 37.4L30.8 32L30.3 32.3L29.7 32.6L29.1 32.9L28.6 33.1L28 33.4L27.4 33.7L27.6 34.2L27.6 34.2L30.9 36.4L31.3 36.2L31.8 35.9L32.1 35.8L32.6 37.4Z" fill="#4880de" stroke="#4880de"/>
|
||||
<path d="M20.9 12.3L20.6 19.3L18.1 18.6Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M17.7 12.3L19.3 12.3L15.5 18.6Z" fill="#e95247" stroke="#e95247"/>
|
||||
<path d="M19.3 12.3L20.9 12.3L15.5 18.6Z" fill="#e95247" stroke="#e95247"/>
|
||||
<path d="M42.3 31.2L46 37.1L41.5 35.4Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M41.8 33.8L41.9 33.9L42 34.3L42.2 34.7L42.3 35.1L42.5 35.5L42.5 35.8L41.5 35.4Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M41.5 35.4L50 42.5L45 40.4Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M42.9 36.6L43.1 37L43.2 37.3L43.3 37.6L43.4 38L43.3 37.9L41.5 35.4L42.9 36.5Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M17.7 12.3L15.5 18.6L13 19.1Z" fill="#ff7466" stroke="#ff7466"/>
|
||||
<path d="M14.7 38.9L14.7 45.6L9.7 44Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M14.4 41.7L14.3 41.1L14.1 40.6L14 40L13.9 39.7L14.7 38.9L14.7 42.4L14.5 42.2Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M9.7 44L15.2 52L9.6 50.2Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M30.4 12.3L33.2 18.4L30.7 18.7Z" fill="#f26154" stroke="#f26154"/>
|
||||
<path d="M30.4 12.3L35.7 18.7L33.2 18.4Z" fill="#d6382f" stroke="#d6382f"/>
|
||||
<path d="M20.9 12.3L18.1 18.6L15.5 18.6Z" fill="#dd4136" stroke="#dd4136"/>
|
||||
<path d="M30.7 18.7L32.5 24.7L29.2 25.9Z" fill="#eb564a" stroke="#eb564a"/>
|
||||
<path d="M30 22.1L30.4 22.1L30.9 22.2L31.5 22.2L31.7 22.3L32.5 24.7L29.2 25.9Z" fill="#ffd570" stroke="#ffd570"/>
|
||||
<path d="M30.8 25.1L30.2 25.1L29.7 25L29.4 25L29.2 25.9L31.2 25.2Z" fill="#4c83e1" stroke="#4c83e1"/>
|
||||
<path d="M18.1 18.6L20.6 19.3L16.3 25.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M16.6 24.5L16.7 24.4L17.1 24.3L17.1 24.2L16.3 25.3Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M13 19.1L15.5 18.6L9.9 25.6Z" fill="#ff7466" stroke="#ff7466"/>
|
||||
<path d="M35.7 24.3L38.9 25L42.3 31.2Z" fill="#90241e" stroke="#90241e"/>
|
||||
<path d="M37.9 25.2L38.4 25.5L38.9 25.8L39.4 26.1L39.5 26.2L40.7 28.3L40.7 28.5L40.8 28.9L40.9 29.4L41 29.8L41.1 29.9L35.7 24.3L37 24.6L37.4 24.8Z" fill="#af7c13" stroke="#af7c13"/>
|
||||
<path d="M29.2 25.9L34.6 30.2L30.7 31.8Z" fill="#ee5a4e" stroke="#ee5a4e"/>
|
||||
<path d="M30.7 31.8L29.2 25.9L34.6 30.2Z" fill="#ffd876" stroke="#ffd876"/>
|
||||
<path d="M30.2 29.8L30.4 29.8L30.9 29.8L31.4 29.8L32 29.9L32.5 29.9L33 29.9L33.5 30L34 30L34.4 30L29.2 25.9Z" fill="#5087e5" stroke="#5087e5"/>
|
||||
<path d="M35.7 18.7L38.9 25L35.7 24.3Z" fill="#9b2721" stroke="#9b2721"/>
|
||||
<path d="M35.7 23.8L35.8 23.8L36.4 24.2L36.9 24.5L37 24.6L35.7 24.3Z" fill="#ba8619" stroke="#ba8619"/>
|
||||
<path d="M15.5 18.6L18.1 18.6L16.3 25.3Z" fill="#ca352c" stroke="#ca352c"/>
|
||||
<path d="M16.3 24.7L16.3 24.7L16.6 24.5L16.3 25.3Z" fill="#f0b535" stroke="#f0b535"/>
|
||||
<path d="M11.4 31.3L15.2 32.1L14.7 38.9Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M13.4 35.9L13.4 35.9L13.3 35.3L13.2 34.8L13.1 34.3L13 33.7L12.9 33.2L12.8 32.6L12.7 32.1L12.5 31.5L12.5 31.5L15.2 32.1L14.7 38.9Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M30.7 18.7L33.2 18.4L35.7 24.3Z" fill="#eb5549" stroke="#eb5549"/>
|
||||
<path d="M34.8 23.3L35 23.4L35.4 23.5L35.7 24.3Z" fill="#ffd56e" stroke="#ffd56e"/>
|
||||
<path d="M33.2 18.4L35.7 18.7L35.7 24.3Z" fill="#cb352c" stroke="#cb352c"/>
|
||||
<path d="M35.4 23.5L35.4 23.6L35.7 23.8L35.7 24.3Z" fill="#f1b535" stroke="#f1b535"/>
|
||||
<path d="M29.2 25.9L32.5 24.7L34.6 30.2Z" fill="#e95347" stroke="#e95347"/>
|
||||
<path d="M29.2 25.9L32.5 24.7L34.6 30.2Z" fill="#ffd36a" stroke="#ffd36a"/>
|
||||
<path d="M32.3 25.2L31.8 25.2L31.3 25.2L31.2 25.2L29.2 25.9L34.4 30L34.5 30L34.5 29.9L32.7 25.3Z" fill="#4880de" stroke="#4880de"/>
|
||||
<path d="M30.7 18.7L35.7 24.3L32.5 24.7Z" fill="#ed594d" stroke="#ed594d"/>
|
||||
<path d="M31.7 22.3L32 22.3L32.5 22.5L33 22.7L33.5 22.9L34 23L34.5 23.2L34.8 23.3L35.7 24.3L32.5 24.7Z" fill="#ffd775" stroke="#ffd775"/>
|
||||
<path d="M35.7 24.3L42.3 31.2L38.5 30Z" fill="#8b231d" stroke="#8b231d"/>
|
||||
<path d="M35.7 24.3L41.1 29.9L41.1 30.2L41.1 30.6L41.2 30.9L38.5 30Z" fill="#a97710" stroke="#a97710"/>
|
||||
<path d="M15.5 18.6L13.1 24.9L9.9 25.6Z" fill="#fe7264" stroke="#fe7264"/>
|
||||
<path d="M38.5 30L42.3 31.2L41.5 35.4Z" fill="#88221c" stroke="#88221c"/>
|
||||
<path d="M41.3 31.4L41.3 31.7L41.4 32.1L41.5 32.5L41.6 32.8L41.7 33.2L41.8 33.6L41.8 33.8L41.5 35.4L38.5 30L41.2 30.9L41.2 31Z" fill="#a6740e" stroke="#a6740e"/>
|
||||
<path d="M15.5 18.6L16.3 25.3L13.1 24.9Z" fill="#a22922" stroke="#a22922"/>
|
||||
<path d="M15.3 25L15.8 24.9L16.3 24.7L16.3 25.3L15 25.2Z" fill="#c28d1d" stroke="#c28d1d"/>
|
||||
<path d="M32.6 37.4L34.9 42.7L29.8 46.2Z" fill="#e74f44" stroke="#e74f44"/>
|
||||
<path d="M32.6 37.4L34.9 42.7L29.8 46.2Z" fill="#ffd164" stroke="#ffd164"/>
|
||||
<path d="M29.8 46.2L31.9 44.8L32.3 44.3L32.7 43.7L33.1 43.2L33.6 42.6L34 42L34.4 41.5L32.6 37.4L32.6 37.4L32.7 37.6L32.6 37.6L32.5 37.8Z" fill="#447cda" stroke="#447cda"/>
|
||||
<path d="M29.8 46.2L37.6 48L32 52.3Z" fill="#ed594d" stroke="#ed594d"/>
|
||||
<path d="M32.5 48.2L32 48.8L31.6 49.4L31.2 50L31.2 50L29.8 46.2L33.3 47L32.9 47.5Z" fill="#ffd774" stroke="#ffd774"/>
|
||||
<path d="M30.2 47.2L30.2 47.2L30.7 46.6L30.7 46.4L29.8 46.2Z" fill="#4e86e4" stroke="#4e86e4"/>
|
||||
<path d="M16.3 25.3L15.2 32.1L11.4 31.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M12.5 31.5L12.5 31L12.4 30.4L12.3 30.2L16.3 25.3L15.2 32.1L12.5 31.5Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M15.1 28.4L15.1 29L15.2 29.6L15.3 30.1L15.3 30.7L15.4 31.2L15.9 28.2L15.6 28.3Z" fill="#123574" stroke="#123574"/>
|
||||
<path d="M30.7 31.8L34.6 30.2L32.6 37.4Z" fill="#ef5c50" stroke="#ef5c50"/>
|
||||
<path d="M30.7 31.8L34.6 30.2L32.6 37.4Z" fill="#ffd979" stroke="#ffd979"/>
|
||||
<path d="M32.6 37.4L34.5 30.5L34.2 30.6L33.7 30.8L33.1 31.1L32.5 31.3L32 31.5L31.4 31.8L30.8 32L30.8 32L32.1 35.8L32.4 35.7L32.9 35.4L33.2 35.3L32.6 37.4Z" fill="#5289e7" stroke="#5289e7"/>
|
||||
<path d="M10.2 37.6L14.7 38.9L9.7 44Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M13.9 39.5L13.8 39L13.7 38.6L14.7 38.9L13.9 39.7Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M11.4 31.3L14.7 38.9L10.2 37.6Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M13.7 38.5L13.6 38L13.6 37.4L13.5 36.9L13.5 36.4L13.4 35.9L14.7 38.9L13.7 38.6Z" fill="#9a6a08" stroke="#9a6a08"/>
|
||||
<path d="M39.9 40.3L45 40.4L48.8 44.9Z" fill="#8b231d" stroke="#8b231d"/>
|
||||
<path d="M9.9 25.6L13.1 24.9L11.4 31.3Z" fill="#f96c5e" stroke="#f96c5e"/>
|
||||
<path d="M12.2 28L12.1 27.5L12.1 27.1L12 26.6L12.5 26.3L12.8 26.1L12.2 28.2Z" fill="#ffe395" stroke="#ffe395"/>
|
||||
<path d="M9.9 25.6L11.4 31.3L7.5 32Z" fill="#f6675a" stroke="#f6675a"/>
|
||||
<path d="M13.1 24.9L16.3 25.3L11.4 31.3Z" fill="#9e2821" stroke="#9e2821"/>
|
||||
<path d="M12.3 29.9L12.3 29.4L12.3 28.9L12.2 28.4L12.2 28.2L12.8 26.1L12.9 26L13.4 25.8L13.8 25.6L14.3 25.4L14.8 25.2L15 25.2L16.3 25.3L12.3 30.2Z" fill="#be891b" stroke="#be891b"/>
|
||||
<path d="M32.5 24.7L35.7 24.3L34.6 30.2Z" fill="#ee5a4e" stroke="#ee5a4e"/>
|
||||
<path d="M32.5 24.7L35.7 24.3L34.6 30.2Z" fill="#ffd876" stroke="#ffd876"/>
|
||||
<path d="M35.2 26.1L34.8 26L34.3 25.8L33.8 25.6L33.3 25.5L32.8 25.3L32.7 25.3L34.5 29.9L34.6 29.6L34.7 29.4L35.3 26.2Z" fill="#5087e5" stroke="#5087e5"/>
|
||||
<path d="M29.8 46.2L34.9 42.7L37.6 48Z" fill="#e2483d" stroke="#e2483d"/>
|
||||
<path d="M35.2 44.3L34.8 44.8L34.5 45.3L34.1 45.9L33.7 46.4L33.3 46.9L33.3 47L29.8 46.2L34.9 42.7L35.5 43.9Z" fill="#ffcc56" stroke="#ffcc56"/>
|
||||
<path d="M30.7 46.4L31.1 46L31.5 45.4L31.9 44.9L31.9 44.8L29.8 46.2Z" fill="#3b73d3" stroke="#3b73d3"/>
|
||||
<path d="M35.7 24.3L38.5 30L34.6 30.2Z" fill="#d93a30" stroke="#d93a30"/>
|
||||
<path d="M35.7 24.3L38.5 30L34.6 30.2Z" fill="#ffc33f" stroke="#ffc33f"/>
|
||||
<path d="M34.7 29.4L34.8 29.2L35 28.9L35.2 28.5L35.4 28.1L35.6 27.7L35.9 27.3L36.1 26.9L36.3 26.5L35.8 26.3L35.3 26.2Z" fill="#2b64c5" stroke="#2b64c5"/>
|
||||
<path d="M34.6 30.2L38.5 30L41.5 35.4Z" fill="#c8342b" stroke="#c8342b"/>
|
||||
<path d="M34.6 30.2L38.5 30L41.5 35.4Z" fill="#edb233" stroke="#edb233"/>
|
||||
<path d="M39.2 33.7L39.2 33.6L39.1 33.1L38.9 32.7L38.8 32.3L38.7 31.9L38.6 31.5L38.5 31L38.4 30.6L38.3 30.2L37.7 30.2L37.1 30.3L36.6 30.3L36 30.3L35.4 30.3L34.8 30.4L34.8 30.4Z" fill="#265bb5" stroke="#265bb5"/>
|
||||
<path d="M41.5 35.4L45 40.4L39.9 40.3Z" fill="#92251f" stroke="#92251f"/>
|
||||
<path d="M41.5 35.4L43.3 37.9L43 38.1L42.5 38.2L42.1 38.4L41.7 38.6L41.3 38.7L40.8 38.9L40.4 39.1L40.3 39.1Z" fill="#b17e14" stroke="#b17e14"/>
|
||||
<path d="M34.6 30.2L37.1 35.4L32.6 37.4Z" fill="#ea5448" stroke="#ea5448"/>
|
||||
<path d="M34.6 30.2L37.1 35.4L32.6 37.4Z" fill="#ffd46c" stroke="#ffd46c"/>
|
||||
<path d="M32.6 37.4L37.1 35.4L34.7 30.4L34.5 30.5L33.2 35.3L33.5 35.2L34.1 34.9L34.2 35.4L34.4 35.8L33.9 36.3L33.5 36.7L33.1 37.1L33 37.2L32.6 37.4Z" fill="#4981df" stroke="#4981df"/>
|
||||
<path d="M7.5 32L11.4 31.3L5.8 38.4Z" fill="#f56659" stroke="#f56659"/>
|
||||
<path d="M39.9 40.3L48.8 44.9L43.2 44.9Z" fill="#9d2821" stroke="#9d2821"/>
|
||||
<path d="M34.6 30.2L41.5 35.4L37.1 35.4Z" fill="#ca352c" stroke="#ca352c"/>
|
||||
<path d="M37.1 35.4L34.6 30.2L41.5 35.4Z" fill="#efb435" stroke="#efb435"/>
|
||||
<path d="M37.1 35.4L39.6 35.4L39.5 35.2L39.4 34.8L39.4 34.4L39.3 34L39.2 33.7L34.8 30.4L34.7 30.4Z" fill="#265cb8" stroke="#265cb8"/>
|
||||
<path d="M5.8 38.4L10.2 37.6L9.7 44Z" fill="#b52f27" stroke="#b52f27"/>
|
||||
<path d="M11.4 31.3L10.2 37.6L5.8 38.4Z" fill="#ca352c" stroke="#ca352c"/>
|
||||
<path d="M9.7 44L9.6 50.2L4 51.3Z" fill="#7e1f1a" stroke="#7e1f1a"/>
|
||||
<path d="M32.6 37.4L39.9 40.3L34.9 42.7Z" fill="#f46356" stroke="#f46356"/>
|
||||
<path d="M38.5 40.6L38 41.1L37.9 41.3L34.9 42.7L32.6 37.4L39.1 39.9L38.9 40.2Z" fill="#ffde85" stroke="#ffde85"/>
|
||||
<path d="M34.4 41.5L34.4 41.5L34.9 41L35.3 40.5L35.8 40.1L36.3 39.6L36.7 39.1L36.8 39L32.6 37.4L32.6 37.4L32.8 37.5L32.7 37.6Z" fill="#5a91ee" stroke="#5a91ee"/>
|
||||
<path d="M32.6 37.4L37.1 35.4L39.9 40.3Z" fill="#e0453a" stroke="#e0453a"/>
|
||||
<path d="M39.3 39.8L39.1 39.9L32.6 37.4L37.1 35.4L39.5 39.5Z" fill="#ffca52" stroke="#ffca52"/>
|
||||
<path d="M36.8 39L37.1 38.7L37.5 38.3L37.9 37.8L38.3 37.4L37.1 35.4L33 37.2L32.8 37.5Z" fill="#3870d0" stroke="#3870d0"/>
|
||||
<path d="M37.1 35.4L41.5 35.4L39.9 40.3Z" fill="#c6342b" stroke="#c6342b"/>
|
||||
<path d="M40 39.3L39.7 39.5L39.5 39.5L37.1 35.4L41.5 35.4L40.3 39.1Z" fill="#ebb133" stroke="#ebb133"/>
|
||||
<path d="M38.3 37.4L38.3 37.4L38.7 37.2L39.1 37L39.5 36.9L40 36.7L39.8 36.3L39.7 35.9L39.6 35.5L39.6 35.4L37.1 35.4Z" fill="#255ab4" stroke="#255ab4"/>
|
||||
<path d="M5.8 38.4L9.7 44L4.6 44.7Z" fill="#a82b24" stroke="#a82b24"/>
|
||||
<path d="M4.6 44.7L9.7 44L4 51.3Z" fill="#9e2822" stroke="#9e2822"/>
|
||||
<path d="M34.9 42.7L39.9 40.3L37.6 48Z" fill="#f15f53" stroke="#f15f53"/>
|
||||
<path d="M37.2 42L36.8 42.4L36.4 42.9L36 43.3L35.6 43.8L35.5 43.9L34.9 42.7L37.9 41.3L37.6 41.6Z" fill="#ffdb7f" stroke="#ffdb7f"/>
|
||||
<path d="M39.9 40.3L43.2 44.9L37.6 48Z" fill="#d4382e" stroke="#d4382e"/>
|
||||
<path d="M16.7 9L34.6 9L34.1 12.5L17.2 12.5Z" fill="#ffd34d" stroke="#ffd34d"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 22 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#FFDD00"/><path transform="translate(5 5) scale(.9167)" fill="#000" d="M20.216 6.415l-.132-.666c-.119-.598-.388-1.163-1.001-1.379-.197-.069-.42-.098-.57-.241-.152-.143-.196-.366-.231-.572-.065-.378-.125-.756-.192-1.133-.057-.325-.102-.69-.25-.987-.195-.4-.597-.634-.996-.788a5.723 5.723 0 00-.626-.194c-1-.263-2.05-.36-3.077-.416a25.834 25.834 0 00-3.7.062c-.915.083-1.88.184-2.75.5-.318.116-.646.256-.888.501-.297.302-.393.77-.177 1.146.154.267.415.456.692.58.36.162.737.284 1.123.366 1.075.238 2.189.331 3.287.37 1.218.05 2.437.01 3.65-.118.299-.033.598-.073.896-.119.352-.054.578-.513.474-.834-.124-.383-.457-.531-.834-.473-.466.074-.96.108-1.382.146-1.177.08-2.358.082-3.536.006a22.228 22.228 0 01-1.157-.107c-.086-.01-.18-.025-.258-.036-.243-.036-.484-.08-.724-.13-.111-.027-.111-.185 0-.212h.005c.277-.06.557-.108.838-.147h.002c.131-.009.263-.032.394-.048a25.076 25.076 0 013.426-.12c.674.019 1.347.067 2.017.144l.228.031c.267.04.533.088.798.145.392.085.895.113 1.07.542.055.137.08.288.111.431l.319 1.484a.237.237 0 01-.199.284h-.003c-.037.006-.075.01-.112.015a36.704 36.704 0 01-4.743.295 37.059 37.059 0 01-4.699-.304c-.14-.017-.293-.042-.417-.06-.326-.048-.649-.108-.973-.161-.393-.065-.768-.032-1.123.161-.29.16-.527.404-.675.701-.154.316-.199.66-.267 1-.069.34-.176.707-.135 1.056.087.753.613 1.365 1.37 1.502a39.69 39.69 0 0011.343.376.483.483 0 01.535.53l-.071.697-1.018 9.907c-.041.41-.047.832-.125 1.237-.122.637-.553 1.028-1.182 1.171-.577.131-1.165.2-1.756.205-.656.004-1.31-.025-1.966-.022-.699.004-1.556-.06-2.095-.58-.475-.458-.54-1.174-.605-1.793l-.731-7.013-.322-3.094c-.037-.351-.286-.695-.678-.678-.336.015-.718.3-.678.679l.228 2.185.949 9.112c.147 1.344 1.174 2.068 2.446 2.272.742.12 1.503.144 2.257.156.966.016 1.942.053 2.892-.122 1.408-.258 2.465-1.198 2.616-2.657.34-3.332.683-6.663 1.024-9.995l.215-2.087a.484.484 0 01.39-.426c.402-.078.787-.212 1.074-.518.455-.488.546-1.124.385-1.766zm-1.478.772c-.145.137-.363.201-.578.233-2.416.359-4.866.54-7.308.46-1.748-.06-3.477-.254-5.207-.498-.17-.024-.353-.055-.47-.18-.22-.236-.111-.71-.054-.995.052-.26.152-.609.463-.646.484-.057 1.046.148 1.526.22.577.088 1.156.159 1.737.212 2.48.226 5.002.19 7.472-.14.45-.06.899-.13 1.345-.21.399-.072.84-.206 1.08.206.166.281.188.657.162.974a.544.544 0 01-.169.364zm-6.159 3.9c-.862.37-1.84.788-3.109.788a5.884 5.884 0 01-1.569-.217l.877 9.004c.065.78.717 1.38 1.5 1.38 0 0 1.243.065 1.658.065.447 0 1.786-.065 1.786-.065.783 0 1.434-.6 1.499-1.38l.94-9.95a3.996 3.996 0 00-1.322-.238c-.826 0-1.491.284-2.26.613z"/></svg>
|
||||
|
Before Width: | Height: | Size: 2.6 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#635BFF"/><path transform="translate(8 7) scale(.75)" fill="#fff" d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.594-7.305h.003z"/></svg>
|
||||
|
Before Width: | Height: | Size: 659 B |
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "supergeometry.app",
|
||||
"short_name": "supergeometry",
|
||||
"name": "superGeometry.app",
|
||||
"short_name": "superGeometry",
|
||||
"description": "Free 3D CAD and 3D modeling in your browser, for phone, tablet, computer and VR.",
|
||||
"start_url": "./",
|
||||
"display": "standalone",
|
||||
|
||||
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 87 KiB |
@@ -1,15 +1,18 @@
|
||||
// Make the PNG app icons (home screen / install) from the shapes in public/icon.svg.
|
||||
// Make the PNG app icons (home screen / install) from the paths in public/icon.svg
|
||||
// (scripts/logo.py writes that file).
|
||||
// Run: node scripts/icons.mjs
|
||||
import { deflateSync } from "node:zlib";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const hex = (h) => [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)];
|
||||
const BG = hex("#1f2125");
|
||||
const shapes = [
|
||||
[hex("#3d8bff"), [[32, 10], [51, 21], [51, 43], [32, 54], [13, 43], [13, 21]]],
|
||||
[hex("#8bb8ff"), [[32, 10], [51, 21], [32, 32], [13, 21]]],
|
||||
[hex("#2a63c4"), [[32, 32], [32, 54], [13, 43], [13, 21]]],
|
||||
];
|
||||
const svg = readFileSync("public/icon.svg", "utf8");
|
||||
const BG = hex(svg.match(/<rect[^>]*fill="(#[0-9a-f]{6})"/i)[1]);
|
||||
// Every filled path, in drawing order, with its bounding box (to skip it quickly).
|
||||
const shapes = [...svg.matchAll(/<path d="M([^"]+)Z" fill="(#[0-9a-f]{6})"/gi)].map(([, d, fill]) => {
|
||||
const P = d.split("L").map((q) => q.trim().split(/\s+/).map(Number));
|
||||
const xs = P.map((p) => p[0]), ys = P.map((p) => p[1]);
|
||||
return [hex(fill), P, [Math.min(...xs), Math.min(...ys), Math.max(...xs), Math.max(...ys)]];
|
||||
});
|
||||
const inPoly = (x, y, P) => {
|
||||
let c = false;
|
||||
for (let i = 0, j = P.length - 1; i < P.length; j = i++) {
|
||||
@@ -35,7 +38,7 @@ function render(n, { rounded = true, scale = 1 } = {}) {
|
||||
// The logo, scaled about the middle (smaller for maskable icons).
|
||||
const lu = 32 + (u - 32) / scale, lv = 32 + (v - 32) / scale;
|
||||
let c = BG;
|
||||
for (const [col, P] of shapes) if (inPoly(lu, lv, P)) c = col;
|
||||
for (const [col, P, b] of shapes) if (lu >= b[0] && lu <= b[2] && lv >= b[1] && lv <= b[3] && inPoly(lu, lv, P)) c = col;
|
||||
r += c[0]; g += c[1]; b += c[2]; a += 255;
|
||||
}
|
||||
const k = S * S, o = (y * n + x) * 4;
|
||||
@@ -71,7 +74,7 @@ function png(w, h, rgba) {
|
||||
writeFileSync("public/icon-192.png", render(192));
|
||||
writeFileSync("public/icon-512.png", render(512));
|
||||
// Maskable: full square, logo inside the safe circle.
|
||||
writeFileSync("public/icon-maskable-512.png", render(512, { rounded: false, scale: 0.8 }));
|
||||
writeFileSync("public/icon-maskable-512.png", render(512, { rounded: false, scale: 0.75 }));
|
||||
// iOS rounds the corners itself.
|
||||
writeFileSync("public/apple-touch-icon.png", render(180, { rounded: false }));
|
||||
console.log("icons written");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Is the push live? Compares the commit supergeometry.app was built from
|
||||
// Is the push live? Compares the commit superGeometry.app was built from
|
||||
// (its /version.json) with main here.
|
||||
//
|
||||
// npx tsx scripts/live.ts once
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"""superGeometry.app logo: a faceted red cape blowing in the wind, a yellow clasp, and a yellow
|
||||
hexagon with a blue G printed on the cloth (it folds and shades with the facets).
|
||||
|
||||
Run: python scripts/logo.py (writes public/icon.svg; then node scripts/icons.mjs for the PNGs)"""
|
||||
import math
|
||||
import sys
|
||||
|
||||
TILE = "#1f2125"
|
||||
RED = ("#7e1f1a", "#d8392f", "#ff7466")
|
||||
YEL = ("#9a6a08", "#ffc23d", "#ffe9a3")
|
||||
BLU = ("#123574", "#2a63c4", "#6ea4ff")
|
||||
CLASP = "#ffd34d"
|
||||
|
||||
|
||||
def stroke(pl, t):
|
||||
"""A thick polyline (miter joins, butt ends) as one polygon."""
|
||||
h = t / 2
|
||||
def nrm(a, b):
|
||||
dx, dy = b[0] - a[0], b[1] - a[1]; L = math.hypot(dx, dy)
|
||||
return (-dy / L, dx / L)
|
||||
left, right = [], []
|
||||
n = len(pl)
|
||||
for i in range(n):
|
||||
if i == 0: m = nrm(pl[0], pl[1]); k = 1
|
||||
elif i == n - 1: m = nrm(pl[-2], pl[-1]); k = 1
|
||||
else:
|
||||
a, b = nrm(pl[i - 1], pl[i]), nrm(pl[i], pl[i + 1])
|
||||
m = (a[0] + b[0], a[1] + b[1]); L = math.hypot(*m); m = (m[0] / L, m[1] / L)
|
||||
k = 1 / (m[0] * a[0] + m[1] * a[1])
|
||||
left.append((pl[i][0] + m[0] * h * k, pl[i][1] + m[1] * h * k))
|
||||
right.append((pl[i][0] - m[0] * h * k, pl[i][1] - m[1] * h * k))
|
||||
return left + right[::-1]
|
||||
|
||||
|
||||
def hexpts(cx, cy, r, angles):
|
||||
return [(cx + r * math.cos(math.radians(a)), cy + r * math.sin(math.radians(a))) for a in angles]
|
||||
|
||||
|
||||
def lerp(a, b, t): return a + (b - a) * t
|
||||
|
||||
|
||||
def mix(c1, c2, t):
|
||||
a = [int(c1[i:i + 2], 16) for i in (1, 3, 5)]; b = [int(c2[i:i + 2], 16) for i in (1, 3, 5)]
|
||||
return "#" + "".join(f"{round(lerp(x, y, t)):02x}" for x, y in zip(a, b))
|
||||
|
||||
|
||||
def tone(pal, s):
|
||||
return mix(pal[0], pal[1], s / 0.55) if s < 0.55 else mix(pal[1], pal[2], (s - 0.55) / 0.45)
|
||||
|
||||
|
||||
def width(v): return lerp(0.3, 1.0, v ** 0.8)
|
||||
|
||||
|
||||
def surf(u, v, wind=1.0, folds=1.0):
|
||||
x = (u - 0.5) * 2 * width(v) + wind * 0.3 * v * v - 0.12 * v * (1 - u)
|
||||
y = v * 1.6 - wind * 0.32 * v * v * u + 0.1 * v ** 3 * math.cos(u * math.pi * 3 + 1.8)
|
||||
z = folds * (v ** 0.7) * math.sin(u * math.pi * 3 + v * 1.8) * 0.3
|
||||
return (x, y, z)
|
||||
|
||||
|
||||
def flat_to_uv(p):
|
||||
"""A point on the cloth laid flat (X across from the middle, Y down) to its (u, v)."""
|
||||
X, Y = p
|
||||
v = Y / 1.6
|
||||
return (0.5 + X / (2 * width(v)), v)
|
||||
|
||||
|
||||
def densify(P, step=0.02):
|
||||
out = []
|
||||
for i in range(len(P)):
|
||||
a, b = P[i], P[(i + 1) % len(P)]
|
||||
n = max(1, int(math.dist(a, b) / step))
|
||||
out += [(lerp(a[0], b[0], k / n), lerp(a[1], b[1], k / n)) for k in range(n)]
|
||||
return out
|
||||
|
||||
|
||||
def clip(subject, tri):
|
||||
"""Sutherland-Hodgman: the part of a polygon inside a triangle (counter-clockwise or not)."""
|
||||
area = (tri[1][0] - tri[0][0]) * (tri[2][1] - tri[0][1]) - (tri[1][1] - tri[0][1]) * (tri[2][0] - tri[0][0])
|
||||
sgn = 1 if area > 0 else -1
|
||||
out = subject
|
||||
for i in range(3):
|
||||
a, b = tri[i], tri[(i + 1) % 3]
|
||||
inside = lambda p: sgn * ((b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])) >= 0
|
||||
src, out = out, []
|
||||
if not src: break
|
||||
for j in range(len(src)):
|
||||
p, q = src[j], src[(j + 1) % len(src)]
|
||||
if inside(q):
|
||||
if not inside(p): out.append(cross(p, q, a, b))
|
||||
out.append(q)
|
||||
elif inside(p):
|
||||
out.append(cross(p, q, a, b))
|
||||
return out
|
||||
|
||||
|
||||
def cross(p, q, a, b):
|
||||
d1 = (q[0] - p[0], q[1] - p[1]); d2 = (b[0] - a[0], b[1] - a[1])
|
||||
den = d1[0] * d2[1] - d1[1] * d2[0]
|
||||
t = ((a[0] - p[0]) * d2[1] - (a[1] - p[1]) * d2[0]) / den
|
||||
return (p[0] + t * d1[0], p[1] + t * d1[1])
|
||||
|
||||
|
||||
def logo(nu=10, nv=6, badge_y=0.9, badge_r=0.6):
|
||||
# the print, laid flat, then into (u, v)
|
||||
hexa = [flat_to_uv(p) for p in densify(hexpts(0, badge_y, badge_r, [-90, -30, 30, 90, 150, 210]))]
|
||||
g = [flat_to_uv(p) for p in densify(gmark_flat(0, badge_y, badge_r * 0.77, badge_r * 0.3))]
|
||||
L = (-0.5, -0.6, 0.62); n = math.sqrt(sum(c * c for c in L)); L = tuple(c / n for c in L)
|
||||
UV = [[(i / nu, j / nv) for i in range(nu + 1)] for j in range(nv + 1)]
|
||||
tris = []
|
||||
for j in range(nv):
|
||||
for i in range(nu):
|
||||
a, b, c, d = UV[j][i], UV[j][i + 1], UV[j + 1][i + 1], UV[j + 1][i]
|
||||
for t in ((a, b, c), (a, c, d)) if (i + j) % 2 == 0 else ((a, b, d), (b, c, d)):
|
||||
P = [surf(*q) for q in t]
|
||||
e1 = [P[1][k] - P[0][k] for k in range(3)]; e2 = [P[2][k] - P[0][k] for k in range(3)]
|
||||
nn = (e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0])
|
||||
m = math.sqrt(sum(q * q for q in nn)) or 1
|
||||
nn = tuple(q / m for q in nn)
|
||||
if nn[2] < 0: nn = tuple(-q for q in nn)
|
||||
s = max(0.0, sum(nn[k] * L[k] for k in range(3)))
|
||||
s = min(1, max(0, (s - 0.25) / 0.7))
|
||||
tris.append((sum(q[2] for q in P) / 3, s, t, P))
|
||||
tris.sort(key=lambda q: q[0])
|
||||
proj = lambda p: (p[0], p[1] - 0.35 * p[2])
|
||||
pts = [proj(p) for *_, P in tris for p in P]
|
||||
x0, x1 = min(p[0] for p in pts), max(p[0] for p in pts)
|
||||
y0, y1 = min(p[1] for p in pts), max(p[1] for p in pts)
|
||||
k = min(56 / (x1 - x0), 49 / (y1 - y0))
|
||||
ox = 32 - (x0 + x1) / 2 * k
|
||||
tx = lambda p: (ox + p[0] * k, 12.3 + (p[1] - y0) * k)
|
||||
out = []
|
||||
for _, s, t, P in tris:
|
||||
S = [tx(proj(p)) for p in P]
|
||||
# the facet's own affine map from (u, v) to the picture
|
||||
(u0, v0), (u1, v1), (u2, v2) = t
|
||||
det = (u1 - u0) * (v2 - v0) - (u2 - u0) * (v1 - v0)
|
||||
def amap(q, S=S, u0=u0, v0=v0, u1=u1, v1=v1, u2=u2, v2=v2, det=det):
|
||||
a = ((q[0] - u0) * (v2 - v0) - (u2 - u0) * (q[1] - v0)) / det
|
||||
b = ((u1 - u0) * (q[1] - v0) - (q[0] - u0) * (v1 - v0)) / det
|
||||
return (S[0][0] + a * (S[1][0] - S[0][0]) + b * (S[2][0] - S[0][0]),
|
||||
S[0][1] + a * (S[1][1] - S[0][1]) + b * (S[2][1] - S[0][1]))
|
||||
out.append((tone(RED, s), S))
|
||||
for pal, poly in ((YEL, hexa), (BLU, g)):
|
||||
c = clip(poly, list(t))
|
||||
if len(c) >= 3:
|
||||
out.append((tone(pal, s), [amap(q) for q in c]))
|
||||
top = [tx(proj(surf(0, 0))), tx(proj(surf(1, 0)))]
|
||||
out.append((CLASP, [(top[0][0] - 1, 9), (top[1][0] + 1, 9), (top[1][0] + 0.5, 12.5), (top[0][0] - 0.5, 12.5)]))
|
||||
return out
|
||||
|
||||
|
||||
def gmark_flat(cx, cy, r, t):
|
||||
rr = r - t / 2
|
||||
P = hexpts(cx, cy, rr, [-30, -90, -150, 150, 90, 30])
|
||||
P.append((cx + rr * math.cos(math.radians(30)), cy))
|
||||
P.append((cx + rr * 0.05, cy))
|
||||
return stroke(P, t)
|
||||
|
||||
|
||||
def svg(shapes, tile=True):
|
||||
parts = ['<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">']
|
||||
if tile: parts.append(f'<rect width="64" height="64" rx="14" fill="{TILE}"/>')
|
||||
# each facet is also stroked in its own colour, so no hairline seams show between them
|
||||
parts.append('<g stroke-width=".2" stroke-linejoin="round">')
|
||||
num = lambda a: f"{a:.1f}".rstrip("0").rstrip(".")
|
||||
for c, P in shapes:
|
||||
parts.append(f'<path d="M{"L".join(num(x) + " " + num(y) for x, y in P)}Z" fill="{c}" stroke="{c}"/>')
|
||||
return "\n".join(parts) + "\n</g>\n</svg>\n"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
out = sys.argv[1] if len(sys.argv) > 1 else "public/icon.svg"
|
||||
with open(out, "w", encoding="utf-8", newline="\n") as f:
|
||||
f.write(svg(logo()))
|
||||
print("wrote", out)
|
||||
@@ -0,0 +1,637 @@
|
||||
// Assemblies, in the app: joints between the project's bodies, and the bodies dragged by them.
|
||||
//
|
||||
// The bodies are where they were modelled, so there is nothing to put in place. A joint is two taps - a face on
|
||||
// each of two bodies - and the app says what kind it is from the faces as they stand (see `propose`). A body
|
||||
// dragged then moves the way its joint lets it. Moving is a pose, not an edit: Home, or leaving Assemblies, has
|
||||
// every body where it was modelled again.
|
||||
|
||||
import { BufferGeometry, Line, LineBasicMaterial, Vector3 } from "three";
|
||||
import type { ThreadFeature, Vec3 } from "../doc/types";
|
||||
import { add, cross, dot, len, norm, scale, sub } from "../geom";
|
||||
import { fmtLen } from "../units";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
import type { ToolPointer } from "../view/input";
|
||||
import { axisDrag } from "../tools/handles";
|
||||
import { roundAxis } from "../tools/select";
|
||||
import { faceIndexOf, faceRefOf, type AppContext, type Tool } from "../tools/tool";
|
||||
import { inverse, penetrates, Solid } from "./contact";
|
||||
import { apply, driverOf, effective, JOINT_NAMES, propose, solve, tree, mul, turn, turnAxis, type Joint, type JointType, type Mat4, type PickLine } from "./joints";
|
||||
|
||||
interface Pick {
|
||||
body: string;
|
||||
face: number;
|
||||
line: PickLine | null;
|
||||
}
|
||||
|
||||
/** Stop on contact, as it was last set (for this visit to the page). */
|
||||
let stopOnContact = false;
|
||||
/** How far into each other two parts may be shown before they count as run into each other (mm): what touches, or sits with a hair of play, is not. */
|
||||
const CONTACT_TOL = 0.25;
|
||||
|
||||
const uid = () => `joint-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
|
||||
const AXIS_COLOR = 0xff9d2e;
|
||||
|
||||
export class AssemblyTool implements Tool {
|
||||
readonly id = "assembly";
|
||||
/** How far each joint is from home (degrees; mm for a slide). Gone when the tool is left. */
|
||||
private values: Record<string, number> = {};
|
||||
/** 0 to 1: how far the bodies are pulled apart. */
|
||||
private exploded = 0;
|
||||
private mode: "list" | "add" | "edit" = "list";
|
||||
private first: Pick | null = null;
|
||||
private editing: string | null = null;
|
||||
private axisLine: Line | null = null;
|
||||
private dragging: {
|
||||
from: ToolPointer;
|
||||
joint: Joint;
|
||||
/** The joint whose own value is set (the dragged one, or the one it follows), and by how much it is followed. */
|
||||
driver: Joint;
|
||||
ratio: number;
|
||||
sign: number;
|
||||
v0: number;
|
||||
/** Where it was taken hold of, and the joint's line as it is now (its parent moved, it moved with it). */
|
||||
grab: Vec3;
|
||||
origin: Vec3;
|
||||
axis: Vec3;
|
||||
/** Round the line: the turn so far, and where the pointer was on the last move. */
|
||||
turned: number;
|
||||
last: Vec3 | null;
|
||||
/** Stop on contact: the pairs of bodies in each other as the drag began (left alone), how each pair stood then, and the last value nothing ran into anything at. */
|
||||
inEachOther: Set<string>;
|
||||
stood: Map<string, Mat4>;
|
||||
free: number;
|
||||
} | null = null;
|
||||
private solids = new Map<string, { key: unknown; solid: Solid }>();
|
||||
/** Each body's middle and size, by its mesh (measured once for each). */
|
||||
private measured = new Map<string, { key: unknown; center: Vec3; size: number }>();
|
||||
|
||||
constructor(private app: AppContext, private start?: { a: { body: string; face: number }; b: { body: string; face: number } }) {}
|
||||
|
||||
private get joints(): Joint[] {
|
||||
return this.app.store.doc.joints ?? [];
|
||||
}
|
||||
private get bodies(): string[] {
|
||||
return this.app.view.bodyList.map((b) => b.id);
|
||||
}
|
||||
private nameOf(body: string): string {
|
||||
return this.app.store.doc.names?.[body] ?? this.app.view.body(body)?.name ?? "a part";
|
||||
}
|
||||
|
||||
enter(): void {
|
||||
this.app.ui.setTools([{ id: "exit", label: "Exit Assemblies", icon: "exit", shortcut: "Esc", run: () => this.leave() }]);
|
||||
this.app.ui.setBottom(this.app.bottomTools());
|
||||
this.app.setSelection([]);
|
||||
this.app.setHover(null);
|
||||
// Where the parts were left (asked for: "if i click on assembly again ... it doesnt show what i made before").
|
||||
this.values = { ...(this.app.store.doc.pose?.values ?? {}) };
|
||||
this.exploded = this.app.store.doc.pose?.exploded ?? 0;
|
||||
const s = this.start;
|
||||
this.start = undefined;
|
||||
if (s && s.a.body !== s.b.body) this.make(this.pickOf(s.a.body, s.a.face), this.pickOf(s.b.body, s.b.face));
|
||||
else this.render();
|
||||
this.show();
|
||||
}
|
||||
|
||||
/** The pose as it is, kept in the project: what is shown after Assemblies is left, and when it is opened again. */
|
||||
private save(): void {
|
||||
const values: Record<string, number> = {};
|
||||
for (const j of this.joints) if (Math.abs(this.values[j.id] ?? 0) > 1e-9) values[j.id] = this.values[j.id];
|
||||
const pose = Object.keys(values).length || this.exploded > 0 ? { values, ...(this.exploded > 0 ? { exploded: this.exploded } : {}) } : undefined;
|
||||
if (JSON.stringify(pose) === JSON.stringify(this.app.store.doc.pose)) return;
|
||||
this.app.store.commit((d) => {
|
||||
if (pose) d.pose = pose;
|
||||
else delete d.pose;
|
||||
});
|
||||
}
|
||||
|
||||
private leave(): void {
|
||||
this.save();
|
||||
this.app.setTool(null);
|
||||
}
|
||||
|
||||
exit(): void {
|
||||
// (The parts stay as they were left: the app shows the project's pose while nothing is being worked on.)
|
||||
this.dropAxis();
|
||||
this.app.ui.showPanel(null);
|
||||
this.app.ui.setHint(null);
|
||||
this.app.ui.setLabel(0, 0, null);
|
||||
this.app.setSelection([]);
|
||||
this.app.setHover(null);
|
||||
}
|
||||
|
||||
key(e: KeyboardEvent): boolean {
|
||||
if (e.key !== "Escape") return false;
|
||||
if (this.mode === "list") this.leave();
|
||||
else this.toList();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The model was made again: the bodies are shown at their joints' values still. */
|
||||
refresh(): void {
|
||||
// (A pose undone or redone: the parts go where the project has them.)
|
||||
if (!this.dragging) this.values = { ...(this.app.store.doc.pose?.values ?? {}) };
|
||||
this.show();
|
||||
this.render();
|
||||
}
|
||||
|
||||
/** The project's pose, for the app to show when Assemblies is not open (null: all as modelled). */
|
||||
static posesOf(app: AppContext): Map<string, Mat4> | null {
|
||||
const pose = app.store.doc.pose;
|
||||
if (!pose || !app.store.doc.joints?.length) return null;
|
||||
const t = new AssemblyTool(app);
|
||||
t.values = { ...pose.values };
|
||||
t.exploded = pose.exploded ?? 0;
|
||||
return t.poses();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ what is shown
|
||||
|
||||
/** A joint with its line where the faces it was picked by are now (the model changed since: it follows them). */
|
||||
private live(j: Joint): Joint {
|
||||
if (!j.refA) return j;
|
||||
const i = faceIndexOf(this.app, j.refA);
|
||||
const line = i === null ? null : this.pickOf(j.refA.body, i).line;
|
||||
if (!line) return j;
|
||||
const flipped = dot(norm(line.dir), norm(j.axis)) < 0;
|
||||
return { ...j, origin: line.origin, axis: flipped ? scale(norm(line.dir), -1) : norm(line.dir) };
|
||||
}
|
||||
|
||||
private liveJoints(): Joint[] {
|
||||
return this.joints.map((j) => this.live(j));
|
||||
}
|
||||
|
||||
private measure(body: string): { center: Vec3; size: number } | null {
|
||||
const b = this.app.view.body(body);
|
||||
if (!b) return null;
|
||||
const was = this.measured.get(body);
|
||||
if (was && was.key === b.key) return was;
|
||||
const P = b.positions;
|
||||
const lo: Vec3 = [Infinity, Infinity, Infinity];
|
||||
const hi: Vec3 = [-Infinity, -Infinity, -Infinity];
|
||||
for (let i = 0; i < P.length; i += 3) for (let k = 0; k < 3; k++) (lo[k] = Math.min(lo[k], P[i + k])), (hi[k] = Math.max(hi[k], P[i + k]));
|
||||
const m = { key: b.key, center: scale(add(lo, hi), 0.5), size: len(sub(hi, lo)) / 2 };
|
||||
this.measured.set(body, m);
|
||||
return m;
|
||||
}
|
||||
|
||||
private poses(): Map<string, Mat4> {
|
||||
const bodies = this.bodies;
|
||||
const centers: Record<string, Vec3> = {};
|
||||
const sizes: Record<string, number> = {};
|
||||
if (this.exploded > 0) {
|
||||
for (const b of bodies) {
|
||||
const m = this.measure(b);
|
||||
if (m) (centers[b] = m.center), (sizes[b] = m.size);
|
||||
}
|
||||
}
|
||||
return solve(this.liveJoints(), bodies, this.values, this.app.store.doc.ground, this.exploded > 0 ? { factor: this.exploded * 0.8, centers, sizes } : undefined);
|
||||
}
|
||||
|
||||
private solid(body: string): Solid | null {
|
||||
const b = this.app.view.body(body);
|
||||
if (!b) return null;
|
||||
const was = this.solids.get(body);
|
||||
if (was && was.key === b.key) return was.solid;
|
||||
const solid = new Solid(b.positions, b.indices);
|
||||
this.solids.set(body, { key: b.key, solid });
|
||||
return solid;
|
||||
}
|
||||
|
||||
/** Each pair of bodies shown: how the second stands against the first (the second's move, seen from the first). */
|
||||
private standing(poses: Map<string, Mat4>): Map<string, Mat4> {
|
||||
const ids = this.bodies.filter((b) => !this.app.view.isHidden(b));
|
||||
const out = new Map<string, Mat4>();
|
||||
const I: Mat4 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||
for (let i = 0; i < ids.length; i++)
|
||||
for (let j = i + 1; j < ids.length; j++) {
|
||||
const a = poses.get(ids[i]);
|
||||
const b = poses.get(ids[j]);
|
||||
out.set(`${ids[i]}|${ids[j]}`, a || b ? mul(inverse(a ?? I), b ?? I) : I);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The pairs of bodies run into each other, of those in `pairs` (all of them; or only those that stand otherwise than in `than`). */
|
||||
private clashes(pairs: Map<string, Mat4>, than?: Map<string, Mat4>, skip?: Set<string>): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const [key, m] of pairs) {
|
||||
if (skip?.has(key)) continue;
|
||||
const was = than?.get(key);
|
||||
if (was && was.every((v, i) => Math.abs(v - m[i]) < 1e-9)) continue;
|
||||
const [a, b] = key.split("|");
|
||||
const sa = this.solid(a);
|
||||
const sb = this.solid(b);
|
||||
if (sa && sb && penetrates(sa, sb, m, CONTACT_TOL)) out.add(key);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private show(): void {
|
||||
const poses = this.poses();
|
||||
this.app.view.setPoses(poses);
|
||||
this.placeAxis(poses);
|
||||
}
|
||||
|
||||
private dropAxis(): void {
|
||||
if (!this.axisLine) return;
|
||||
this.app.view.overlay.remove(this.axisLine);
|
||||
this.axisLine.geometry.dispose();
|
||||
(this.axisLine.material as LineBasicMaterial).dispose();
|
||||
this.axisLine = null;
|
||||
}
|
||||
|
||||
/** The line of the joint that is open, drawn through the model (with the body that carries it, when that moved). */
|
||||
private placeAxis(poses: Map<string, Mat4>): void {
|
||||
this.dropAxis();
|
||||
const j0 = this.joints.find((x) => x.id === this.editing);
|
||||
if (!j0 || j0.type === "fixed" || this.mode !== "edit") return;
|
||||
const j = this.live(j0);
|
||||
const t = tree(this.liveJoints(), this.bodies, this.app.store.doc.ground);
|
||||
const child = t.up.get(j.b)?.joint.id === j.id ? j.b : j.a;
|
||||
const parent = t.up.get(child)?.parent;
|
||||
const m = (parent && poses.get(parent)) || null;
|
||||
const o = m ? apply(m, j.origin) : j.origin;
|
||||
const a = norm(m ? turn(m, j.axis) : j.axis);
|
||||
const reach = Math.max(this.measure(j.a)?.size ?? 10, this.measure(j.b)?.size ?? 10) * 1.6;
|
||||
const g = new BufferGeometry().setFromPoints([new Vector3(...add(o, scale(a, -reach))), new Vector3(...add(o, scale(a, reach)))]);
|
||||
this.axisLine = new Line(g, new LineBasicMaterial({ color: AXIS_COLOR, depthTest: false, transparent: true }));
|
||||
this.axisLine.renderOrder = 60;
|
||||
this.app.view.overlay.add(this.axisLine);
|
||||
this.app.view.requestRender();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ picks
|
||||
|
||||
/**
|
||||
* A flat face's middle: the middle of the box round it (measured along the face). Not its centre of area - a
|
||||
* nut's top is a ring whose hole the thread runs out of, a little to one side, and its centre of area is a
|
||||
* quarter of a millimetre off the nut's line; its outline's middle is on it.
|
||||
*/
|
||||
private centroid(body: string, face: number): Vec3 | null {
|
||||
const b = this.app.view.body(body);
|
||||
const f = b?.faces[face];
|
||||
const g = b?.faceGroups.find((x) => x.face === face);
|
||||
if (!b || !f?.plane || !g) return null;
|
||||
const P = b.positions;
|
||||
const I = b.indices;
|
||||
const x = norm(f.plane.xDir);
|
||||
const y = norm(cross(f.plane.normal, f.plane.xDir));
|
||||
const o = f.plane.origin;
|
||||
let u0 = Infinity;
|
||||
let u1 = -Infinity;
|
||||
let v0 = Infinity;
|
||||
let v1 = -Infinity;
|
||||
for (let k = g.start; k < g.start + g.count; k++) {
|
||||
const i = I[k];
|
||||
const d: Vec3 = [P[3 * i] - o[0], P[3 * i + 1] - o[1], P[3 * i + 2] - o[2]];
|
||||
const u = dot(d, x);
|
||||
const v = dot(d, y);
|
||||
u0 = Math.min(u0, u);
|
||||
u1 = Math.max(u1, u);
|
||||
v0 = Math.min(v0, v);
|
||||
v1 = Math.max(v1, v);
|
||||
}
|
||||
if (!(u1 >= u0)) return null;
|
||||
// (On the face's own plane: the drawn points are kept to seven digits, the plane is exact.)
|
||||
const n = norm(f.plane.normal);
|
||||
const flat = add(add(o, scale(x, (u0 + u1) / 2)), scale(y, (v0 + v1) / 2));
|
||||
return add(flat, scale(n, dot(sub(f.center, flat), n)));
|
||||
}
|
||||
|
||||
private pickOf(body: string, face: number): Pick {
|
||||
const f = this.app.view.body(body)?.faces[face];
|
||||
let line: PickLine | null = null;
|
||||
if (f?.round) {
|
||||
const ax = roundAxis(this.app, body, face);
|
||||
if (ax) line = { origin: ax.origin, dir: ax.dir, round: true };
|
||||
} else if (f?.plane) line = { origin: this.centroid(body, face) ?? f.center, dir: f.normal, round: false };
|
||||
// Any other face that is turned round a line - a thread's flank, a cone: that line, found from its points.
|
||||
else if (f) {
|
||||
const b = this.app.view.body(body)!;
|
||||
const g = b.faceGroups.find((x) => x.face === face);
|
||||
if (g) {
|
||||
const seen = new Set<number>();
|
||||
const pts: Vec3[] = [];
|
||||
const nrm: Vec3[] = [];
|
||||
for (let k = g.start; k < g.start + g.count; k++) {
|
||||
const i = b.indices[k];
|
||||
if (seen.has(i)) continue;
|
||||
seen.add(i);
|
||||
pts.push([b.positions[3 * i], b.positions[3 * i + 1], b.positions[3 * i + 2]]);
|
||||
nrm.push([b.normals[3 * i], b.normals[3 * i + 1], b.normals[3 * i + 2]]);
|
||||
}
|
||||
const ax = turnAxis(pts, nrm);
|
||||
if (ax) line = { origin: ax.origin, dir: ax.dir, round: true, rough: true };
|
||||
}
|
||||
}
|
||||
return { body, face, line };
|
||||
}
|
||||
|
||||
private faceAt(p: ToolPointer): { body: string; face: number; point: Vec3 } | null {
|
||||
const h = this.app.view.facesAt(p.x, p.y)[0];
|
||||
return h && h.kind === "face" ? { body: h.body, face: h.face, point: h.point } : null;
|
||||
}
|
||||
|
||||
hover(p: ToolPointer | null): void {
|
||||
if (this.mode !== "add") return this.app.setHover(null);
|
||||
const h = p ? this.faceAt(p) : null;
|
||||
this.app.setHover(h ? { kind: "face", body: h.body, face: h.face } : null);
|
||||
}
|
||||
|
||||
tap(p: ToolPointer): void {
|
||||
const h = this.faceAt(p);
|
||||
if (this.mode === "add") {
|
||||
if (!h) return;
|
||||
if (!this.first) {
|
||||
this.first = this.pickOf(h.body, h.face);
|
||||
this.app.setSelection([{ kind: "face", body: h.body, face: h.face }]);
|
||||
return this.render();
|
||||
}
|
||||
if (h.body === this.first.body) return this.app.ui.toast("Tap a face of another part: a joint is between two");
|
||||
return this.make(this.first, this.pickOf(h.body, h.face));
|
||||
}
|
||||
// A part tapped: the joint that holds it is opened. Nothing tapped: back to the list.
|
||||
if (!h) return this.mode === "edit" ? this.toList() : undefined;
|
||||
const t = tree(this.liveJoints(), this.bodies, this.app.store.doc.ground);
|
||||
const j = t.up.get(h.body)?.joint ?? this.joints.find((x) => x.a === h.body || x.b === h.body);
|
||||
if (j) this.open(j.id);
|
||||
else this.app.ui.toast("No joint holds that part yet. Add joint, then tap it and the part it moves against.");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ joints made and changed
|
||||
|
||||
private change(mutate: (joints: Joint[]) => void): void {
|
||||
this.app.store.commit((d) => {
|
||||
d.joints ??= [];
|
||||
mutate(d.joints);
|
||||
if (!d.joints.length) delete d.joints;
|
||||
});
|
||||
}
|
||||
|
||||
private patch(id: string, p: Partial<Joint>): void {
|
||||
this.change((js) => {
|
||||
const j = js.find((x) => x.id === id);
|
||||
if (j) Object.assign(j, p);
|
||||
});
|
||||
this.show();
|
||||
this.render();
|
||||
}
|
||||
|
||||
/** The pitch of a thread on either body (mm for each full turn), when one of them is threaded. */
|
||||
private threadOn(a: string, b: string): number | undefined {
|
||||
const t = this.app.store.doc.features.find((f): f is ThreadFeature => f.type === "thread" && !f.suppressed && (f.face.body === a || f.face.body === b));
|
||||
return t ? t.pitch * (t.starts ?? 1) : undefined;
|
||||
}
|
||||
|
||||
private make(a: Pick, b: Pick): void {
|
||||
const p = propose(a.line, b.line, this.threadOn(a.body, b.body));
|
||||
const n = this.joints.length + 1;
|
||||
const refA = faceRefOf(this.app, a.line ? a : b) ?? undefined;
|
||||
const refB = faceRefOf(this.app, a.line ? b : a) ?? undefined;
|
||||
const joint: Joint = { id: uid(), name: `Joint ${n}`, type: p.type, a: a.body, b: b.body, origin: p.origin, axis: p.axis, ...(p.pitch ? { pitch: p.pitch } : {}), ...(refA ? { refA } : {}), ...(refB ? { refB } : {}) };
|
||||
this.change((js) => js.push(joint));
|
||||
this.first = null;
|
||||
this.app.setSelection([]);
|
||||
this.app.ui.toast(`${JOINT_NAMES[p.type]} joint: ${this.nameOf(a.body)} and ${this.nameOf(b.body)}`);
|
||||
this.open(joint.id);
|
||||
}
|
||||
|
||||
private open(id: string): void {
|
||||
this.mode = "edit";
|
||||
this.editing = id;
|
||||
this.show();
|
||||
this.render();
|
||||
}
|
||||
|
||||
private toList(): void {
|
||||
this.save();
|
||||
this.mode = "list";
|
||||
this.editing = null;
|
||||
this.first = null;
|
||||
this.app.setSelection([]);
|
||||
this.show();
|
||||
this.render();
|
||||
}
|
||||
|
||||
private home(): void {
|
||||
this.values = {};
|
||||
this.exploded = 0;
|
||||
this.show();
|
||||
this.save();
|
||||
this.render();
|
||||
}
|
||||
|
||||
private setType(j: Joint, type: JointType): void {
|
||||
delete this.values[j.id];
|
||||
const pitch = type === "screw" ? (j.pitch ?? this.threadOn(j.a, j.b) ?? 1.5) : undefined;
|
||||
// (Limits are in the joint's own measure - degrees or mm: another kind of joint starts without them.)
|
||||
this.patch(j.id, { type, pitch, min: undefined, max: undefined, ...(type === "fixed" ? { drive: undefined } : {}) });
|
||||
}
|
||||
|
||||
private setValue(j: Joint, v: number): void {
|
||||
const d = driverOf(this.liveJoints(), j.id);
|
||||
if (!d || !d.ratio) return;
|
||||
this.values[d.joint.id] = v / d.ratio;
|
||||
// (Kept in its limits: what is stored is where it is.)
|
||||
this.values[d.joint.id] = effective(this.liveJoints(), this.values)[d.joint.id] ?? 0;
|
||||
this.show();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ dragging a part
|
||||
|
||||
dragStart(from: ToolPointer): boolean {
|
||||
if (this.mode === "add" || this.exploded > 0) return false;
|
||||
const h = this.faceAt(from);
|
||||
if (!h) return false;
|
||||
const joints = this.liveJoints();
|
||||
const t = tree(joints, this.bodies, this.app.store.doc.ground);
|
||||
// The joint that lets it move: its own, or - held fast to another part - that part's.
|
||||
let body = h.body;
|
||||
let up = t.up.get(body);
|
||||
while (up && up.joint.type === "fixed") (body = up.parent), (up = t.up.get(body));
|
||||
if (!up) {
|
||||
if (joints.some((j) => j.a === h.body || j.b === h.body)) this.app.ui.toast("That part stands still: drag the part that moves against it");
|
||||
return false;
|
||||
}
|
||||
const d = driverOf(joints, up.joint.id);
|
||||
if (!d || !d.ratio) return false;
|
||||
const poses = this.poses();
|
||||
const m = poses.get(up.parent) ?? null;
|
||||
const origin = m ? apply(m, up.joint.origin) : up.joint.origin;
|
||||
const axis = norm(m ? turn(m, up.joint.axis) : up.joint.axis);
|
||||
// Stop on contact: what is in each other already is left to be (parts modelled into each other, or touching).
|
||||
const stood = stopOnContact ? this.standing(poses) : new Map<string, Mat4>();
|
||||
const inEachOther = stopOnContact ? this.clashes(stood) : new Set<string>();
|
||||
this.dragging = { from, joint: up.joint, driver: d.joint, ratio: d.ratio, sign: up.joint.b === body ? 1 : -1, v0: effective(joints, this.values)[up.joint.id] ?? 0, grab: h.point, origin, axis, turned: 0, last: null, inEachOther, stood, free: this.values[d.joint.id] ?? 0 };
|
||||
return true;
|
||||
}
|
||||
|
||||
drag(p: ToolPointer): void {
|
||||
const g = this.dragging;
|
||||
if (!g) return;
|
||||
let moved: number;
|
||||
if (g.joint.type === "slide") moved = axisDrag(this.app.view, g.grab, g.axis, g.from, p);
|
||||
else {
|
||||
// Round the line. Seen along it (enough): by where the pointer is on the plane across it, turn by turn.
|
||||
// Seen from the side: by how far the pointer went the way the grabbed point goes round.
|
||||
const centre = add(g.origin, scale(g.axis, dot(sub(g.grab, g.origin), g.axis)));
|
||||
const arm = sub(g.grab, centre);
|
||||
const ray = this.app.view.pointerRay(p.x, p.y);
|
||||
const facing = dot(ray.d, g.axis);
|
||||
if (Math.abs(facing) > 0.3 && len(arm) > 1e-6) {
|
||||
const s = dot(sub(centre, ray.o), g.axis) / facing;
|
||||
const at = sub(add(ray.o, scale(ray.d, s)), centre);
|
||||
const prev = g.last ?? arm;
|
||||
g.turned += (Math.atan2(dot(cross(prev, at), g.axis), dot(prev, at)) * 180) / Math.PI;
|
||||
g.last = at;
|
||||
moved = g.turned;
|
||||
} else {
|
||||
const r = len(arm) || 1;
|
||||
moved = (axisDrag(this.app.view, g.grab, norm(cross(g.axis, arm)), g.from, p) / r) * (180 / Math.PI);
|
||||
}
|
||||
}
|
||||
const want = g.v0 + g.sign * moved;
|
||||
this.values[g.driver.id] = want / g.ratio;
|
||||
// (Kept in the limits: what is stored is what it is, so the next drag starts from there.)
|
||||
let v = effective(this.liveJoints(), this.values);
|
||||
this.values[g.driver.id] = v[g.driver.id];
|
||||
// Stop on contact: a move that runs a part into another goes only as far as it can - found by halving, between
|
||||
// the last value nothing was run into at and the one asked for.
|
||||
let stopped = false;
|
||||
if (stopOnContact) {
|
||||
const hits = (value: number): boolean => {
|
||||
this.values[g.driver.id] = value;
|
||||
return this.clashes(this.standing(this.poses()), g.stood, g.inEachOther).size > 0;
|
||||
};
|
||||
const asked = this.values[g.driver.id];
|
||||
// (The way there is gone in steps - a millimetre, or three degrees, of the dragged joint - so a part is not
|
||||
// carried through another and out of its far side by one long move.)
|
||||
const pace = (g.joint.type === "slide" ? 1 : 3) / Math.abs(g.ratio || 1);
|
||||
const steps = Math.min(40, Math.max(1, Math.ceil(Math.abs(asked - g.free) / pace)));
|
||||
let lo = g.free;
|
||||
let hi: number | null = null;
|
||||
for (let i = 1; i <= steps; i++) {
|
||||
const at = g.free + ((asked - g.free) * i) / steps;
|
||||
if (hits(at)) {
|
||||
hi = at;
|
||||
break;
|
||||
}
|
||||
lo = at;
|
||||
}
|
||||
if (hi !== null) {
|
||||
stopped = true;
|
||||
let top: number = hi;
|
||||
for (let i = 0; i < 7; i++) {
|
||||
const mid: number = (lo + top) / 2;
|
||||
if (hits(mid)) top = mid;
|
||||
else lo = mid;
|
||||
}
|
||||
}
|
||||
this.values[g.driver.id] = lo;
|
||||
g.free = this.values[g.driver.id];
|
||||
v = effective(this.liveJoints(), this.values);
|
||||
}
|
||||
this.show();
|
||||
const now = v[g.joint.id] ?? 0;
|
||||
this.app.ui.setLabel(p.x, p.y, `${g.joint.type === "slide" ? fmtLen(now) : `${+now.toFixed(1)}°`}${stopped ? " · contact" : ""}`);
|
||||
}
|
||||
|
||||
up(): void {
|
||||
if (!this.dragging) return;
|
||||
this.dragging = null;
|
||||
this.app.ui.setLabel(0, 0, null);
|
||||
this.save();
|
||||
this.render();
|
||||
}
|
||||
|
||||
breakOff(): void {
|
||||
const g = this.dragging;
|
||||
if (!g) return;
|
||||
this.values[g.driver.id] = (g.v0 * 1) / g.ratio;
|
||||
this.dragging = null;
|
||||
this.app.ui.setLabel(0, 0, null);
|
||||
this.show();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ the line at the bottom
|
||||
|
||||
private render(): void {
|
||||
const ui = this.app.ui;
|
||||
const joints = this.joints;
|
||||
if (this.mode === "add") {
|
||||
ui.setHint(this.first ? "Now tap a face of the part it moves against." : "Tap a face of the first part. A round face or a flat one gives the joint its line.");
|
||||
ui.showPanel({
|
||||
title: "New joint",
|
||||
items: [
|
||||
{ type: "slot", label: "First part", value: this.first ? this.nameOf(this.first.body) : "", active: !this.first, filled: !!this.first, onClick: () => ((this.first = null), this.app.setSelection([]), this.render()) },
|
||||
{ type: "slot", label: "Second part", value: "", active: !!this.first, filled: false, onClick: () => undefined },
|
||||
],
|
||||
onCancel: () => this.toList(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const j0 = this.mode === "edit" ? joints.find((x) => x.id === this.editing) : undefined;
|
||||
if (j0) {
|
||||
const j = j0;
|
||||
const turns = j.type === "hinge" || j.type === "screw";
|
||||
const now = effective(this.liveJoints(), this.values)[j.id] ?? 0;
|
||||
const limited = j.min !== undefined || j.max !== undefined;
|
||||
const others = joints.filter((x) => x.id !== j.id && x.type !== "fixed" && x.drive?.joint !== j.id);
|
||||
const items: PanelItem[] = [{ type: "choice", label: "Type", list: true, options: (Object.keys(JOINT_NAMES) as JointType[]).map((id) => ({ id, label: JOINT_NAMES[id] })), value: j.type, onChange: (id) => this.setType(j, id as JointType) }];
|
||||
if (j.type !== "fixed") {
|
||||
items.push({ type: "number", label: turns ? "Angle" : "Distance", value: now, kind: turns ? "angle" : "length", onInput: (v) => (this.setValue(j, v), this.save(), this.render()) });
|
||||
if (j.type === "screw") items.push({ type: "number", label: "Pitch", value: j.pitch ?? 1.5, kind: "length", min: 0.01, onInput: (v) => v > 0 && this.patch(j.id, { pitch: v }) });
|
||||
items.push({ type: "toggle", label: "Limits", value: limited, onChange: (on) => this.patch(j.id, on ? { min: turns ? 0 : 0, max: turns ? 90 : 20 } : { min: undefined, max: undefined }) });
|
||||
if (limited) {
|
||||
items.push({ type: "number", label: "From", value: j.min ?? 0, kind: turns ? "angle" : "length", onInput: (v) => this.patch(j.id, { min: Math.min(v, j.max ?? v) }) });
|
||||
items.push({ type: "number", label: "To", value: j.max ?? 0, kind: turns ? "angle" : "length", onInput: (v) => this.patch(j.id, { max: Math.max(v, j.min ?? v) }) });
|
||||
}
|
||||
items.push({ type: "button", label: "Flip", icon: "flip", onClick: () => this.patch(j.id, { axis: scale(j.axis, -1) }) });
|
||||
if (others.length) {
|
||||
items.push({ type: "choice", label: "Follows", list: true, options: [{ id: "", label: "Nothing" }, ...others.map((x) => ({ id: x.id, label: x.name }))], value: j.drive?.joint ?? "", onChange: (id) => this.patch(j.id, { drive: id ? { joint: id, ratio: j.drive?.ratio ?? 1 } : undefined }) });
|
||||
if (j.drive) items.push({ type: "number", label: "Ratio", value: j.drive.ratio, kind: "number", onInput: (v) => v && this.patch(j.id, { drive: { joint: j.drive!.joint, ratio: v } }) });
|
||||
}
|
||||
}
|
||||
ui.setHint(j.type === "fixed" ? `${this.nameOf(j.a)} and ${this.nameOf(j.b)} are held together. Change its Type to let them move.` : `Drag ${this.nameOf(j.b)} to move it. Home puts every part back where it was modelled.`);
|
||||
ui.showPanel({
|
||||
title: `${j.name}: ${this.nameOf(j.a)} and ${this.nameOf(j.b)}`,
|
||||
beta: true,
|
||||
items,
|
||||
actions: [
|
||||
{
|
||||
id: "delete",
|
||||
label: "Delete joint",
|
||||
icon: "trash",
|
||||
run: () => {
|
||||
this.change((js) => {
|
||||
const i = js.findIndex((x) => x.id === j.id);
|
||||
if (i >= 0) js.splice(i, 1);
|
||||
for (const x of js) if (x.drive?.joint === j.id) delete x.drive;
|
||||
});
|
||||
delete this.values[j.id];
|
||||
this.toList();
|
||||
},
|
||||
},
|
||||
],
|
||||
onDone: () => this.toList(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.mode = "list";
|
||||
const held = [...new Set(joints.flatMap((x) => [x.a, x.b]))].filter((b) => this.app.view.body(b));
|
||||
const ground = this.app.store.doc.ground && held.includes(this.app.store.doc.ground) ? this.app.store.doc.ground : (tree(joints, this.bodies).roots[0] ?? "");
|
||||
const moved = this.exploded > 0 || Object.values(this.values).some((v) => Math.abs(v) > 1e-9);
|
||||
const items: PanelItem[] = [
|
||||
{ type: "button", label: "Add joint", icon: "assembly", primary: !joints.length, onClick: () => (this.home(), (this.mode = "add"), (this.first = null), this.render()) },
|
||||
{ type: "chips", label: "Joints", empty: "None yet", chips: joints.map((x) => ({ label: `${x.name} · ${JOINT_NAMES[x.type]}`, title: `${this.nameOf(x.a)} and ${this.nameOf(x.b)}`, onClick: () => this.open(x.id) })) },
|
||||
];
|
||||
if (joints.length) {
|
||||
items.push({ type: "slider", label: "Explode", value: Math.round(this.exploded * 100), min: 0, max: 100, step: 1, show: (v) => `${v}%`, onInput: (v) => ((this.exploded = v / 100), this.show()) });
|
||||
if (held.length > 1) items.push({ type: "choice", label: "Stands still", list: true, options: held.map((b) => ({ id: b, label: this.nameOf(b) })), value: ground, onChange: (id) => (this.app.store.commit((d) => void (d.ground = id)), this.show(), this.render()) });
|
||||
items.push({ type: "toggle", label: "Stop on contact", value: stopOnContact, onChange: (on) => ((stopOnContact = on), this.render()) });
|
||||
if (moved) items.push({ type: "button", label: "Home", onClick: () => this.home() });
|
||||
}
|
||||
ui.setHint(joints.length ? "Drag a part to move it by its joint. Tap a part to change its joint." : "The parts stay where you modelled them. Add a joint to say how two of them move.");
|
||||
ui.showPanel({ title: "Assemblies", beta: true, items, onDone: () => this.leave() });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
// Assemblies: do two bodies run into each other where they are shown?
|
||||
//
|
||||
// Asked on every move of a drag, of bodies that are only moved (their meshes stay as they are), so each body's
|
||||
// mesh is put in a tree of boxes once and the question is asked of the trees. Two bodies are in each other when
|
||||
// a corner of one is inside the other by more than a little: parts that touch, or sit in each other with a hair
|
||||
// of play (a nut on its thread), are not - their drawn facets cross here and there without the parts doing so.
|
||||
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { apply, type Mat4 } from "./joints";
|
||||
|
||||
/** A rigid move undone (a turn and a shift: the turn's transpose, the shift taken back through it). */
|
||||
export function inverse(m: Mat4): Mat4 {
|
||||
const t: Vec3 = [m[12], m[13], m[14]];
|
||||
return [m[0], m[4], m[8], 0, m[1], m[5], m[9], 0, m[2], m[6], m[10], 0, -(m[0] * t[0] + m[1] * t[1] + m[2] * t[2]), -(m[4] * t[0] + m[5] * t[1] + m[6] * t[2]), -(m[8] * t[0] + m[9] * t[1] + m[10] * t[2]), 1];
|
||||
}
|
||||
|
||||
const LEAF = 6;
|
||||
// (Not along an axis: a ray along one runs down the edges and corners of boxy parts, where "how many faces
|
||||
// did it cross" has no clean answer.)
|
||||
const RAY: Vec3 = [0.8017837257372732, 0.5345224838248488, 0.2672612419124244];
|
||||
|
||||
/** A body's mesh, ready to be asked whether a point is inside it. */
|
||||
export class Solid {
|
||||
/** The mesh's corners, each once (or one in every few, of a very fine mesh). */
|
||||
readonly corners: Float32Array;
|
||||
readonly lo: Vec3 = [Infinity, Infinity, Infinity];
|
||||
readonly hi: Vec3 = [-Infinity, -Infinity, -Infinity];
|
||||
/** The tree: each node's box (6 numbers), and either its two children or its run of triangles. */
|
||||
private boxes: number[] = [];
|
||||
private kids: number[] = [];
|
||||
private tris: Uint32Array;
|
||||
|
||||
constructor(private P: Float32Array, private I: Uint32Array) {
|
||||
const n = Math.floor(I.length / 3);
|
||||
this.tris = new Uint32Array(n);
|
||||
const mid = new Float32Array(n * 3);
|
||||
for (let t = 0; t < n; t++) {
|
||||
this.tris[t] = t;
|
||||
for (let k = 0; k < 3; k++) mid[t * 3 + k] = (P[I[t * 3] * 3 + k] + P[I[t * 3 + 1] * 3 + k] + P[I[t * 3 + 2] * 3 + k]) / 3;
|
||||
}
|
||||
for (let i = 0; i < P.length; i += 3) for (let k = 0; k < 3; k++) (this.lo[k] = Math.min(this.lo[k], P[i + k])), (this.hi[k] = Math.max(this.hi[k], P[i + k]));
|
||||
if (n) this.build(0, n, mid);
|
||||
// Corners: one of each place (a mesh has a corner once for every face that meets there).
|
||||
const seen = new Set<string>();
|
||||
const out: number[] = [];
|
||||
const step = Math.max(1, Math.floor(P.length / 3 / 60000));
|
||||
for (let i = 0; i < P.length; i += 3 * step) {
|
||||
const key = `${Math.round(P[i] * 1e4)},${Math.round(P[i + 1] * 1e4)},${Math.round(P[i + 2] * 1e4)}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(P[i], P[i + 1], P[i + 2]);
|
||||
}
|
||||
this.corners = new Float32Array(out);
|
||||
}
|
||||
|
||||
private build(from: number, to: number, mid: Float32Array): number {
|
||||
const node = this.kids.length / 2;
|
||||
this.kids.push(0, 0);
|
||||
const b = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
|
||||
const c = [Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity];
|
||||
for (let s = from; s < to; s++) {
|
||||
const t = this.tris[s];
|
||||
for (let v = 0; v < 3; v++) {
|
||||
const i = this.I[t * 3 + v] * 3;
|
||||
for (let k = 0; k < 3; k++) (b[k] = Math.min(b[k], this.P[i + k])), (b[3 + k] = Math.max(b[3 + k], this.P[i + k]));
|
||||
}
|
||||
for (let k = 0; k < 3; k++) (c[k] = Math.min(c[k], mid[t * 3 + k])), (c[3 + k] = Math.max(c[3 + k], mid[t * 3 + k]));
|
||||
}
|
||||
this.boxes.push(...b);
|
||||
const axis = c[3] - c[0] > c[4] - c[1] ? (c[3] - c[0] > c[5] - c[2] ? 0 : 2) : c[4] - c[1] > c[5] - c[2] ? 1 : 2;
|
||||
const cut = (c[axis] + c[3 + axis]) / 2;
|
||||
let m = from;
|
||||
for (let s = from; s < to; s++) {
|
||||
if (mid[this.tris[s] * 3 + axis] < cut) {
|
||||
const w = this.tris[s];
|
||||
this.tris[s] = this.tris[m];
|
||||
this.tris[m++] = w;
|
||||
}
|
||||
}
|
||||
if (to - from <= LEAF || m === from || m === to) {
|
||||
// A leaf: its triangles, marked by a minus.
|
||||
this.kids[node * 2] = -(from + 1);
|
||||
this.kids[node * 2 + 1] = to - from;
|
||||
return node;
|
||||
}
|
||||
const l = this.build(from, m, mid);
|
||||
const r = this.build(m, to, mid);
|
||||
this.kids[node * 2] = l;
|
||||
this.kids[node * 2 + 1] = r;
|
||||
return node;
|
||||
}
|
||||
|
||||
/** How many of the mesh's triangles a ray from `p` goes through: odd, the point is inside. */
|
||||
inside(p: Vec3): boolean {
|
||||
if (!this.tris.length) return false;
|
||||
for (let k = 0; k < 3; k++) if (p[k] < this.lo[k] || p[k] > this.hi[k]) return false;
|
||||
let crossings = 0;
|
||||
const stack = [0];
|
||||
const P = this.P;
|
||||
const I = this.I;
|
||||
while (stack.length) {
|
||||
const node = stack.pop()!;
|
||||
// The ray and the node's box (the ray goes the positive way along all three).
|
||||
let t0 = 0;
|
||||
let t1 = Infinity;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const a = (this.boxes[node * 6 + k] - p[k]) / RAY[k];
|
||||
const b = (this.boxes[node * 6 + 3 + k] - p[k]) / RAY[k];
|
||||
t0 = Math.max(t0, a);
|
||||
t1 = Math.min(t1, b);
|
||||
}
|
||||
if (t1 < t0) continue;
|
||||
const a = this.kids[node * 2];
|
||||
if (a >= 0) {
|
||||
stack.push(a, this.kids[node * 2 + 1]);
|
||||
continue;
|
||||
}
|
||||
const from = -a - 1;
|
||||
const count = this.kids[node * 2 + 1];
|
||||
for (let s = from; s < from + count; s++) {
|
||||
const t = this.tris[s] * 3;
|
||||
const i0 = I[t] * 3;
|
||||
const i1 = I[t + 1] * 3;
|
||||
const i2 = I[t + 2] * 3;
|
||||
// Möller-Trumbore.
|
||||
const e1x = P[i1] - P[i0];
|
||||
const e1y = P[i1 + 1] - P[i0 + 1];
|
||||
const e1z = P[i1 + 2] - P[i0 + 2];
|
||||
const e2x = P[i2] - P[i0];
|
||||
const e2y = P[i2 + 1] - P[i0 + 1];
|
||||
const e2z = P[i2 + 2] - P[i0 + 2];
|
||||
const px = RAY[1] * e2z - RAY[2] * e2y;
|
||||
const py = RAY[2] * e2x - RAY[0] * e2z;
|
||||
const pz = RAY[0] * e2y - RAY[1] * e2x;
|
||||
const det = e1x * px + e1y * py + e1z * pz;
|
||||
if (Math.abs(det) < 1e-14) continue;
|
||||
const inv = 1 / det;
|
||||
const tx = p[0] - P[i0];
|
||||
const ty = p[1] - P[i0 + 1];
|
||||
const tz = p[2] - P[i0 + 2];
|
||||
const u = (tx * px + ty * py + tz * pz) * inv;
|
||||
if (u < 0 || u > 1) continue;
|
||||
const qx = ty * e1z - tz * e1y;
|
||||
const qy = tz * e1x - tx * e1z;
|
||||
const qz = tx * e1y - ty * e1x;
|
||||
const v = (RAY[0] * qx + RAY[1] * qy + RAY[2] * qz) * inv;
|
||||
if (v < 0 || u + v > 1) continue;
|
||||
if ((e2x * qx + e2y * qy + e2z * qz) * inv > 0) crossings++;
|
||||
}
|
||||
}
|
||||
return (crossings & 1) === 1;
|
||||
}
|
||||
|
||||
/** Inside, and not within `tol` of the surface (as far as six points round it tell). */
|
||||
deepInside(p: Vec3, tol: number): boolean {
|
||||
if (!this.inside(p)) return false;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
for (const s of [-tol, tol]) {
|
||||
const q: Vec3 = [p[0], p[1], p[2]];
|
||||
q[k] += s;
|
||||
if (!this.inside(q)) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does `b`, moved by `bToA` into `a`'s own space, run into `a`: a corner of either more than `tol` inside the
|
||||
* other. (Both where they were modelled: `bToA` is none.)
|
||||
*/
|
||||
export function penetrates(a: Solid, b: Solid, bToA: Mat4, tol: number): boolean {
|
||||
const one = (into: Solid, of: Solid, m: Mat4): boolean => {
|
||||
const C = of.corners;
|
||||
for (let i = 0; i < C.length; i += 3) {
|
||||
const p = apply(m, [C[i], C[i + 1], C[i + 2]]);
|
||||
if (p[0] < into.lo[0] || p[1] < into.lo[1] || p[2] < into.lo[2] || p[0] > into.hi[0] || p[1] > into.hi[1] || p[2] > into.hi[2]) continue;
|
||||
if (into.deepInside(p, tol)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
return one(a, b, bToA) || one(b, a, inverse(bToA));
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
// Assemblies: how the bodies of a project are held together, and where each is when they move.
|
||||
//
|
||||
// The bodies are modelled where they belong, so nothing is put in place: a joint only says how two bodies may
|
||||
// move against each other - not at all (fixed), round an axis (hinge), along it (slide), or both at once as a
|
||||
// nut on its thread (screw). Where everything was modelled is home: a joint's value is how far it is from
|
||||
// there (degrees, or mm for a slide), and all of them at 0 is the model as it was built.
|
||||
//
|
||||
// Kinematics only: no weight, no forces. A joint can follow another by a ratio (a gear turning its neighbour).
|
||||
|
||||
import type { FaceRef, Vec3 } from "../doc/types";
|
||||
|
||||
export type JointType = "fixed" | "hinge" | "slide" | "screw";
|
||||
|
||||
export interface Joint {
|
||||
id: string;
|
||||
name: string;
|
||||
type: JointType;
|
||||
/** The two bodies: `b` moves against `a` (which of them stays still is told by what is grounded). */
|
||||
a: string;
|
||||
b: string;
|
||||
/** The joint's line, where the bodies were modelled: a point on it and its direction. */
|
||||
origin: Vec3;
|
||||
axis: Vec3;
|
||||
/** How far it may go (degrees; mm for a slide). Missing: as far as it is dragged. */
|
||||
min?: number;
|
||||
max?: number;
|
||||
/** A screw's: mm along the axis for each full turn. */
|
||||
pitch?: number;
|
||||
/** It follows another joint: its value is that one's, times `ratio` (a gear: minus the teeth's ratio). */
|
||||
drive?: { joint: string; ratio: number };
|
||||
/** The faces it was picked by, so its line follows them when the model changes. */
|
||||
refA?: FaceRef;
|
||||
refB?: FaceRef;
|
||||
}
|
||||
|
||||
/** A 4 x 4 matrix, column by column (as three.js keeps it). */
|
||||
export type Mat4 = number[];
|
||||
|
||||
export const IDENTITY: Mat4 = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
|
||||
|
||||
export function mul(a: Mat4, b: Mat4): Mat4 {
|
||||
const o = new Array<number>(16);
|
||||
for (let c = 0; c < 4; c++) for (let r = 0; r < 4; r++) o[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
|
||||
return o;
|
||||
}
|
||||
|
||||
export function translation(v: Vec3): Mat4 {
|
||||
return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, v[0], v[1], v[2], 1];
|
||||
}
|
||||
|
||||
export function apply(m: Mat4, p: Vec3): Vec3 {
|
||||
return [m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12], m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13], m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14]];
|
||||
}
|
||||
|
||||
/** A direction through a matrix (its turning only). */
|
||||
export function turn(m: Mat4, d: Vec3): Vec3 {
|
||||
return [m[0] * d[0] + m[4] * d[1] + m[8] * d[2], m[1] * d[0] + m[5] * d[1] + m[9] * d[2], m[2] * d[0] + m[6] * d[1] + m[10] * d[2]];
|
||||
}
|
||||
|
||||
const unit = (v: Vec3): Vec3 => {
|
||||
const l = Math.hypot(v[0], v[1], v[2]) || 1;
|
||||
return [v[0] / l, v[1] / l, v[2] / l];
|
||||
};
|
||||
|
||||
/** A turn of `deg` round the line through `origin` along `axis`, and `along` mm along it. */
|
||||
export function about(origin: Vec3, axis: Vec3, deg: number, along = 0): Mat4 {
|
||||
const [x, y, z] = unit(axis);
|
||||
const t = (deg * Math.PI) / 180;
|
||||
const c = Math.cos(t);
|
||||
const s = Math.sin(t);
|
||||
const k = 1 - c;
|
||||
// Rodrigues, column by column.
|
||||
const r = [c + x * x * k, y * x * k + z * s, z * x * k - y * s, x * y * k - z * s, c + y * y * k, z * y * k + x * s, x * z * k + y * s, y * z * k - x * s, c + z * z * k];
|
||||
const ro: Vec3 = [r[0] * origin[0] + r[3] * origin[1] + r[6] * origin[2], r[1] * origin[0] + r[4] * origin[1] + r[7] * origin[2], r[2] * origin[0] + r[5] * origin[1] + r[8] * origin[2]];
|
||||
return [r[0], r[1], r[2], 0, r[3], r[4], r[5], 0, r[6], r[7], r[8], 0, origin[0] - ro[0] + x * along, origin[1] - ro[1] + y * along, origin[2] - ro[2] + z * along, 1];
|
||||
}
|
||||
|
||||
/** What a joint does to its `b` at a value: the move from home. */
|
||||
export function motion(j: Joint, value: number): Mat4 {
|
||||
if (j.type === "hinge") return about(j.origin, j.axis, value);
|
||||
if (j.type === "slide") return about(j.origin, j.axis, 0, value);
|
||||
if (j.type === "screw") return about(j.origin, j.axis, value, ((j.pitch ?? 1) * value) / 360);
|
||||
return IDENTITY;
|
||||
}
|
||||
|
||||
const clamp = (j: Joint, v: number): number => Math.min(j.max ?? Infinity, Math.max(j.min ?? -Infinity, v));
|
||||
|
||||
/** Each joint's value as it is: its own, kept in its limits - or what the joint it follows gives it. */
|
||||
export function effective(joints: Joint[], values: Record<string, number>): Record<string, number> {
|
||||
const by = new Map(joints.map((j) => [j.id, j]));
|
||||
const out: Record<string, number> = {};
|
||||
const of = (j: Joint, depth: number): number => {
|
||||
if (j.id in out) return out[j.id];
|
||||
const d = j.drive && depth < 32 ? by.get(j.drive.joint) : undefined;
|
||||
const v = j.type === "fixed" ? 0 : d && d.id !== j.id ? of(d, depth + 1) * j.drive!.ratio : clamp(j, values[j.id] ?? 0);
|
||||
return (out[j.id] = v);
|
||||
};
|
||||
for (const j of joints) of(j, 0);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The joint whose own value sets this one's (itself, when it follows no other), and by how much. */
|
||||
export function driverOf(joints: Joint[], id: string): { joint: Joint; ratio: number } | null {
|
||||
const by = new Map(joints.map((j) => [j.id, j]));
|
||||
let j = by.get(id);
|
||||
let ratio = 1;
|
||||
for (let i = 0; j && i < 32; i++) {
|
||||
const d = j.drive ? by.get(j.drive.joint) : undefined;
|
||||
if (!d || d.id === j.id) return { joint: j, ratio };
|
||||
ratio *= j.drive!.ratio;
|
||||
j = d;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface Tree {
|
||||
/** Each body's joint towards what is grounded, the body on its other side, and how many joints away the ground is. */
|
||||
up: Map<string, { joint: Joint; parent: string; depth: number }>;
|
||||
roots: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The bodies as a tree from what stands still: `ground` when it is given and there, else - in each group of
|
||||
* bodies joined together - the one that comes first in the project. A joint that would close a ring of bodies
|
||||
* is left out (the ring's other joints carry it).
|
||||
*/
|
||||
export function tree(joints: Joint[], bodies: string[], ground?: string): Tree {
|
||||
const have = new Set(bodies);
|
||||
const live = joints.filter((j) => have.has(j.a) && have.has(j.b) && j.a !== j.b);
|
||||
const up: Tree["up"] = new Map();
|
||||
const seen = new Set<string>();
|
||||
const roots: string[] = [];
|
||||
const order = ground && have.has(ground) ? [ground, ...bodies.filter((b) => b !== ground)] : bodies;
|
||||
for (const root of order) {
|
||||
if (seen.has(root) || !live.some((j) => j.a === root || j.b === root)) continue;
|
||||
roots.push(root);
|
||||
seen.add(root);
|
||||
const queue = [root];
|
||||
while (queue.length) {
|
||||
const p = queue.shift()!;
|
||||
const depth = (up.get(p)?.depth ?? 0) + 1;
|
||||
for (const j of live) {
|
||||
const c = j.a === p ? j.b : j.b === p ? j.a : null;
|
||||
if (!c || seen.has(c)) continue;
|
||||
seen.add(c);
|
||||
up.set(c, { joint: j, parent: p, depth });
|
||||
queue.push(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return { up, roots };
|
||||
}
|
||||
|
||||
export interface Explode {
|
||||
/** 0: together. 1: each body a body's width from its neighbour. */
|
||||
factor: number;
|
||||
/** Each body's middle and how big it is (the radius of a ball round it), where it was modelled. */
|
||||
centers: Record<string, Vec3>;
|
||||
sizes: Record<string, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where every body is: its move from where it was modelled. Bodies no joint holds (and what is grounded) stay.
|
||||
* Exploded, each body is pushed off its neighbour along their joint's line (a fixed joint: from middle to middle).
|
||||
*/
|
||||
export function solve(joints: Joint[], bodies: string[], values: Record<string, number>, ground?: string, explode?: Explode): Map<string, Mat4> {
|
||||
const t = tree(joints, bodies, ground);
|
||||
const v = effective(joints, values);
|
||||
const out = new Map<string, Mat4>();
|
||||
const push = new Map<string, Vec3>();
|
||||
for (const r of t.roots) out.set(r, IDENTITY);
|
||||
// (Parents before children: by how far from the ground they are.)
|
||||
const order = [...t.up.entries()].sort((p, q) => p[1].depth - q[1].depth);
|
||||
for (const [body, { joint, parent }] of order) {
|
||||
const m = motion(joint, joint.b === body ? v[joint.id] : -v[joint.id]);
|
||||
out.set(body, mul(out.get(parent) ?? IDENTITY, m));
|
||||
if (!explode || !(explode.factor > 0)) continue;
|
||||
const cp = explode.centers[parent];
|
||||
const cc = explode.centers[body];
|
||||
const between: Vec3 = cp && cc ? [cc[0] - cp[0], cc[1] - cp[1], cc[2] - cp[2]] : [0, 0, 0];
|
||||
let dir = unit(joint.axis);
|
||||
const side = dir[0] * between[0] + dir[1] * between[1] + dir[2] * between[2];
|
||||
if (joint.type === "fixed" && Math.hypot(...between) > 1e-9) dir = unit(between);
|
||||
else if (side < 0) dir = [-dir[0], -dir[1], -dir[2]];
|
||||
const far = explode.factor * ((explode.sizes[parent] ?? 0) + (explode.sizes[body] ?? 0));
|
||||
const base = push.get(parent) ?? [0, 0, 0];
|
||||
push.set(body, [base[0] + dir[0] * far, base[1] + dir[1] * far, base[2] + dir[2] * far]);
|
||||
}
|
||||
for (const [body, p] of push) out.set(body, mul(translation(p), out.get(body)!));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What a face gives a joint: a line (a round face's axis; a flat face's normal through its middle), or nothing. */
|
||||
export interface PickLine {
|
||||
origin: Vec3;
|
||||
dir: Vec3;
|
||||
round: boolean;
|
||||
/** Found from the face's drawn points (a thread's flank), not known exactly: good to a twentieth of a millimetre. */
|
||||
rough?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* The joint two picks make, as they stand: on one line (two round faces on one axis, two flat faces one above the
|
||||
* other) - a hinge, or a screw when one of the bodies is threaded; two flat faces side by side - a slide along
|
||||
* the first's normal; anything else - fixed. Its line is the first pick's.
|
||||
*/
|
||||
export function propose(a: PickLine | null, b: PickLine | null, pitch?: number): { type: JointType; origin: Vec3; axis: Vec3; pitch?: number } {
|
||||
// (The joint's line is the first pick's - or the second's, where only that one is known exactly.)
|
||||
const line = a && b && a.rough && !b.rough ? b : (a ?? b);
|
||||
if (!line) return { type: "fixed", origin: [0, 0, 0], axis: [0, 0, 1] };
|
||||
const axis = unit(line.dir);
|
||||
const base = { origin: line.origin, axis };
|
||||
if (!a || !b) return { type: "fixed", ...base };
|
||||
const da = unit(a.dir);
|
||||
const d = unit(b.dir);
|
||||
const parallel = Math.abs(da[0] * d[0] + da[1] * d[1] + da[2] * d[2]) > (a.rough || b.rough ? 0.995 : 0.999);
|
||||
if (!parallel) return { type: "fixed", ...base };
|
||||
const w: Vec3 = [b.origin[0] - a.origin[0], b.origin[1] - a.origin[1], b.origin[2] - a.origin[2]];
|
||||
const along = w[0] * axis[0] + w[1] * axis[1] + w[2] * axis[2];
|
||||
const off = Math.hypot(w[0] - axis[0] * along, w[1] - axis[1] * along, w[2] - axis[2] * along);
|
||||
const size = Math.max(1, Math.hypot(...w));
|
||||
// (To a hundredth of a millimetre and a thousandth of how far apart they are: faces are found by their drawn points.)
|
||||
if (off < 1e-3 * size + (a.rough || b.rough ? 0.15 : 1e-2)) return pitch ? { type: "screw", ...base, pitch } : { type: "hinge", ...base };
|
||||
return a.round || b.round ? { type: "fixed", ...base } : { type: "slide", ...base };
|
||||
}
|
||||
|
||||
/**
|
||||
* The line a face is turned round, from its points and the way it faces at each: a thread's flank, a cone, any
|
||||
* face made by turning a curve round a line (or screwing it along one). Along that line the face's normals all
|
||||
* lean the same - so it is the direction their leaning varies least in - and seen along it they all point at it.
|
||||
* Null where there is no such line (a flat face, a ball, a freeform face).
|
||||
*/
|
||||
export function turnAxis(points: Vec3[], normals: Vec3[]): { origin: Vec3; dir: Vec3 } | null {
|
||||
const n = Math.min(points.length, normals.length);
|
||||
if (n < 6) return null;
|
||||
const mean: Vec3 = [0, 0, 0];
|
||||
for (let i = 0; i < n; i++) for (let k = 0; k < 3; k++) mean[k] += normals[i][k] / n;
|
||||
// How the normals spread, as a symmetric 3 x 3; its axes by Jacobi turns.
|
||||
const a = [[0, 0, 0], [0, 0, 0], [0, 0, 0]];
|
||||
for (let i = 0; i < n; i++) for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) a[r][c] += ((normals[i][r] - mean[r]) * (normals[i][c] - mean[c])) / n;
|
||||
const v = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
|
||||
for (let sweep = 0; sweep < 24; sweep++) {
|
||||
for (const [p, q] of [[0, 1], [0, 2], [1, 2]] as const) {
|
||||
if (Math.abs(a[p][q]) < 1e-15) continue;
|
||||
const th = (a[q][q] - a[p][p]) / (2 * a[p][q]);
|
||||
const tt = Math.sign(th || 1) / (Math.abs(th) + Math.sqrt(th * th + 1));
|
||||
const c = 1 / Math.sqrt(tt * tt + 1);
|
||||
const s = tt * c;
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const akp = a[k][p];
|
||||
const akq = a[k][q];
|
||||
a[k][p] = c * akp - s * akq;
|
||||
a[k][q] = s * akp + c * akq;
|
||||
}
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const apk = a[p][k];
|
||||
const aqk = a[q][k];
|
||||
a[p][k] = c * apk - s * aqk;
|
||||
a[q][k] = s * apk + c * aqk;
|
||||
}
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const vkp = v[k][p];
|
||||
const vkq = v[k][q];
|
||||
v[k][p] = c * vkp - s * vkq;
|
||||
v[k][q] = s * vkp + c * vkq;
|
||||
}
|
||||
}
|
||||
}
|
||||
const ev = [a[0][0], a[1][1], a[2][2]];
|
||||
const lo = ev.indexOf(Math.min(...ev));
|
||||
const hi = Math.max(...ev);
|
||||
const mid = ev.filter((_, i) => i !== lo).reduce((p, q) => Math.min(p, q));
|
||||
// Round a line: no spread along it, and a spread both ways across it (a face that only bends one way has none).
|
||||
if (!(hi > 1e-6) || ev[lo] > 0.02 * hi || mid < 0.05 * hi) return null;
|
||||
const dir = unit([v[0][lo], v[1][lo], v[2][lo]]);
|
||||
// Across the line: each normal's part there points along a line through the axis. Where those lines meet.
|
||||
const x = unit(Math.abs(dir[0]) < 0.9 ? [0, -dir[2], dir[1]] : [-dir[2], 0, dir[0]]);
|
||||
const y: Vec3 = [dir[1] * x[2] - dir[2] * x[1], dir[2] * x[0] - dir[0] * x[2], dir[0] * x[1] - dir[1] * x[0]];
|
||||
const d3 = (p: Vec3, q: Vec3) => p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
|
||||
let m00 = 0;
|
||||
let m01 = 0;
|
||||
let m11 = 0;
|
||||
let b0 = 0;
|
||||
let b1 = 0;
|
||||
let used = 0;
|
||||
for (let i = 0; i < n; i++) {
|
||||
const nx = d3(normals[i], x);
|
||||
const ny = d3(normals[i], y);
|
||||
const l = Math.hypot(nx, ny);
|
||||
if (l < 0.2) continue;
|
||||
// (The line through the point along its normal: every point c of it has u.c = u.p, u across the normal.)
|
||||
const ux = -ny / l;
|
||||
const uy = nx / l;
|
||||
const k = ux * d3(points[i], x) + uy * d3(points[i], y);
|
||||
m00 += ux * ux;
|
||||
m01 += ux * uy;
|
||||
m11 += uy * uy;
|
||||
b0 += ux * k;
|
||||
b1 += uy * k;
|
||||
used++;
|
||||
}
|
||||
const det = m00 * m11 - m01 * m01;
|
||||
if (used < 6 || Math.abs(det) < 1e-9 * used * used) return null;
|
||||
const cx = (b0 * m11 - b1 * m01) / det;
|
||||
const cy = (m00 * b1 - m01 * b0) / det;
|
||||
// (A point of the line, level with the face's points.)
|
||||
let along = 0;
|
||||
for (let i = 0; i < n; i++) along += d3(points[i], dir) / n;
|
||||
return { origin: [x[0] * cx + y[0] * cy + dir[0] * along, x[1] * cx + y[1] * cy + dir[1] * along, x[2] * cx + y[2] * cy + dir[2] * along], dir };
|
||||
}
|
||||
|
||||
export const JOINT_NAMES: Record<JointType, string> = { fixed: "Fixed", hinge: "Hinge", slide: "Slide", screw: "Screw" };
|
||||
@@ -8,6 +8,7 @@
|
||||
import type { MaterialDef } from "../doc/types";
|
||||
import type { BodyProps } from "../kernel/protocol";
|
||||
import { el } from "../ui/ui";
|
||||
import { caretToEnd, textField } from "../ui/textField";
|
||||
import { icons } from "../ui/icons";
|
||||
import type { ToolPointer } from "../view/input";
|
||||
import { hitToSel, type AppContext, type Sel, type Tool } from "../tools/tool";
|
||||
@@ -16,6 +17,7 @@ import { allMaterials, assignMaterial, fmtMass, fmtVolume, massOf, MATERIAL_CLAS
|
||||
export { fmtArea, fmtMass, fmtVolume } from "./materials";
|
||||
import { openSheet } from "./sheet";
|
||||
import { openDrawing } from "./drawing";
|
||||
import { AssemblyTool } from "../assembly/assemblyTool";
|
||||
|
||||
/** Each body's properties, measured on the solids (kept until the project changes). */
|
||||
export async function measureBodies(app: AppContext): Promise<Map<string, BodyProps>> {
|
||||
@@ -48,18 +50,17 @@ export class BimTool implements Tool {
|
||||
}
|
||||
|
||||
enter(): void {
|
||||
const soon = "Coming next";
|
||||
this.app.ui.setTools([
|
||||
{ id: "exit", label: "Exit BIM", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) },
|
||||
{ id: "bimMaterials", label: "Materials", icon: "bim", active: true, sub: "a material for each body" },
|
||||
{ id: "bimSheet", label: "Technical Sheet", icon: "sheet", sub: "parts, masses, data", run: () => openSheet(this.app) },
|
||||
{ id: "bimDrawings", label: "Drawings", icon: "drawing", sub: "views, dimensions, balloons", run: () => openDrawing(this.app) },
|
||||
{ id: "bimAssemblies", label: "Assemblies", icon: "assembly", disabled: true, why: soon },
|
||||
{ id: "bimAssemblies", label: "Assemblies", icon: "assembly", sub: "joints: how the parts move", run: () => this.app.setTool(new AssemblyTool(this.app)) },
|
||||
]);
|
||||
this.app.ui.setBottom(this.app.bottomTools());
|
||||
this.app.ui.setHint("Tap a body, then its material. The material's data gives the body its mass.");
|
||||
this.card = el("div", "bim-card");
|
||||
this.body = el("div", "bim-body");
|
||||
this.body = el("div", "bim-inner");
|
||||
this.card.append(this.header(), this.body);
|
||||
document.body.append(this.card);
|
||||
this.putCard(BimTool.spot());
|
||||
@@ -256,16 +257,15 @@ export class BimTool implements Tool {
|
||||
card.append(info);
|
||||
|
||||
// ---- The library, by class; search to narrow it.
|
||||
const find = el("input", "bim-search");
|
||||
find.type = "search";
|
||||
const find = textField("bim-search");
|
||||
find.placeholder = "Search materials (steel, PLA, oak…)";
|
||||
find.value = this.search;
|
||||
find.addEventListener("input", () => {
|
||||
this.search = find.value;
|
||||
this.render();
|
||||
const again = this.card?.querySelector<HTMLInputElement>(".bim-search");
|
||||
const again = this.card?.querySelector<HTMLElement>(".bim-search");
|
||||
again?.focus();
|
||||
again?.setSelectionRange(again.value.length, again.value.length);
|
||||
if (again) caretToEnd(again);
|
||||
});
|
||||
card.append(find);
|
||||
const box = el("div", "bim-materials");
|
||||
|
||||
@@ -9,13 +9,14 @@ import type { DimText, DrawingDim, DrawingMark, DrawingNote, DrawingOptions, Pro
|
||||
import type { ProjectedView, ViewSpec } from "../kernel/protocol";
|
||||
import { icons, type IconName } from "../ui/icons";
|
||||
import { el, textButton } from "../ui/ui";
|
||||
import { textField as typingBox } from "../ui/textField";
|
||||
import { UNIT_MM } from "../units";
|
||||
import type { AppContext } from "../tools/tool";
|
||||
import { measureBodies } from "./bimTool";
|
||||
import { SheetCamera } from "./sheetCamera";
|
||||
import { sheetToDXF } from "../io/sheetDxf";
|
||||
import { zip } from "../io/threemf";
|
||||
import { partsList, type PartRow } from "./sheet";
|
||||
import { partsList, printPage, type PartRow } from "./sheet";
|
||||
import {
|
||||
arrangeDims,
|
||||
drawingsOf,
|
||||
@@ -291,6 +292,10 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
let picks: Pick[] = [];
|
||||
/** While dragging: the drawing as it would be (committed when let go). */
|
||||
let draft: DrawingOptions | null = null;
|
||||
/** Where each item number's circle is drawn now (dragged from there). */
|
||||
let balloonsNow: { id: string; x: number; y: number }[] = [];
|
||||
/** Where the one being dragged started. */
|
||||
let balloonFrom: [number, number] | null = null;
|
||||
const date = new Date();
|
||||
/** The sheet as printed or saved (made then: each redraw needn't). */
|
||||
const sheetOut = () => drawingSVG({ doc: docNow(), views, parts, date }).svg;
|
||||
@@ -384,6 +389,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
const doc = docNow();
|
||||
const made = drawingSVG({ doc, views, parts, date, interactive: true, selected });
|
||||
layout = made.layout;
|
||||
balloonsNow = made.balloons;
|
||||
paper.innerHTML = made.svg;
|
||||
const s = paper.querySelector("svg");
|
||||
if (s) {
|
||||
@@ -399,6 +405,32 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
applyCamera();
|
||||
}
|
||||
if (!fetching) name.textContent = `Drawing · ${drawingOptions(doc).title}`;
|
||||
// Its number or its words are what a dimension or a note is grabbed by: a see-through pad round each, a finger
|
||||
// wide on the screen (the text of a dimension is 3 mm tall on the paper - a few pixels with the sheet all in view).
|
||||
if (s) {
|
||||
const pad = Math.max(1.2, tolerance() * 0.6);
|
||||
for (const g of Array.from(s.querySelectorAll<SVGGElement>("[data-ann]"))) {
|
||||
for (const tx of Array.from(g.querySelectorAll<SVGTextElement>("text"))) {
|
||||
let b: DOMRect;
|
||||
try {
|
||||
b = tx.getBBox();
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!b.width && !b.height) continue;
|
||||
const r = document.createElementNS("http://www.w3.org/2000/svg", "rect");
|
||||
r.setAttribute("x", String(b.x - pad));
|
||||
r.setAttribute("y", String(b.y - pad));
|
||||
r.setAttribute("width", String(b.width + pad * 2));
|
||||
r.setAttribute("height", String(b.height + pad * 2));
|
||||
r.setAttribute("fill", "transparent");
|
||||
r.setAttribute("class", "bim-ann-pad");
|
||||
const tf = tx.getAttribute("transform");
|
||||
if (tf) r.setAttribute("transform", tf);
|
||||
tx.before(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (s) s.insertAdjacentHTML("beforeend", picksSVG());
|
||||
hoverKey = "";
|
||||
drawHover();
|
||||
@@ -461,7 +493,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
|
||||
// ---- Tapping and dragging on the sheet
|
||||
let frame = 0;
|
||||
let drag: { id: number; x: number; y: number; target: string; moved: boolean; start: DrawingOptions } | null = null;
|
||||
let drag: { id: number; x: number; y: number; target: string; moved: boolean; start: DrawingOptions; tap?: { q: P2; e: PointerEvent } } | null = null;
|
||||
/** The fingers (or the mouse) down on the paper, where they are (px). */
|
||||
const fingers = new Map<number, [number, number]>();
|
||||
let pinch: { d: number; mid: [number, number] } | null = null;
|
||||
@@ -504,6 +536,15 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
const q = sheetPoint(e);
|
||||
if (!q || !layout) return;
|
||||
if (tool) {
|
||||
// A dimension, a note or a picture already on the sheet, pressed with a tool still on: dragged from there it
|
||||
// moves (the tool stays on); just tapped, the tap is the tool's as ever. (A dimension is put on, and the next
|
||||
// thing a hand does is drag it where it reads well - which put on another, or did nothing.)
|
||||
const there = (e.target as Element).closest?.("[data-ann]")?.getAttribute("data-ann");
|
||||
if (there && !picks.length) {
|
||||
e.preventDefault();
|
||||
drag = { id: e.pointerId, x: q[0], y: q[1], target: there, moved: false, start: structuredClone(curDrawing() ?? {}), tap: { q, e } };
|
||||
return;
|
||||
}
|
||||
// Off the paper (the grey round it): nothing to pick, no note out there.
|
||||
const [W, H] = sheetSize(opts());
|
||||
if (q[0] < 0 || q[1] < 0 || q[0] > W || q[1] > H) return;
|
||||
@@ -572,9 +613,17 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
if (!drag || e.pointerId !== drag.id || !layout) return;
|
||||
const q = sheetPoint(e);
|
||||
if (!q) return;
|
||||
// (A dimension, a note or a picture stays on the paper: dragged past its edge it stops there - one pulled off
|
||||
// the sheet was out of the print, and with a tool on could not be got back.)
|
||||
if (!drag.target.startsWith("view:")) {
|
||||
const [W, H] = sheetSize(opts());
|
||||
q[0] = Math.min(W - 2, Math.max(2, q[0]));
|
||||
q[1] = Math.min(H - 2, Math.max(2, q[1]));
|
||||
}
|
||||
const dx = q[0] - drag.x;
|
||||
const dy = q[1] - drag.y;
|
||||
if (!drag.moved && Math.hypot(dx, dy) < tolerance() / 4) return;
|
||||
if (!drag.moved) balloonFrom = null;
|
||||
drag.moved = true;
|
||||
const next: DrawingOptions = structuredClone(drag.start);
|
||||
const o = drawingOptions({ ...store.doc, drawing: drag.start });
|
||||
@@ -609,6 +658,14 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
}
|
||||
} else {
|
||||
const id = drag.target;
|
||||
if (id.startsWith("balloon:")) {
|
||||
// An item number: its circle goes where it is dragged (its line still runs to its part).
|
||||
if (!drag.moved || !balloonFrom) {
|
||||
const b = balloonsNow.find((x) => x.id === id);
|
||||
balloonFrom = b ? [b.x, b.y] : [drag.x, drag.y];
|
||||
}
|
||||
next.balloonAt = { ...o.balloonAt, [id.slice(8)]: [balloonFrom[0] + dx, balloonFrom[1] + dy] };
|
||||
}
|
||||
const dim = dimsOf(o).find((d) => d.id === id);
|
||||
const note = o.notes.find((n) => n.id === id);
|
||||
const img = o.images.find((m) => m.id === id);
|
||||
@@ -643,10 +700,12 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
}
|
||||
if (!drag || e.pointerId !== drag.id) return;
|
||||
const moved = drag.moved;
|
||||
const tap = drag.tap;
|
||||
drag = null;
|
||||
const d = draft;
|
||||
draft = null;
|
||||
if (moved && d) store.commit((doc) => putDrawing(doc, current, d));
|
||||
else if (tap && tool) useTool(tap.q, tap.e);
|
||||
else render();
|
||||
};
|
||||
paper.addEventListener("pointerup", endDrag);
|
||||
@@ -1123,7 +1182,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
const noteInput = (q: [number, number], cx: number, cy: number, edit?: DrawingNote, to?: DrawingNote["to"]) => {
|
||||
// One being written already: kept as it is.
|
||||
closeNote?.();
|
||||
const input = el("input", "bim-note-input");
|
||||
const input = typingBox("bim-note-input");
|
||||
input.placeholder = "Note";
|
||||
input.value = edit?.text ?? "";
|
||||
const r = stage.getBoundingClientRect();
|
||||
@@ -1160,6 +1219,12 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
if (!id) return;
|
||||
selected = null;
|
||||
const o = opts();
|
||||
if (id.startsWith("balloon:")) {
|
||||
// (An item number is the parts list's: it is not taken off here - Balloons, in Properties, does that for all
|
||||
// of them. One moved by hand goes back to where the sheet puts it.)
|
||||
const { [id.slice(8)]: _gone, ...rest } = o.balloonAt;
|
||||
return void set({ balloonAt: Object.keys(rest).length ? rest : undefined });
|
||||
}
|
||||
if (id.startsWith("view:")) {
|
||||
const v = id.slice(5);
|
||||
// A section, a detail or an added view: gone with what was put on it, and the views made from it.
|
||||
@@ -1179,7 +1244,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
extra: keep(o.extra),
|
||||
dims: keep(o.dims),
|
||||
marks: keep(o.marks),
|
||||
notes: o.notes.map((n) => (n.to && gone.has(n.to.view) ? { id: n.id, x: n.x, y: n.y, text: n.text } : n)),
|
||||
notes: o.notes.map((n) => (n.to && gone.has(n.to.view) ? { id: n.id, x: n.x, y: n.y, text: n.text, ...(n.size ? { size: n.size } : {}) } : n)),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1222,8 +1287,12 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
chip.hidden = true;
|
||||
if (tool) return;
|
||||
hint.innerHTML = "";
|
||||
hint.hidden = !selected;
|
||||
if (!selected) return;
|
||||
hint.hidden = false;
|
||||
if (!selected) {
|
||||
// Nothing picked, no tool on: what can be done from here (it said nothing, and the sheet looked like a picture).
|
||||
hint.append(el("span", "bim-idle-hint", "Drag a dimension or a note to move it. Tap a view for its handle. Double-tap text to edit it. Tools are on the left."));
|
||||
return;
|
||||
}
|
||||
const id = selected;
|
||||
const o = opts();
|
||||
const button = (label: string, run: () => void, on = false) => {
|
||||
@@ -1279,6 +1348,20 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
const d = dimsOf(o).find((x) => x.id === id);
|
||||
const n = o.notes.find((x) => x.id === id);
|
||||
const img = o.images.find((x) => x.id === id);
|
||||
if (id.startsWith("balloon:")) {
|
||||
hint.append(el("span", "", "Item number"));
|
||||
hint.append(el("span", "bim-sub", "Drag it where it reads well"));
|
||||
// (Put by hand: back to where the sheet puts it.)
|
||||
if (o.balloonAt[id.slice(8)]) {
|
||||
button("Put back", () => {
|
||||
const { [id.slice(8)]: _gone, ...rest } = o.balloonAt;
|
||||
selected = null;
|
||||
set({ balloonAt: Object.keys(rest).length ? rest : undefined });
|
||||
});
|
||||
}
|
||||
button("Done", () => ((selected = null), render()), true);
|
||||
return;
|
||||
}
|
||||
if (img) {
|
||||
hint.append(el("span", "", "Picture"));
|
||||
// Bigger or smaller about its middle.
|
||||
@@ -1299,10 +1382,8 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
button("Max", () => flip(true), !!d.max);
|
||||
}
|
||||
// How far out from what it measures, typed (mm on the paper).
|
||||
const far = el("input", "bim-input bim-dim-far");
|
||||
far.type = "number";
|
||||
far.min = "1";
|
||||
far.step = "1";
|
||||
const far = typingBox("bim-input bim-dim-far");
|
||||
far.inputMode = "decimal";
|
||||
far.value = String(Math.round(Math.abs(d.offset) * 10) / 10);
|
||||
far.title = "How far out from what it measures (mm on the paper)";
|
||||
far.addEventListener("change", () => {
|
||||
@@ -1318,6 +1399,20 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
button("Text and tolerance", () => void editDim(d));
|
||||
} else if (n) {
|
||||
hint.append(el("span", "", "Note"));
|
||||
// How tall its letters are: a step smaller or bigger (2.5 to 14 mm on the paper).
|
||||
const SIZES = [2.5, 3.5, 5, 7, 10, 14];
|
||||
const now = n.size ?? 3.5;
|
||||
const at = SIZES.reduce((best, s, i) => (Math.abs(s - now) < Math.abs(SIZES[best] - now) ? i : best), 0);
|
||||
const resize = (to: number) => set({ notes: o.notes.map((x) => (x === n ? { ...x, size: SIZES[to] === 3.5 ? undefined : SIZES[to] } : x)) });
|
||||
const smaller = el("button", "text-btn", "A−");
|
||||
smaller.title = "Smaller text";
|
||||
(smaller as HTMLButtonElement).disabled = at === 0;
|
||||
smaller.addEventListener("click", () => resize(at - 1));
|
||||
const bigger = el("button", "text-btn", "A+");
|
||||
bigger.title = "Bigger text";
|
||||
(bigger as HTMLButtonElement).disabled = at === SIZES.length - 1;
|
||||
bigger.addEventListener("click", () => resize(at + 1));
|
||||
hint.append(smaller, el("span", "bim-sub", `${now} mm`), bigger);
|
||||
button("Edit", () => {
|
||||
const [cx, cy] = clientOf([n.x, n.y]);
|
||||
noteInput([n.x, n.y], cx, cy, n);
|
||||
@@ -1415,7 +1510,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
back.append(box);
|
||||
back.addEventListener("pointerdown", (e) => e.target === back && done(false));
|
||||
document.body.append(back);
|
||||
(list.querySelector("input, select") as HTMLElement | null)?.focus();
|
||||
(list.querySelector("input, select, .text-field") as HTMLElement | null)?.focus();
|
||||
});
|
||||
const select = (value: string, options: [string, string][]) => {
|
||||
const s = el("select", "bim-select");
|
||||
@@ -1428,10 +1523,9 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
return s;
|
||||
};
|
||||
const input = (value: string, placeholder = "") => {
|
||||
const i = el("input", "");
|
||||
const i = typingBox();
|
||||
i.value = value;
|
||||
i.placeholder = placeholder;
|
||||
i.autocomplete = "off";
|
||||
return i;
|
||||
};
|
||||
|
||||
@@ -1513,6 +1607,28 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
removeSelected();
|
||||
} else if (e.key.startsWith("Arrow") && selected && !tool && !selected.startsWith("view:")) {
|
||||
// The arrows nudge what is picked: half a millimetre on the paper (Shift: five). A note or a picture any
|
||||
// way; a dimension nearer to or further from what it measures (up and right: further).
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const step = e.shiftKey ? 5 : 0.5;
|
||||
const dx = e.key === "ArrowLeft" ? -step : e.key === "ArrowRight" ? step : 0;
|
||||
const dy = e.key === "ArrowUp" ? -step : e.key === "ArrowDown" ? step : 0;
|
||||
const o = opts();
|
||||
const id = selected;
|
||||
const note = o.notes.find((n) => n.id === id);
|
||||
const img = o.images.find((m) => m.id === id);
|
||||
const dim = dimsOf(o).find((d) => d.id === id);
|
||||
const ball = id.startsWith("balloon:") ? balloonsNow.find((b) => b.id === id) : undefined;
|
||||
if (ball) set({ balloonAt: { ...o.balloonAt, [id.slice(8)]: [ball.x + dx, ball.y + dy] } });
|
||||
else if (note) set({ notes: o.notes.map((n) => (n === note ? { ...n, x: note.x + dx, y: note.y + dy } : n)) });
|
||||
else if (img) set({ images: o.images.map((m) => (m === img ? { ...m, x: img.x + dx, y: img.y + dy } : m)) });
|
||||
else if (dim) {
|
||||
const out = dx - dy;
|
||||
const far = Math.max(1, Math.abs(dim.offset) + out);
|
||||
set(withDim(o, { ...dim, offset: (Math.sign(dim.offset) || 1) * far }));
|
||||
}
|
||||
} else if (!e.ctrlKey && !e.metaKey && !e.altKey && ["+", "=", "-", "_", "f", "F", "0"].includes(e.key)) {
|
||||
// Zoom in / out, all of the sheet.
|
||||
e.preventDefault();
|
||||
@@ -1545,7 +1661,13 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
into.append(b);
|
||||
};
|
||||
button("Exit Drawing", "close", shut);
|
||||
const pick = (t: ToolId, label: string, icon: IconName) => button(label, icon, () => startTool(tool === t ? null : t), { on: tool === t, sub: true });
|
||||
// (A phone: a group's tools are listed by name over the sheet; one picked, the list folds away and the sheet is
|
||||
// clear to tap - the bar at the top says which tool is on.)
|
||||
const pick = (t: ToolId, label: string, icon: IconName) =>
|
||||
button(label, icon, () => {
|
||||
if (document.documentElement.dataset.screen === "phone" && tool !== t) open = null;
|
||||
startTool(tool === t ? null : t);
|
||||
}, { on: tool === t, sub: true });
|
||||
button("Views", "views", () => ((open = open === "views" ? null : "views"), renderTools()), { on: open === "views" || tool === "section" || tool === "detail" || tool === "base" || tool === "projection" });
|
||||
if (open === "views") {
|
||||
const toggle = (k: "front" | "top" | "side" | "iso", label: string) =>
|
||||
@@ -1614,8 +1736,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
sheets.append(acts);
|
||||
// Many drawings: a box to find one by its title (the list narrows as it's typed).
|
||||
if (listed.length > 8) {
|
||||
const find = el("input", "bim-input bim-dfind");
|
||||
find.type = "search";
|
||||
const find = typingBox("bim-input bim-dfind");
|
||||
find.placeholder = `Find among ${listed.length}…`;
|
||||
find.value = listFilter;
|
||||
find.addEventListener("keydown", (e) => e.stopPropagation());
|
||||
@@ -1677,7 +1798,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
return s;
|
||||
};
|
||||
const textField = (value: string, change: (v: string) => void) => {
|
||||
const i = el("input", "bim-input");
|
||||
const i = typingBox("bim-input");
|
||||
i.value = value;
|
||||
i.placeholder = "-";
|
||||
i.addEventListener("change", () => change(i.value.trim()));
|
||||
@@ -1874,11 +1995,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
const holder = el("div", "bim-drawing-print");
|
||||
holder.innerHTML = sheetOut();
|
||||
document.body.append(holder);
|
||||
document.body.classList.add("printing-drawing");
|
||||
window.print();
|
||||
document.body.classList.remove("printing-drawing");
|
||||
holder.remove();
|
||||
page.remove();
|
||||
printPage("printing-drawing", holder, page);
|
||||
});
|
||||
svgBtn.addEventListener("click", () => {
|
||||
const a = document.createElement("a");
|
||||
@@ -1938,11 +2055,7 @@ export async function openDrawing(app: AppContext, which?: string): Promise<void
|
||||
holder.append(one);
|
||||
}
|
||||
document.body.append(holder);
|
||||
document.body.classList.add("printing-drawing");
|
||||
window.print();
|
||||
document.body.classList.remove("printing-drawing");
|
||||
holder.remove();
|
||||
page.remove();
|
||||
printPage("printing-drawing", holder, page);
|
||||
};
|
||||
const printAll = async () => {
|
||||
const sheets = await allSheets("Print");
|
||||
|
||||
@@ -77,6 +77,7 @@ export function drawingOptions(doc: ProjectDoc) {
|
||||
comma: o.comma ?? false,
|
||||
lines: { visible: o.lines?.visible ?? 0.5, hidden: o.lines?.hidden ?? 0.25, dims: o.lines?.dims ?? 0.25, center: o.lines?.center ?? 0.25, section: o.lines?.section ?? 0.18 },
|
||||
balloons: o.balloons ?? true,
|
||||
balloonAt: o.balloonAt ?? {},
|
||||
overall: o.overall ?? true,
|
||||
overallDims: o.overallDims ?? {},
|
||||
moved: o.moved ?? {},
|
||||
@@ -529,7 +530,7 @@ function placePath(d: string, p: Placed): string {
|
||||
|
||||
function text(x: number, y: number, t: string, size: number, opts: { anchor?: string; angle?: number; weight?: string; fill?: string } = {}): string {
|
||||
const rot = opts.angle ? ` transform="rotate(${f(opts.angle)} ${f(x)} ${f(y)})"` : "";
|
||||
return `<text x="${f(x)}" y="${f(y)}" font-size="${size}" ${FONT} text-anchor="${opts.anchor ?? "start"}"${opts.weight ? ` font-weight="${opts.weight}"` : ""} fill="${opts.fill ?? "#000"}"${rot}>${esc(t)}</text>`;
|
||||
return `<text x="${f(x)}" y="${f(y)}" font-size="${f(+size)}" ${FONT} text-anchor="${esc(String(opts.anchor ?? "start"))}"${opts.weight ? ` font-weight="${esc(String(opts.weight))}"` : ""} fill="${esc(String(opts.fill ?? "#000"))}"${rot}>${esc(t)}</text>`;
|
||||
}
|
||||
|
||||
/** A rough width of a text (Arial: about 0.55 of its size a letter). */
|
||||
@@ -684,7 +685,7 @@ export interface SheetData {
|
||||
}
|
||||
|
||||
/** The whole sheet as an SVG document (mm). */
|
||||
export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
export function drawingSVG(data: SheetData): { svg: string; layout: Layout; balloons: { id: string; x: number; y: number }[] } {
|
||||
const { doc, views, parts } = data;
|
||||
const o = drawingOptions(doc);
|
||||
const L = layoutSheet(views, o, parts.length);
|
||||
@@ -750,7 +751,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
for (const im of o.images) {
|
||||
const sel = data.interactive && data.selected === im.id;
|
||||
const svg = `<image href="${esc(im.src)}" x="${f(im.x)}" y="${f(im.y)}" width="${f(im.w)}" height="${f(im.h)}" preserveAspectRatio="none"/>${sel ? `<rect x="${f(im.x)}" y="${f(im.y)}" width="${f(im.w)}" height="${f(im.h)}" fill="none" stroke="${SEL}" stroke-width="0.4" stroke-dasharray="2 1"/>` : ""}`;
|
||||
out.push(data.interactive ? `<g data-ann="${im.id}">${svg}</g>` : svg);
|
||||
out.push(data.interactive ? `<g data-ann="${esc(String(im.id))}">${svg}</g>` : svg);
|
||||
}
|
||||
for (const p of L.views) {
|
||||
const v = views.get(p.src ?? p.id);
|
||||
@@ -788,7 +789,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
}
|
||||
if (sec) g.push(text((r.x0 + r.x1) / 2, r.y1 + 8, `${sec.letter}-${sec.letter}`, 5, { anchor: "middle", fill: c }));
|
||||
if (det) g.push(text((r.x0 + r.x1) / 2, r.y1 + 8, `${det.letter} (${scaleLabel(p.s)})`, 5, { anchor: "middle", fill: c }));
|
||||
out.push(data.interactive ? `<g data-view="${p.id}">${g.join("")}</g>` : g.join("\n"));
|
||||
out.push(data.interactive ? `<g data-view="${esc(String(p.id))}">${g.join("")}</g>` : g.join("\n"));
|
||||
}
|
||||
|
||||
// ---- Where the sections are cut (ISO 128-40: a chain line, thick at its
|
||||
@@ -798,7 +799,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
const p = placed.get(sec.view);
|
||||
if (!p || !placed.has(sec.id)) continue;
|
||||
const c = color(`view:${sec.id}`);
|
||||
out.push(`<g${data.interactive ? ` data-view="${sec.id}"` : ""}>${cutLine(toPaper(p, sec.a), toPaper(p, sec.b), sec.look, sec.letter, lw, c)}</g>`);
|
||||
out.push(`<g${data.interactive ? ` data-view="${esc(String(sec.id))}"` : ""}>${cutLine(toPaper(p, sec.a), toPaper(p, sec.b), sec.look, sec.letter, lw, c)}</g>`);
|
||||
}
|
||||
for (const det of o.details) {
|
||||
const p = placed.get(det.view);
|
||||
@@ -808,7 +809,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
const R = det.r * p.s;
|
||||
const at: [number, number] = [C[0] + (R + 2.5) * Math.SQRT1_2, C[1] - (R + 2.5) * Math.SQRT1_2];
|
||||
out.push(
|
||||
`<g${data.interactive ? ` data-view="${det.id}"` : ""}><circle cx="${f(C[0])}" cy="${f(C[1])}" r="${f(R)}" stroke="${c}" stroke-width="${lw.dims}" fill="none"/>${text(at[0], at[1], det.letter, 5, { fill: c })}</g>`,
|
||||
`<g${data.interactive ? ` data-view="${esc(String(det.id))}"` : ""}><circle cx="${f(C[0])}" cy="${f(C[1])}" r="${f(R)}" stroke="${c}" stroke-width="${lw.dims}" fill="none"/>${text(at[0], at[1], det.letter, 5, { fill: c })}</g>`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -817,7 +818,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
const p = placed.get(m.view);
|
||||
if (!p) continue;
|
||||
const svg = markSVG(m, p, lw.center, color(m.id));
|
||||
out.push(data.interactive ? `<g data-ann="${m.id}">${svg}</g>` : svg);
|
||||
out.push(data.interactive ? `<g data-ann="${esc(String(m.id))}">${svg}</g>` : svg);
|
||||
}
|
||||
|
||||
// ---- Overall dimensions (width and height on the front view, depth on the
|
||||
@@ -827,13 +828,13 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
if (!p) continue;
|
||||
const c = color(d.id);
|
||||
const svg = dimSVG(d, p, o, c);
|
||||
out.push(data.interactive ? `<g data-ann="${d.id}">${svg}</g>` : svg);
|
||||
out.push(data.interactive ? `<g data-ann="${esc(String(d.id))}">${svg}</g>` : svg);
|
||||
}
|
||||
|
||||
// ---- Notes (pointing at what they are about).
|
||||
for (const n of o.notes) {
|
||||
const svg = noteSVG(n, n.to ? placed.get(n.to.view) : undefined, lw.dims, color(n.id));
|
||||
out.push(data.interactive ? `<g data-ann="${n.id}">${svg}</g>` : svg);
|
||||
out.push(data.interactive ? `<g data-ann="${esc(String(n.id))}">${svg}</g>` : svg);
|
||||
}
|
||||
|
||||
// ---- Balloons: item numbers of the parts list, each on the isometric view - or,
|
||||
@@ -841,6 +842,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
// housing, seen in no view, points at its hidden lines.
|
||||
const hosts = ["iso", "front", L.side, "top", ...o.extra.map((v) => v.id)].map((id) => placed.get(id)).filter((p): p is Placed => !!p);
|
||||
const byHost = new Map<Placed, { item: number; at: [number, number] }[]>();
|
||||
const balloonsAt: { id: string; x: number; y: number }[] = [];
|
||||
const spot = (r: PartRow) => {
|
||||
for (const p of hosts) {
|
||||
const b = views.get(p.id)?.bodies.find((x) => x.id === r.id);
|
||||
@@ -906,13 +908,21 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
taken.push([x, y]);
|
||||
}
|
||||
for (const b of spots) {
|
||||
const dx = b.at[0] - b.x;
|
||||
const dy = b.at[1] - b.y;
|
||||
// Put somewhere by hand: there (its line still runs to its part).
|
||||
const part = parts.find((r) => r.item === b.item)?.id ?? String(b.item);
|
||||
const id = `balloon:${part}`;
|
||||
const [bx, by] = o.balloonAt[part] ?? [b.x, b.y];
|
||||
const c = color(id);
|
||||
const dx = b.at[0] - bx;
|
||||
const dy = b.at[1] - by;
|
||||
const d = Math.hypot(dx, dy) || 1;
|
||||
out.push(`<path d="M${f(b.x + (dx / d) * 4)} ${f(b.y + (dy / d) * 4)}L${f(b.at[0])} ${f(b.at[1])}" stroke="#000" stroke-width="${lw.dims}"/>`);
|
||||
out.push(`<circle cx="${f(b.at[0])}" cy="${f(b.at[1])}" r="0.6" fill="#000"/>`);
|
||||
out.push(`<circle cx="${f(b.x)}" cy="${f(b.y)}" r="4" stroke="#000" stroke-width="0.35" fill="#fff"/>`);
|
||||
out.push(text(b.x, b.y + 1.4, String(b.item), 4, { anchor: "middle" }));
|
||||
const svg =
|
||||
`<path d="M${f(bx + (dx / d) * 4)} ${f(by + (dy / d) * 4)}L${f(b.at[0])} ${f(b.at[1])}" stroke="${c}" stroke-width="${lw.dims}"/>` +
|
||||
`<circle cx="${f(b.at[0])}" cy="${f(b.at[1])}" r="0.6" fill="${c}"/>` +
|
||||
`<circle cx="${f(bx)}" cy="${f(by)}" r="4" stroke="${c}" stroke-width="0.35" fill="#fff"/>` +
|
||||
text(bx, by + 1.4, String(b.item), 4, { anchor: "middle", fill: c });
|
||||
out.push(data.interactive ? `<g data-ann="${esc(String(id))}">${svg}</g>` : svg);
|
||||
balloonsAt.push({ id, x: bx, y: by });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -923,7 +933,7 @@ export function drawingSVG(data: SheetData): { svg: string; layout: Layout } {
|
||||
else if (o.titleBlock === "horizontal") out.push(stripBlock(o, doc.info ?? {}, data.date, L));
|
||||
else if (o.titleBlock === "vertical") out.push(columnBlock(o, doc.info ?? {}, data.date, L));
|
||||
out.push(`</svg>`);
|
||||
return { svg: out.join("\n"), layout: L };
|
||||
return { svg: out.join("\n"), layout: L, balloons: balloonsAt };
|
||||
}
|
||||
|
||||
/** Dimension lines (ISO 129-1): the first this far out from the view (mm on the paper), each next one this much further. */
|
||||
@@ -1270,12 +1280,13 @@ export function markSVG(m: DrawingMark, p: Placed, width: number, color = "#000"
|
||||
|
||||
/** A note: its text; pointing at something, a leader from the near end of its text with an arrow there. */
|
||||
export function noteSVG(n: DrawingNote, p: Placed | undefined, width: number, color = "#000"): string {
|
||||
let out = text(n.x, n.y, n.text, 3.5, { fill: color });
|
||||
const size = n.size ?? 3.5;
|
||||
let out = text(n.x, n.y, n.text, size, { fill: color });
|
||||
if (n.to && p) {
|
||||
const P = toPaper(p, n.to.p);
|
||||
const w = textWidth(n.text, 3.5);
|
||||
const w = textWidth(n.text, size);
|
||||
const toLeft = P[0] < n.x + w / 2;
|
||||
const E: [number, number] = [toLeft ? n.x - 1 : n.x + w + 1, n.y - 1.2];
|
||||
const E: [number, number] = [toLeft ? n.x - 1 : n.x + w + 1, n.y - size * 0.34];
|
||||
const S: [number, number] = [E[0] + (toLeft ? -2.5 : 2.5), E[1]];
|
||||
const d = Math.hypot(P[0] - S[0], P[1] - S[1]) || 1;
|
||||
out += `<path d="M${f(E[0])} ${f(E[1])}L${f(S[0])} ${f(S[1])}L${f(P[0])} ${f(P[1])}" stroke="${color}" stroke-width="${width}" fill="none"/>`;
|
||||
|
||||
@@ -8,49 +8,124 @@
|
||||
// Values: strengths are the minimums the named standard gives the grade,
|
||||
// where it has one; the rest are typical values for the material. Thermal
|
||||
// values for building materials are the ISO 10456 design values. A supplier's
|
||||
// own data sheet comes first wherever it differs.
|
||||
// own data sheet comes first wherever it differs. A ductile metal's
|
||||
// compressive strength is its yield; wood's are along the grain; an
|
||||
// insulation's compressive strength is the stress that squeezes it by 10 %.
|
||||
|
||||
import type { MaterialDef, ProjectDoc } from "../doc/types";
|
||||
import { trim, UNIT_LABEL, UNIT_MM, units } from "../units";
|
||||
|
||||
export const MATERIAL_CLASSES = ["Metal", "Plastic", "Concrete & masonry", "Wood", "Glass & stone", "Insulation & boards"] as const;
|
||||
export const MATERIAL_CLASSES = ["Metal", "Plastic", "Composite", "Concrete & masonry", "Wood", "Glass & stone", "Ceramic & other", "Insulation & boards"] as const;
|
||||
|
||||
export const MATERIALS: MaterialDef[] = [
|
||||
// ---- Metals
|
||||
{ id: "steel-s235", name: "Structural steel S235JR", category: "Metal", standard: "EN 10025-2", color: "#8f959c", density: 7850, youngs: 210, poisson: 0.3, yield: 235, tensile: 360, expansion: 12, conductivity: 53, specificHeat: 440 },
|
||||
{ id: "steel-s355", name: "Structural steel S355J2", category: "Metal", standard: "EN 10025-2", color: "#888e96", density: 7850, youngs: 210, poisson: 0.3, yield: 355, tensile: 470, expansion: 12, conductivity: 53, specificHeat: 440 },
|
||||
{ id: "ss-304", name: "Stainless steel 1.4301 (304)", category: "Metal", standard: "EN 10088-2", color: "#b8bec5", density: 7900, youngs: 200, poisson: 0.3, yield: 210, tensile: 520, expansion: 16, conductivity: 15, specificHeat: 500 },
|
||||
{ id: "ss-316", name: "Stainless steel 1.4401 (316)", category: "Metal", standard: "EN 10088-2", color: "#b3b9c0", density: 8000, youngs: 200, poisson: 0.3, yield: 220, tensile: 520, expansion: 16, conductivity: 15, specificHeat: 500 },
|
||||
{ id: "al-6061", name: "Aluminium EN AW-6061-T6", category: "Metal", standard: "EN 755-2", color: "#c9ced4", density: 2700, youngs: 70, poisson: 0.3, yield: 240, tensile: 260, expansion: 23, conductivity: 167, specificHeat: 896 },
|
||||
{ id: "al-6082", name: "Aluminium EN AW-6082-T6", category: "Metal", standard: "EN 1999-1-1", color: "#c4c9cf", density: 2700, youngs: 70, poisson: 0.3, yield: 260, tensile: 310, expansion: 23, conductivity: 170, specificHeat: 900 },
|
||||
{ id: "cast-iron", name: "Grey cast iron EN-GJL-250", category: "Metal", standard: "EN 1561", color: "#5d6066", density: 7200, youngs: 110, poisson: 0.26, tensile: 250, expansion: 11, conductivity: 48, specificHeat: 460 },
|
||||
{ id: "brass", name: "Brass CW614N (CuZn39Pb3)", category: "Metal", standard: "EN 12164", color: "#c9a64e", density: 8470, youngs: 96, poisson: 0.34, yield: 250, tensile: 430, expansion: 21, conductivity: 113, specificHeat: 377 },
|
||||
{ id: "copper", name: "Copper Cu-ETP (CW004A)", category: "Metal", standard: "EN 13601", color: "#b87333", density: 8930, youngs: 117, poisson: 0.34, yield: 70, tensile: 200, expansion: 17, conductivity: 390, specificHeat: 385 },
|
||||
{ id: "ti-5", name: "Titanium Grade 5 (Ti-6Al-4V)", category: "Metal", standard: "ASTM B348", color: "#8c8e91", density: 4430, youngs: 114, poisson: 0.34, yield: 828, tensile: 895, expansion: 8.6, conductivity: 6.7, specificHeat: 526 },
|
||||
{ id: "steel-s235", name: "Structural steel S235JR", category: "Metal", standard: "EN 10025-2", color: "#8f959c", density: 7850, youngs: 210, poisson: 0.3, yield: 235, tensile: 360, compressive: 235, elongation: 26, expansion: 12, conductivity: 53, specificHeat: 440, melting: 1500 },
|
||||
{ id: "steel-s355", name: "Structural steel S355J2", category: "Metal", standard: "EN 10025-2", color: "#888e96", density: 7850, youngs: 210, poisson: 0.3, yield: 355, tensile: 470, compressive: 355, elongation: 22, expansion: 12, conductivity: 53, specificHeat: 440, melting: 1500 },
|
||||
{ id: "ss-304", name: "Stainless steel 1.4301 (304)", category: "Metal", standard: "EN 10088-2", color: "#b8bec5", density: 7900, youngs: 200, poisson: 0.3, yield: 210, tensile: 520, compressive: 210, elongation: 45, expansion: 16, conductivity: 15, specificHeat: 500, melting: 1450 },
|
||||
{ id: "ss-316", name: "Stainless steel 1.4401 (316)", category: "Metal", standard: "EN 10088-2", color: "#b3b9c0", density: 8000, youngs: 200, poisson: 0.3, yield: 220, tensile: 520, compressive: 220, elongation: 40, expansion: 16, conductivity: 15, specificHeat: 500, melting: 1400 },
|
||||
{ id: "al-6061", name: "Aluminium EN AW-6061-T6", category: "Metal", standard: "EN 755-2", color: "#c9ced4", density: 2700, youngs: 70, poisson: 0.3, yield: 240, tensile: 260, compressive: 240, elongation: 10, expansion: 23, conductivity: 167, specificHeat: 896, melting: 650 },
|
||||
{ id: "al-6082", name: "Aluminium EN AW-6082-T6", category: "Metal", standard: "EN 1999-1-1", color: "#c4c9cf", density: 2700, youngs: 70, poisson: 0.3, yield: 260, tensile: 310, compressive: 260, elongation: 10, expansion: 23, conductivity: 170, specificHeat: 900, melting: 650 },
|
||||
{ id: "cast-iron", name: "Grey cast iron EN-GJL-250", category: "Metal", standard: "EN 1561", color: "#5d6066", density: 7200, youngs: 110, poisson: 0.26, tensile: 250, compressive: 840, elongation: 0.5, expansion: 11, conductivity: 48, specificHeat: 460, melting: 1200 },
|
||||
{ id: "brass", name: "Brass CW614N (CuZn39Pb3)", category: "Metal", standard: "EN 12164", color: "#c9a64e", density: 8470, youngs: 96, poisson: 0.34, yield: 250, tensile: 430, compressive: 250, elongation: 15, expansion: 21, conductivity: 113, specificHeat: 377, melting: 900 },
|
||||
{ id: "copper", name: "Copper Cu-ETP (CW004A)", category: "Metal", standard: "EN 13601", color: "#b87333", density: 8930, youngs: 117, poisson: 0.34, yield: 70, tensile: 200, compressive: 70, elongation: 40, expansion: 17, conductivity: 390, specificHeat: 385, melting: 1083 },
|
||||
{ id: "ti-5", name: "Titanium Grade 5 (Ti-6Al-4V)", category: "Metal", standard: "ASTM B348", color: "#8c8e91", density: 4430, youngs: 114, poisson: 0.34, yield: 828, tensile: 895, compressive: 970, elongation: 10, expansion: 8.6, conductivity: 6.7, specificHeat: 526, melting: 1660 },
|
||||
{ id: "steel-c45", name: "Carbon steel C45 (1045)", category: "Metal", standard: "EN 10083-2", color: "#868c93", density: 7850, youngs: 210, poisson: 0.29, yield: 340, tensile: 620, compressive: 340, elongation: 14, expansion: 11.5, conductivity: 50, specificHeat: 486, melting: 1500 },
|
||||
{ id: "steel-42crmo4", name: "Alloy steel 42CrMo4 (4140), quenched & tempered", category: "Metal", standard: "EN 10083-3", color: "#7f858c", density: 7850, youngs: 210, poisson: 0.29, yield: 650, tensile: 900, compressive: 650, elongation: 12, expansion: 12.3, conductivity: 42.6, specificHeat: 473, melting: 1450 },
|
||||
{ id: "tool-d2", name: "Tool steel 1.2379 (D2)", category: "Metal", standard: "ISO 4957", note: "Hardened, 58-62 HRC", color: "#73797f", density: 7700, youngs: 210, poisson: 0.3, compressive: 2200, elongation: 1, expansion: 10.5, conductivity: 20, specificHeat: 460, melting: 1420 },
|
||||
{ id: "ss-303", name: "Stainless steel 1.4305 (303)", category: "Metal", standard: "EN 10088-3", color: "#bac0c7", density: 7900, youngs: 193, poisson: 0.29, yield: 190, tensile: 500, compressive: 190, elongation: 35, expansion: 17.3, conductivity: 16.2, specificHeat: 500, melting: 1420 },
|
||||
{ id: "ss-17-4", name: "Stainless steel 1.4542 (17-4 PH), H900", category: "Metal", standard: "EN 10088-3", color: "#a9afb6", density: 7780, youngs: 197, poisson: 0.27, yield: 1170, tensile: 1310, compressive: 1170, elongation: 10, expansion: 10.8, conductivity: 18.3, specificHeat: 460, melting: 1440 },
|
||||
{ id: "ductile-iron", name: "Ductile iron EN-GJS-400-15", category: "Metal", standard: "EN 1563", color: "#63666c", density: 7100, youngs: 169, poisson: 0.275, yield: 250, tensile: 400, compressive: 700, elongation: 15, expansion: 12.5, conductivity: 36, specificHeat: 515, melting: 1150 },
|
||||
{ id: "al-5052", name: "Aluminium EN AW-5052-H32", category: "Metal", standard: "EN 485-2", color: "#ccd1d7", density: 2680, youngs: 70, poisson: 0.33, yield: 193, tensile: 228, compressive: 193, elongation: 12, expansion: 23.8, conductivity: 138, specificHeat: 880, melting: 650 },
|
||||
{ id: "al-7075", name: "Aluminium EN AW-7075-T6", category: "Metal", standard: "EN 755-2", color: "#c2c7cd", density: 2810, youngs: 71.7, poisson: 0.33, yield: 503, tensile: 572, compressive: 503, elongation: 11, expansion: 23.6, conductivity: 130, specificHeat: 960, melting: 635 },
|
||||
{ id: "al-2024", name: "Aluminium EN AW-2024-T3", category: "Metal", standard: "EN 485-2", color: "#c0c5cb", density: 2780, youngs: 73.1, poisson: 0.33, yield: 345, tensile: 483, compressive: 345, elongation: 18, expansion: 23.2, conductivity: 121, specificHeat: 875, melting: 640 },
|
||||
{ id: "al-cast", name: "Cast aluminium EN AC-46500 (A380)", category: "Metal", standard: "EN 1706", color: "#b7bcc2", density: 2760, youngs: 71, poisson: 0.33, yield: 160, tensile: 324, compressive: 160, elongation: 3.5, expansion: 21.8, conductivity: 96, specificHeat: 963, melting: 595 },
|
||||
{ id: "bronze", name: "Phosphor bronze CuSn8 (CW453K)", category: "Metal", standard: "EN 1652", color: "#b0884a", density: 8800, youngs: 115, poisson: 0.34, yield: 260, tensile: 390, compressive: 260, elongation: 45, expansion: 17, conductivity: 67, specificHeat: 380, melting: 1000 },
|
||||
{ id: "ti-2", name: "Titanium Grade 2 (commercially pure)", category: "Metal", standard: "ASTM B348", color: "#96989b", density: 4510, youngs: 105, poisson: 0.37, yield: 275, tensile: 345, compressive: 275, elongation: 20, expansion: 8.6, conductivity: 16.4, specificHeat: 523, melting: 1665 },
|
||||
{ id: "mg-az31", name: "Magnesium AZ31B", category: "Metal", standard: "ASTM B90", color: "#a7aaa8", density: 1770, youngs: 45, poisson: 0.35, yield: 200, tensile: 260, compressive: 97, elongation: 15, expansion: 26, conductivity: 96, specificHeat: 1000, melting: 630 },
|
||||
{ id: "zamak3", name: "Zinc die-cast Zamak 3 (ZP3)", category: "Metal", standard: "EN 12844", color: "#a3a7ad", density: 6600, youngs: 96, poisson: 0.27, yield: 208, tensile: 283, compressive: 414, elongation: 10, expansion: 27.4, conductivity: 113, specificHeat: 419, melting: 387 },
|
||||
{ id: "inconel-718", name: "Nickel alloy 718", category: "Metal", standard: "ASTM B637", color: "#9a9c98", density: 8190, youngs: 200, poisson: 0.29, yield: 1035, tensile: 1240, compressive: 1035, elongation: 12, expansion: 13, conductivity: 11.4, specificHeat: 435, melting: 1336 },
|
||||
{ id: "lead", name: "Lead", category: "Metal", color: "#6e7279", density: 11340, youngs: 16, poisson: 0.44, yield: 5, tensile: 18, compressive: 5, elongation: 50, expansion: 29, conductivity: 35, specificHeat: 128, melting: 327 },
|
||||
{ id: "tungsten", name: "Tungsten", category: "Metal", color: "#7d7f82", density: 19300, youngs: 411, poisson: 0.28, yield: 750, tensile: 980, compressive: 750, elongation: 2, expansion: 4.5, conductivity: 173, specificHeat: 134, melting: 3422 },
|
||||
{ id: "gold", name: "Gold (fine)", category: "Metal", color: "#d4af37", density: 19300, youngs: 79, poisson: 0.42, yield: 25, tensile: 120, compressive: 25, elongation: 40, expansion: 14.2, conductivity: 318, specificHeat: 129, melting: 1064 },
|
||||
{ id: "silver", name: "Silver (fine)", category: "Metal", color: "#c9cbcd", density: 10490, youngs: 83, poisson: 0.37, yield: 55, tensile: 140, compressive: 55, elongation: 45, expansion: 18.9, conductivity: 429, specificHeat: 235, melting: 962 },
|
||||
// ---- Plastics (typical values; a printed part is weaker than a moulded one)
|
||||
{ id: "pla", name: "PLA", category: "Plastic", color: "#e9e4d8", density: 1240, youngs: 3.5, poisson: 0.36, tensile: 50, expansion: 68, conductivity: 0.13, specificHeat: 1800 },
|
||||
{ id: "petg", name: "PETG", category: "Plastic", color: "#cfe3e8", opacity: 0.85, density: 1270, youngs: 2, tensile: 50, conductivity: 0.2 },
|
||||
{ id: "abs", name: "ABS", category: "Plastic", color: "#d9d4c7", density: 1050, youngs: 2.3, poisson: 0.35, tensile: 40, expansion: 90, conductivity: 0.17, specificHeat: 1400 },
|
||||
{ id: "pa6", name: "Nylon PA6 (dry)", category: "Plastic", color: "#e8e2d0", density: 1140, youngs: 3, tensile: 80, expansion: 80, conductivity: 0.25, specificHeat: 1700 },
|
||||
{ id: "pc", name: "Polycarbonate (PC)", category: "Plastic", color: "#dfe8ee", opacity: 0.6, density: 1200, youngs: 2.4, poisson: 0.37, yield: 62, tensile: 65, expansion: 70, conductivity: 0.2, specificHeat: 1200 },
|
||||
{ id: "pmma", name: "Acrylic (PMMA)", category: "Plastic", color: "#e3f1f3", opacity: 0.4, density: 1190, youngs: 3.2, poisson: 0.37, tensile: 70, expansion: 70, conductivity: 0.19, specificHeat: 1470 },
|
||||
{ id: "pom", name: "Acetal (POM)", category: "Plastic", color: "#f1efe9", density: 1410, youngs: 2.9, tensile: 65, expansion: 110, conductivity: 0.31, specificHeat: 1470 },
|
||||
{ id: "epdm", name: "Rubber (EPDM)", category: "Plastic", standard: "ISO 10456", color: "#2e2f31", density: 1150, conductivity: 0.25, specificHeat: 1000 },
|
||||
{ id: "pla", name: "PLA", category: "Plastic", color: "#e9e4d8", density: 1240, youngs: 3.5, poisson: 0.36, yield: 50, tensile: 50, compressive: 80, bending: 80, elongation: 6, expansion: 68, conductivity: 0.13, specificHeat: 1800, melting: 160, maxTemp: 50 },
|
||||
{ id: "petg", name: "PETG", category: "Plastic", color: "#cfe3e8", opacity: 0.85, density: 1270, youngs: 2, poisson: 0.38, yield: 50, tensile: 50, compressive: 55, bending: 70, elongation: 80, expansion: 68, conductivity: 0.2, specificHeat: 1200, maxTemp: 70 },
|
||||
{ id: "abs", name: "ABS", category: "Plastic", color: "#d9d4c7", density: 1050, youngs: 2.3, poisson: 0.35, yield: 40, tensile: 40, compressive: 65, bending: 65, elongation: 20, expansion: 90, conductivity: 0.17, specificHeat: 1400, maxTemp: 80 },
|
||||
{ id: "pa6", name: "Nylon PA6 (dry)", category: "Plastic", color: "#e8e2d0", density: 1140, youngs: 3, poisson: 0.39, yield: 80, tensile: 80, compressive: 90, bending: 110, elongation: 30, expansion: 80, conductivity: 0.25, specificHeat: 1700, melting: 220, maxTemp: 100 },
|
||||
{ id: "pc", name: "Polycarbonate (PC)", category: "Plastic", color: "#dfe8ee", opacity: 0.6, density: 1200, youngs: 2.4, poisson: 0.37, yield: 62, tensile: 65, compressive: 80, bending: 93, elongation: 110, expansion: 70, conductivity: 0.2, specificHeat: 1200, maxTemp: 125 },
|
||||
{ id: "pmma", name: "Acrylic (PMMA)", category: "Plastic", color: "#e3f1f3", opacity: 0.4, density: 1190, youngs: 3.2, poisson: 0.37, tensile: 70, compressive: 110, bending: 110, elongation: 4, expansion: 70, conductivity: 0.19, specificHeat: 1470, maxTemp: 80 },
|
||||
{ id: "pom", name: "Acetal (POM)", category: "Plastic", color: "#f1efe9", density: 1410, youngs: 2.9, poisson: 0.35, yield: 65, tensile: 65, compressive: 110, bending: 90, elongation: 40, expansion: 110, conductivity: 0.31, specificHeat: 1470, melting: 175, maxTemp: 100 },
|
||||
{ id: "epdm", name: "Rubber (EPDM)", category: "Plastic", standard: "ISO 10456", color: "#2e2f31", density: 1150, youngs: 0.005, poisson: 0.49, tensile: 10, elongation: 300, expansion: 160, conductivity: 0.25, specificHeat: 1000, maxTemp: 130 },
|
||||
{ id: "asa", name: "ASA", category: "Plastic", color: "#d6d2c8", density: 1070, youngs: 2, poisson: 0.36, yield: 45, tensile: 45, compressive: 60, bending: 70, elongation: 25, expansion: 95, conductivity: 0.17, specificHeat: 1300, maxTemp: 85 },
|
||||
{ id: "tpu", name: "TPU (flexible, Shore 95A)", category: "Plastic", color: "#d9dde0", density: 1210, youngs: 0.026, poisson: 0.48, tensile: 35, elongation: 550, expansion: 150, conductivity: 0.2, specificHeat: 1800, maxTemp: 80 },
|
||||
{ id: "resin-sla", name: "Photopolymer resin (SLA, standard)", category: "Plastic", note: "Typical cured values; each resin's data sheet differs", color: "#c9ccd0", density: 1180, youngs: 2.8, poisson: 0.35, tensile: 60, compressive: 90, bending: 100, elongation: 6, expansion: 80, conductivity: 0.2, specificHeat: 1300, maxTemp: 60 },
|
||||
{ id: "pa12", name: "Nylon PA12", category: "Plastic", note: "Printed (SLS) parts are lighter: about 950 kg/m³", color: "#ecebe6", density: 1010, youngs: 1.7, poisson: 0.4, yield: 45, tensile: 48, compressive: 60, bending: 60, elongation: 20, expansion: 110, conductivity: 0.23, specificHeat: 1700, melting: 178, maxTemp: 100 },
|
||||
{ id: "pa66", name: "Nylon PA66 (dry)", category: "Plastic", color: "#ebe5d4", density: 1140, youngs: 3, poisson: 0.39, yield: 85, tensile: 85, compressive: 100, bending: 120, elongation: 25, expansion: 80, conductivity: 0.25, specificHeat: 1700, melting: 260, maxTemp: 110 },
|
||||
{ id: "hdpe", name: "Polyethylene HDPE", category: "Plastic", color: "#f0efea", density: 950, youngs: 1, poisson: 0.42, yield: 26, tensile: 30, compressive: 25, bending: 35, elongation: 600, expansion: 120, conductivity: 0.48, specificHeat: 1900, melting: 130, maxTemp: 80 },
|
||||
{ id: "ldpe", name: "Polyethylene LDPE", category: "Plastic", color: "#f2f1ec", opacity: 0.85, density: 920, youngs: 0.25, poisson: 0.45, yield: 10, tensile: 10, compressive: 10, elongation: 500, expansion: 200, conductivity: 0.33, specificHeat: 2300, melting: 110, maxTemp: 60 },
|
||||
{ id: "pp", name: "Polypropylene (PP)", category: "Plastic", color: "#ece9e0", density: 905, youngs: 1.5, poisson: 0.42, yield: 32, tensile: 33, compressive: 45, bending: 45, elongation: 300, expansion: 100, conductivity: 0.22, specificHeat: 1920, melting: 165, maxTemp: 100 },
|
||||
{ id: "pet", name: "PET", category: "Plastic", color: "#d8e8ec", opacity: 0.7, density: 1380, youngs: 2.8, poisson: 0.38, yield: 55, tensile: 55, compressive: 80, bending: 90, elongation: 70, expansion: 70, conductivity: 0.24, specificHeat: 1100, melting: 255, maxTemp: 70 },
|
||||
{ id: "pvc", name: "PVC (rigid)", category: "Plastic", color: "#d5d7d9", density: 1400, youngs: 3, poisson: 0.38, yield: 50, tensile: 50, compressive: 65, bending: 80, elongation: 40, expansion: 70, conductivity: 0.17, specificHeat: 900, maxTemp: 60 },
|
||||
{ id: "ptfe", name: "PTFE", category: "Plastic", color: "#f4f3ef", density: 2200, youngs: 0.5, poisson: 0.46, yield: 12, tensile: 25, compressive: 12, elongation: 300, expansion: 120, conductivity: 0.25, specificHeat: 1000, melting: 327, maxTemp: 260 },
|
||||
{ id: "peek", name: "PEEK", category: "Plastic", color: "#c9b48e", density: 1300, youngs: 3.6, poisson: 0.4, yield: 97, tensile: 100, compressive: 118, bending: 170, elongation: 30, expansion: 47, conductivity: 0.25, specificHeat: 1340, melting: 343, maxTemp: 250 },
|
||||
{ id: "hips", name: "Polystyrene (HIPS)", category: "Plastic", color: "#efeeea", density: 1040, youngs: 2, poisson: 0.35, yield: 20, tensile: 26, compressive: 40, bending: 45, elongation: 40, expansion: 80, conductivity: 0.17, specificHeat: 1300, maxTemp: 75 },
|
||||
{ id: "epoxy", name: "Epoxy resin (cast)", category: "Plastic", color: "#d9c78f", opacity: 0.7, density: 1200, youngs: 3, poisson: 0.35, tensile: 60, compressive: 110, bending: 100, elongation: 4, expansion: 60, conductivity: 0.2, specificHeat: 1100, maxTemp: 100 },
|
||||
{ id: "silicone", name: "Silicone rubber", category: "Plastic", color: "#d8d4cc", density: 1150, youngs: 0.005, poisson: 0.49, tensile: 7, elongation: 400, expansion: 250, conductivity: 0.2, specificHeat: 1300, maxTemp: 200 },
|
||||
{ id: "natural-rubber", name: "Natural rubber", category: "Plastic", color: "#3a3631", density: 930, youngs: 0.002, poisson: 0.49, tensile: 20, elongation: 600, expansion: 220, conductivity: 0.13, specificHeat: 1900, maxTemp: 70 },
|
||||
// ---- Composites (in the plane of the layers; across them far less)
|
||||
{ id: "cfrp", name: "Carbon fibre / epoxy (quasi-isotropic)", category: "Composite", color: "#2b2d30", density: 1600, youngs: 70, poisson: 0.3, tensile: 600, compressive: 500, bending: 700, elongation: 1, expansion: 2, conductivity: 5, specificHeat: 1000, maxTemp: 120 },
|
||||
{ id: "gfrp", name: "Glass fibre / epoxy (woven)", category: "Composite", color: "#d9d6c4", density: 1900, youngs: 25, poisson: 0.28, tensile: 350, compressive: 300, bending: 400, elongation: 2, expansion: 12, conductivity: 0.35, specificHeat: 900, maxTemp: 120 },
|
||||
// ---- Concrete and masonry
|
||||
{ id: "concrete-c25", name: "Concrete C25/30", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#a3a29d", density: 2400, youngs: 31, poisson: 0.2, compressive: 25, tensile: 2.6, expansion: 10, conductivity: 2, specificHeat: 1000 },
|
||||
{ id: "concrete-c30-rc", name: "Reinforced concrete C30/37 (1 % steel)", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#9c9b96", density: 2500, youngs: 33, poisson: 0.2, compressive: 30, tensile: 2.9, expansion: 10, conductivity: 2.3, specificHeat: 1000 },
|
||||
{ id: "brick", name: "Clay brickwork (outer leaf)", category: "Concrete & masonry", color: "#a55a3f", density: 1700, conductivity: 0.77, specificHeat: 800 },
|
||||
{ id: "concrete-c25", name: "Concrete C25/30", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#a3a29d", density: 2400, youngs: 31, poisson: 0.2, tensile: 2.6, compressive: 25, bending: 3.6, expansion: 10, conductivity: 2, specificHeat: 1000 },
|
||||
{ id: "concrete-c30-rc", name: "Reinforced concrete C30/37 (1 % steel)", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#9c9b96", density: 2500, youngs: 33, poisson: 0.2, tensile: 2.9, compressive: 30, bending: 4.1, expansion: 10, conductivity: 2.3, specificHeat: 1000 },
|
||||
{ id: "brick", name: "Clay brickwork (outer leaf)", category: "Concrete & masonry", color: "#a55a3f", density: 1700, youngs: 5, poisson: 0.2, compressive: 7, bending: 0.4, expansion: 6, conductivity: 0.77, specificHeat: 800 },
|
||||
{ id: "concrete-c40", name: "Concrete C40/50", category: "Concrete & masonry", standard: "EN 1992-1-1", color: "#a6a5a0", density: 2400, youngs: 35, poisson: 0.2, tensile: 3.5, compressive: 40, bending: 4.9, expansion: 10, conductivity: 2, specificHeat: 1000 },
|
||||
{ id: "aac", name: "Aerated concrete block (AAC)", category: "Concrete & masonry", color: "#e2e0da", density: 500, youngs: 1.75, poisson: 0.2, tensile: 0.5, compressive: 4, bending: 0.8, expansion: 8, conductivity: 0.13, specificHeat: 1000 },
|
||||
// ---- Wood
|
||||
{ id: "c24", name: "Softwood C24", category: "Wood", standard: "EN 338", color: "#d8b77e", density: 420, youngs: 11, bending: 24, tensile: 14.5, compressive: 21, expansion: 5, conductivity: 0.12, specificHeat: 1600 },
|
||||
{ id: "d30", name: "Hardwood D30 (oak)", category: "Wood", standard: "EN 338", color: "#a97a4c", density: 640, youngs: 11, bending: 30, tensile: 18, compressive: 24, expansion: 5, conductivity: 0.18, specificHeat: 1600 },
|
||||
{ id: "plywood", name: "Plywood", category: "Wood", standard: "ISO 10456", color: "#cfa86f", density: 500, conductivity: 0.13, specificHeat: 1600 },
|
||||
{ id: "plywood", name: "Plywood", category: "Wood", standard: "ISO 10456", color: "#cfa86f", density: 500, youngs: 8, tensile: 30, compressive: 25, bending: 40, expansion: 7, conductivity: 0.13, specificHeat: 1600 },
|
||||
{ id: "gl24h", name: "Glulam GL24h", category: "Wood", standard: "EN 14080", color: "#d9b97f", density: 420, youngs: 11.5, bending: 24, tensile: 19.2, compressive: 24, expansion: 5, conductivity: 0.12, specificHeat: 1600 },
|
||||
// (Species: typical values at 12 % moisture, along the grain.)
|
||||
{ id: "pine", name: "Pine", category: "Wood", color: "#ddbd85", density: 520, youngs: 12, tensile: 100, compressive: 45, bending: 80, expansion: 5, conductivity: 0.13, specificHeat: 1600 },
|
||||
{ id: "spruce", name: "Spruce", category: "Wood", color: "#e3c995", density: 450, youngs: 10, tensile: 90, compressive: 40, bending: 70, expansion: 5, conductivity: 0.12, specificHeat: 1600 },
|
||||
{ id: "beech", name: "Beech", category: "Wood", color: "#d2a77a", density: 720, youngs: 14, tensile: 135, compressive: 55, bending: 110, expansion: 5, conductivity: 0.17, specificHeat: 1600 },
|
||||
{ id: "birch", name: "Birch", category: "Wood", color: "#e0c69d", density: 670, youngs: 14, tensile: 140, compressive: 55, bending: 115, expansion: 5, conductivity: 0.15, specificHeat: 1600 },
|
||||
{ id: "maple", name: "Maple (hard)", category: "Wood", color: "#e6cfa6", density: 705, youngs: 12.6, tensile: 110, compressive: 54, bending: 109, expansion: 5, conductivity: 0.16, specificHeat: 1600 },
|
||||
{ id: "ash", name: "Ash", category: "Wood", color: "#dbc296", density: 680, youngs: 12.3, tensile: 110, compressive: 51, bending: 103, expansion: 5, conductivity: 0.16, specificHeat: 1600 },
|
||||
{ id: "walnut", name: "Walnut", category: "Wood", color: "#6b4a33", density: 610, youngs: 11.6, tensile: 100, compressive: 52, bending: 101, expansion: 5, conductivity: 0.14, specificHeat: 1600 },
|
||||
{ id: "cherry", name: "Cherry", category: "Wood", color: "#a0603f", density: 560, youngs: 10.3, tensile: 90, compressive: 49, bending: 85, expansion: 5, conductivity: 0.13, specificHeat: 1600 },
|
||||
{ id: "mahogany", name: "Mahogany", category: "Wood", color: "#80422e", density: 590, youngs: 10, tensile: 90, compressive: 46, bending: 80, expansion: 5, conductivity: 0.13, specificHeat: 1600 },
|
||||
{ id: "teak", name: "Teak", category: "Wood", color: "#a87a45", density: 650, youngs: 12.3, tensile: 100, compressive: 55, bending: 97, expansion: 5, conductivity: 0.15, specificHeat: 1600 },
|
||||
{ id: "balsa", name: "Balsa", category: "Wood", color: "#ead9b4", density: 160, youngs: 3.7, tensile: 20, compressive: 12, bending: 20, expansion: 5, conductivity: 0.05, specificHeat: 1600 },
|
||||
{ id: "bamboo", name: "Bamboo", category: "Wood", color: "#d9c28a", density: 700, youngs: 17, tensile: 150, compressive: 60, bending: 140, expansion: 4, conductivity: 0.17, specificHeat: 1600 },
|
||||
{ id: "mdf", name: "MDF", category: "Wood", color: "#b99a74", density: 750, youngs: 3.5, bending: 30, expansion: 8, conductivity: 0.14, specificHeat: 1700 },
|
||||
{ id: "chipboard", name: "Particle board (chipboard)", category: "Wood", standard: "ISO 10456", color: "#c8a878", density: 600, youngs: 2.5, bending: 13, expansion: 10, conductivity: 0.14, specificHeat: 1700 },
|
||||
{ id: "osb", name: "OSB", category: "Wood", standard: "ISO 10456", color: "#c69e62", density: 650, youngs: 4.9, bending: 20, expansion: 8, conductivity: 0.13, specificHeat: 1700 },
|
||||
// ---- Glass and stone
|
||||
{ id: "glass", name: "Float glass (soda-lime)", category: "Glass & stone", standard: "EN 572-1", color: "#bfdde0", opacity: 0.3, density: 2500, youngs: 70, poisson: 0.2, bending: 45, expansion: 9, conductivity: 1, specificHeat: 720 },
|
||||
{ id: "granite", name: "Granite", category: "Glass & stone", standard: "ISO 10456", color: "#8b8580", density: 2700, conductivity: 2.8, specificHeat: 1000 },
|
||||
{ id: "glass", name: "Float glass (soda-lime)", category: "Glass & stone", standard: "EN 572-1", color: "#bfdde0", opacity: 0.3, density: 2500, youngs: 70, poisson: 0.2, compressive: 1000, bending: 45, expansion: 9, conductivity: 1, specificHeat: 720, maxTemp: 200 },
|
||||
{ id: "granite", name: "Granite", category: "Glass & stone", standard: "ISO 10456", color: "#8b8580", density: 2700, youngs: 50, poisson: 0.25, tensile: 10, compressive: 150, bending: 15, expansion: 8, conductivity: 2.8, specificHeat: 1000 },
|
||||
{ id: "glass-tempered", name: "Toughened glass", category: "Glass & stone", standard: "EN 12150-1", color: "#bcdade", opacity: 0.3, density: 2500, youngs: 70, poisson: 0.2, compressive: 1000, bending: 120, expansion: 9, conductivity: 1, specificHeat: 720, maxTemp: 250 },
|
||||
{ id: "borosilicate", name: "Borosilicate glass", category: "Glass & stone", color: "#cfe6e8", opacity: 0.3, density: 2230, youngs: 64, poisson: 0.2, compressive: 1000, bending: 45, expansion: 3.3, conductivity: 1.14, specificHeat: 830, maxTemp: 450 },
|
||||
{ id: "marble", name: "Marble", category: "Glass & stone", standard: "ISO 10456", color: "#e7e4de", density: 2800, youngs: 50, poisson: 0.27, tensile: 8, compressive: 100, bending: 12, expansion: 7, conductivity: 3.5, specificHeat: 1000 },
|
||||
{ id: "limestone", name: "Limestone (hard)", category: "Glass & stone", standard: "ISO 10456", color: "#d8cfb8", density: 2200, youngs: 40, poisson: 0.25, tensile: 6, compressive: 80, bending: 10, expansion: 6, conductivity: 1.7, specificHeat: 1000 },
|
||||
{ id: "sandstone", name: "Sandstone", category: "Glass & stone", standard: "ISO 10456", color: "#cdb48a", density: 2600, youngs: 20, poisson: 0.25, tensile: 4, compressive: 60, bending: 7, expansion: 11, conductivity: 2.3, specificHeat: 1000 },
|
||||
{ id: "slate", name: "Slate", category: "Glass & stone", standard: "ISO 10456", color: "#4f5559", density: 2400, youngs: 80, poisson: 0.25, tensile: 20, compressive: 140, bending: 50, expansion: 9, conductivity: 2.2, specificHeat: 1000 },
|
||||
// ---- Ceramics and the rest
|
||||
{ id: "alumina", name: "Alumina ceramic (99.5 %)", category: "Ceramic & other", color: "#f1efe8", density: 3890, youngs: 370, poisson: 0.22, tensile: 260, compressive: 2600, bending: 379, expansion: 8.1, conductivity: 30, specificHeat: 880, melting: 2072, maxTemp: 1650 },
|
||||
{ id: "porcelain", name: "Porcelain", category: "Ceramic & other", color: "#f3f2ee", density: 2400, youngs: 70, poisson: 0.17, compressive: 500, bending: 70, expansion: 6, conductivity: 1.5, specificHeat: 1085, maxTemp: 1000 },
|
||||
{ id: "cardboard", name: "Cardboard", category: "Ceramic & other", color: "#b8946a", density: 700, youngs: 3, tensile: 20, conductivity: 0.07, specificHeat: 1400, maxTemp: 150 },
|
||||
{ id: "leather", name: "Leather", category: "Ceramic & other", color: "#8a5a3b", density: 860, youngs: 0.1, tensile: 20, elongation: 50, conductivity: 0.16, specificHeat: 1500, maxTemp: 100 },
|
||||
// ---- Insulation and boards
|
||||
{ id: "plasterboard", name: "Gypsum plasterboard", category: "Insulation & boards", standard: "ISO 10456", color: "#ece9e2", density: 900, conductivity: 0.25, specificHeat: 1000 },
|
||||
{ id: "mineral-wool", name: "Mineral wool", category: "Insulation & boards", color: "#d8c27a", density: 30, conductivity: 0.035, specificHeat: 1030 },
|
||||
{ id: "eps", name: "Expanded polystyrene (EPS)", category: "Insulation & boards", color: "#f3f3f0", density: 20, conductivity: 0.035, specificHeat: 1450 },
|
||||
{ id: "plasterboard", name: "Gypsum plasterboard", category: "Insulation & boards", standard: "ISO 10456", color: "#ece9e2", density: 900, youngs: 2, compressive: 5, bending: 5, expansion: 16, conductivity: 0.25, specificHeat: 1000, maxTemp: 50 },
|
||||
{ id: "mineral-wool", name: "Mineral wool", category: "Insulation & boards", color: "#d8c27a", density: 30, compressive: 0.01, conductivity: 0.035, specificHeat: 1030, maxTemp: 700 },
|
||||
{ id: "eps", name: "Expanded polystyrene (EPS)", category: "Insulation & boards", color: "#f3f3f0", density: 20, youngs: 0.004, compressive: 0.1, bending: 0.15, expansion: 60, conductivity: 0.035, specificHeat: 1450, maxTemp: 80 },
|
||||
{ id: "xps", name: "Extruded polystyrene (XPS)", category: "Insulation & boards", color: "#9fc3e0", density: 35, youngs: 0.015, compressive: 0.3, bending: 0.4, expansion: 70, conductivity: 0.034, specificHeat: 1450, maxTemp: 75 },
|
||||
{ id: "pir", name: "PIR foam board", category: "Insulation & boards", color: "#e6d9a8", density: 30, youngs: 0.005, compressive: 0.12, expansion: 60, conductivity: 0.022, specificHeat: 1400, maxTemp: 100 },
|
||||
{ id: "glass-wool", name: "Glass wool", category: "Insulation & boards", color: "#e7d38a", density: 20, conductivity: 0.035, specificHeat: 1030, maxTemp: 250 },
|
||||
{ id: "wood-fibre", name: "Wood fibre insulation", category: "Insulation & boards", color: "#b8925e", density: 160, compressive: 0.1, conductivity: 0.04, specificHeat: 2100, maxTemp: 100 },
|
||||
{ id: "cork", name: "Cork board", category: "Insulation & boards", standard: "ISO 10456", color: "#a87b52", density: 120, youngs: 0.02, compressive: 0.1, conductivity: 0.04, specificHeat: 1560, maxTemp: 110 },
|
||||
];
|
||||
|
||||
/** Every material the project can use: the library, and its own. */
|
||||
@@ -80,11 +155,18 @@ export function materialRows(m: MaterialDef): { group: string; rows: [string, st
|
||||
...row("Tensile strength", m.tensile, "MPa"),
|
||||
...row("Compressive strength", m.compressive, "MPa"),
|
||||
...row("Bending strength", m.bending, "MPa"),
|
||||
...row("Elongation at break", m.elongation, "%"),
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Thermal",
|
||||
rows: [...row("Thermal conductivity", m.conductivity, "W/(m·K)"), ...row("Specific heat", m.specificHeat, "J/(kg·K)"), ...row("Thermal expansion", m.expansion, "µm/(m·K)")],
|
||||
rows: [
|
||||
...row("Thermal conductivity", m.conductivity, "W/(m·K)"),
|
||||
...row("Specific heat", m.specificHeat, "J/(kg·K)"),
|
||||
...row("Thermal expansion", m.expansion, "µm/(m·K)"),
|
||||
...row("Melting point", m.melting, "°C"),
|
||||
...row("Max service temperature", m.maxTemp, "°C"),
|
||||
],
|
||||
},
|
||||
];
|
||||
return groups.filter((g) => g.rows.length);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import type { ProjectInfo } from "../doc/types";
|
||||
import type { BodyProps } from "../kernel/protocol";
|
||||
import { el } from "../ui/ui";
|
||||
import { textField } from "../ui/textField";
|
||||
import { trim, UNIT_LABEL, UNIT_MM, units } from "../units";
|
||||
import type { AppContext } from "../tools/tool";
|
||||
import { dataTable, fmtArea, fmtMass, fmtVolume, measureBodies } from "./bimTool";
|
||||
@@ -53,6 +54,42 @@ export function partsList(app: AppContext, props: Map<string, BodyProps>): PartR
|
||||
|
||||
const len = (mm: number) => trim(mm / UNIT_MM[units()], 2);
|
||||
|
||||
let afterPrint: (() => void) | null = null;
|
||||
/**
|
||||
* The print window, with `cls` on the page while it is up (the styles for printing go by it) and `extra` (a style,
|
||||
* the sheets to print) in the page that long. Put right when printing is over, not when print() returns: on a phone
|
||||
* print() returns at once, before the preview has drawn the page - what it then drew was the page put back already
|
||||
* (a blank sheet, or the app itself).
|
||||
*/
|
||||
export function printPage(cls: string, ...extra: HTMLElement[]): void {
|
||||
afterPrint?.();
|
||||
let over = false;
|
||||
const tidy = () => {
|
||||
if (over) return;
|
||||
over = true;
|
||||
afterPrint = null;
|
||||
removeEventListener("afterprint", tidy);
|
||||
removeEventListener("focus", late);
|
||||
document.body.classList.remove(cls);
|
||||
for (const e of extra) e.remove();
|
||||
};
|
||||
// (A browser that never says printing is over: tidied when the app is come back to, a moment after.)
|
||||
const late = () => setTimeout(() => !matchMedia("print").matches && tidy(), 1500);
|
||||
afterPrint = tidy;
|
||||
document.body.classList.add(cls);
|
||||
addEventListener("afterprint", tidy);
|
||||
const t0 = performance.now();
|
||||
try {
|
||||
window.print();
|
||||
} catch {
|
||||
tidy();
|
||||
return;
|
||||
}
|
||||
// (print() that waited for the window to close - a computer's browser: over now, whether or not it said so.)
|
||||
if (performance.now() - t0 > 400) tidy();
|
||||
else addEventListener("focus", late);
|
||||
}
|
||||
|
||||
export async function openSheet(app: AppContext): Promise<void> {
|
||||
document.querySelector(".bim-sheet")?.remove();
|
||||
const back = el("div", "bim-sheet");
|
||||
@@ -74,11 +111,7 @@ export async function openSheet(app: AppContext): Promise<void> {
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
close.addEventListener("click", shut);
|
||||
print.addEventListener("click", () => {
|
||||
document.body.classList.add("printing-sheet");
|
||||
window.print();
|
||||
document.body.classList.remove("printing-sheet");
|
||||
});
|
||||
print.addEventListener("click", () => printPage("printing-sheet"));
|
||||
|
||||
let rows: PartRow[] = [];
|
||||
try {
|
||||
@@ -119,7 +152,7 @@ function render(app: AppContext, paper: HTMLElement, rows: PartRow[]): void {
|
||||
f.append(el("span", "bim-tb-label", label));
|
||||
if (!key) f.append(el("span", "bim-tb-value", value));
|
||||
else {
|
||||
const input = el("input", "bim-tb-value");
|
||||
const input = textField("bim-tb-value");
|
||||
input.value = value;
|
||||
input.placeholder = "-";
|
||||
input.addEventListener("change", () => app.store.commit((d) => (d.info = { ...(d.info ?? {}), [key]: input.value.trim() || undefined })));
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { App } from "./app";
|
||||
import type { ToolItem, PanelItem } from "./ui/ui";
|
||||
import type { Feature } from "./doc/types";
|
||||
import type { Sel } from "./tools/tool";
|
||||
import type { SweepWord } from "./ui/sentence";
|
||||
import type { PickHit } from "./view/viewport";
|
||||
import type { ProjectDoc } from "./doc/types";
|
||||
import { parseProject } from "./doc/store";
|
||||
@@ -134,6 +135,199 @@ export function installDebug(app: App): void {
|
||||
return `ran ${hit.path}`;
|
||||
},
|
||||
|
||||
/** The sentence bar: what it says now (its words, where each is). */
|
||||
sentence: () => app.sentence.describe(),
|
||||
|
||||
/**
|
||||
* Every tool, from every kind of pick there is in the model, started
|
||||
* through the line at the bottom - and in each every option tried (each
|
||||
* choice, switch, number, blank). Lists what did nothing, what threw, and
|
||||
* for each tool whether it has a handle on the model, a value box, and
|
||||
* lit picks while it is open (what a tool that takes a distance should
|
||||
* have). Changes nothing for good: each tool is cancelled, each step
|
||||
* undone. `only`: just the picks named ("face", "edge", "body"...).
|
||||
* `options` false: the tools are only started and looked at (much quicker).
|
||||
*/
|
||||
async sweep(only?: string[], options = true): Promise<{ started: number; nothing: string[]; errors: string[]; options: string[]; audit: { pick: string; tool: string; handle: boolean; box: boolean; lit: boolean; numbers: number }[] }> {
|
||||
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
const errors: string[] = [];
|
||||
const onError = (e: ErrorEvent) => errors.push(`${e.message}`);
|
||||
const onReject = (e: PromiseRejectionEvent) => errors.push(String((e.reason as Error)?.message ?? e.reason));
|
||||
addEventListener("error", onError);
|
||||
addEventListener("unhandledrejection", onReject);
|
||||
const steps = app.store.doc.features.length;
|
||||
const state = () => app.sentence.state;
|
||||
const settle = async () => {
|
||||
app.sentence.changed();
|
||||
await wait(120);
|
||||
await Promise.race([sg.idle(), wait(4000)]);
|
||||
};
|
||||
const reset = async () => {
|
||||
for (const d of Array.from(document.querySelectorAll<HTMLElement>(".dialog-back .dialog, .bim-sheet")).reverse()) {
|
||||
const b = Array.from(d.querySelectorAll("button")).find((x) => /^(Cancel|Close)/i.test(x.textContent?.trim() ?? "") || /close/i.test(x.className) || /close/i.test(x.title));
|
||||
b?.click();
|
||||
await wait(120);
|
||||
}
|
||||
for (let i = 0; i < 4 && inside.tool.id !== "select"; i++) {
|
||||
document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
await wait(150);
|
||||
}
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const s = state();
|
||||
if (!s?.about.startsWith("tool:")) break;
|
||||
(s.cancel ?? s.done)?.();
|
||||
await wait(200);
|
||||
}
|
||||
if (inside.tool.id !== "select") app.setTool(null);
|
||||
while (app.store.doc.features.length > steps) {
|
||||
inside.undo();
|
||||
await wait(120);
|
||||
}
|
||||
if (app.isolated) app.isolate(null);
|
||||
await Promise.race([sg.idle(), wait(4000)]);
|
||||
};
|
||||
const snap = () => JSON.stringify([inside.tool.id, ui.panelSpec?.title ?? null, app.store.doc.features.length, app.selection, document.querySelectorAll(".dialog, .menu:not([hidden]), .ref-win, .bim-sheet").length, ui.recentToasts?.length ?? 0, !!app.isolated, !!app.section, app.varsOn, JSON.stringify(app.store.doc), ui.hintText]);
|
||||
const leaves = () => {
|
||||
const out: { path: string; key: string }[] = [];
|
||||
const walk = (ws: SweepWord[], path: string[]) => {
|
||||
for (const w of ws) {
|
||||
if (w.kids?.length) walk(w.kids, [...path, w.label]);
|
||||
else if (w.run || w.value) out.push({ path: [...path, w.label].join(" > "), key: w.key });
|
||||
}
|
||||
};
|
||||
for (const g of state()?.groups ?? []) walk(g.words, [g.cap]);
|
||||
return out;
|
||||
};
|
||||
const find = (key: string): SweepWord | null => {
|
||||
let hit: SweepWord | null = null;
|
||||
const walk = (ws: SweepWord[]) => {
|
||||
for (const w of ws) {
|
||||
if (w.key === key) hit = w;
|
||||
if (w.kids) walk(w.kids);
|
||||
}
|
||||
};
|
||||
for (const g of state()?.groups ?? []) walk(g.words);
|
||||
return hit;
|
||||
};
|
||||
// The picks there are in this model.
|
||||
const bodies = app.view.bodyList;
|
||||
const picks: [string, Sel[]][] = [["nothing", []]];
|
||||
const b0 = bodies[0];
|
||||
if (b0) {
|
||||
const flat = b0.faces.findIndex((f) => f.type === "PLANE");
|
||||
const straight = b0.edges.findIndex((e) => e.type === "LINE");
|
||||
if (flat >= 0) picks.push(["face", [{ kind: "face", body: b0.id, face: flat }]]);
|
||||
if (straight >= 0) picks.push(["edge", [{ kind: "edge", body: b0.id, edge: straight }]]);
|
||||
picks.push(["corner", [{ kind: "vertex", body: b0.id, vertex: 0 }]], ["body", [{ kind: "body", body: b0.id }]]);
|
||||
if (bodies[1]) picks.push(["two bodies", [{ kind: "body", body: b0.id }, { kind: "body", body: bodies[1].id }]]);
|
||||
}
|
||||
for (const b of bodies) {
|
||||
const round = b.faces.findIndex((f) => f.type !== "PLANE");
|
||||
const rim = b.edges.findIndex((e) => e.type === "CIRCLE");
|
||||
if (round >= 0 && !picks.some((p) => p[0] === "round face")) picks.push(["round face", [{ kind: "face", body: b.id, face: round }]]);
|
||||
if (rim >= 0 && !picks.some((p) => p[0] === "round edge")) picks.push(["round edge", [{ kind: "edge", body: b.id, edge: rim }]]);
|
||||
}
|
||||
const loose = features().find((f) => f.type === "sketch" && !features().some((g) => JSON.stringify(g).includes(`"sketch":"${f.id}"`) && g.id !== f.id));
|
||||
if (loose) picks.push(["sketch shape", [{ kind: "profile", sketch: loose.id, region: 0 }]]);
|
||||
picks.push(["plane", [{ kind: "plane", id: "XY" }]]);
|
||||
// (Things that open a chooser of the device's, which cannot be closed from here.)
|
||||
const skip = /-image$|-file$|insert-project$|refImage$|browser$|custom/i;
|
||||
const out = { started: 0, nothing: [] as string[], errors: [] as string[], options: [] as string[], audit: [] as { pick: string; tool: string; handle: boolean; box: boolean; lit: boolean; numbers: number }[] };
|
||||
for (const [name, sel] of picks) {
|
||||
if (only && !only.includes(name)) continue;
|
||||
await reset();
|
||||
app.setSelection(sel);
|
||||
await settle();
|
||||
for (const leaf of leaves()) {
|
||||
if (skip.test(leaf.key)) continue;
|
||||
await reset();
|
||||
app.setSelection(sel);
|
||||
await settle();
|
||||
const w = find(leaf.key);
|
||||
if (!w) {
|
||||
out.nothing.push(`${name}: ${leaf.path} (not offered a second time)`);
|
||||
continue;
|
||||
}
|
||||
const before = snap();
|
||||
const e0 = errors.length;
|
||||
try {
|
||||
if (w.value) w.value.put(w.value.now + (w.value.max !== undefined && w.value.now >= w.value.max ? -1 : 1));
|
||||
else w.run?.();
|
||||
} catch (err) {
|
||||
out.errors.push(`${name}: ${leaf.path}: ${(err as Error).message}`);
|
||||
continue;
|
||||
}
|
||||
await settle();
|
||||
if (errors.length > e0) out.errors.push(`${name}: ${leaf.path}: ${errors.slice(e0).join("; ")}`);
|
||||
if (snap() === before) {
|
||||
out.nothing.push(`${name}: ${leaf.path}`);
|
||||
continue;
|
||||
}
|
||||
out.started++;
|
||||
const s = state();
|
||||
if (!s?.about.startsWith("tool:")) continue;
|
||||
// What a tool that takes a size should have: a handle on the model, a box for the value, its picks lit.
|
||||
const numbers = s.words.filter((x) => x.value && (x.value.kind === "length" || x.value.kind === "angle")).length;
|
||||
out.audit.push({ pick: name, tool: leaf.path.split(" > ").pop()!, handle: Array.from(app.view.helpers).some((h) => /Handle|Gimbal/.test(h.constructor.name)), box: Array.from(document.querySelectorAll<HTMLElement>(".dim-widget")).some((d) => d.getBoundingClientRect().width > 0), lit: app.selection.length > 0 || ((app.view as unknown as { highlightGroup?: { children: unknown[] } }).highlightGroup?.children.length ?? 0) > 0, numbers });
|
||||
if (!options) continue;
|
||||
// Every option of it.
|
||||
for (const key of s.words.map((x) => x.key)) {
|
||||
const at = () => state()?.words.find((x) => x.key === key);
|
||||
const it = at();
|
||||
if (!it) continue;
|
||||
const what = `${name}: ${leaf.path}: ${it.cap ?? it.label}`;
|
||||
const e1 = errors.length;
|
||||
try {
|
||||
if (it.kind === "choice" && it.kids) {
|
||||
const first = it.kids.find((k) => k.on)?.key;
|
||||
for (const kid of it.kids.map((k) => k.key)) {
|
||||
const k = at()?.kids?.find((x) => x.key === kid);
|
||||
if (!k || k.on) continue;
|
||||
k.run?.();
|
||||
await settle();
|
||||
if (inside.tool.id === "select") break;
|
||||
const now = at()?.kids?.find((x) => x.key === kid);
|
||||
if (k.kind === "verb" && now && !now.on) out.options.push(`${what} > ${k.label}: not set`);
|
||||
}
|
||||
const back = at()?.kids?.find((x) => x.key === first);
|
||||
if (back && !back.on) (back.run?.(), await settle());
|
||||
} else if (it.kind === "toggle") {
|
||||
const was = !!it.on;
|
||||
it.run?.();
|
||||
await settle();
|
||||
const now = at();
|
||||
if (now && !!now.on === was) out.options.push(`${what}: switch did not flip`);
|
||||
now?.run?.();
|
||||
await settle();
|
||||
} else if (it.kind === "value" && it.value) {
|
||||
const v = it.value;
|
||||
v.put(v.kind === "int" ? v.now + 1 : v.kind === "angle" ? v.now + 5 : v.now === 0 ? 3 : v.now * 1.25);
|
||||
await settle();
|
||||
const now = at();
|
||||
if (now?.value && now.value.now === v.now && (v.max === undefined || v.now < v.max)) out.options.push(`${what}: value did not change`);
|
||||
} else if (it.kind === "slot") {
|
||||
it.run?.();
|
||||
await settle();
|
||||
}
|
||||
} catch (err) {
|
||||
out.options.push(`${what}: ${(err as Error).message}`);
|
||||
}
|
||||
if (errors.length > e1) out.options.push(`${what}: ${errors.slice(e1).join("; ")}`);
|
||||
if (inside.tool.id === "select") break;
|
||||
}
|
||||
}
|
||||
}
|
||||
await reset();
|
||||
app.setSelection([]);
|
||||
removeEventListener("error", onError);
|
||||
removeEventListener("unhandledrejection", onReject);
|
||||
return out;
|
||||
},
|
||||
|
||||
/** The reference image windows and their tabs; refAdd(name, dataUrl) opens one as Insert › Reference Image does. */
|
||||
refImages: () => app.refImages.describe(),
|
||||
refAdd: (name: string, src: string) => void app.refImages.add(name, src),
|
||||
|
||||
/** Pick things, as taps would (sg.sel builds them). */
|
||||
select(...sel: Sel[]) {
|
||||
app.setSelection(sel);
|
||||
|
||||
@@ -19,7 +19,7 @@ const dist = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b
|
||||
function worldCage(doc: ProjectDoc, body: string): { feature: FreeformFeature; cage: Cage; m: number[] } | null {
|
||||
const ff = freeformBodies(doc.features).get(body);
|
||||
if (!ff || ff.feature.id !== body) return null;
|
||||
return { feature: ff.feature, m: ff.m, cage: { faces: ff.feature.cage.faces, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) } };
|
||||
return { feature: ff.feature, m: ff.m, cage: { ...ff.feature.cage, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) } };
|
||||
}
|
||||
|
||||
/** The open-border cage edges under the picked body edges (null if one isn't on a border). */
|
||||
@@ -41,12 +41,6 @@ function cageEdgesAt(cage: Cage, picks: Vec3[]): Set<string> | null {
|
||||
|
||||
export type ConnectResult = { doc: ProjectDoc; body: string } | { error: string };
|
||||
|
||||
/** Can these picked edges be connected (for showing the button)? */
|
||||
export function canConnect(doc: ProjectDoc, picks: PickedEdge[]): boolean {
|
||||
const bodies = [...new Set(picks.map((p) => p.body))];
|
||||
return picks.length >= 2 && bodies.length <= 2 && bodies.every((b) => !!worldCage(doc, b));
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect the picked border edges. They must make two runs with the same
|
||||
* number of edges (two edges, two rows, or two hole rims), on one freeform or
|
||||
@@ -88,12 +82,19 @@ export function connectEdges(doc: ProjectDoc, picks: PickedEdge[]): ConnectResul
|
||||
}
|
||||
if (!Q) return { doc: store(doc, P.feature, next, P.m), body: P.feature.id };
|
||||
// Two freeforms → one: the later step keeps it, the earlier one goes.
|
||||
const ia = doc.features.indexOf(P.feature);
|
||||
const ib = doc.features.indexOf(Q.feature);
|
||||
const [keep, drop, mKeep] = ia < ib ? [Q.feature, P.feature, Q.m] : [P.feature, Q.feature, P.m];
|
||||
const users = doc.features.filter((f) => f !== drop && JSON.stringify(f).includes(`"${drop.id}`) && !(f.type === "transform" && !f.copy && ["move", "scale", "mirror", "scaleXYZ"].includes(f.op.kind)));
|
||||
// (By id: an edited freeform's feature here is its step with the edits put in, not the step itself.)
|
||||
const at = (id: string) => doc.features.findIndex((f) => f.id === id);
|
||||
const [keep, drop, mKeep] = at(P.feature.id) < at(Q.feature.id) ? [Q.feature, P.feature, Q.m] : [P.feature, Q.feature, P.m];
|
||||
// Its Edit Freeform steps and its own moves are in the merged cage: they don't keep it from going.
|
||||
const users = doc.features.filter(
|
||||
(f) =>
|
||||
f.id !== drop.id &&
|
||||
!(f.type === "freeformEdit" && (f.target === drop.id || f.target === keep.id)) &&
|
||||
JSON.stringify(f).includes(`"${drop.id}"`) &&
|
||||
!(f.type === "transform" && !f.copy && ["move", "scale", "mirror", "scaleXYZ"].includes(f.op.kind)),
|
||||
);
|
||||
if (users.length) return { error: `“${drop.name}” is used by “${users[0].name}” later on - it can't be merged into the other surface` };
|
||||
const out = store(doc, keep, next, mKeep, { surface: !!(keep.surface || drop.surface) });
|
||||
const out = store({ ...doc, features: doc.features.filter((f) => !(f.type === "freeformEdit" && f.target === drop.id)) }, keep, next, mKeep, { surface: !!(keep.surface || drop.surface) });
|
||||
// The dropped one's own moves go with it (they are already in the merged cage).
|
||||
out.features = out.features
|
||||
.filter((f) => f.id !== drop.id)
|
||||
@@ -103,9 +104,13 @@ export function connectEdges(doc: ProjectDoc, picks: PickedEdge[]): ConnectResul
|
||||
return { doc: out, body: keep.id };
|
||||
}
|
||||
|
||||
/** Put a world-space cage back into a freeform step (in its own coordinates). */
|
||||
/**
|
||||
* Put a world-space cage back into a freeform step (in its own coordinates).
|
||||
* Its Edit Freeform steps go: their edits are in that cage already (and a
|
||||
* later one would otherwise put its own cage back over it).
|
||||
*/
|
||||
function store(doc: ProjectDoc, f: FreeformFeature, cage: Cage, m: number[], extra: Partial<FreeformFeature> = {}): ProjectDoc {
|
||||
const inv = invertAffine(m);
|
||||
const updated: FreeformFeature = { ...f, ...extra, cage: { faces: cage.faces, verts: cage.verts.map((v) => applyAffine(inv, v)) } };
|
||||
return { ...doc, features: doc.features.map((x): Feature => (x.id === f.id ? updated : x)) };
|
||||
const updated: FreeformFeature = { ...f, ...extra, cage: { ...cage, verts: cage.verts.map((v) => applyAffine(inv, v)) } };
|
||||
return { ...doc, features: doc.features.filter((x) => !(x.type === "freeformEdit" && x.target === f.id)).map((x): Feature => (x.id === f.id ? updated : x)) };
|
||||
}
|
||||
|
||||
@@ -83,6 +83,11 @@ export function freeformBodies(features: readonly Feature[], upto = features.len
|
||||
out.set(f.id, { feature: f, m: ID });
|
||||
continue;
|
||||
}
|
||||
// An Edit Freeform step: the freeform (and its copies) with the new cage.
|
||||
if (f.type === "freeformEdit") {
|
||||
for (const [id, ff] of out) if (ff.feature.id === f.target) out.set(id, { ...ff, feature: { ...ff.feature, ...f.patch } });
|
||||
continue;
|
||||
}
|
||||
if (f.type === "transform") {
|
||||
const step = stepAffine(f.op);
|
||||
for (const id of f.bodies) {
|
||||
@@ -130,6 +135,7 @@ export function detachFreeformCopy(doc: ProjectDoc, bodyId: string, newId: strin
|
||||
verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)),
|
||||
// A mirror turns the shape inside out: wind the quads the other way.
|
||||
faces: ff.feature.cage.faces.map((q) => (flip ? ([q[0], q[3], q[2], q[1]] as typeof q) : ([...q] as typeof q))),
|
||||
...(ff.feature.cage.creases ? { creases: structuredClone(ff.feature.cage.creases) } : {}),
|
||||
},
|
||||
};
|
||||
const features = [...doc.features];
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Edit Freeform steps: each holds the new cage of a freeform (or a Freeform
|
||||
// Face step) made earlier. Before a rebuild - and wherever a freeform's cage
|
||||
// is read - the steps that are on are put into what they edit, in order, so
|
||||
// the shape is the last edit's; deleting or rolling back an edit gives the
|
||||
// shape as it was before it.
|
||||
|
||||
import type { Feature, FreeformEditFeature } from "./types";
|
||||
|
||||
/** The steps with their edits put in (the edit steps themselves stay, doing nothing more). */
|
||||
export function applyFreeformEdits<T extends Feature>(features: readonly T[]): T[] {
|
||||
const edits = features.filter((f): f is T & FreeformEditFeature => f.type === "freeformEdit" && !f.suppressed && !f.rolledBack);
|
||||
if (!edits.length) return features as T[];
|
||||
const patch = new Map<string, FreeformEditFeature["patch"]>();
|
||||
for (const e of edits) patch.set(e.target, { ...(patch.get(e.target) ?? {}), ...e.patch });
|
||||
return features.map((f) => {
|
||||
const p = patch.get(f.id);
|
||||
return p && (f.type === "freeform" || f.type === "faceFreeform") ? ({ ...f, ...p } as T) : f;
|
||||
});
|
||||
}
|
||||
|
||||
/** One step as its edits leave it (up to and with the edit `upto`, when given). */
|
||||
export function editedStep<T extends Feature>(features: readonly Feature[], id: string, upto?: string): T | undefined {
|
||||
const end = upto ? features.findIndex((f) => f.id === upto) + 1 : features.length;
|
||||
return applyFreeformEdits(features.slice(0, end > 0 ? end : features.length)).find((f) => f.id === id) as T | undefined;
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
// Parametric document: evaluate expressions (variables) into feature values and
|
||||
// re-solve sketch constraints, so the document's numbers are always consistent.
|
||||
|
||||
import { transformEntity } from "../sketch/edit";
|
||||
import { dot, toPlane, toWorld } from "../geom";
|
||||
import { applyRepeats } from "../sketch/repeat";
|
||||
import { refill } from "../sketch/fill";
|
||||
import { solveFine } from "../sketch/constraints";
|
||||
import { evaluate, setVariables } from "../units";
|
||||
import type { Feature, ProjectDoc } from "./types";
|
||||
import { evaluate, setUnits, setVariables } from "../units";
|
||||
import type { Feature, ProjectDoc, SketchEntity } from "./types";
|
||||
|
||||
/** Kind of value stored at a path (for units: lengths are mm, angles degrees). */
|
||||
export function kindOfPath(path: string): "length" | "angle" | "number" {
|
||||
@@ -13,7 +17,7 @@ export function kindOfPath(path: string): "length" | "angle" | "number" {
|
||||
// A turn's pivot point is a length (only its angle is an angle): a pivot
|
||||
// driven by a variable ("p1") was refused as "can't be evaluated".
|
||||
if (/angle|rot/i.test(last) && !/origin|translate|center/i.test(last)) return "angle";
|
||||
if (/count|factor|sides|opacity|taper/i.test(last)) return "number";
|
||||
if (/count|factor|sides|opacity|taper|starts/i.test(last)) return "number";
|
||||
return "length";
|
||||
}
|
||||
|
||||
@@ -34,6 +38,9 @@ export function setPath(obj: unknown, path: string, value: unknown): void {
|
||||
/** Recompute every expression-driven value and re-solve constrained sketches (in place). */
|
||||
export function resolveDoc(doc: ProjectDoc): string[] {
|
||||
const problems: string[] = [];
|
||||
// (Its own unit, before anything is read: the app set it after this ran, so a project whose unit had just changed
|
||||
// was worked out once more in the old one.)
|
||||
if (doc.units) setUnits(doc.units);
|
||||
setVariables(doc.variables ?? []);
|
||||
for (const f of doc.features as Feature[]) {
|
||||
for (const [path, expr] of Object.entries(f.exprs ?? {})) {
|
||||
@@ -41,6 +48,23 @@ export function resolveDoc(doc: ProjectDoc): string[] {
|
||||
if (v === null) problems.push(`${f.name}: "${expr}" can't be evaluated`);
|
||||
else setPath(f, path, v);
|
||||
}
|
||||
// Curves projected from an earlier sketch: put where that sketch's curves are now (it was changed in History,
|
||||
// or by a variable - a step before this one, already worked out above).
|
||||
if (f.type === "sketch" && f.refs?.length) {
|
||||
const next = refreshRefs(f, doc.features as Feature[]);
|
||||
if (next && !sameNumbers(f.entities, next, 1e-9)) f.entities = next;
|
||||
}
|
||||
// A sketch's patterns that follow a count: the count worked out, their copies made again if it is another number.
|
||||
if (f.type === "sketch" && f.repeats?.length) {
|
||||
for (const r of f.repeats) {
|
||||
const v = evaluate(r.countExpr, "number");
|
||||
if (v === null) problems.push(`${f.name}: "${r.countExpr}" can't be evaluated`);
|
||||
else if (!(v >= 1)) problems.push(`${f.name}: a pattern's count is ${Math.round(v)} ("${r.countExpr}") - it has to be at least 1`);
|
||||
else r.count = Math.round(v);
|
||||
}
|
||||
const again = applyRepeats(f.entities, f.constraints ?? [], f.repeats);
|
||||
if (again) ((f.entities = again.entities), (f.constraints = again.constraints));
|
||||
}
|
||||
if (f.type === "sketch" && f.constraints?.length) {
|
||||
for (const c of f.constraints) {
|
||||
// A point held where X / Y were typed with a variable.
|
||||
@@ -57,7 +81,9 @@ export function resolveDoc(doc: ProjectDoc): string[] {
|
||||
if (v === null) problems.push(`${f.name}: "${c.expr}" can't be evaluated`);
|
||||
else c.value = v;
|
||||
}
|
||||
const r = solveFine(f.entities, f.constraints);
|
||||
// (Curves that are another sketch's stay where that sketch has them: the rest is solved round them.)
|
||||
const held = new Set((f.refs ?? []).map((x) => x.id));
|
||||
const r = solveFine(f.entities, f.constraints, held.size ? { fixed: held } : {});
|
||||
// Can't all be met: the sketch stays as it was rather than being bent out of shape.
|
||||
// Met already (only rounding noise in the 14th digit): kept exactly as it
|
||||
// was - the noise changed the step, and every change anywhere (a colour,
|
||||
@@ -66,10 +92,35 @@ export function resolveDoc(doc: ProjectDoc): string[] {
|
||||
if (!r.ok) problems.push(`${f.name}: constraints can't all be met`);
|
||||
else if (!sameNumbers(f.entities, r.entities, 1e-9)) f.entities = r.entities;
|
||||
}
|
||||
// Fill patterns follow their shapes, here too: a shape that changed size by a variable or a dimension has its
|
||||
// pattern made again (it was only made again when the sketch was changed in the sketch tool).
|
||||
if (f.type === "sketch" && f.fills?.length) {
|
||||
const filled = refill(f.entities, f.fills);
|
||||
if (!sameNumbers(f.entities, filled, 1e-9)) f.entities = filled;
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* A sketch's curves with those it has from an earlier sketch as that sketch has them now, seen from this one's plane
|
||||
* (the two parallel: the same shapes, moved and turned into it). Null: none could be found again.
|
||||
*/
|
||||
function refreshRefs(f: Extract<Feature, { type: "sketch" }>, all: Feature[]): SketchEntity[] | null {
|
||||
let changed = false;
|
||||
const out = f.entities.map((e) => {
|
||||
const ref = f.refs!.find((r) => r.id === e.id);
|
||||
if (!ref) return e;
|
||||
const from = all.find((x) => x.id === ref.sketch);
|
||||
if (!from || from.type !== "sketch" || from === f) return e;
|
||||
const src = from.entities.find((x) => x.id === ref.entity);
|
||||
if (!src || Math.abs(dot(from.plane.normal, f.plane.normal)) < 1 - 1e-9) return e;
|
||||
changed = true;
|
||||
return { ...transformEntity(src, (uv) => toPlane(f.plane, toWorld(from.plane, uv))), id: e.id, ...(e.construction ? { construction: true } : { construction: undefined }) } as SketchEntity;
|
||||
});
|
||||
return changed ? out : null;
|
||||
}
|
||||
|
||||
/** The same structure with every number within `tol` of the other's. */
|
||||
function sameNumbers(a: unknown, b: unknown, tol: number): boolean {
|
||||
if (typeof a === "number" && typeof b === "number") return Math.abs(a - b) <= tol;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// A variable given another name: every formula that uses it says the new name - other variables' values, steps'
|
||||
// sizes, a sketch's dimensions and the points placed by it. Nothing changes size. (A variable could only be deleted
|
||||
// and made again under another name, and everything that used it lost its link to it.)
|
||||
|
||||
import type { ProjectDoc } from "./types";
|
||||
import { RESERVED } from "../units";
|
||||
|
||||
/** A name as it stands in a formula: not part of a longer name or a number ("w" in "w2", in "2.5e3"). */
|
||||
const word = (name: string) => new RegExp(`(^|[^A-Za-z0-9_.])${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![A-Za-z0-9_])`, "g");
|
||||
|
||||
/** `from` replaced by `to` wherever it stands as a name in the formula. */
|
||||
export function renameIn(expr: string, from: string, to: string): string {
|
||||
return expr.replace(word(from), (_, before: string) => `${before}${to}`);
|
||||
}
|
||||
|
||||
/** Why `to` can't be a variable's name here (null: it can). */
|
||||
export function nameProblem(doc: ProjectDoc, from: string, to: string): string | null {
|
||||
if (!/^[a-z_][a-z0-9_]*$/i.test(to) || RESERVED.test(to)) return "Names use letters, digits and _ (not starting with a digit, and not a unit or a function like sin or pi)";
|
||||
const twin = doc.variables.find((v) => v.name !== from && v.name.toLowerCase() === to.toLowerCase());
|
||||
if (twin) return twin.name === to ? `There is a variable ${to} already` : `There is a variable ${twin.name} already: ${to} differs only in its capitals`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The variable `from` called `to` from now on, in place. How many formulas were rewritten (-1: no such variable). */
|
||||
export function renameVariable(doc: ProjectDoc, from: string, to: string): number {
|
||||
const v = doc.variables.find((x) => x.name === from);
|
||||
if (!v || from === to) return v ? 0 : -1;
|
||||
let n = 0;
|
||||
const re = (expr: string): string => {
|
||||
const next = renameIn(expr, from, to);
|
||||
if (next !== expr) n++;
|
||||
return next;
|
||||
};
|
||||
v.name = to;
|
||||
for (const x of doc.variables) x.expr = re(x.expr);
|
||||
for (const f of doc.features) {
|
||||
if (f.exprs) for (const k of Object.keys(f.exprs)) f.exprs[k] = re(f.exprs[k]);
|
||||
if (f.type !== "sketch") continue;
|
||||
for (const r of f.repeats ?? []) r.countExpr = re(r.countExpr);
|
||||
for (const c of f.constraints ?? []) {
|
||||
if (c.expr) c.expr = re(c.expr);
|
||||
if (c.atExpr) c.atExpr = c.atExpr.map((e) => (e ? re(e) : e)) as typeof c.atExpr;
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -57,6 +57,7 @@ const LABELS: Record<FeatureType, string> = {
|
||||
fill: "Fill",
|
||||
connect: "Connect",
|
||||
faceFreeform: "Freeform Face",
|
||||
freeformEdit: "Edit Freeform",
|
||||
thread: "Thread",
|
||||
imprint: "Project as Edge",
|
||||
wrap: "Wrap & Emboss",
|
||||
@@ -175,8 +176,9 @@ export class DocStore {
|
||||
/** Unique id + "Extrude 03"-style name for a new feature. */
|
||||
newIdentity(type: FeatureType, label = LABELS[type]): { id: string; name: string } {
|
||||
// One past the highest number in use (a step deleted from the middle doesn't free its number for a duplicate).
|
||||
const nums = this.doc.features.map((f) => (f.name.startsWith(label + " ") ? Number(f.name.slice(label.length + 1)) : NaN)).filter((x) => Number.isFinite(x));
|
||||
const n = Math.max(0, this.doc.features.filter((f) => f.name.startsWith(label + " ")).length, ...nums) + 1;
|
||||
// Only "<label> <number>": "Freeform surface 01" isn't one of the "Freeform"s.
|
||||
const mine = this.doc.features.filter((f) => f.name.startsWith(label + " ") && /^\d+$/.test(f.name.slice(label.length + 1)));
|
||||
const n = Math.max(0, mine.length, ...mine.map((f) => Number(f.name.slice(label.length + 1)))) + 1;
|
||||
return { id: newId(type), name: `${label} ${String(n).padStart(2, "0")}` };
|
||||
}
|
||||
|
||||
@@ -353,7 +355,13 @@ export class DocStore {
|
||||
this.saveTimer = window.setTimeout(() => {
|
||||
const v = this.edits;
|
||||
const text = JSON.stringify(this.doc);
|
||||
void idbSet("autosave", text).then(() => this.wrote(v));
|
||||
// (A write that failed is tried again: left, the name's mark said "Saving…" from then on.)
|
||||
const write = (tries: number): void =>
|
||||
void idbSet("autosave", text).then(
|
||||
() => this.wrote(v),
|
||||
() => tries > 0 && v === this.edits && window.setTimeout(() => write(tries - 1), 2000),
|
||||
);
|
||||
write(3);
|
||||
this.onSaved?.(text);
|
||||
// The undo steps less eagerly: they're bigger, and only matter after a reload.
|
||||
clearTimeout(this.historyTimer);
|
||||
@@ -402,10 +410,28 @@ export function parseProject(text: string): ProjectDoc {
|
||||
// ------------------------------------------------------------------ migration
|
||||
|
||||
/** Bring any saved project up to the current format. */
|
||||
/**
|
||||
* A project file can come from anyone: what the app later puts on the page as a colour is kept to what a colour
|
||||
* is ("#rrggbb"), and what it uses as a number is a number. Anything else is dropped (the body is the default grey).
|
||||
*/
|
||||
function cleanLooks(doc: ProjectDoc): void {
|
||||
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
|
||||
const record = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
if (doc.colors !== undefined) doc.colors = record(doc.colors) ? Object.fromEntries(Object.entries(doc.colors).filter((e): e is [string, string] => typeof e[1] === "string" && hex.test(e[1]))) : undefined;
|
||||
if (doc.opacity !== undefined) doc.opacity = record(doc.opacity) ? Object.fromEntries(Object.entries(doc.opacity).filter((e): e is [string, number] => typeof e[1] === "number" && Number.isFinite(e[1]))) : undefined;
|
||||
if (Array.isArray(doc.customMaterials)) for (const m of doc.customMaterials) if (typeof m.color !== "string" || !hex.test(m.color)) m.color = "#9aa3ad";
|
||||
}
|
||||
|
||||
export function migrate(raw: unknown): ProjectDoc {
|
||||
const out = migrate0(raw);
|
||||
cleanLooks(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
function migrate0(raw: unknown): ProjectDoc {
|
||||
const doc = raw as ProjectDoc & { version: number };
|
||||
// "tessel" is the format name of files saved before the rename.
|
||||
if (!doc || (doc.format !== "super" && (doc.format as string) !== "tessel") || !Array.isArray(doc.features)) throw new Error("Not a supergeometry.app project file");
|
||||
if (!doc || (doc.format !== "super" && (doc.format as string) !== "tessel") || !Array.isArray(doc.features)) throw new Error("Not a superGeometry.app project file");
|
||||
if (doc.version === 2) return { ...emptyDoc(), ...doc, format: "super" };
|
||||
// A newer app saved it: read as an old one, it would come out mangled.
|
||||
if (doc.version > 2) throw new Error("This project was saved by a newer version of the app - reload the page to update");
|
||||
|
||||
@@ -23,15 +23,23 @@ export type SketchEntity = EntityBase &
|
||||
/** Arc through a (start), m (any point on it) and b (end). */
|
||||
| { kind: "arc"; a: Vec2; m: Vec2; b: Vec2 }
|
||||
| { kind: "circle"; center: Vec2; radius: number }
|
||||
| { kind: "ellipse"; center: Vec2; rx: number; ry: number; rotation: number }
|
||||
| { kind: "spline"; points: Vec2[]; closed: boolean; mode: "fit" | "control" }
|
||||
/**
|
||||
* `sweep` given: a part of the ellipse, from the angle `a0` on it (0 is the
|
||||
* end of its rx axis) round by `sweep` (radians, + anticlockwise) - what a
|
||||
* round edge seen at a slant is, with two ends like the edge. Neither: whole.
|
||||
*/
|
||||
| { kind: "ellipse"; center: Vec2; rx: number; ry: number; rotation: number; a0?: number; sweep?: number }
|
||||
/**
|
||||
* `z`: how far each of its points is off the sketch's plane (mm along the plane's normal; missing, or not one
|
||||
* for each point: flat). The curve then runs through space - a path for a sweep, a guide for a loft. Everything
|
||||
* that works in the plane (shapes to extrude, constraints, snapping, DXF) goes by its shadow on the plane.
|
||||
*/
|
||||
| { kind: "spline"; points: Vec2[]; closed: boolean; mode: "fit" | "control"; z?: number[] }
|
||||
| { kind: "rect"; center: Vec2; w: number; h: number; rotation: number }
|
||||
| { kind: "polygon"; center: Vec2; radius: number; sides: number; angle: number }
|
||||
| { kind: "polyline"; points: Vec2[]; closed: boolean }
|
||||
);
|
||||
|
||||
export type EntityKind = SketchEntity["kind"];
|
||||
|
||||
/** A sketch region, referenced by where it is rather than an index (see regions.ts). */
|
||||
export interface RegionRef {
|
||||
c: Vec2;
|
||||
@@ -121,7 +129,8 @@ export type ConstraintType =
|
||||
| "fix"
|
||||
| "distance"
|
||||
| "dim"
|
||||
| "pattern";
|
||||
| "pattern"
|
||||
| "follow";
|
||||
|
||||
/**
|
||||
* Sketch constraint. Geometry refs: `pts` (points) and `curves` (entity ids).
|
||||
@@ -142,6 +151,14 @@ export interface SketchConstraint {
|
||||
atExpr?: (string | null)[];
|
||||
/** pattern: "turn" - the copy is the original turned `value` degrees round `at`; else moved by `at`. */
|
||||
turn?: boolean;
|
||||
/** dim: put on by Lock (a locked circle keeps its size) - Unlock takes it off with the lock. */
|
||||
held?: boolean;
|
||||
/**
|
||||
* follow: how the second curve is made from the first - its offset by so much, or its mirror image across a line.
|
||||
* The copy stays that as the original changes. `loose`: a piece of an offset outline, trimmed to meet its
|
||||
* neighbours - it stays on the original's offset, its ends where its neighbours put them.
|
||||
*/
|
||||
how?: { offset?: number; mirror?: [Vec2, Vec2]; loose?: boolean };
|
||||
}
|
||||
|
||||
export interface SketchFeature extends FeatureBase {
|
||||
@@ -171,7 +188,61 @@ export interface SketchFeature extends FeatureBase {
|
||||
links?: EdgeLink[];
|
||||
|
||||
/** What was done in the sketch, in order (shown under it in History); repeats are counted. */
|
||||
log?: { op: string; n: number }[];
|
||||
log?: { op: string; n: number; ids?: string[] }[];
|
||||
/**
|
||||
* Fill patterns: closed shapes of the sketch filled with lines or small shapes (see sketch/fill.ts). Each one's
|
||||
* curves are among `entities`, named "fp-<fill id>-<n>", and are made again when the sketch's curves change.
|
||||
*/
|
||||
fills?: SketchFill[];
|
||||
/**
|
||||
* Patterns whose count is a variable or a formula (see sketch/repeat.ts): their copies - curves named
|
||||
* "rp-<pattern>-<copy>-<curve>" - are made again when the count comes to another number.
|
||||
*/
|
||||
repeats?: SketchRepeat[];
|
||||
/**
|
||||
* Curves projected from another sketch: each is that sketch's curve, seen from this one's plane, and is put there
|
||||
* again whenever that sketch changes (the two planes parallel).
|
||||
*/
|
||||
refs?: SketchRef[];
|
||||
}
|
||||
|
||||
/** A curve of a sketch that is a curve of an earlier sketch, projected (see SketchFeature.refs). */
|
||||
export interface SketchRef {
|
||||
/** The curve here. */
|
||||
id: string;
|
||||
/** The sketch it comes from, and its curve there. */
|
||||
sketch: string;
|
||||
entity: string;
|
||||
}
|
||||
|
||||
/** A sketch pattern that follows its count (a pattern made with a plain number is only its copies). */
|
||||
export interface SketchRepeat {
|
||||
id: string;
|
||||
/** The curves repeated. */
|
||||
src: string[];
|
||||
kind: "linear" | "circular";
|
||||
/** How many there are, the originals counted (worked out from `countExpr`). */
|
||||
count: number;
|
||||
countExpr: string;
|
||||
/** Linear: from one to the next. */
|
||||
step?: Vec2;
|
||||
/** Circular: the point they go round, and the angle they are spread over (degrees; 360: all the way). */
|
||||
at?: Vec2;
|
||||
angle?: number;
|
||||
}
|
||||
|
||||
/** A closed shape of a sketch filled with a pattern (Fill Pattern). */
|
||||
export interface SketchFill {
|
||||
id: string;
|
||||
/** A point inside the shape it fills. */
|
||||
at: Vec2;
|
||||
kind: "lines" | "cross" | "zigzag" | "waves" | "dots" | "hex" | "squares" | "diamonds";
|
||||
/** Lines: how far apart. Shapes: the gap between one and the next (mm). */
|
||||
spacing: number;
|
||||
/** The pattern turned by this much (degrees). */
|
||||
angle: number;
|
||||
/** Shapes: how big each is. Zigzag, waves: how big a tooth or a wave is (mm). */
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface ExtrudeFeature extends FeatureBase {
|
||||
@@ -181,6 +252,14 @@ export interface ExtrudeFeature extends FeatureBase {
|
||||
/** auto: join `target` when distance > 0, cut it when < 0; new body without a target. */
|
||||
mode: "auto" | "new" | "join" | "cut" | "intersect";
|
||||
target?: string;
|
||||
/**
|
||||
* Auto by the way it goes (extrudes made since this was added): with no body
|
||||
* of its own (drawn on a plane, not on a face) a new body going +, a cut of
|
||||
* what it runs into going - (a new body if it runs into nothing). Without
|
||||
* it, as before: a cut of whatever it runs into, either way - kept so that
|
||||
* projects made then come out as they were.
|
||||
*/
|
||||
byDirection?: boolean;
|
||||
/**
|
||||
* How big the far end is, as a fraction of the shape (1 or missing: straight
|
||||
* sides; 0.5: half size; near 0: to a point - a spire, a pyramid, a cone).
|
||||
@@ -229,6 +308,14 @@ export interface BooleanFeature extends FeatureBase {
|
||||
keepTarget?: boolean;
|
||||
/** Subtract / Intersect: the bodies it was changed with stay. */
|
||||
keepTools?: boolean;
|
||||
/** Subtract: the gap (mm) the cut leaves between the bodies (missing: none, they meet). */
|
||||
clearance?: number;
|
||||
/**
|
||||
* Subtract: which bodies give way - the body (missing: the usual subtract),
|
||||
* the bodies it's subtracted with (each cut by the body, which stays), or
|
||||
* all of them (each cut by every other, half the gap each).
|
||||
*/
|
||||
cutFrom?: "body" | "tools" | "all";
|
||||
/**
|
||||
* Patterns it used whole (`<pattern step>:<original body>`): the original and
|
||||
* every copy there was when it was made. They stay whole when the pattern's
|
||||
@@ -333,6 +420,11 @@ export interface TransformFeature extends FeatureBase {
|
||||
* freeform copies become freeforms of their own.
|
||||
*/
|
||||
link?: boolean;
|
||||
/**
|
||||
* A pattern of a hole (its round wall picked): the hole is cut again at each place of the pattern, in the body it
|
||||
* is in - the body itself is not copied. `bodies` is that one body.
|
||||
*/
|
||||
hole?: FaceRef;
|
||||
op:
|
||||
| { kind: "move"; translate: Vec3; rotate?: { origin: Vec3; axis: Vec3; angle: number } }
|
||||
/** `ref`: scaled by reference - the two points picked (center is the first), the distance typed between them. */
|
||||
@@ -372,8 +464,12 @@ export interface AxisFeature extends FeatureBase {
|
||||
type: "axis";
|
||||
origin: Vec3;
|
||||
dir: Vec3;
|
||||
/** What it was made from (its icon): square to a face, along an edge, a round face's middle, two points, two planes. */
|
||||
kind?: AxisKind;
|
||||
}
|
||||
|
||||
export type AxisKind = "face" | "edge" | "round" | "2pt" | "planes";
|
||||
|
||||
/** A body imported from a file. The file content travels inside the project. */
|
||||
export interface ImportFeature extends FeatureBase {
|
||||
type: "import";
|
||||
@@ -381,6 +477,11 @@ export interface ImportFeature extends FeatureBase {
|
||||
fileName: string;
|
||||
/** Base64 of the file. */
|
||||
data: string;
|
||||
/**
|
||||
* Each solid in the file is a body of its own (the first has this step's id, the others "<id>:1", "<id>:2"...).
|
||||
* Missing (files put in before this): all of them one body, as they were - what was built on that body stays.
|
||||
*/
|
||||
apart?: boolean;
|
||||
}
|
||||
|
||||
/** A reference image placed on a plane (for tracing). */
|
||||
@@ -426,7 +527,7 @@ export interface MoveFaceFeature extends FeatureBase {
|
||||
*/
|
||||
export interface FreeformFeature extends FeatureBase {
|
||||
type: "freeform";
|
||||
cage: { verts: Vec3[]; faces: [number, number, number, number][] };
|
||||
cage: { verts: Vec3[]; faces: [number, number, number, number][]; creases?: [number, number][] };
|
||||
/** Made as an open surface on purpose (a sheet): no "not closed" warning. */
|
||||
surface?: boolean;
|
||||
/** An open freeform becomes a solid this thick (0 / missing: stays a surface). */
|
||||
@@ -437,6 +538,19 @@ export interface FreeformFeature extends FeatureBase {
|
||||
symmetry?: { origin: Vec3; normal: Vec3 };
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit Freeform done on a freeform (or a Freeform Face step) made earlier: its
|
||||
* new cage, a step of its own in History. The shape is the earlier step's with
|
||||
* this put in (see applyFreeformEdits): delete or roll back this step and the
|
||||
* shape is as it was before the edit.
|
||||
*/
|
||||
export interface FreeformEditFeature extends FeatureBase {
|
||||
type: "freeformEdit";
|
||||
/** The freeform / Freeform Face step it edits. */
|
||||
target: string;
|
||||
patch: Partial<Pick<FreeformFeature, "cage" | "surface" | "thickness" | "thickSide" | "symmetry">> & { grid?: number; more?: FaceRef[] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Scale one flat face within its own plane (factors along its u and v axes);
|
||||
* the flat faces around it tilt to follow its edges.
|
||||
@@ -481,6 +595,11 @@ export interface ThreadFeature extends FeatureBase {
|
||||
pitch: number;
|
||||
/** Left-handed (turns the other way). */
|
||||
left?: boolean;
|
||||
/**
|
||||
* How many threads run side by side (missing: 1). `pitch` stays the distance from one crest to the next; one turn
|
||||
* then moves a nut `starts` pitches along - a jar's lid, on in a quarter turn.
|
||||
*/
|
||||
starts?: number;
|
||||
/** The face as it was picked (for the panel when editing: the face itself is threaded by then). */
|
||||
round?: { r: number; hole: boolean };
|
||||
}
|
||||
@@ -504,6 +623,11 @@ export interface ThreadFeature extends FeatureBase {
|
||||
export interface FaceFreeformFeature extends FeatureBase {
|
||||
type: "faceFreeform";
|
||||
face: FaceRef;
|
||||
/**
|
||||
* More faces of the body, side by side with `face`, made one smooth
|
||||
* surface with it (no edge left where they met).
|
||||
*/
|
||||
more?: FaceRef[];
|
||||
/**
|
||||
* The cage shaping it, laid over the face: points relative to the face's
|
||||
* middle (so it follows the face when an earlier step moves it). Its border
|
||||
@@ -586,6 +710,7 @@ export type Feature =
|
||||
| ScaleFaceFeature
|
||||
| ReplaceFaceFeature
|
||||
| FreeformFeature
|
||||
| FreeformEditFeature
|
||||
| DeleteGeomFeature
|
||||
| MoveFaceFeature
|
||||
| SketchFeature
|
||||
@@ -661,6 +786,12 @@ export interface ProjectDoc {
|
||||
drawing?: DrawingOptions;
|
||||
/** BIM: the project's drawings, each its own sheet. */
|
||||
drawings?: DrawingOptions[];
|
||||
/** Assemblies: how the bodies are held together (see assembly/joints.ts). */
|
||||
joints?: import("../assembly/joints").Joint[];
|
||||
/** Assemblies: the body that stands still (missing: the first of each group of joined bodies). */
|
||||
ground?: string;
|
||||
/** Assemblies: where the parts were left - each joint's value by its id (0, or missing: as modelled), and how far they are pulled apart (0 to 1). */
|
||||
pose?: { values: Record<string, number>; exploded?: number };
|
||||
}
|
||||
|
||||
/** The drawing sheet: paper size, projection method, scale (missing: the largest that fits), what it shows. */
|
||||
@@ -694,6 +825,8 @@ export interface DrawingOptions {
|
||||
/** Line widths, mm. */
|
||||
lines?: { visible?: number; hidden?: number; dims?: number; center?: number; section?: number };
|
||||
balloons?: boolean;
|
||||
/** Item numbers moved by hand: where each one's circle is (mm on the paper), by the part it numbers. */
|
||||
balloonAt?: Record<string, [number, number]>;
|
||||
/** The overall sizes dimensioned by themselves. */
|
||||
overall?: boolean;
|
||||
/** What was changed on an overall size, by its id (overall-width, overall-height, overall-depth): where it sits, its text, taken off. */
|
||||
@@ -840,6 +973,8 @@ export interface DrawingNote {
|
||||
x: number;
|
||||
y: number;
|
||||
text: string;
|
||||
/** How tall its letters are, mm on the paper (missing: 3.5). */
|
||||
size?: number;
|
||||
/** What it points at: a point on a view (that view's coordinates), its leader drawn to it. */
|
||||
to?: { view: string; p: [number, number] };
|
||||
}
|
||||
@@ -885,12 +1020,18 @@ export interface MaterialDef {
|
||||
expansion?: number;
|
||||
conductivity?: number;
|
||||
specificHeat?: number;
|
||||
/** Elongation at break, %. */
|
||||
elongation?: number;
|
||||
/** Melting point (a metal's: where it starts to melt), °C. */
|
||||
melting?: number;
|
||||
/** The warmest it is used at for long (a plastic's: about where it starts to soften under load), °C. */
|
||||
maxTemp?: number;
|
||||
}
|
||||
|
||||
/** The body colours offered by the Color tool (first = default). */
|
||||
/** The body colours offered by the Color tool: seven, Custom the eighth (no Grey - a body is grey until given one; a tap on its lit colour makes it grey again). Bodies given another before keep it (shown as Custom). */
|
||||
export const DEFAULT_BODY_COLOR = "#b9bec7";
|
||||
export const BODY_COLORS: { name: string; hex: string }[] = [
|
||||
// Soft, muted tones (easy on the eyes, still easy to tell apart).
|
||||
{ name: "Grey", hex: "#b9bec7" },
|
||||
{ name: "Red", hex: "#b9726b" },
|
||||
{ name: "Orange", hex: "#c29069" },
|
||||
{ name: "Yellow", hex: "#c4b277" },
|
||||
@@ -898,8 +1039,6 @@ export const BODY_COLORS: { name: string; hex: string }[] = [
|
||||
{ name: "Teal", hex: "#71a39c" },
|
||||
{ name: "Blue", hex: "#7c98c2" },
|
||||
{ name: "Violet", hex: "#9a8bc0" },
|
||||
{ name: "Pink", hex: "#bb8aa9" },
|
||||
{ name: "Brown", hex: "#93806e" },
|
||||
];
|
||||
|
||||
/** The first, brighter palette → its softer version (projects saved before keep their choice). */
|
||||
@@ -922,10 +1061,11 @@ export function bodyColor(hex: string | undefined): string | undefined {
|
||||
|
||||
/** The see-through levels offered next to Color (1 = solid). */
|
||||
export const BODY_OPACITY: { name: string; value: number }[] = [
|
||||
// (Named by how see-through, as the Transparency list says: 25% lets a little through.)
|
||||
{ name: "Solid", value: 1 },
|
||||
{ name: "75%", value: 0.75 },
|
||||
{ name: "25%", value: 0.75 },
|
||||
{ name: "50%", value: 0.5 },
|
||||
{ name: "25%", value: 0.25 },
|
||||
{ name: "75%", value: 0.25 },
|
||||
];
|
||||
|
||||
export interface HistoryGroup {
|
||||
@@ -962,4 +1102,6 @@ export interface OutlineOffset {
|
||||
distance: number;
|
||||
/** Where the outline was tapped (sketch coordinates): the loop nearest it is offset. */
|
||||
at: Vec2;
|
||||
/** Just the edge nearest `at`, not the whole loop it is part of (Offset Edge's "Edge"). */
|
||||
single?: boolean;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
// The project's unit changed: every formula keeps the size it had.
|
||||
//
|
||||
// A plain number in a formula is in the unit in use ("160" is 160 mm, or 160 in). So with the unit changed from mm to
|
||||
// inches, a variable od = 160 was 160 inches from then on, and the whole model 25 times its size. Here each formula
|
||||
// that would change is written so that it does not: its plain lengths get the unit they were typed in ("160 mm",
|
||||
// "od / 2 + 5 mm"). What is no length - a count, a factor, an angle - is left as it is.
|
||||
|
||||
import { kindOfPath } from "./params";
|
||||
import { namesIn } from "./varAnchors";
|
||||
import type { ProjectDoc, Units, Variable } from "./types";
|
||||
import { UNIT_MM, valueAt } from "../units";
|
||||
|
||||
const NUM = String.raw`(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?`;
|
||||
|
||||
/** Rewrites the project's formulas for a change of unit (in place). Returns how many it could not keep as they were. */
|
||||
export function keepSizes(doc: ProjectDoc, from: Units, to: Units): { changed: number; lost: number } {
|
||||
const out = { changed: 0, lost: 0 };
|
||||
if (from === to) return out;
|
||||
const sFrom = UNIT_MM[from];
|
||||
const sTo = UNIT_MM[to];
|
||||
const old: Variable[] = doc.variables.map((v) => ({ ...v }));
|
||||
const vars = doc.variables;
|
||||
const same = (a: number, b: number) => Math.abs(a - b) <= 1e-9 * Math.max(1, Math.abs(a), Math.abs(b));
|
||||
/** How a formula's size goes with the unit in use: 0 not at all, 1 in step with it; NaN neither (or it can't be read). */
|
||||
const degree = (text: string): number => {
|
||||
const a = valueAt(text, sFrom, vars);
|
||||
const b = valueAt(text, sFrom * 2, vars);
|
||||
if (a === null || b === null) return NaN;
|
||||
return same(a, b) ? 0 : same(b, 2 * a) ? 1 : NaN;
|
||||
};
|
||||
/** One part of a sum, its size fixed to the unit it was typed in. */
|
||||
const pin = (term: string): string | null => {
|
||||
const want = valueAt(term, sFrom, vars);
|
||||
if (want === null) return null;
|
||||
// (The spaces round it stay where they were.)
|
||||
const [, pre, core, post] = /^(\s*)(.*?)(\s*)$/s.exec(term)!;
|
||||
const lead = new RegExp(String.raw`^(-?\s*${NUM})(\s*(?:[*/].*)?)$`, "is").exec(core);
|
||||
const tries = [...(lead ? [`${lead[1]} ${from}${lead[2]}`] : []), `(${core}) ${from}`];
|
||||
for (const t of tries) {
|
||||
const got = valueAt(t, sTo, vars);
|
||||
if (got !== null && same(got, want) && degree(t) === 0) return pre + t + post;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
/** A formula with each part that goes with the unit fixed to it - into its brackets where a part is mixed. */
|
||||
const fixed = (expr: string): string => {
|
||||
if (degree(expr) === 0) return expr;
|
||||
return terms(expr)
|
||||
.map((t) => {
|
||||
if (t.op) return t.text;
|
||||
const d = degree(t.text);
|
||||
if (d === 0) return t.text;
|
||||
const whole = d === 1 ? pin(t.text) : null;
|
||||
if (whole) return whole;
|
||||
// Mixed (a length with its unit beside a plain one, inside brackets): each bracket's own parts.
|
||||
const inner = brackets(t.text, fixed);
|
||||
return degree(inner) === 1 ? (pin(inner) ?? inner) : inner;
|
||||
})
|
||||
.join("");
|
||||
};
|
||||
const rewrite = (expr: string, was: number | null): string => {
|
||||
if (was === null) return expr;
|
||||
const now = valueAt(expr, sTo, vars);
|
||||
if (now !== null && same(now, was)) return expr;
|
||||
const next = fixed(expr);
|
||||
const got = valueAt(next, sTo, vars);
|
||||
if (got !== null && same(got, was)) {
|
||||
out.changed++;
|
||||
return next;
|
||||
}
|
||||
// (Not a sum of plain parts - "a * b" of two lengths: the whole of it, if that is in step with the unit.)
|
||||
const whole = degree(expr) === 1 ? pin(expr) : null;
|
||||
if (whole) {
|
||||
out.changed++;
|
||||
return whole;
|
||||
}
|
||||
out.lost++;
|
||||
return expr;
|
||||
};
|
||||
|
||||
// What each formula comes to now, before anything is touched.
|
||||
const before = new Map<string, number | null>();
|
||||
for (const v of old) before.set(`v:${v.name}`, valueAt(v.expr, sFrom, old));
|
||||
// Variables used as a count, a factor or an angle somewhere (and the ones those are made from) stay as they are:
|
||||
// "6" with a unit after it is no count. Where one of them is used as a length, that place is fixed instead.
|
||||
const plain = new Set<string>();
|
||||
const mark = (expr: string) => {
|
||||
for (const n of namesIn(expr)) {
|
||||
if (plain.has(n)) continue;
|
||||
const v = old.find((x) => x.name === n);
|
||||
if (!v) continue;
|
||||
plain.add(n);
|
||||
mark(v.expr);
|
||||
}
|
||||
};
|
||||
for (const f of doc.features) {
|
||||
for (const [path, expr] of Object.entries(f.exprs ?? {})) if (kindOfPath(path) !== "length") mark(expr);
|
||||
if (f.type === "sketch") for (const c of f.constraints ?? []) if (c.expr && c.prop === "angle") mark(c.expr);
|
||||
}
|
||||
// Variables first, each after the ones it is made from (so those are already as they will be).
|
||||
const done = new Set<string>();
|
||||
for (let pass = 0; pass <= vars.length; pass++) {
|
||||
for (const v of vars) {
|
||||
if (done.has(v.name)) continue;
|
||||
const needs = namesIn(v.expr).filter((n) => n !== v.name && vars.some((x) => x.name === n));
|
||||
if (pass < vars.length && needs.some((n) => !done.has(n))) continue;
|
||||
done.add(v.name);
|
||||
if (!plain.has(v.name)) v.expr = rewrite(v.expr, before.get(`v:${v.name}`) ?? null);
|
||||
}
|
||||
}
|
||||
// Then every size that follows a formula.
|
||||
const length = (expr: string) => rewrite(expr, valueAt(expr, sFrom, old));
|
||||
for (const f of doc.features) {
|
||||
for (const [path, expr] of Object.entries(f.exprs ?? {})) if (kindOfPath(path) === "length") f.exprs![path] = length(expr);
|
||||
if (f.type !== "sketch") continue;
|
||||
for (const c of f.constraints ?? []) {
|
||||
if (c.expr && c.prop !== "angle") c.expr = length(c.expr);
|
||||
if (c.atExpr) c.atExpr = c.atExpr.map((e) => (e ? length(e) : e));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A formula as the parts of its sum: each part, and the + or - between them (brackets kept whole). */
|
||||
function terms(expr: string): { text: string; op: boolean }[] {
|
||||
const out: { text: string; op: boolean }[] = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
for (let i = 0; i < expr.length; i++) {
|
||||
const c = expr[i];
|
||||
if (c === "(") depth++;
|
||||
else if (c === ")") depth--;
|
||||
else if ((c === "+" || c === "-") && depth === 0) {
|
||||
const before = expr.slice(start, i).trimEnd();
|
||||
// A sign, not a sum: at the start, after another operator, or the exponent of 1e-3.
|
||||
if (!before || /[-+*/^(]$/.test(before) || (/\de$/i.test(before) && /^\d/.test(expr.slice(i + 1)))) continue;
|
||||
out.push({ text: expr.slice(start, i), op: false }, { text: c, op: true });
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
out.push({ text: expr.slice(start), op: false });
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A part of a formula with what is inside each of its outermost brackets put through `each` - the values of min(...)
|
||||
* and max(...) one by one.
|
||||
*/
|
||||
function brackets(text: string, each: (inner: string) => string): string {
|
||||
let out = "";
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
let many = false;
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
const c = text[i];
|
||||
if (c === "(") {
|
||||
if (depth++ === 0) {
|
||||
many = /\b(min|max)\s*$/i.test(text.slice(0, i));
|
||||
out += text.slice(start, i + 1);
|
||||
start = i + 1;
|
||||
}
|
||||
} else if (c === ")") {
|
||||
if (--depth === 0) {
|
||||
out += each(text.slice(start, i));
|
||||
start = i;
|
||||
}
|
||||
} else if ((c === "," || c === ";") && depth === 1 && many) {
|
||||
out += each(text.slice(start, i)) + c;
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
return out + text.slice(start);
|
||||
}
|
||||
@@ -276,7 +276,8 @@ export function useSpot(u: VarUse, features: readonly Feature[], world: AnchorWo
|
||||
if (!f) return null;
|
||||
if (f.type === "sketch") {
|
||||
const c = f.constraints?.find((x) => x.id === u.where);
|
||||
const at = c && dimSpot(c, f.entities);
|
||||
// (A point placed by it - X typed as "pcd / 2": at that point. It had no tag at all.)
|
||||
const at = c && (dimSpot(c, f.entities) ?? (c.type === "fix" && c.at ? c.at : null));
|
||||
if (!at) return null;
|
||||
const p = toWorld(world.sketchPlanes[f.id] ?? f.plane, at);
|
||||
// A construction line is no part of a body: it stays where it was drawn
|
||||
@@ -308,7 +309,12 @@ export function useSpot(u: VarUse, features: readonly Feature[], world: AnchorWo
|
||||
const plane = world.planes?.find((x) => x.id === f.id);
|
||||
if (plane) return plane.plane.origin;
|
||||
const b = bodyOf(f);
|
||||
return b ? bodyMiddle(world, b) : null;
|
||||
const mid = b ? bodyMiddle(world, b) : null;
|
||||
if (mid) return mid;
|
||||
// A pattern whose copies have since gone into another body (holes cut with them): on what it turns about, or at
|
||||
// its first copy's place - the count of a ring of holes had no tag.
|
||||
if (f.type === "transform" && f.op.kind === "circular") return f.op.axis.origin;
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface VarTag {
|
||||
@@ -329,7 +335,7 @@ export interface VarTag {
|
||||
/** One tag per variable. */
|
||||
export function variableTags(variables: readonly Variable[], features: readonly Feature[], world: AnchorWorld): VarTag[] {
|
||||
const uses = usesOf(features);
|
||||
return variables.map((v) => {
|
||||
const tags: VarTag[] = variables.map((v) => {
|
||||
// Its tag at the use that says most where it acts: a turn's pivot, then a
|
||||
// step's value, then a dimension of the shape, then a construction line -
|
||||
// where it's the value itself before where it's part of a formula.
|
||||
@@ -352,4 +358,16 @@ export function variableTags(variables: readonly Variable[], features: readonly
|
||||
const to = variables.filter((w) => madeFrom(w.name, variables).includes(v.name)).map((w) => w.name);
|
||||
return { name: v.name, marks, to, kind: kindOfVariable(v.name, variables, uses), at: spots[0] ?? null, others: spots.slice(1), from: madeFrom(v.name, variables) };
|
||||
});
|
||||
// One that only other variables are made from (a wall that the hub's size is worked out from) has no place of its
|
||||
// own: it goes by the first of those that has one (the tags there fan out), so it can be tapped like the rest.
|
||||
for (let pass = 0; pass < tags.length; pass++) {
|
||||
let moved = false;
|
||||
for (const t of tags) {
|
||||
if (t.at) continue;
|
||||
const by = t.to.map((n) => tags.find((x) => x.name === n)).find((x) => x?.at);
|
||||
if (by?.at) (t.at = by.at), (moved = true);
|
||||
}
|
||||
if (!moved) break;
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
@@ -11,9 +11,17 @@ export interface Cage {
|
||||
verts: Vec3[];
|
||||
/** Quads, as vertex indices in order around the face. */
|
||||
faces: [number, number, number, number][];
|
||||
/**
|
||||
* Sharp edges: cage edges the surface keeps a crease along instead of
|
||||
* rounding over - it follows them as an open border is followed (a smooth
|
||||
* curve through the edge's points), and where three or more meet, or one
|
||||
* ends at a corner of the border, the point is a corner. One on its own,
|
||||
* ending in the middle of the surface, fades out there.
|
||||
*/
|
||||
creases?: [number, number][];
|
||||
}
|
||||
|
||||
export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere";
|
||||
export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere" | "torus";
|
||||
|
||||
// ------------------------------------------------------------- primitives
|
||||
|
||||
@@ -95,6 +103,32 @@ export function cylinderCage(d = 40, h = 40, rows = 2, at: Vec3 = [0, 0, 0]): Ca
|
||||
return { verts, faces };
|
||||
}
|
||||
|
||||
/**
|
||||
* A ring (a torus) lying on `at`: `d` across the outside, `t` thick (its
|
||||
* tube), 8 faces round the ring and 2·rows round the tube (4 at least).
|
||||
* Every point has four faces round it, so it comes out smooth all over.
|
||||
*/
|
||||
export function torusCage(d = 40, t = 12, rows = 2, at: Vec3 = [0, 0, 0]): Cage {
|
||||
const N = 8;
|
||||
const M = Math.max(4, 2 * Math.round(rows));
|
||||
const R = Math.max(0.01, (d - t) / 2);
|
||||
// A cage a little bigger round the tube than the tube: subdivision shrinks it.
|
||||
const r = (t / 2) * (M <= 4 ? 1.3 : 1.12);
|
||||
const verts: Vec3[] = [];
|
||||
for (let i = 0; i < N; i++)
|
||||
for (let j = 0; j < M; j++) {
|
||||
const a = (i / N) * Math.PI * 2;
|
||||
const b = (j / M) * Math.PI * 2;
|
||||
const w = R + Math.cos(b) * r;
|
||||
verts.push([at[0] + Math.cos(a) * w, at[1] + Math.sin(a) * w, at[2] + t / 2 + Math.sin(b) * r]);
|
||||
}
|
||||
const id = (i: number, j: number) => (i % N) * M + (j % M);
|
||||
const faces: Cage["faces"] = [];
|
||||
// (Wound so the normals point out of the tube.)
|
||||
for (let i = 0; i < N; i++) for (let j = 0; j < M; j++) faces.push([id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)]);
|
||||
return { verts, faces };
|
||||
}
|
||||
|
||||
/**
|
||||
* Close an 8-point rim with a 2×2 grid of quads: its corners are rim points
|
||||
* 1, 3, 5, 7, its edge midpoints rim 0, 2, 4, 6, and a new centre point.
|
||||
@@ -120,6 +154,7 @@ function capGrid(verts: Vec3[], faces: Cage["faces"], R: number, N: number, z: n
|
||||
export function shapeCage(kind: Exclude<CagePrimitive, "plane">, size: Vec3, rows = 2): Cage {
|
||||
const r = Math.max(1, Math.round(rows));
|
||||
if (kind === "box") return boxCage(size, r);
|
||||
if (kind === "torus") return torusCage(size[0], size[2], r);
|
||||
if (kind === "sphere") {
|
||||
const c = sphereCage(size[0]);
|
||||
return { faces: c.faces, verts: c.verts.map((v) => [v[0], (v[1] * size[1]) / size[0], (v[2] * size[2]) / size[0]] as Vec3) };
|
||||
@@ -140,6 +175,8 @@ export function primitiveCage(kind: CagePrimitive, at: Vec3 = [0, 0, 0]): Cage {
|
||||
return cylinderCage(40, 40, 2, at);
|
||||
case "sphere":
|
||||
return sphereCage(40, at);
|
||||
case "torus":
|
||||
return torusCage(40, 12, 2, at);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +189,8 @@ export interface Subdivided {
|
||||
grids: number[][][];
|
||||
/** Size of each grid side in cells (2^levels). */
|
||||
n: number;
|
||||
/** The sharp edges at this level (as "a,b" with a < b), where the cage has some. */
|
||||
creased?: Set<string>;
|
||||
}
|
||||
|
||||
const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
|
||||
@@ -163,6 +202,8 @@ const mul3 = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];
|
||||
* corner (a sheet laid over a face: the face's own corners).
|
||||
*/
|
||||
export function subdivide(cage: Cage, levels = 3, sharp?: Set<number>): Subdivided {
|
||||
// Sharp edges, as they are at each level (each is two at the next).
|
||||
let creased = new Set((cage.creases ?? []).map(([a, b]) => (a < b ? `${a},${b}` : `${b},${a}`)));
|
||||
let points = cage.verts.map((p) => [...p] as Vec3);
|
||||
let grids = cage.faces.map((f) => [
|
||||
[f[0], f[3]],
|
||||
@@ -193,7 +234,7 @@ export function subdivide(cage: Cage, levels = 3, sharp?: Set<number>): Subdivid
|
||||
for (const [key, fs] of edgeFaces) {
|
||||
const [a, b] = key.split(",").map(Number);
|
||||
const mid = mul3(add3(points[a], points[b]), 0.5);
|
||||
edgePos.set(key, fs.length === 2 ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid);
|
||||
edgePos.set(key, fs.length === 2 && !creased.has(key) ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid);
|
||||
}
|
||||
// Vertex points.
|
||||
const vFaces = new Map<number, number[]>();
|
||||
@@ -204,11 +245,15 @@ export function subdivide(cage: Cage, levels = 3, sharp?: Set<number>): Subdivid
|
||||
const es = vEdges.get(v);
|
||||
const fs = vFaces.get(v);
|
||||
if (!es || !fs) return p;
|
||||
const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1);
|
||||
const border = es.filter((k) => edgeFaces.get(k)!.length === 1);
|
||||
const crease = creased.size ? es.filter((k) => creased.has(k) && edgeFaces.get(k)!.length === 2) : [];
|
||||
// (A sharp edge is followed as the border is. Three or more at a point, sharp or border: a corner.)
|
||||
if (crease.length && border.length + crease.length > 2) return p;
|
||||
const boundary = crease.length ? [...border, ...crease] : border;
|
||||
if (boundary.length >= 2) {
|
||||
// Boundary: a cubic B-spline along the border; a corner (two faces meet at an angle) stays put.
|
||||
// (Told which points are corners: only those - a sheet's own corner on a round edge isn't one.)
|
||||
if (sharp ? sharp.has(v) : fs.length === 1) return p;
|
||||
if (!crease.length && (sharp ? sharp.has(v) : fs.length === 1)) return p;
|
||||
const others = boundary.slice(0, 2).map((k) => {
|
||||
const [a, b] = k.split(",").map(Number);
|
||||
return points[a === v ? b : a];
|
||||
@@ -237,10 +282,20 @@ export function subdivide(cage: Cage, levels = 3, sharp?: Set<number>): Subdivid
|
||||
for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) ng[2 * i + 1][2 * j + 1] = faceIdx[qi++];
|
||||
return ng;
|
||||
});
|
||||
if (creased.size) {
|
||||
const halves = new Set<string>();
|
||||
for (const key of creased) {
|
||||
const m = edgeIdx.get(key);
|
||||
if (m === undefined) continue;
|
||||
const [a, b] = key.split(",").map(Number);
|
||||
halves.add(ekey(a, m)).add(ekey(m, b));
|
||||
}
|
||||
creased = halves;
|
||||
}
|
||||
points = next;
|
||||
n = N;
|
||||
}
|
||||
return { points, grids, n };
|
||||
return { points, grids, n, ...(creased.size ? { creased } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -274,9 +329,25 @@ export function limitPoints(s: Subdivided, sharp?: Set<number>): Vec3[] {
|
||||
if (edgeCount.get(ekey(v, a)) === 1) border[v].push(a);
|
||||
if (edgeCount.get(ekey(v, b)) === 1) border[v].push(b);
|
||||
}
|
||||
// Sharp edges: followed as the border is.
|
||||
const sharpAt = P.map(() => [] as number[]);
|
||||
for (const key of s.creased ?? []) {
|
||||
const [a, b] = key.split(",").map(Number);
|
||||
if (edgeCount.get(key) !== 2) continue;
|
||||
sharpAt[a].push(b);
|
||||
sharpAt[b].push(a);
|
||||
}
|
||||
return P.map((p, v) => {
|
||||
if (!faces[v]) return p;
|
||||
const bd = [...new Set(border[v])];
|
||||
const open = [...new Set(border[v])];
|
||||
const cr = sharpAt[v];
|
||||
if (cr.length) {
|
||||
// Two (sharp or border) through the point: on that curve. More: a corner. One, in the middle: it fades out (smooth).
|
||||
const through = [...new Set([...open, ...cr])];
|
||||
if (through.length > 2) return p;
|
||||
if (through.length === 2) return [0, 1, 2].map((k) => (P[through[0]][k] + 4 * p[k] + P[through[1]][k]) / 6) as Vec3;
|
||||
}
|
||||
const bd = open;
|
||||
if (bd.length) {
|
||||
// On an open border: a corner (one face) stays; otherwise the border curve's point.
|
||||
if ((sharp ? sharp.has(v) : faces[v] === 1) || bd.length !== 2) return p;
|
||||
@@ -405,7 +476,7 @@ function compose(a: Rows, b: Rows): Rows {
|
||||
|
||||
/** The layout key of a cage: its faces (positions don't matter). */
|
||||
export function layoutKey(cage: Cage): string {
|
||||
return `${cage.verts.length}|${cage.faces.join(";")}`;
|
||||
return `${cage.verts.length}|${cage.faces.join(";")}${cage.creases?.length ? `|${cage.creases.join(";")}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -423,11 +494,14 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
|
||||
[f[1], f[2]],
|
||||
]);
|
||||
let n = 1;
|
||||
// Sharp edges (see subdivide), as pairs: the numbering of a level's edges changes with it.
|
||||
let sharpPairs: [number, number][] = (cage.creases ?? []).map(([a, b]) => [a, b]);
|
||||
const addTo = (m: Map<number, number>, i: number, w: number) => m.set(i, (m.get(i) ?? 0) + w);
|
||||
for (let lvl = 0; lvl < levels; lvl++) {
|
||||
const quads: number[][] = [];
|
||||
for (const g of grids) for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) quads.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]);
|
||||
const ekey = (a: number, b: number) => (a < b ? a * count + b : b * count + a);
|
||||
const creased = new Set(sharpPairs.map(([a, b]) => ekey(a, b)));
|
||||
// Edges in first-seen order (subdivide numbers its edge points that way).
|
||||
const edgeFaces = new Map<number, number[]>();
|
||||
quads.forEach((q, qi) => {
|
||||
@@ -457,9 +531,12 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
|
||||
if (!es.length || !fs.length) {
|
||||
m.set(v, 1);
|
||||
} else {
|
||||
const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1);
|
||||
if (boundary.length >= 2) {
|
||||
if (fs.length === 1) m.set(v, 1);
|
||||
const border = es.filter((k) => edgeFaces.get(k)!.length === 1);
|
||||
const crease = creased.size ? es.filter((k) => creased.has(k) && edgeFaces.get(k)!.length === 2) : [];
|
||||
const boundary = crease.length ? [...border, ...crease] : border;
|
||||
if (crease.length && boundary.length > 2) m.set(v, 1);
|
||||
else if (boundary.length >= 2) {
|
||||
if (!crease.length && fs.length === 1) m.set(v, 1);
|
||||
else {
|
||||
addTo(m, v, 0.75);
|
||||
for (const k of boundary.slice(0, 2)) {
|
||||
@@ -485,7 +562,7 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
|
||||
for (const [key, fs] of edgeFaces) {
|
||||
const [a, b] = ends(key);
|
||||
const m = new Map<number, number>();
|
||||
if (fs.length === 2) {
|
||||
if (fs.length === 2 && !creased.has(key)) {
|
||||
addTo(m, a, 0.25);
|
||||
addTo(m, b, 0.25);
|
||||
for (const f of fs) for (const q of quads[f]) addTo(m, q, 0.0625);
|
||||
@@ -506,6 +583,14 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
|
||||
const edgeIdx = new Map<number, number>();
|
||||
let e = count;
|
||||
for (const key of edgeFaces.keys()) edgeIdx.set(key, e++);
|
||||
if (sharpPairs.length) {
|
||||
const halves: [number, number][] = [];
|
||||
for (const [a, b] of sharpPairs) {
|
||||
const mid = edgeIdx.get(ekey(a, b));
|
||||
if (mid !== undefined) halves.push([a, mid], [mid, b]);
|
||||
}
|
||||
sharpPairs = halves;
|
||||
}
|
||||
let qi = 0;
|
||||
const N = 2 * n;
|
||||
const faceBase = e;
|
||||
@@ -541,12 +626,24 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan {
|
||||
if (edgeCount.get(ek(v, a)) === 1) border[v].push(a);
|
||||
if (edgeCount.get(ek(v, b)) === 1) border[v].push(b);
|
||||
}
|
||||
const sharpAt: number[][] = Array.from({ length: count }, () => []);
|
||||
for (const [a, b] of sharpPairs) {
|
||||
if (edgeCount.get(ek(a, b)) !== 2) continue;
|
||||
sharpAt[a].push(b);
|
||||
sharpAt[b].push(a);
|
||||
}
|
||||
const lim = new RowBuilder();
|
||||
for (let v = 0; v < count; v++) {
|
||||
const m = new Map<number, number>();
|
||||
const bd = [...new Set(border[v])];
|
||||
const nE = nbE[v].size;
|
||||
if (!faces[v] || (bd.length && (faces[v] === 1 || bd.length !== 2)) || (!bd.length && nE !== faces[v])) m.set(v, 1);
|
||||
const through = sharpAt[v].length ? [...new Set([...bd, ...sharpAt[v]])] : [];
|
||||
if (through.length > 2) m.set(v, 1);
|
||||
else if (through.length === 2) {
|
||||
addTo(m, through[0], 1 / 6);
|
||||
addTo(m, v, 4 / 6);
|
||||
addTo(m, through[1], 1 / 6);
|
||||
} else if (!faces[v] || (bd.length && (faces[v] === 1 || bd.length !== 2)) || (!bd.length && nE !== faces[v])) m.set(v, 1);
|
||||
else if (bd.length) {
|
||||
addTo(m, bd[0], 1 / 6);
|
||||
addTo(m, v, 4 / 6);
|
||||
@@ -619,37 +716,6 @@ export function smoothNormals(pos: Float32Array, tri: Uint32Array, out?: Float32
|
||||
return nrm;
|
||||
}
|
||||
|
||||
/** Triangles of the subdivided surface (for the live preview). */
|
||||
export function previewMesh(s: Subdivided): { positions: Float32Array; normals: Float32Array; indices: Uint32Array } {
|
||||
const positions = new Float32Array(s.points.flat());
|
||||
const idx: number[] = [];
|
||||
for (const g of s.grids)
|
||||
for (let i = 0; i < s.n; i++)
|
||||
for (let j = 0; j < s.n; j++) {
|
||||
const a = g[i][j];
|
||||
const b = g[i + 1][j];
|
||||
const c = g[i + 1][j + 1];
|
||||
const d = g[i][j + 1];
|
||||
idx.push(a, b, c, a, c, d);
|
||||
}
|
||||
// Smooth normals: area-weighted average of the triangles around each point.
|
||||
const nrm = new Float32Array(positions.length);
|
||||
for (let t = 0; t < idx.length; t += 3) {
|
||||
const [a, b, c] = [idx[t], idx[t + 1], idx[t + 2]].map((k) => s.points[k]);
|
||||
const u: Vec3 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||
const v: Vec3 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
|
||||
const n: Vec3 = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
|
||||
for (const k of [idx[t], idx[t + 1], idx[t + 2]]) for (let q = 0; q < 3; q++) nrm[k * 3 + q] += n[q];
|
||||
}
|
||||
for (let k = 0; k < nrm.length; k += 3) {
|
||||
const l = Math.hypot(nrm[k], nrm[k + 1], nrm[k + 2]) || 1;
|
||||
nrm[k] /= l;
|
||||
nrm[k + 1] /= l;
|
||||
nrm[k + 2] /= l;
|
||||
}
|
||||
return { positions, normals: nrm, indices: new Uint32Array(idx) };
|
||||
}
|
||||
|
||||
/** Cage edges (each once), for drawing and picking. */
|
||||
export function cageEdges(cage: Cage): [number, number][] {
|
||||
const seen = new Set<string>();
|
||||
@@ -708,13 +774,65 @@ export function moveTurnScale(pts: Vec3[], mode: "move" | "turn" | "scale", [x,
|
||||
/** Remove faces; points no face uses any more go too (indices are renumbered). */
|
||||
export function deleteFaces(cage: Cage, faces: number[]): Cage {
|
||||
const drop = new Set(faces);
|
||||
return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)) });
|
||||
return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)), creases: cage.creases });
|
||||
}
|
||||
|
||||
function compact(cage: Cage): Cage {
|
||||
const used = [...new Set(cage.faces.flat())].sort((a, b) => a - b);
|
||||
const map = new Map(used.map((v, i) => [v, i]));
|
||||
return { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) };
|
||||
const out: Cage = { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) };
|
||||
return withCreases(out, (cage.creases ?? []).flatMap(([a, b]) => (map.has(a) && map.has(b) ? [[map.get(a)!, map.get(b)!] as [number, number]] : [])));
|
||||
}
|
||||
|
||||
/** The cage with these sharp edges - those that are edges of it (none: no list at all). */
|
||||
export function withCreases(cage: Cage, creases: [number, number][]): Cage {
|
||||
const { creases: _old, ...rest } = cage;
|
||||
if (!creases.length) return rest;
|
||||
const edges = new Set<string>();
|
||||
for (const f of cage.faces) for (let k = 0; k < 4; k++) edges.add(ekey(f[k], f[(k + 1) % 4]));
|
||||
const seen = new Set<string>();
|
||||
const kept = creases.filter(([a, b]) => edges.has(ekey(a, b)) && !seen.has(ekey(a, b)) && !!seen.add(ekey(a, b)));
|
||||
return kept.length ? { ...rest, creases: kept } : rest;
|
||||
}
|
||||
|
||||
/**
|
||||
* A cage made from another by a tool (a loop added, faces pulled out, a hole
|
||||
* filled...) with the other's sharp edges on it: each where it still is - the
|
||||
* same edge, or, where the tool cut it (a loop across it), the pieces of it.
|
||||
* Found by where the points are: the tools number points as they please.
|
||||
*/
|
||||
export function carryCreases(prev: Cage, next: Cage): Cage {
|
||||
if (next.creases || !prev.creases?.length) return next;
|
||||
const at = new Map<string, number>();
|
||||
const pos = (p: Vec3) => `${p[0].toFixed(6)},${p[1].toFixed(6)},${p[2].toFixed(6)}`;
|
||||
next.verts.forEach((p, i) => at.set(pos(p), i));
|
||||
const edges = new Set<string>();
|
||||
for (const f of next.faces) for (let k = 0; k < 4; k++) edges.add(ekey(f[k], f[(k + 1) % 4]));
|
||||
const out: [number, number][] = [];
|
||||
for (const [a, b] of prev.creases) {
|
||||
const [pa, pb] = [prev.verts[a], prev.verts[b]];
|
||||
const [ia, ib] = [at.get(pos(pa)), at.get(pos(pb))];
|
||||
if (ia === undefined || ib === undefined) continue;
|
||||
if (edges.has(ekey(ia, ib))) {
|
||||
out.push([ia, ib]);
|
||||
continue;
|
||||
}
|
||||
// Cut: the points of the new cage along it, in order, joined where they are edges.
|
||||
const d: Vec3 = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]];
|
||||
const l2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
|
||||
if (l2 < 1e-18) continue;
|
||||
const on: { i: number; t: number }[] = [];
|
||||
next.verts.forEach((q, i) => {
|
||||
const w: Vec3 = [q[0] - pa[0], q[1] - pa[1], q[2] - pa[2]];
|
||||
const t = (w[0] * d[0] + w[1] * d[1] + w[2] * d[2]) / l2;
|
||||
if (t < -1e-9 || t > 1 + 1e-9) return;
|
||||
const off = Math.hypot(w[0] - d[0] * t, w[1] - d[1] * t, w[2] - d[2] * t);
|
||||
if (off < Math.sqrt(l2) * 1e-6) on.push({ i, t });
|
||||
});
|
||||
on.sort((x, y) => x.t - y.t);
|
||||
for (let k = 0; k + 1 < on.length; k++) if (edges.has(ekey(on[k].i, on[k + 1].i))) out.push([on[k].i, on[k + 1].i]);
|
||||
}
|
||||
return withCreases(next, out);
|
||||
}
|
||||
|
||||
const ekey = (a: number, b: number) => (a < b ? `${a},${b}` : `${b},${a}`);
|
||||
@@ -778,7 +896,7 @@ export function refineCage(cage: Cage): Cage {
|
||||
const s = subdivide(cage, 1);
|
||||
const faces: Cage["faces"] = [];
|
||||
for (const g of s.grids) for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) faces.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]);
|
||||
return compact({ verts: s.points, faces });
|
||||
return compact({ verts: s.points, faces, creases: [...(s.creased ?? [])].map((k) => k.split(",").map(Number) as [number, number]) });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1223,6 +1341,102 @@ const cross3 = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[
|
||||
|
||||
// ------------------------------------------------- adding cage detail
|
||||
|
||||
/**
|
||||
* Take an edge loop out: the loop of edges through a-b (straight on through
|
||||
* each point four edges meet at, round the shape or from border to border)
|
||||
* goes, and the two faces either side of each of its edges become one. The
|
||||
* points of the loop go with it. Null where the loop cannot be followed (a
|
||||
* point on it where three or five edges meet), or where an edge of it is on
|
||||
* the border.
|
||||
*/
|
||||
/**
|
||||
* The loop of edges through a-b: straight on through each point four edges
|
||||
* meet at, round the shape or from border to border. Null where it cannot be
|
||||
* followed (a point where three or five edges meet) - or, `lenient`, the part
|
||||
* of it that can.
|
||||
*/
|
||||
export function edgeLoopOf(cage: Cage, a: number, b: number, lenient = false): [number, number][] | null {
|
||||
const efs = edgeFaceMap(cage);
|
||||
if (!efs.has(ekey(a, b))) return null;
|
||||
const around = new Map<number, number[]>();
|
||||
for (const key of efs.keys()) {
|
||||
const [p, q] = key.split(",").map(Number);
|
||||
around.set(p, [...(around.get(p) ?? []), q]);
|
||||
around.set(q, [...(around.get(q) ?? []), p]);
|
||||
}
|
||||
// From `from` on through `at`: the edge at `at` that shares no face with the one arrived by.
|
||||
const onward = (from: number, at: number): number | null | undefined => {
|
||||
const ns = around.get(at) ?? [];
|
||||
const border = ns.filter((n) => efs.get(ekey(at, n))!.length === 1);
|
||||
// (At the border the loop ends: its last point has the two border edges and the one arrived by.)
|
||||
if (border.length) return ns.length === 3 && border.length === 2 ? null : undefined;
|
||||
if (ns.length !== 4) return undefined;
|
||||
const mine = new Set(efs.get(ekey(from, at)));
|
||||
const next = ns.filter((n) => n !== from && !efs.get(ekey(at, n))!.some((f) => mine.has(f)));
|
||||
return next.length === 1 ? next[0] : undefined;
|
||||
};
|
||||
const loop: [number, number][] = [[a, b]];
|
||||
const seen = new Set([ekey(a, b)]);
|
||||
let closed = false;
|
||||
for (const dir of [0, 1]) {
|
||||
let [from, at] = dir ? [b, a] : [a, b];
|
||||
for (let guard = 0; guard < cage.verts.length + 2; guard++) {
|
||||
const next = onward(from, at);
|
||||
if (next === undefined) {
|
||||
if (lenient) break;
|
||||
return null;
|
||||
}
|
||||
if (next === null) break;
|
||||
if (seen.has(ekey(at, next))) {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
seen.add(ekey(at, next));
|
||||
loop.push([at, next]);
|
||||
[from, at] = [at, next];
|
||||
}
|
||||
if (closed) break;
|
||||
}
|
||||
return loop;
|
||||
}
|
||||
|
||||
export function removeEdgeLoop(cage: Cage, a: number, b: number): Cage | null {
|
||||
const efs = edgeFaceMap(cage);
|
||||
const loop = edgeLoopOf(cage, a, b);
|
||||
if (!loop) return null;
|
||||
const gone = new Set<number>();
|
||||
const made: Quad[] = [];
|
||||
for (const [p, q] of loop) {
|
||||
const fs = efs.get(ekey(p, q))!;
|
||||
if (fs.length !== 2) return null;
|
||||
// The face that winds p then q, and the one that winds q then p: p-q-c-d and q-p-e-f.
|
||||
const turn = (f: Quad, x: number, y: number): Quad | null => {
|
||||
for (let k = 0; k < 4; k++) if (f[k] === x && f[(k + 1) % 4] === y) return [f[k], f[(k + 1) % 4], f[(k + 2) % 4], f[(k + 3) % 4]];
|
||||
return null;
|
||||
};
|
||||
const A = turn(cage.faces[fs[0]], p, q) ?? turn(cage.faces[fs[1]], p, q);
|
||||
const B = turn(cage.faces[fs[0]], q, p) ?? turn(cage.faces[fs[1]], q, p);
|
||||
if (!A || !B) return null;
|
||||
made.push([A[3], B[2], B[3], A[2]]);
|
||||
gone.add(fs[0]).add(fs[1]);
|
||||
}
|
||||
// (A face on both sides of two loop edges - a loop one face wide round a corner - cannot be merged twice.)
|
||||
if (gone.size !== loop.length * 2) return null;
|
||||
// Sharp edges the loop crossed: each was cut in two at a point of the loop - with that point gone, it is one again.
|
||||
const onLoop = new Set(loop.flat());
|
||||
const creases: [number, number][] = [];
|
||||
const cutAt = new Map<number, number[]>();
|
||||
for (const [p, q] of cage.creases ?? []) {
|
||||
if (onLoop.has(p) && onLoop.has(q)) continue;
|
||||
if (onLoop.has(p)) cutAt.set(p, [...(cutAt.get(p) ?? []), q]);
|
||||
else if (onLoop.has(q)) cutAt.set(q, [...(cutAt.get(q) ?? []), p]);
|
||||
else creases.push([p, q]);
|
||||
}
|
||||
for (const ends of cutAt.values()) if (ends.length === 2) creases.push([ends[0], ends[1]]);
|
||||
const out = compact({ verts: cage.verts, faces: [...cage.faces.filter((_, i) => !gone.has(i)), ...made], creases });
|
||||
return out.faces.length ? out : null;
|
||||
}
|
||||
|
||||
type Quad = Cage["faces"][number];
|
||||
|
||||
/** Faces using each edge. */
|
||||
|
||||
@@ -98,6 +98,9 @@ function carried(c: (t: number) => Vec3, n: number): { P: Vec3[]; F: Frame[] } {
|
||||
return { P, F };
|
||||
}
|
||||
|
||||
/** The directions across a curve at `n` + 1 points along it, carried without twisting (as the sweep carries the bridge's outline). */
|
||||
export const carriedFrames = (c: (t: number) => Vec3, n: number): Frame[] => carried(c, n).F;
|
||||
|
||||
/**
|
||||
* Whether a curve (0..1) never turns tighter than the bridge is wide: at each
|
||||
* point its radius more than how far the outline reaches towards the middle
|
||||
|
||||
@@ -238,3 +238,115 @@ export function faceCage(tris: [Vec3, Vec3, Vec3][], center: Vec3, normal: Vec3,
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Freeform Face over several faces side by side (a top and the side it bends
|
||||
* into): one way they all face - the middle of their normals - to lay one grid
|
||||
* over all of them, seen along it.
|
||||
*/
|
||||
export function facesNormal(normals: Vec3[]): Vec3 {
|
||||
const s = normals.reduce((a, n) => {
|
||||
const m = norm(n);
|
||||
return [a[0] + m[0], a[1] + m[1], a[2] + m[2]] as Vec3;
|
||||
}, [0, 0, 0] as Vec3);
|
||||
return norm(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* How far along `normal` from `p` the faces made of `tris` are (the nearest
|
||||
* way; null when no triangle is under or over it).
|
||||
*/
|
||||
export function toFaces(p: Vec3, normal: Vec3, tris: [Vec3, Vec3, Vec3][]): number | null {
|
||||
let best: number | null = null;
|
||||
for (const [a, b, c] of tris) {
|
||||
// Where the line p + t·normal meets the triangle's plane, and whether that is inside it.
|
||||
const e1 = sub(b, a);
|
||||
const e2 = sub(c, a);
|
||||
const h = cross(normal, e2);
|
||||
const det = dot(e1, h);
|
||||
if (Math.abs(det) < 1e-12) continue;
|
||||
const s = sub(p, a);
|
||||
const u = dot(s, h) / det;
|
||||
const q = cross(s, e1);
|
||||
const v = dot(normal, q) / det;
|
||||
const eps = 1e-6;
|
||||
if (u < -eps || v < -eps || u + v > 1 + eps) continue;
|
||||
const t = dot(e2, q) / det;
|
||||
if (best === null || Math.abs(t) < Math.abs(best)) best = t;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** A grid laid flat (points relative to `center`) put down onto the faces it was laid over, each point straight along `normal`. */
|
||||
export function liftOnto(cage: Cage, center: Vec3, normal: Vec3, tris: [Vec3, Vec3, Vec3][]): Cage {
|
||||
const n = norm(normal);
|
||||
return {
|
||||
faces: cage.faces,
|
||||
verts: cage.verts.map((v) => {
|
||||
const t = toFaces([center[0] + v[0], center[1] + v[1], center[2] + v[2]], n, tris);
|
||||
return t === null || Math.abs(t) < 1e-9 ? v : ([v[0] + n[0] * t, v[1] + n[1] * t, v[2] + n[2] * t] as Vec3);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the outline of faces side by side turns sharply (a top meeting the
|
||||
* side it bends into: its outline turns down there), the nearest border point
|
||||
* of the grid goes right onto that corner - the smooth surface's border bends
|
||||
* only at its points, and would cut the corner off the body's edge. (Points
|
||||
* relative to `center`.)
|
||||
*/
|
||||
export function onCorners(cage: Cage, center: Vec3, tris: [Vec3, Vec3, Vec3][]): Cage {
|
||||
const key = (p: Vec3) => p.map((x) => Math.round(x * 1e4)).join(",");
|
||||
const at = new Map<string, Vec3>();
|
||||
const uses = new Map<string, number>();
|
||||
for (const t of tris)
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const a = key(t[k]);
|
||||
const b = key(t[(k + 1) % 3]);
|
||||
if (a === b) continue;
|
||||
at.set(a, t[k]);
|
||||
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
|
||||
uses.set(e, (uses.get(e) ?? 0) + 1);
|
||||
}
|
||||
const nb = new Map<string, string[]>();
|
||||
for (const [e, c] of uses) {
|
||||
if (c !== 1) continue;
|
||||
const [a, b] = e.split("|");
|
||||
nb.set(a, [...(nb.get(a) ?? []), b]);
|
||||
nb.set(b, [...(nb.get(b) ?? []), a]);
|
||||
}
|
||||
const corners: Vec3[] = [];
|
||||
for (const [k, ns] of nb) {
|
||||
if (ns.length !== 2) continue;
|
||||
const p = at.get(k)!;
|
||||
const d1 = norm(sub(p, at.get(ns[0])!));
|
||||
const d2 = norm(sub(at.get(ns[1])!, p));
|
||||
if (dot(d1, d2) < Math.cos((25 * Math.PI) / 180)) corners.push(p);
|
||||
}
|
||||
const border = new Set<number>();
|
||||
const count = new Map<string, number>();
|
||||
for (const f of cage.faces)
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const a = f[k];
|
||||
const b = f[(k + 1) % 4];
|
||||
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
|
||||
count.set(e, (count.get(e) ?? 0) + 1);
|
||||
}
|
||||
for (const [e, c] of count) if (c === 1) for (const v of e.split("|")) border.add(Number(v));
|
||||
const verts = cage.verts.map((v) => [...v] as Vec3);
|
||||
const taken = new Set<number>();
|
||||
for (const c of corners) {
|
||||
const rel = sub(c, center);
|
||||
let best = -1;
|
||||
let bd = Infinity;
|
||||
for (const i of border) {
|
||||
const d = Math.hypot(verts[i][0] - rel[0], verts[i][1] - rel[1], verts[i][2] - rel[2]);
|
||||
if (d < bd) ((bd = d), (best = i));
|
||||
}
|
||||
if (best < 0 || taken.has(best)) continue;
|
||||
taken.add(best);
|
||||
verts[best] = rel;
|
||||
}
|
||||
return { faces: cage.faces, verts };
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ export function glb(bodies: GlbBody[], title: string): Uint8Array {
|
||||
nodes.push({ name: b.name, mesh: i });
|
||||
});
|
||||
const json = {
|
||||
asset: { version: "2.0", generator: "supergeometry.app" },
|
||||
asset: { version: "2.0", generator: "superGeometry.app" },
|
||||
scene: 0,
|
||||
scenes: [{ name: title, nodes: [0] }],
|
||||
nodes,
|
||||
|
||||
@@ -5,16 +5,29 @@ import type { Feature, ImageFeature, PlaneDef, SketchEntity, SketchFeature } fro
|
||||
import { GROUND } from "../geom";
|
||||
import { uid } from "../sketch/edit";
|
||||
import type { AppContext } from "../tools/tool";
|
||||
import { bareExpr, evaluate, fmtLen, setVariables, withUnitOf } from "../units";
|
||||
import { bareExpr, evaluate, fmtLen, RESERVED, setVariables, withUnitOf } from "../units";
|
||||
import { namesIn } from "../doc/varAnchors";
|
||||
import { nameProblem, renameVariable } from "../doc/renameVariable";
|
||||
import { DIALOG_ACTION } from "../ui/dialogAction";
|
||||
import { read3mf } from "./formats";
|
||||
import { parseSVG } from "./svg";
|
||||
|
||||
/**
|
||||
* What a file picker is told to offer. On an iPad or iPhone, nothing: told a list of endings (".stl,.step,.super"),
|
||||
* the Files window there greys out every file whose kind it has no name for - STL and STEP files and the app's own
|
||||
* projects could not be tapped (reported from an iPad, files in iCloud Drive). Every file can be picked there, and
|
||||
* one that is not of a kind the app reads is said so once picked. (A list of kinds alone, "image/*", is understood.)
|
||||
*/
|
||||
export function acceptFor(accept: string): string {
|
||||
const apple = /iPad|iPhone|iPod/.test(navigator.userAgent) || (/Macintosh/.test(navigator.userAgent) && navigator.maxTouchPoints > 1);
|
||||
return apple && accept.split(",").some((a) => a.trim().startsWith(".")) ? "" : accept;
|
||||
}
|
||||
|
||||
export function pickFile(accept: string): Promise<File | null> {
|
||||
return new Promise((resolve) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = accept;
|
||||
input.accept = acceptFor(accept);
|
||||
input.onchange = () => resolve(input.files?.[0] ?? null);
|
||||
input.click();
|
||||
});
|
||||
@@ -67,6 +80,8 @@ export async function insertFile(app: AppContext): Promise<void> {
|
||||
insertProject(app, parseProject(await file.text()).features, file.name);
|
||||
return;
|
||||
}
|
||||
// (Any file can be picked on an iPad: see acceptFor.)
|
||||
if (!["step", "stp", "stl", "obj", "3mf"].includes(ext)) return app.ui.toast(`Could not insert ${file.name}: it is not a kind of file the app reads (STEP, STL, OBJ, 3MF, DXF, SVG or a project)`, "error");
|
||||
let bytes: Uint8Array = new Uint8Array(await file.arrayBuffer());
|
||||
let format: "step" | "stl" = ext === "stl" ? "stl" : "step";
|
||||
if (ext === "obj") {
|
||||
@@ -80,7 +95,7 @@ export async function insertFile(app: AppContext): Promise<void> {
|
||||
const why = unreadable(bytes, format);
|
||||
if (why) return app.ui.toast(`Could not insert ${file.name}: ${why}`, "error");
|
||||
app.ui.setStatus(`Importing ${file.name}…`);
|
||||
app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes) });
|
||||
app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes), apart: true });
|
||||
app.ui.setStatus(null);
|
||||
} catch (err) {
|
||||
app.ui.setStatus(null);
|
||||
@@ -146,8 +161,10 @@ export async function createVariable(app: AppContext, value = ""): Promise<strin
|
||||
for (;;) {
|
||||
const r = await createOne(app, name, value);
|
||||
first ??= r.made;
|
||||
if (!r.another) return first;
|
||||
// A bad name or value: the next window has what was typed, to put right.
|
||||
// A bad name or value: the next window has what was typed, to put right (after OK too: the window closed, and
|
||||
// what was typed was gone).
|
||||
const again = !r.made && !!(r.typed.name.trim() || r.typed.expr.trim());
|
||||
if (!r.another && !again) return first;
|
||||
[name, value] = r.made ? ["", ""] : [r.typed.name, r.typed.expr];
|
||||
}
|
||||
}
|
||||
@@ -166,19 +183,36 @@ async function createOne(app: AppContext, name: string, value: string): Promise<
|
||||
function makeVariable(app: AppContext, list: AppContext["store"]["doc"]["variables"], v: Record<string, string>): string | null {
|
||||
const name = v.name.trim();
|
||||
// (A variable called sin or pi hid the function: sin(30) stopped working.)
|
||||
if (!/^[a-z_][a-z0-9_]*$/i.test(name) || /^(mm|cm|m|in|ft|deg|pi|sqrt|abs|sin|cos|tan)$/i.test(name)) {
|
||||
if (!/^[a-z_][a-z0-9_]*$/i.test(name) || RESERVED.test(name)) {
|
||||
app.ui.toast("Names use letters, digits and _ (not starting with a digit, and not a unit or a function like sin or pi)", "error");
|
||||
return null;
|
||||
}
|
||||
// (od and Od would be two variables, and one typed for the other is a wrong size with nothing said.)
|
||||
const twin = list.find((x) => x.name !== name && x.name.toLowerCase() === name.toLowerCase());
|
||||
if (twin) {
|
||||
app.ui.toast(`There is a variable ${twin.name} already: ${name} differs only in its capitals`, "error");
|
||||
return null;
|
||||
}
|
||||
const was = list.find((x) => x.name === name);
|
||||
const next = [...list.filter((x) => x.name !== name), { name, expr: v.expr.trim() || "0" }];
|
||||
setVariables(next);
|
||||
if (evaluate(v.expr || "0") === null) {
|
||||
// (An angle - "30 deg" - is a value too: it was refused here, and taken in the list of them all.)
|
||||
if (evaluate(v.expr || "0") === null && evaluate(v.expr || "0", "angle") === null) {
|
||||
setVariables(list);
|
||||
app.ui.toast(`"${v.expr}" isn't a valid value`, "error");
|
||||
const unknown = namesIn(v.expr).filter((x) => x !== name && !next.some((y) => y.name === x) && !RESERVED.test(x));
|
||||
app.ui.toast(
|
||||
new RegExp(`(^|[^A-Za-z0-9_])${name}($|[^A-Za-z0-9_])`).test(v.expr)
|
||||
? `${name} can't use itself`
|
||||
: unknown.length
|
||||
? `${unknown.join(", ")}: no variable has that name`
|
||||
: `"${v.expr}" isn't a valid value`,
|
||||
"error",
|
||||
);
|
||||
return null;
|
||||
}
|
||||
app.store.commit((d) => (d.variables = next));
|
||||
app.ui.toast(`${name} = ${v.expr}`);
|
||||
// (One there already by that name is changed, and said so.)
|
||||
app.ui.toast(was && was.expr !== v.expr.trim() ? `${name} changed: ${was.expr} → ${v.expr.trim()}` : `${name} = ${v.expr}`);
|
||||
return name;
|
||||
}
|
||||
|
||||
@@ -207,19 +241,37 @@ export async function editVariables(app: AppContext): Promise<void> {
|
||||
const bad = next.find((x) => evaluate(x.expr) === null && evaluate(x.expr, "angle") === null);
|
||||
if (bad) {
|
||||
setVariables(list);
|
||||
return app.ui.toast(`"${bad.expr}" isn't a valid value for ${bad.name}`, "error");
|
||||
// (Said as it is: another variable still uses the one being deleted.)
|
||||
const lost = list.filter((x) => !next.some((y) => y.name === x.name)).find((x) => new RegExp(`(^|[^A-Za-z0-9_])${x.name}($|[^A-Za-z0-9_])`).test(bad.expr));
|
||||
return app.ui.toast(lost ? `${bad.name} uses ${lost.name} (${bad.name} = ${bad.expr}): change ${bad.name} first` : `"${bad.expr}" isn't a valid value for ${bad.name}`, "error");
|
||||
}
|
||||
// Deleted while steps still use it: they keep the sizes they have now, as
|
||||
// plain numbers (else every rebuild said "can't be evaluated").
|
||||
const gone = list.filter((x) => !next.some((y) => y.name === x.name)).map((x) => x.name);
|
||||
const uses = (expr: string) => gone.some((n) => new RegExp(`(^|[^a-z0-9_])${n}($|[^a-z0-9_])`, "i").test(expr));
|
||||
// (Capitals count: W deleted is not w deleted.)
|
||||
const uses = (expr: string) => gone.some((n) => new RegExp(`(^|[^A-Za-z0-9_])${n}($|[^A-Za-z0-9_])`).test(expr));
|
||||
let kept = 0;
|
||||
if (next.some((x, i) => x.name !== list[i]?.name || x.expr !== list[i]?.expr) || next.length !== list.length)
|
||||
app.store.commit((d) => {
|
||||
d.variables = next;
|
||||
for (const f of d.features) {
|
||||
for (const [path, expr] of Object.entries(f.exprs ?? {})) if (uses(expr)) (delete f.exprs![path], kept++);
|
||||
if (f.type === "sketch") for (const c of f.constraints ?? []) if (c.expr && uses(c.expr)) (delete c.expr, kept++);
|
||||
// (A sketch pattern that followed it: its copies stay as they are, plain curves from now on.)
|
||||
if (f.type === "sketch" && f.repeats?.some((r) => uses(r.countExpr))) {
|
||||
kept += f.repeats.filter((r) => uses(r.countExpr)).length;
|
||||
f.repeats = f.repeats.filter((r) => !uses(r.countExpr));
|
||||
if (!f.repeats.length) delete f.repeats;
|
||||
}
|
||||
if (f.type === "sketch")
|
||||
for (const c of f.constraints ?? []) {
|
||||
if (c.expr && uses(c.expr)) (delete c.expr, kept++);
|
||||
// (A point placed by it too: left, every rebuild said it can't be evaluated.)
|
||||
if (c.atExpr?.some((e) => e && uses(e))) {
|
||||
c.atExpr = c.atExpr.map((e) => (e && uses(e) ? null : e));
|
||||
if (!c.atExpr.some((e) => e)) delete c.atExpr;
|
||||
kept++;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (kept) app.ui.toast(`${gone.join(", ")} deleted - the ${kept === 1 ? "size" : `${kept} sizes`} that used ${gone.length > 1 ? "them" : "it"} ${kept === 1 ? "keeps its value" : "keep their values"}`);
|
||||
@@ -229,14 +281,36 @@ export async function editVariables(app: AppContext): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function editImage(app: AppContext, f: ImageFeature): Promise<void> {
|
||||
const v = await app.ui.dialog("Image", [
|
||||
{ key: "width", label: "Width (mm)", value: String(f.width) },
|
||||
{ key: "opacity", label: "Opacity (0–1)", value: String(f.opacity) },
|
||||
]);
|
||||
/**
|
||||
* Rename Variables: each variable's name in a box, to change. Everything that uses a renamed variable - other
|
||||
* variables, steps' sizes, sketch dimensions - says its new name; nothing changes size. (A variable could only be
|
||||
* deleted and made again under another name, and what used it lost its link to it.)
|
||||
*/
|
||||
export async function renameVariables(app: AppContext): Promise<void> {
|
||||
const list = app.store.doc.variables;
|
||||
if (!list.length) return;
|
||||
const v = await app.ui.dialog(
|
||||
"Rename Variables",
|
||||
list.map((x) => ({ key: x.name, label: `${x.name} = ${bareExpr(x.expr)}`, value: x.name })),
|
||||
"Type a new name over an old one. Everything that uses it follows, and nothing changes size.",
|
||||
);
|
||||
if (!v) return;
|
||||
const width = Number(v.width) || f.width;
|
||||
app.store.update(f.id, { width, height: (f.height * width) / f.width, opacity: Math.min(1, Math.max(0.05, Number(v.opacity) || f.opacity)) });
|
||||
const wanted = list.map((x) => ({ from: x.name, to: (v[x.name] ?? x.name).trim() || x.name })).filter((x) => x.from !== x.to);
|
||||
if (!wanted.length) return;
|
||||
// Tried on a copy first: all of them, or none (two swapping names go by way of a spare one).
|
||||
const trial = structuredClone(app.store.doc);
|
||||
const spare = (i: number) => `__renaming_${i}__`;
|
||||
wanted.forEach((w, i) => renameVariable(trial, w.from, spare(i)));
|
||||
for (const [i, w] of wanted.entries()) {
|
||||
const problem = nameProblem(trial, spare(i), w.to);
|
||||
if (problem) return app.ui.toast(`${w.from} → ${w.to}: ${problem}`, "error");
|
||||
renameVariable(trial, spare(i), w.to);
|
||||
}
|
||||
app.store.commit((d) => {
|
||||
d.variables = trial.variables;
|
||||
d.features = trial.features;
|
||||
});
|
||||
app.ui.toast(wanted.length === 1 ? `${wanted[0].from} is ${wanted[0].to} now, everywhere it is used` : `${wanted.length} variables renamed, everywhere they are used`);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- DXF
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
import type { SketchEntity, Vec2 } from "../doc/types";
|
||||
import { uid } from "../sketch/edit";
|
||||
import { entityPrims, samplePrim, type Prim } from "../sketch/curves";
|
||||
|
||||
/** 2D affine map [a b c d e f]: x' = a x + c y + e, y' = b x + d y + f (SVG's matrix order). */
|
||||
type M = [number, number, number, number, number, number];
|
||||
@@ -406,3 +407,60 @@ function shift(e: SketchEntity, dx: number, dy: number): SketchEntity {
|
||||
return e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A sketch's curves as an SVG file's text: millimetres, the page just round the drawing, up as in the sketch (SVG's
|
||||
* y runs down, so it is turned over). Lines, circles and arcs stay exact; ellipses and splines are fine polylines.
|
||||
* Construction curves are in a group of their own, dashed.
|
||||
*/
|
||||
export function sketchToSVG(entities: SketchEntity[], title = "Sketch"): string {
|
||||
const f = (v: number) => String(Math.round(v * 1e4) / 1e4 || 0);
|
||||
const pt = (p: Vec2) => `${f(p[0])} ${f(-p[1])}`;
|
||||
let lo: Vec2 = [Infinity, Infinity];
|
||||
let hi: Vec2 = [-Infinity, -Infinity];
|
||||
const see = (p: Vec2) => {
|
||||
lo = [Math.min(lo[0], p[0]), Math.min(lo[1], -p[1])];
|
||||
hi = [Math.max(hi[0], p[0]), Math.max(hi[1], -p[1])];
|
||||
};
|
||||
const TAU = Math.PI * 2;
|
||||
const draw = (p: Prim): string => {
|
||||
if (p.t === "line") {
|
||||
see(p.a);
|
||||
see(p.b);
|
||||
return `<path d="M${pt(p.a)} L${pt(p.b)}"/>`;
|
||||
}
|
||||
if (p.t === "circle") {
|
||||
const at = (t: number): Vec2 => [p.c[0] + p.r * Math.cos(t), p.c[1] + p.r * Math.sin(t)];
|
||||
// (Its whole round counted for the page's size: an arc can bulge past its ends.)
|
||||
for (const q of samplePrim(p, 0, 1, 32)) see(q);
|
||||
if (Math.abs(Math.abs(p.sweep) - TAU) < 1e-9) return `<circle cx="${f(p.c[0])}" cy="${f(-p.c[1])}" r="${f(p.r)}"/>`;
|
||||
// Turned over, anticlockwise in the sketch is clockwise on the page: sweep flag 0 for a positive sweep.
|
||||
return `<path d="M${pt(at(p.a0))} A${f(p.r)} ${f(p.r)} 0 ${Math.abs(p.sweep) > Math.PI ? 1 : 0} ${p.sweep > 0 ? 0 : 1} ${pt(at(p.a0 + p.sweep))}"/>`;
|
||||
}
|
||||
const closed = p.t === "spline" ? p.closed : Math.abs(Math.abs(p.sweep) - TAU) < 1e-9;
|
||||
let pts = samplePrim(p, 0, 1, p.t === "spline" ? Math.max(64, p.pts.length * 16) : 128);
|
||||
if (closed && pts.length > 1) pts = pts.slice(0, -1);
|
||||
pts.forEach(see);
|
||||
return `<path d="M${pts.map(pt).join(" L")}${closed ? " Z" : ""}"/>`;
|
||||
};
|
||||
const solid: string[] = [];
|
||||
const construction: string[] = [];
|
||||
for (const e of entities) for (const p of entityPrims(e)) (e.construction ? construction : solid).push(draw(p));
|
||||
if (!Number.isFinite(lo[0])) [lo, hi] = [[0, 0], [1, 1]];
|
||||
const pad = Math.max(1, Math.max(hi[0] - lo[0], hi[1] - lo[1]) * 0.02);
|
||||
const w = hi[0] - lo[0] + pad * 2;
|
||||
const h = hi[1] - lo[1] + pad * 2;
|
||||
const stroke = Math.max(0.05, Math.min(0.35, Math.max(w, h) / 600));
|
||||
const safe = title.replace(/[<>&]/g, "");
|
||||
return [
|
||||
`<?xml version="1.0" encoding="UTF-8"?>`,
|
||||
`<svg xmlns="http://www.w3.org/2000/svg" width="${f(w)}mm" height="${f(h)}mm" viewBox="${f(lo[0] - pad)} ${f(lo[1] - pad)} ${f(w)} ${f(h)}">`,
|
||||
`<title>${safe}</title>`,
|
||||
`<g fill="none" stroke="#000" stroke-width="${f(stroke)}" stroke-linecap="round" stroke-linejoin="round">`,
|
||||
...solid,
|
||||
`</g>`,
|
||||
...(construction.length ? [`<g id="construction" fill="none" stroke="#888" stroke-width="${f(stroke)}" stroke-dasharray="${f(stroke * 6)} ${f(stroke * 4)}">`, ...construction, `</g>`] : []),
|
||||
`</svg>`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ function modelXml(bodies: MeshBody[], title: string): string {
|
||||
out.push('<?xml version="1.0" encoding="UTF-8"?>');
|
||||
out.push('<model unit="millimeter" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02">');
|
||||
out.push(`<metadata name="Title">${esc(title)}</metadata>`);
|
||||
out.push('<metadata name="Application">supergeometry.app</metadata>');
|
||||
out.push('<metadata name="Application">superGeometry.app</metadata>');
|
||||
out.push("<resources>");
|
||||
if (colors.length) {
|
||||
out.push('<basematerials id="1">');
|
||||
|
||||
@@ -66,6 +66,15 @@ export class KernelClient {
|
||||
this.meshes = new Map();
|
||||
this.worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
|
||||
this.worker.onmessage = this.handler;
|
||||
// The engine died without an answer (out of memory, a fault outside any step): what waits on it would wait for
|
||||
// ever, and "Working…" with it. Everything waiting ends, and a fresh engine is started.
|
||||
const worker = this.worker;
|
||||
worker.onerror = (e) => {
|
||||
if (worker !== this.worker) return;
|
||||
console.error("The geometry engine stopped:", e.message);
|
||||
this.stop();
|
||||
this.onLost?.();
|
||||
};
|
||||
this.ready = this.call({ type: "init" }).then((r) => {
|
||||
if (r.type === "error") throw new Error(r.message);
|
||||
});
|
||||
@@ -141,6 +150,12 @@ export class KernelClient {
|
||||
|
||||
/** Told when the kernel starts and stops being busy (to show a busy indicator). */
|
||||
onBusy: ((busy: boolean) => void) | null = null;
|
||||
/** Told when the engine died and was started again (what was being made is not made). */
|
||||
onLost: (() => void) | null = null;
|
||||
/** Is anything being worked on, or waiting to be? (What the busy indicator is checked against.) */
|
||||
get busy(): boolean {
|
||||
return this.pending.size > 0 || this.regenRunning || !!this.regenQueued;
|
||||
}
|
||||
|
||||
private call(msg: Request): Promise<Response> {
|
||||
const id = this.nextId++;
|
||||
|
||||
@@ -6,11 +6,11 @@
|
||||
// the body is on (planes → half-spaces, cylinders → infinite cylinders). Changing
|
||||
// F then only means adding/removing the right slab of E.
|
||||
|
||||
import { assembleWire, basicFaceExtrusion, getOC, loft, makeFace, makeBSplineApproximation, makeCylinder, makeLine, makePolygon, makeSphere, measureArea, cast, Vector, type Edge, type Face, type Shape3D } from "replicad";
|
||||
import { measureVolume } from "./ocFree";
|
||||
import { assembleWire, basicFaceExtrusion, getOC, loft, makeFace, makeBSplineApproximation, makeCylinder, makeLine, makePolygon, makeSphere, measureArea, cast, revolution, Vector, type Edge, type Face, type Shape3D } from "replicad";
|
||||
import { measureVolume, quickVolume } from "./ocFree";
|
||||
import type { PlaneDef, Vec3 } from "../doc/types";
|
||||
import { add, cross, dist, dot, len, norm, scale, sub, xDirFor } from "../geom";
|
||||
import { subShapes, validNow } from "./health";
|
||||
import { shapeValid, subShapes, validNow } from "./health";
|
||||
import { faceTriangles } from "./meshing";
|
||||
import { borderPieces, borderThrough, boundaryEdges, limitPoints, subdivide, type Cage } from "../freeform/cage";
|
||||
import { cageToShape } from "./freeform";
|
||||
@@ -35,13 +35,60 @@ export function sizeOf(body: Shape3D): number {
|
||||
const key = body.wrapped as object;
|
||||
let s = sizes.get(key);
|
||||
if (s === undefined) {
|
||||
const bb = body.boundingBox;
|
||||
s = Math.hypot(bb.width, bb.height, bb.depth) || 1;
|
||||
s = looseSize(body);
|
||||
sizes.set(key, s);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* About how big a shape is (the diagonal of the kernel's quick box: never smaller than the shape, a few percent
|
||||
* bigger on curved faces). Its exact box takes 0.4 to 1 s on a body with curved faces (a mug with its handle, a
|
||||
* freeform) - asked for by every step that touched such a body, just to know how big a helper to make.
|
||||
*/
|
||||
function looseSize(body: Shape3D): number {
|
||||
const [lo, hi] = looseBox(body);
|
||||
return Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The kernel's quick box of a shape, [low corner, high corner]: the shape is all inside it, and it is a little
|
||||
* bigger than the shape where its faces are curved. For telling shapes apart that can't touch, and how far
|
||||
* something reaches. (An empty shape: an upside-down box, as the exact one's.)
|
||||
*/
|
||||
const looseBoxes = new WeakMap<object, [Vec3, Vec3]>();
|
||||
export function looseBox(body: Shape3D): [Vec3, Vec3] {
|
||||
const key = body.wrapped as object;
|
||||
const had = looseBoxes.get(key);
|
||||
if (had) return had;
|
||||
const oc = getOC();
|
||||
const box = new oc.Bnd_Box();
|
||||
let out: [Vec3, Vec3] | null = null;
|
||||
try {
|
||||
oc.BRepBndLib.Add(body.wrapped, box, false);
|
||||
if (!box.IsVoid()) {
|
||||
const [a, b] = [box.CornerMin(), box.CornerMax()];
|
||||
const got: [Vec3, Vec3] = [
|
||||
[a.X(), a.Y(), a.Z()],
|
||||
[b.X(), b.Y(), b.Z()],
|
||||
];
|
||||
a.delete();
|
||||
b.delete();
|
||||
if ([...got[0], ...got[1]].every(Number.isFinite)) out = got;
|
||||
}
|
||||
} catch {
|
||||
// The exact one, below.
|
||||
} finally {
|
||||
box.delete();
|
||||
}
|
||||
if (!out) {
|
||||
const [lo, hi] = body.boundingBox.bounds;
|
||||
out = [[...lo] as Vec3, [...hi] as Vec3];
|
||||
}
|
||||
looseBoxes.set(key, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
// Each helper solid gets a slightly different size: when two of them end on the
|
||||
// same far-away plane, the booleans split surfaces and they no longer re-merge.
|
||||
let jitter = 0;
|
||||
@@ -134,6 +181,51 @@ function infiniteCylinder(cy: Cyl, r: number, L0: number): Shape3D {
|
||||
return makeCylinder(r, 2 * L, sub(cy.c, scale(cy.a, L)), cy.a) as Shape3D;
|
||||
}
|
||||
|
||||
/**
|
||||
* A conical face's apex, its axis pointing into the half of the cone the face
|
||||
* is on, and the tangent of its half-angle - from points on it (this kernel
|
||||
* build can't hand over its cone).
|
||||
*/
|
||||
export function coneOf(f: Face): { apex: Vec3; a: Vec3; t: number } | null {
|
||||
if (f.geomType !== "CONE") return null;
|
||||
try {
|
||||
const at = (u: number, v: number) => tup(f.pointOnSurface(u, v));
|
||||
// A circle round the axis: three points at one height, and its middle.
|
||||
const centre = (p: Vec3, q: Vec3, r: Vec3): Vec3 => {
|
||||
const ab = sub(q, p), ac = sub(r, p);
|
||||
const n = cross(ab, ac);
|
||||
const nn = dot(n, n);
|
||||
if (nn < 1e-18) throw new Error("flat");
|
||||
return add(p, scale(add(scale(cross(n, ab), dot(ac, ac)), scale(cross(ac, n), dot(ab, ab))), 1 / (2 * nn)));
|
||||
};
|
||||
const ring = (v: number) => {
|
||||
const ps = [0.2, 0.5, 0.8].map((u) => at(u, v));
|
||||
return { c: centre(ps[0], ps[1], ps[2]), p: ps[1] };
|
||||
};
|
||||
const lo = ring(0.2), hi = ring(0.8);
|
||||
const r1 = dist(lo.p, lo.c), r2 = dist(hi.p, hi.c);
|
||||
const h = dist(lo.c, hi.c);
|
||||
if (h < 1e-9 || Math.abs(r2 - r1) < 1e-9) return null;
|
||||
const up = norm(sub(hi.c, lo.c));
|
||||
// Radius r1 at lo, r2 at hi: none at the apex.
|
||||
const apex = sub(lo.c, scale(up, (r1 * h) / (r2 - r1)));
|
||||
const t = Math.abs(r2 - r1) / h;
|
||||
const a = dot(sub(lo.p, apex), up) > 0 ? up : scale(up, -1);
|
||||
return t > 1e-9 && t < 1e6 ? { apex, a, t } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The solid inside a cone, from its apex out past `L` (a triangle turned round its axis). */
|
||||
function infiniteCone(k: { apex: Vec3; a: Vec3; t: number }, L0: number): Shape3D {
|
||||
const L = vary(L0);
|
||||
const p = norm(cross(k.a, Math.abs(k.a[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]));
|
||||
const end = add(k.apex, scale(k.a, L));
|
||||
const tri = makeFace(assembleWire([makeLine(k.apex, end), makeLine(end, add(end, scale(p, L * k.t))), makeLine(add(end, scale(p, L * k.t)), k.apex)]));
|
||||
return revolution(tri, k.apex, k.a) as Shape3D;
|
||||
}
|
||||
|
||||
/**
|
||||
* g, a round face next to flat face F, is a convex fillet that ends on F
|
||||
* (its axis runs through F, and it rounds the edge between two flat faces it
|
||||
@@ -169,6 +261,22 @@ function tangentPlaneAlong(F: Face, g: Face): PlaneDef | null {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A flat face drawn inside a bigger flat one (a shape projected onto it): every
|
||||
* face round it lies in its plane, so moving its plane moves nothing.
|
||||
*/
|
||||
export function inFlatFace(body: Shape3D, F: Face): boolean {
|
||||
if (F.geomType !== "PLANE") return false;
|
||||
const p = planeOf(F);
|
||||
const tol = sizeOf(body) * 1e-7;
|
||||
const ns = neighbours(body, F);
|
||||
return ns.length > 0 && ns.every((g) => {
|
||||
if (g.geomType !== "PLANE") return false;
|
||||
const q = planeOf(g);
|
||||
return Math.abs(Math.abs(dot(q.normal, p.normal)) - 1) < 1e-9 && Math.abs(dot(sub(q.origin, p.origin), p.normal)) < tol;
|
||||
});
|
||||
}
|
||||
|
||||
/** Faces sharing an edge with F. */
|
||||
function neighbours(body: Shape3D, F: Face): Face[] {
|
||||
const edges = F.edges;
|
||||
@@ -231,6 +339,17 @@ function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number, pa
|
||||
if (pts.every((p) => dot(off(p), dn) > -cy.r * 1e-6)) keep.push(halfSpace({ origin: cy.c, normal: dn, xDir: xDirFor(dn) }, L));
|
||||
}
|
||||
}
|
||||
} else if (coneOf(g)) {
|
||||
// A tapered side (a foot stepping in under a cup): it carries on as the
|
||||
// cone it is - the inside of it kept or taken away as for a cylinder.
|
||||
// (Treated as any other surface, the region round a cup's floor was open
|
||||
// above and ran off out of the part.)
|
||||
const k = coneOf(g)!;
|
||||
const rel = sub(q, k.apex);
|
||||
const along = dot(rel, k.a);
|
||||
const radial = len(sub(rel, scale(k.a, along)));
|
||||
const reach = len(sub(c, k.apex)) + 2 * L;
|
||||
(along > 0 && radial < along * k.t ? keep : remove).push(infiniteCone(k, reach));
|
||||
} else {
|
||||
// A curve pulled straight (a spline side extruded) meeting F along a
|
||||
// straight edge: it carries on along its tangent there. Bounded only by
|
||||
@@ -298,16 +417,30 @@ export function freeformFace(body: Shape3D, F: Face, points: Vec3[]): Shape3D {
|
||||
* close round the new surface - the fitted way is tried then.
|
||||
*/
|
||||
export function sheetFace(body: Shape3D, F: Face, cage: Cage): Shape3D {
|
||||
return sheetFaces(body, [F], cage, norm(F.normalAt().toTuple() as Vec3));
|
||||
}
|
||||
|
||||
/**
|
||||
* Several faces side by side made one smooth surface (sheetFace's way): its
|
||||
* border on their outer edges, the edges between them gone. `n`: the way they
|
||||
* face together (the middle of their normals).
|
||||
*/
|
||||
export function sheetFaces(body: Shape3D, Fs: Face[], cage: Cage, n: Vec3): Shape3D {
|
||||
const oc = getOC();
|
||||
const ex = new oc.TopExp_Explorer(F.wrapped, oc.TopAbs_ShapeEnum.TopAbs_WIRE, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
|
||||
let wires = 0;
|
||||
for (; ex.More(); ex.Next()) wires++;
|
||||
ex.delete();
|
||||
if (wires !== 1) throw new Error("Faces with holes in them can't be made freeform yet");
|
||||
const size = Math.sqrt(measureArea(F));
|
||||
const tol = Math.max(5e-3, size * 1e-3);
|
||||
// The face's edge, finely (a round edge as short straight pieces).
|
||||
const edge: [Vec3, Vec3][] = F.edges.flatMap((e) => {
|
||||
for (const F of Fs) {
|
||||
const ex = new oc.TopExp_Explorer(F.wrapped, oc.TopAbs_ShapeEnum.TopAbs_WIRE, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
|
||||
let wires = 0;
|
||||
for (; ex.More(); ex.Next()) wires++;
|
||||
ex.delete();
|
||||
if (wires !== 1) throw new Error("Faces with holes in them can't be made freeform yet");
|
||||
}
|
||||
const size = Math.sqrt(Fs.reduce((a, F) => a + measureArea(F), 0));
|
||||
// (Over several faces the border bends round their corners: it follows the edge a hair less closely.)
|
||||
const tol = Math.max(5e-3, size * (Fs.length > 1 ? 3e-3 : 1e-3));
|
||||
// The faces' outer edge, finely (a round edge as short straight pieces) - not the edges between them.
|
||||
const between = (e: Face["edges"][number]) => Fs.filter((F) => F.edges.some((x) => x.isSame(e))).length > 1;
|
||||
const outer = Fs.flatMap((F) => F.edges).filter((e) => !between(e));
|
||||
const edge: [Vec3, Vec3][] = outer.flatMap((e) => {
|
||||
const pts = Array.from({ length: 257 }, (_, i) => e.pointAt(i / 256).toTuple() as Vec3);
|
||||
return pts.slice(1).map((q, i) => [pts[i], q] as [Vec3, Vec3]);
|
||||
});
|
||||
@@ -347,7 +480,6 @@ export function sheetFace(body: Shape3D, F: Face, cage: Cage): Shape3D {
|
||||
// lip over it; pushed in, a cut through the wall): those points are drawn
|
||||
// back onto the edge, at their height. Far past it (a coarse cage whose
|
||||
// cells reach across the corner): not this way.
|
||||
const n = norm(F.normalAt().toTuple() as Vec3);
|
||||
const u = xDirFor(n);
|
||||
const v = norm(cross(n, u));
|
||||
const flat = edge.map(([a, b]) => [dot(a, u), dot(a, v), dot(b, u), dot(b, v)]);
|
||||
@@ -375,7 +507,7 @@ export function sheetFace(body: Shape3D, F: Face, cage: Cage): Shape3D {
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
const sew = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
|
||||
try {
|
||||
const others = body.faces.filter((f) => !f.isSame(F));
|
||||
const others = body.faces.filter((f) => !Fs.some((F) => f.isSame(F)));
|
||||
meetsOnlyAt(sheet.wrapped, others, rim, size);
|
||||
for (const f of others) sew.Add(f.wrapped);
|
||||
for (const f of sheet.faces) sew.Add(f.wrapped);
|
||||
@@ -387,7 +519,7 @@ export function sheetFace(body: Shape3D, F: Face, cage: Cage): Shape3D {
|
||||
fix.delete();
|
||||
oc.BRepLib.OrientClosedSolid(oc.TopoDS.Solid(made));
|
||||
const solid = cast(made) as Shape3D;
|
||||
if (!(measureVolume(solid) > 0)) throw new Error("volume");
|
||||
if (!(quickVolume(solid) > 0)) throw new Error("volume");
|
||||
if (!validNow(solid.wrapped)) throw new Error("invalid");
|
||||
return solid;
|
||||
} finally {
|
||||
@@ -482,7 +614,7 @@ function filledFace(body: Shape3D, F: Face, points: Vec3[], degree: number): Sha
|
||||
fix.delete();
|
||||
oc.BRepLib.OrientClosedSolid(oc.TopoDS.Solid(made));
|
||||
const solid = cast(made) as Shape3D;
|
||||
if (!(measureVolume(solid) > 0)) throw new Error("volume");
|
||||
if (!(quickVolume(solid) > 0)) throw new Error("volume");
|
||||
return solid;
|
||||
} finally {
|
||||
fill.delete();
|
||||
@@ -826,6 +958,9 @@ function needsContinuation(body: Shape3D, F: Face): boolean {
|
||||
* heading there) until it is d further out; the slab between the old and the
|
||||
* new outline is added (d > 0) or taken away (d < 0).
|
||||
*/
|
||||
/** A face pulled past where its sides meet (a cone's end pulled past its point). */
|
||||
export const SIDES_MEET = "Pulled this far, its sides would meet in a point (they lean in) - pull it less, or draw the shape on the face and extrude that for straight sides";
|
||||
|
||||
function offsetByContinuation(body: Shape3D, F: Face, d: number): Shape3D {
|
||||
const fp = planeOf(F);
|
||||
const n = fp.normal;
|
||||
@@ -880,6 +1015,45 @@ function offsetByContinuation(body: Shape3D, F: Face, d: number): Shape3D {
|
||||
// would move it its own way (a wall at 45° and one square to F disagree,
|
||||
// and halfway between them leaves both: slanted slivers stood up as fins).
|
||||
// Without such an edge: halfway between their two estimates.
|
||||
// Do the sides meet on the way (a cone's end pulled past its point)? Each
|
||||
// point of the outline goes in a straight line, so the area inside it is a
|
||||
// quadratic in how far it has gone: down to nothing on the way, or turned
|
||||
// inside out, and what's left is an hourglass (or nothing at all: the
|
||||
// kernel gave the body back unchanged, without a word).
|
||||
{
|
||||
const u = xDirFor(n);
|
||||
const w = cross(n, u);
|
||||
const ps: Vec3[] = [];
|
||||
const vs: Vec3[] = [];
|
||||
for (const { k, rev } of order) {
|
||||
for (let j = 0; j < 8; j++) {
|
||||
const t = rev ? 1 - j / 8 : j / 8;
|
||||
const p = tup(edges[k].pointAt(t));
|
||||
ps.push(p);
|
||||
vs.push(sub(movedAt(k, t), p));
|
||||
}
|
||||
}
|
||||
const areaAt = (s: number) => {
|
||||
let A = 0;
|
||||
for (let i = 0; i < ps.length; i++) {
|
||||
const j = (i + 1) % ps.length;
|
||||
const a = add(ps[i], scale(vs[i], s));
|
||||
const b = add(ps[j], scale(vs[j], s));
|
||||
A += dot(a, u) * dot(b, w) - dot(b, u) * dot(a, w);
|
||||
}
|
||||
return A / 2;
|
||||
};
|
||||
// (Counted the way round that makes it positive at the start.)
|
||||
const sg = Math.sign(areaAt(0)) || 1;
|
||||
const A0 = sg * areaAt(0);
|
||||
const Ah = sg * areaAt(0.5);
|
||||
const A1 = sg * areaAt(1);
|
||||
const qa = 2 * A1 - 4 * Ah + 2 * A0;
|
||||
const qb = 4 * Ah - A1 - 3 * A0;
|
||||
const sv = qa > 0 ? -qb / (2 * qa) : -1;
|
||||
const least = Math.min(A1, sv > 0 && sv < 1 ? qa * sv * sv + qb * sv + A0 : Infinity);
|
||||
if (A0 > 0 && least < A0 * 1e-3) throw new Error(SIDES_MEET);
|
||||
}
|
||||
const m = order.length;
|
||||
const fEdges = F.edges;
|
||||
const bodyEdges = body.edges.filter((e) => !fEdges.some((fe) => fe.isSame(e)));
|
||||
@@ -956,7 +1130,9 @@ export function offsetFace(body: Shape3D, F: Face, d: number): Shape3D {
|
||||
if (F.geomType === "PLANE" && (curved || (!holed && !convexFace(F)))) {
|
||||
try {
|
||||
return offsetByContinuation(body, F, d);
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// (Sides that meet meet with the plane trick too.)
|
||||
if (err instanceof Error && err.message === SIDES_MEET) throw err;
|
||||
// fall through to the plane trick
|
||||
}
|
||||
}
|
||||
@@ -1442,11 +1618,17 @@ export function unify(body: Shape3D, size?: number): Shape3D {
|
||||
u.Build();
|
||||
// (The kernel's handle to the result is given back once the body has its own: release.ts.)
|
||||
const made = u.Shape();
|
||||
let out: Shape3D;
|
||||
try {
|
||||
return cast(made) as Shape3D;
|
||||
out = cast(made) as Shape3D;
|
||||
} finally {
|
||||
made.delete();
|
||||
}
|
||||
// Merged into a broken face: the pieces as they were. (A cut across a
|
||||
// shelled mouse's top was sound; merged again, the two pieces of the
|
||||
// round either side of its seam came out a face that "didn't meet up".)
|
||||
if (out.faces.length !== body.faces.length && !shapeValid(out) && shapeValid(body)) return body;
|
||||
return out;
|
||||
} catch {
|
||||
// Merging is tidying only: if OpenCascade can't (a fillet ending on a face split in two), keep the pieces.
|
||||
return body;
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
// when the cage is closed, made into a solid.
|
||||
|
||||
import { cast, getOC, type Shape3D } from "replicad";
|
||||
import { measureVolume } from "./ocFree";
|
||||
import { quickVolume } from "./ocFree";
|
||||
import { subShapes } from "./health";
|
||||
import { cubicKnots, interpolateGrid } from "../freeform/bspline";
|
||||
import { isClosed, limitPoints, subdivide, type Cage, type Subdivided } from "../freeform/cage";
|
||||
|
||||
@@ -73,8 +74,22 @@ function thickenSheet(sheet: unknown, { thickness: t, side }: Thicken): Shape3D
|
||||
try {
|
||||
mk.MakeThickSolidBySimple(sheet as never, d);
|
||||
const solid = cast(mk.Shape()) as Shape3D;
|
||||
// Growing along the normals comes out inside-out: turn it the right way.
|
||||
return measureVolume(solid) < 0 ? (cast(solid.wrapped.Reversed()) as Shape3D) : solid;
|
||||
// Growing along the normals comes out inside-out, and marking the solid as reversed (as was done) measured
|
||||
// right but left its faces looking inwards: a rounding of its rim took every edge for a hollow one and came
|
||||
// out as rubbish - "would turn the body inside out". A solid made anew from its skin has them outwards.
|
||||
const shells = subShapes(solid, "SHELL");
|
||||
if (shells.length === 1) {
|
||||
const fix = new oc.ShapeFix_Solid();
|
||||
try {
|
||||
const made = cast(fix.SolidFromShell(oc.TopoDS.Shell(shells[0]))) as Shape3D;
|
||||
if (quickVolume(made) > 0) return made;
|
||||
} catch {
|
||||
// as it was, below
|
||||
} finally {
|
||||
fix.delete();
|
||||
}
|
||||
}
|
||||
return quickVolume(solid) < 0 ? (cast(solid.wrapped.Reversed()) as Shape3D) : solid;
|
||||
} finally {
|
||||
mk.delete();
|
||||
}
|
||||
|
||||
@@ -56,30 +56,45 @@ export function validNow(wrapped: unknown): boolean {
|
||||
* shape, like the checks below: every edit asks it of the body as it was
|
||||
* before, which is the same body on each move of a drag.
|
||||
*/
|
||||
const openCache = new WeakMap<Shape3D, number[]>();
|
||||
const openCache = new WeakMap<Shape3D, { open: number[]; pinched: number }>();
|
||||
export function openEdges(shape: Shape3D): number[] {
|
||||
return edgeUse(shape).open;
|
||||
}
|
||||
|
||||
/**
|
||||
* Edges with more than two faces round them: two pieces that only meet
|
||||
* along an edge (a slab stood on a block's edge and "joined"), held
|
||||
* together by nothing - one body by name, two by any printer or saw.
|
||||
*/
|
||||
export function pinchedEdges(shape: Shape3D): number {
|
||||
return edgeUse(shape).pinched;
|
||||
}
|
||||
|
||||
function edgeUse(shape: Shape3D): { open: number[]; pinched: number } {
|
||||
let known = openCache.get(shape);
|
||||
if (!known) openCache.set(shape, (known = findOpenEdges(shape)));
|
||||
if (!known) openCache.set(shape, (known = findEdgeUse(shape)));
|
||||
return known;
|
||||
}
|
||||
|
||||
function findOpenEdges(shape: Shape3D): number[] {
|
||||
function findEdgeUse(shape: Shape3D): { open: number[]; pinched: number } {
|
||||
const edges = shape.edges;
|
||||
const buckets = new Map<number, { e: Edge; i: number; n: number }[]>();
|
||||
const buckets = new Map<number, { e: Edge; i: number; n: number; faces: Set<number> }[]>();
|
||||
edges.forEach((e, i) => {
|
||||
const h = e.hashCode;
|
||||
buckets.set(h, [...(buckets.get(h) ?? []), { e, i, n: 0 }]);
|
||||
buckets.set(h, [...(buckets.get(h) ?? []), { e, i, n: 0, faces: new Set<number>() }]);
|
||||
});
|
||||
const oc = getOC();
|
||||
for (const f of shape.faces) {
|
||||
shape.faces.forEach((f, k) => {
|
||||
for (const fe of f.edges) {
|
||||
const m = buckets.get(fe.hashCode)?.find((x) => x.e.isSame(fe));
|
||||
// A seam (cylinder/torus) belongs to its face twice but is listed once.
|
||||
if (m) m.n += oc.BRep_Tool.IsClosed(fe.wrapped, f.wrapped) ? 2 : 1;
|
||||
m?.faces.add(k);
|
||||
}
|
||||
}
|
||||
});
|
||||
// A pole (where a revolved profile touches the axis) is a point-edge, not a gap.
|
||||
return [...buckets.values()].flat().filter((x) => x.n < 2 && !oc.BRep_Tool.Degenerated(x.e.wrapped)).map((x) => x.i);
|
||||
const all = [...buckets.values()].flat();
|
||||
return { open: all.filter((x) => x.n < 2 && !oc.BRep_Tool.Degenerated(x.e.wrapped)).map((x) => x.i), pinched: all.filter((x) => x.faces.size > 2).length };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -89,6 +89,8 @@ function props(s: Measurable, kind: "volume" | "area") {
|
||||
|
||||
/** The volume (signed: below 0 for a solid inside out), as replicad's but to a millionth. */
|
||||
export function measureVolume(s: Measurable): number {
|
||||
const own = ownSums(s);
|
||||
if (own) return own.vol;
|
||||
const p = props(s, "volume");
|
||||
try {
|
||||
return p.Mass();
|
||||
@@ -97,8 +99,361 @@ export function measureVolume(s: Measurable): number {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The volume to a thousandth or so (measured: within 0.15 %), for checks that need no more: which way out a solid
|
||||
* is, whether it is empty, whether a join or a cut came to about what it should. The measure to a millionth takes
|
||||
* seconds on curved bodies (a mug: 1.7 s; a jet engine's cowl: 10.6 s) where this takes 0.2 s and 0.06 s - and such
|
||||
* checks, asked several times a step, were most of what a join, a cut or a thread on such a body took.
|
||||
* (The exact one where it is known already.)
|
||||
*/
|
||||
const quick = new WeakMap<object, number>();
|
||||
export function quickVolume(s: Measurable): number {
|
||||
const exact = measured.get(s);
|
||||
if (exact) return exact.vol;
|
||||
const had = quick.get(s);
|
||||
if (had !== undefined) return had;
|
||||
const oc = getOC();
|
||||
let v = NaN;
|
||||
const p = new oc.GProp_GProps();
|
||||
try {
|
||||
const err = oc.BRepGProp.VolumeProperties(s.wrapped, p, 1e-3, false, false);
|
||||
if (Number.isFinite(err)) v = p.Mass();
|
||||
} catch {
|
||||
// The plain one, below.
|
||||
} finally {
|
||||
p.delete();
|
||||
}
|
||||
if (!Number.isFinite(v)) v = roughVolume(s);
|
||||
quick.set(s, v);
|
||||
return v;
|
||||
}
|
||||
|
||||
/**
|
||||
* The volume roughly (OpenCascade's plain measure, a percent or so out on
|
||||
* curved sweeps): enough to tell a solid's sign, or that it isn't empty. The
|
||||
* exact measure of a mug handle's sweep took 3.5 s each time, asked twice for
|
||||
* every way tried.
|
||||
*/
|
||||
export function roughVolume(s: Measurable): number {
|
||||
const oc = getOC();
|
||||
const q = new oc.GProp_GProps();
|
||||
try {
|
||||
oc.BRepGProp.VolumeProperties(s.wrapped, q, false, false, false);
|
||||
return q.Mass();
|
||||
} finally {
|
||||
q.delete();
|
||||
}
|
||||
}
|
||||
|
||||
// Faces swept from a curve (an extruded or revolved spline, and offsets of
|
||||
// them) are integrated by OpenCascade over the whole sweep at one fineness,
|
||||
// blind to the curve's own pieces: the side of an extruded closed spline
|
||||
// measured 14 049 mm² for 13 820, its solid 316 000 mm³ for 284 800 (11 %).
|
||||
// (OpenCascade's Gauss-Kronrod measure gets volumes right but took 11 s on a
|
||||
// shelled mouse; its areas have no such measure.) Bodies and faces with such
|
||||
// faces are integrated here instead, piece by piece:
|
||||
// Green's theorem round each face's outline in its own (u, v), so
|
||||
// ∫∫ f du dv = ∮ (∫ f du) dv, with f = |Su × Sv| for area and the divergence
|
||||
// theorem's (X - R)·N / 3 for volume.
|
||||
//
|
||||
// (Five points a piece: every piece is smooth, cut at the surface's and the
|
||||
// outline's joints and where the outline crosses the surface's.)
|
||||
const GAUSS: [number, number][] = [
|
||||
[-0.906179845938664, 0.2369268850561891],
|
||||
[-0.5384693101056831, 0.4786286704993665],
|
||||
[0, 0.5688888888888889],
|
||||
[0.5384693101056831, 0.4786286704993665],
|
||||
[0.906179845938664, 0.2369268850561891],
|
||||
];
|
||||
|
||||
function sweptFace(f: Face): boolean {
|
||||
const oc = getOC();
|
||||
const T = oc.GeomAbs_SurfaceType;
|
||||
const a = new oc.BRepAdaptor_Surface(f.wrapped, true);
|
||||
try {
|
||||
const t = a.GetType();
|
||||
return t === T.GeomAbs_SurfaceOfExtrusion || t === T.GeomAbs_SurfaceOfRevolution || t === T.GeomAbs_OffsetSurface || t === T.GeomAbs_OtherSurface;
|
||||
} finally {
|
||||
a.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** Breaks of [a, b]: its ends and the given joints inside, each piece cut in `k`. */
|
||||
function pieces(a: number, b: number, joints: number[], k: number): number[] {
|
||||
const lo = Math.min(a, b);
|
||||
const hi = Math.max(a, b);
|
||||
const at = [lo, ...joints.filter((x) => x > lo + 1e-12 * (1 + Math.abs(lo)) && x < hi - 1e-12 * (1 + Math.abs(hi))), hi];
|
||||
const out: number[] = [];
|
||||
for (let i = 0; i + 1 < at.length; i++) for (let j = 0; j < k; j++) out.push(at[i] + ((at[i + 1] - at[i]) * j) / k);
|
||||
out.push(hi);
|
||||
return a <= b ? out : out.reverse();
|
||||
}
|
||||
|
||||
/** A face's sums: area, ∫ X dA, its share of the volume (taken from R) and of ∫ (X - R) dV. */
|
||||
type Sums = { area: number; m: Vec3; vol: number; mv: Vec3 };
|
||||
|
||||
/** A face's sums, integrated piece by piece, the pieces halved until two finenesses agree to a millionth. */
|
||||
function faceSums(f: Face, R: Vec3, size: number): Sums {
|
||||
const oc = getOC();
|
||||
const S = oc.GeomAbs_Shape.GeomAbs_C2;
|
||||
const surf = new oc.BRepAdaptor_Surface(f.wrapped, true);
|
||||
const g = new oc.BRepGProp_Face(f.wrapped, false);
|
||||
const p = new oc.gp_Pnt();
|
||||
const n = new oc.gp_Vec();
|
||||
const q = new oc.gp_Pnt2d();
|
||||
const d = new oc.gp_Vec2d();
|
||||
const ex = new oc.TopExp_Explorer(f.wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
|
||||
const intervals = (count: number, fill: (arr: InstanceType<typeof oc.NCollection_Array1_double>) => void) => {
|
||||
const arr = new oc.NCollection_Array1_double(1, count + 1);
|
||||
try {
|
||||
fill(arr);
|
||||
const out: number[] = [];
|
||||
for (let i = 1; i <= count + 1; i++) out.push(arr.Value(i));
|
||||
return out;
|
||||
} finally {
|
||||
arr.delete();
|
||||
}
|
||||
};
|
||||
const edges: { c: InstanceType<typeof oc.BRepAdaptor_Curve2d>; sign: number; t0: number; t1: number; joints: number[] }[] = [];
|
||||
try {
|
||||
// The inner sums run the way the surface has fewer pieces (along an
|
||||
// extrusion's straight side, round a revolve), as each point of the
|
||||
// outline needs one: the other way, across a spline's every piece, a
|
||||
// shelled mouse took 5 s to measure (1 s this way). (Which way round
|
||||
// the outline is then integrated only changes the sign, set below.)
|
||||
const nu = surf.NbUIntervals(S);
|
||||
const nv = surf.NbVIntervals(S);
|
||||
const alongV = nv < nu;
|
||||
const w0 = alongV ? surf.FirstVParameter() : surf.FirstUParameter();
|
||||
const joints = alongV ? intervals(nv, (a) => surf.VIntervals(a, S)) : intervals(nu, (a) => surf.UIntervals(a, S));
|
||||
// The surface's joints the other way: where the outline crosses one, the
|
||||
// sums bend there, so the outline is cut there too.
|
||||
const across = (alongV ? intervals(nu, (a) => surf.UIntervals(a, S)) : intervals(nv, (a) => surf.VIntervals(a, S))).slice(1, -1);
|
||||
for (; ex.More(); ex.Next()) {
|
||||
const cur = ex.Current();
|
||||
const e = oc.TopoDS.Edge(cur);
|
||||
const sign = e.Orientation() === oc.TopAbs_Orientation.TopAbs_REVERSED ? -1 : 1;
|
||||
const c = new oc.BRepAdaptor_Curve2d(e, f.wrapped);
|
||||
e.delete();
|
||||
cur.delete();
|
||||
const tJoints = intervals(c.NbIntervals(S), (a) => c.Intervals(a, S));
|
||||
edges.push({ c, sign, t0: c.FirstParameter(), t1: c.LastParameter(), joints: tJoints });
|
||||
if (!across.length) continue;
|
||||
const other = (t: number) => {
|
||||
c.D1(t, q, d);
|
||||
return alongV ? q.X() : q.Y();
|
||||
};
|
||||
const base = [...tJoints];
|
||||
for (let i = 0; i + 1 < base.length; i++) {
|
||||
// (Sampled, then each crossing found by false position.)
|
||||
const N = 4;
|
||||
let ta = base[i];
|
||||
let oa = other(ta);
|
||||
for (let j = 1; j <= N; j++) {
|
||||
const tb = base[i] + ((base[i + 1] - base[i]) * j) / N;
|
||||
const ob = other(tb);
|
||||
for (const J of across) {
|
||||
if ((oa - J) * (ob - J) >= 0) continue;
|
||||
let [lo, hi, flo, fhi] = [ta, tb, oa - J, ob - J];
|
||||
let side = 0;
|
||||
let t = lo;
|
||||
for (let it = 0; it < 60; it++) {
|
||||
t = (lo * fhi - hi * flo) / (fhi - flo);
|
||||
const ft = other(t) - J;
|
||||
if (Math.abs(ft) <= 1e-13 * (1 + Math.abs(J)) || hi - lo <= 1e-14 * (1 + Math.abs(hi))) break;
|
||||
if (ft * flo < 0) {
|
||||
[hi, fhi] = [t, ft];
|
||||
if (side === -1) flo /= 2;
|
||||
side = -1;
|
||||
} else {
|
||||
[lo, flo] = [t, ft];
|
||||
if (side === 1) fhi /= 2;
|
||||
side = 1;
|
||||
}
|
||||
}
|
||||
tJoints.push(t);
|
||||
}
|
||||
ta = tb;
|
||||
oa = ob;
|
||||
}
|
||||
}
|
||||
tJoints.sort((x, y) => x - y);
|
||||
}
|
||||
const r = new Float64Array(8);
|
||||
const tot = new Float64Array(8);
|
||||
// Both ways each piece is one Gauss pass, checked against its two
|
||||
// halves' and halved again only where they differ, to a tenth of the
|
||||
// millionth (a slow stretch - a blade's trailing edge - doesn't make
|
||||
// every other piece finer: halving all of them, again and again, the
|
||||
// jet's sixteen blade faces took 4 s each and still hadn't agreed).
|
||||
// A first rough pass (five points a piece) sets the scale.
|
||||
// (Each half held to half the tolerance - but never below a thousandth
|
||||
// of it, and no more than a budget of points a face: where the sums can't
|
||||
// settle - rounding, a pole - halving the tolerance on and on split every
|
||||
// piece to the bottom, 2^24 of them, and a lofted grid never finished.)
|
||||
let rough = true;
|
||||
let tolArea = Infinity;
|
||||
let budget = 100000;
|
||||
const gauss = (wa: number, wb: number, o: number) => {
|
||||
budget--;
|
||||
const out = new Float64Array(8);
|
||||
const h = (wb - wa) / 2;
|
||||
const c = (wb + wa) / 2;
|
||||
for (const [x, wt] of GAUSS) {
|
||||
if (alongV) g.Normal(o, c + h * x, p, n);
|
||||
else g.Normal(c + h * x, o, p, n);
|
||||
const nx = n.X();
|
||||
const ny = n.Y();
|
||||
const nz = n.Z();
|
||||
const X = p.X();
|
||||
const Y = p.Y();
|
||||
const Z = p.Z();
|
||||
const dx = X - R[0];
|
||||
const dy = Y - R[1];
|
||||
const dz = Z - R[2];
|
||||
const wh = wt * h;
|
||||
const a = Math.hypot(nx, ny, nz) * wh;
|
||||
out[0] += a;
|
||||
out[1] += a * X;
|
||||
out[2] += a * Y;
|
||||
out[3] += a * Z;
|
||||
out[4] += ((dx * nx + dy * ny + dz * nz) / 3) * wh;
|
||||
out[5] += ((dx * dx) / 2) * nx * wh;
|
||||
out[6] += ((dy * dy) / 2) * ny * wh;
|
||||
out[7] += ((dz * dz) / 2) * nz * wh;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const refine = (whole: Float64Array, wa: number, wb: number, o: number, tolA: number, depth: number) => {
|
||||
const m = (wa + wb) / 2;
|
||||
const l = gauss(wa, m, o);
|
||||
const rr = gauss(m, wb, o);
|
||||
if ((Math.abs(l[0] + rr[0] - whole[0]) <= tolA && Math.abs(l[4] + rr[4] - whole[4]) <= tolA * size) || depth >= 20 || budget <= 0) {
|
||||
for (let j = 0; j < 8; j++) r[j] += l[j] + rr[j];
|
||||
return;
|
||||
}
|
||||
const half = Math.max(tolA / 2, floor);
|
||||
refine(l, wa, m, o, half, depth + 1);
|
||||
refine(rr, m, wb, o, half, depth + 1);
|
||||
};
|
||||
// ∫ from w0 to w, at the other parameter o, of each sum's integrand.
|
||||
let floor = 0;
|
||||
const inner = (w: number, o: number) => {
|
||||
r.fill(0);
|
||||
const ws = pieces(w0, w, joints, 1);
|
||||
const parts: Float64Array[] = [];
|
||||
let scale = 0;
|
||||
for (let i = 0; i + 1 < ws.length; i++) {
|
||||
const got = gauss(ws[i], ws[i + 1], o);
|
||||
parts.push(got);
|
||||
scale += Math.abs(got[0]);
|
||||
}
|
||||
if (rough) {
|
||||
for (const got of parts) for (let j = 0; j < 8; j++) r[j] += got[j];
|
||||
return r;
|
||||
}
|
||||
const span = Math.abs(w - w0) || 1;
|
||||
const tol = scale * EPS * 0.1;
|
||||
floor = tol * 1e-3;
|
||||
for (let i = 0; i + 1 < ws.length; i++) refine(parts[i], ws[i], ws[i + 1], o, (tol * Math.abs(ws[i + 1] - ws[i])) / span, 0);
|
||||
return r;
|
||||
};
|
||||
type Curve2d = (typeof edges)[number]["c"];
|
||||
const piece = (c: Curve2d, sign: number, a: number, b: number) => {
|
||||
const out = new Float64Array(8);
|
||||
const h = (b - a) / 2;
|
||||
const m = (b + a) / 2;
|
||||
for (const [x, wt] of GAUSS) {
|
||||
c.D1(m + h * x, q, d);
|
||||
const dOther = alongV ? d.X() : d.Y();
|
||||
if (dOther === 0) continue;
|
||||
const got = alongV ? inner(q.Y(), q.X()) : inner(q.X(), q.Y());
|
||||
const f2 = sign * dOther * wt * h;
|
||||
for (let j = 0; j < 8; j++) out[j] += got[j] * f2;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const add = (whole: Float64Array, c: Curve2d, sign: number, a: number, b: number, tolA: number, depth: number) => {
|
||||
const m = (a + b) / 2;
|
||||
const l = piece(c, sign, a, m);
|
||||
const rr = piece(c, sign, m, b);
|
||||
if ((Math.abs(l[0] + rr[0] - whole[0]) <= tolA && Math.abs(l[4] + rr[4] - whole[4]) <= tolA * size) || depth >= 24 || budget <= 0) {
|
||||
for (let j = 0; j < 8; j++) tot[j] += l[j] + rr[j];
|
||||
return;
|
||||
}
|
||||
const half = Math.max(tolA / 2, tolArea * 1e-4);
|
||||
add(l, c, sign, a, m, half, depth + 1);
|
||||
add(rr, c, sign, m, b, half, depth + 1);
|
||||
};
|
||||
const sums = (): Sums => {
|
||||
tot.fill(0);
|
||||
for (const { c, sign, t0, t1, joints: tj } of edges) {
|
||||
const ts = pieces(t0, t1, tj, 1);
|
||||
const span = Math.abs(t1 - t0) || 1;
|
||||
for (let i = 0; i + 1 < ts.length; i++) {
|
||||
const share = Math.abs(ts[i + 1] - ts[i]) / span / edges.length;
|
||||
add(piece(c, sign, ts[i], ts[i + 1]), c, sign, ts[i], ts[i + 1], tolArea * share, 0);
|
||||
}
|
||||
}
|
||||
// (Which way round the outline runs depends on the face's own way
|
||||
// round: the area must come out above 0.)
|
||||
const s = tot[0] < 0 ? -1 : 1;
|
||||
return { area: s * tot[0], m: [s * tot[1], s * tot[2], s * tot[3]], vol: s * tot[4], mv: [s * tot[5], s * tot[6], s * tot[7]] };
|
||||
};
|
||||
// (A face an offset closed to nothing - 1e-15 mm² - adds nothing: held
|
||||
// to a tenth of a millionth of its own no area, it never settled, 3 s each
|
||||
// in a split box's shell.)
|
||||
const first = sums();
|
||||
if (Math.abs(first.area) < size * size * 1e-12) return first;
|
||||
tolArea = Math.max(Math.abs(first.area), size * size * 1e-6) * EPS * 0.1;
|
||||
rough = false;
|
||||
return sums();
|
||||
} finally {
|
||||
for (const e of edges) e.c.delete();
|
||||
ex.delete();
|
||||
d.delete();
|
||||
q.delete();
|
||||
n.delete();
|
||||
p.delete();
|
||||
g.delete();
|
||||
surf.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** Sums over all its faces, integrated here - or null when none is swept (OpenCascade measures the rest right). */
|
||||
function ownSums(s: Measurable): (Sums & { R: Vec3 }) | null {
|
||||
// (Kept per shape: a shell's checks measure the same body several times.)
|
||||
const known = measured.get(s);
|
||||
if (known !== undefined) return known;
|
||||
const got = ownSumsNow(s);
|
||||
measured.set(s, got);
|
||||
return got;
|
||||
}
|
||||
const measured = new WeakMap<object, (Sums & { R: Vec3 }) | null>();
|
||||
|
||||
function ownSumsNow(s: Measurable): (Sums & { R: Vec3 }) | null {
|
||||
const faces = s.faces;
|
||||
if (!faces.some(sweptFace)) return null;
|
||||
const b = s.boundingBox;
|
||||
const R = [...b.center] as Vec3;
|
||||
const size = Math.max(1e-9, Math.hypot(b.width, b.height, b.depth));
|
||||
const out: Sums = { area: 0, m: [0, 0, 0], vol: 0, mv: [0, 0, 0] };
|
||||
for (const f of faces) {
|
||||
const r = faceSums(f, R, size);
|
||||
out.area += r.area;
|
||||
out.vol += r.vol;
|
||||
for (let j = 0; j < 3; j++) {
|
||||
out.m[j] += r.m[j];
|
||||
out.mv[j] += r.mv[j];
|
||||
}
|
||||
}
|
||||
return { ...out, R };
|
||||
}
|
||||
|
||||
/** The area of all its faces, to a millionth. */
|
||||
export function measureArea(s: Measurable): number {
|
||||
const own = ownSums(s);
|
||||
if (own) return own.area;
|
||||
const p = props(s, "area");
|
||||
try {
|
||||
return p.Mass();
|
||||
@@ -109,6 +464,8 @@ export function measureArea(s: Measurable): number {
|
||||
|
||||
/** A face's area and its middle (centre of area), measured once - at the plain fineness (for showing, not for checks). */
|
||||
export function areaProperties(f: Face): { area: number; center: Vec3 } {
|
||||
const own = ownSums(f);
|
||||
if (own) return { area: own.area, center: own.m.map((x) => x / own.area) as Vec3 };
|
||||
const oc = getOC();
|
||||
const p = new oc.GProp_GProps();
|
||||
oc.BRepGProp.SurfaceProperties(f.wrapped, p, false, false);
|
||||
@@ -123,6 +480,8 @@ export function areaProperties(f: Face): { area: number; center: Vec3 } {
|
||||
|
||||
/** Volume and centre of mass, to a millionth. */
|
||||
export function volumeProperties(s: Shape3D): { volume: number; centerOfMass: Vec3 } {
|
||||
const own = ownSums(s);
|
||||
if (own) return { volume: own.vol, centerOfMass: own.mv.map((x, j) => own.R[j] + x / own.vol) as Vec3 };
|
||||
const p = props(s, "volume");
|
||||
const c = p.CentreOfMass();
|
||||
try {
|
||||
|
||||
@@ -35,6 +35,8 @@ export interface EdgeInfo {
|
||||
curves?: string[];
|
||||
/** The steps its faces used to be put down to, where that differs (see FaceInfo.was). */
|
||||
was?: string[];
|
||||
/** Where a round face meets itself (one face on both sides): drawn, but nothing to round or chamfer. */
|
||||
seam?: boolean;
|
||||
}
|
||||
|
||||
export interface BodyMesh {
|
||||
@@ -118,6 +120,8 @@ export interface BodyHealth {
|
||||
solids: number;
|
||||
shells: number;
|
||||
openEdges: number;
|
||||
/** Edges more than two faces meet at: pieces that only touch along an edge. */
|
||||
pinched: number;
|
||||
/** Hair-thin faces. */
|
||||
thin: number;
|
||||
volume: number;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
// So each such thing is told to let go just before it is deleted - here, for
|
||||
// its whole class, which covers the deleting done by replicad as well.
|
||||
|
||||
import { getOC } from "replicad";
|
||||
import { BoundingBox, getOC, Solid } from "replicad";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
@@ -27,7 +27,44 @@ function last(handle: any): boolean {
|
||||
return !record?.count || record.count.value === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* A shape's box, worked out once. The kernel's exact box of a body with curved faces takes its time (a mug with its
|
||||
* handle: 0.95 s; a freeform shoe: 0.7 s) and was worked out again each time it was asked for - by every step that
|
||||
* touched the body, several times over, and once more to draw it. Kept by the shape's handle: another shape, or
|
||||
* the same one moved, is another handle. (Each asker gets a box of its own: some delete theirs.)
|
||||
*/
|
||||
const boxes = new WeakMap<object, [number, number, number, number, number, number]>();
|
||||
let boxed = false;
|
||||
function useBoxes(): void {
|
||||
if (boxed) return;
|
||||
boxed = true;
|
||||
let proto: any = Solid.prototype;
|
||||
while (proto && !Object.getOwnPropertyDescriptor(proto, "boundingBox")) proto = Object.getPrototypeOf(proto);
|
||||
const exact = proto && Object.getOwnPropertyDescriptor(proto, "boundingBox")?.get;
|
||||
if (!exact) return;
|
||||
Object.defineProperty(proto, "boundingBox", {
|
||||
configurable: true,
|
||||
get(this: any) {
|
||||
const key = this.wrapped as object;
|
||||
const had = key && boxes.get(key);
|
||||
if (had) return BoundingBox.fromBounds([had[0], had[1], had[2]], [had[3], had[4], had[5]]);
|
||||
const box = exact.call(this);
|
||||
try {
|
||||
// (An empty shape's box is no box: asked again each time, as it was.)
|
||||
if (key && !box.wrapped.IsVoid()) {
|
||||
const [lo, hi] = box.bounds;
|
||||
if ([...lo, ...hi].every(Number.isFinite)) boxes.set(key, [lo[0], lo[1], lo[2], hi[0], hi[1], hi[2]]);
|
||||
}
|
||||
} catch {
|
||||
// As it came.
|
||||
}
|
||||
return box;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function useReleases(): void {
|
||||
useBoxes();
|
||||
const oc = getOC() as any;
|
||||
if (done.has(oc)) return;
|
||||
done.add(oc);
|
||||
|
||||
@@ -7,28 +7,31 @@
|
||||
// one surface merged, skins made solid, inside-out solids turned round.
|
||||
|
||||
import { assembleWire, cast, getOC, makeCompound, makeFace, makeLine, makeThreePointArc, measureArea, type Shape3D, type Wire } from "replicad";
|
||||
import { measureVolume } from "./ocFree";
|
||||
import { measureVolume, quickVolume } from "./ocFree";
|
||||
import { unify } from "./faceEdit";
|
||||
import { deepCopy, hairThin, meshVolume, openEdges, shapeValid, subShapes } from "./health";
|
||||
import { deepCopy, hairThin, meshVolume, openEdges, pinchedEdges, shapeValid, subShapes } from "./health";
|
||||
|
||||
export interface Health {
|
||||
valid: boolean;
|
||||
solids: number;
|
||||
shells: number;
|
||||
openEdges: number;
|
||||
/** Edges more than two faces meet at (pieces touching only along an edge). */
|
||||
pinched: number;
|
||||
thin: number;
|
||||
volume: number;
|
||||
faces: number;
|
||||
}
|
||||
|
||||
export function healthOf(s: Shape3D): Health {
|
||||
const h: Health = { valid: false, solids: 0, shells: 0, openEdges: 0, thin: 0, volume: 0, faces: 0 };
|
||||
const h: Health = { valid: false, solids: 0, shells: 0, openEdges: 0, pinched: 0, thin: 0, volume: 0, faces: 0 };
|
||||
try {
|
||||
h.faces = s.faces.length;
|
||||
h.valid = shapeValid(s);
|
||||
h.solids = subShapes(s, "SOLID").length;
|
||||
h.shells = subShapes(s, "SHELL").length;
|
||||
h.openEdges = openEdges(s).length;
|
||||
h.pinched = pinchedEdges(s);
|
||||
h.thin = hairThin(s);
|
||||
h.volume = h.solids ? measureVolume(s) : 0;
|
||||
} catch {
|
||||
@@ -44,9 +47,9 @@ export interface RepairOptions {
|
||||
volume?: number;
|
||||
}
|
||||
|
||||
/** A clean solid: valid, closed, no hair-thin faces, real volume. */
|
||||
/** A clean solid: valid, closed, no pieces meeting only at an edge, no hair-thin faces, real volume. */
|
||||
export function isHealthy(h: Health, o: RepairOptions = {}): boolean {
|
||||
return h.valid && h.solids >= 1 && (!o.maxSolids || h.solids <= o.maxSolids) && h.openEdges === 0 && h.thin === 0 && h.volume > 0;
|
||||
return h.valid && h.solids >= 1 && (!o.maxSolids || h.solids <= o.maxSolids) && h.openEdges === 0 && !h.pinched && h.thin === 0 && h.volume > 0;
|
||||
}
|
||||
|
||||
/** How broken (0: healthy) - to tell whether a fix helped. */
|
||||
@@ -313,7 +316,7 @@ const FIXES: Fix[] = [
|
||||
label: "turned it the right way out",
|
||||
run: (s) => {
|
||||
const oc = getOC();
|
||||
if (!(measureVolume(s) < 0)) return null;
|
||||
if (!(quickVolume(s) < 0)) return null;
|
||||
const c = deepCopy(s);
|
||||
for (const x of subShapes(c, "SOLID")) oc.BRepLib.OrientClosedSolid(x);
|
||||
return c;
|
||||
@@ -363,6 +366,13 @@ export function repairShape(input: Shape3D, o: RepairOptions = {}): { shape: Sha
|
||||
}
|
||||
const sameShape = (s: Shape3D, hs: Health) => {
|
||||
if (Math.abs(sizeOf(s) - size) > size * 1e-3) return false;
|
||||
// A sound solid measuring below nothing or more than its box is a broken
|
||||
// "fix": said at once. (Meshed to compare, each took 13 s - a cut through a
|
||||
// shelled mouse's curved top spent three minutes here before it said no.)
|
||||
if (hs.valid && hs.solids) {
|
||||
const b = s.boundingBox;
|
||||
if (!(hs.volume > 0) || hs.volume > b.width * b.height * b.depth * 1.001) return false;
|
||||
}
|
||||
if (m0 !== undefined) {
|
||||
try {
|
||||
return Math.abs(meshVolume(s, size) - m0) <= m0 * 5e-3;
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from "replicad";
|
||||
import type { PlaneDef, SketchEntity, Vec2, Vec3 } from "../doc/types";
|
||||
import { toWorld } from "../geom";
|
||||
import { entityPrims, evalPrim, isClosedPrim, SPLINE_PER_SPAN, splineSpanAt, splineSpans, type Prim } from "../sketch/curves";
|
||||
import { entityPolylines, entityPrims, evalPrim, isClosedPrim, SPLINE_PER_SPAN, splineHeightSamples, splineSpanAt, splineSpans, type Prim } from "../sketch/curves";
|
||||
import { arrangement, resolveRegion, type Arrangement, type Loop, type LoopRef, type Piece, type RegionRef } from "../sketch/regions";
|
||||
|
||||
/** Faces for the referenced regions of a sketch (one face per region, holes included). */
|
||||
@@ -54,6 +54,22 @@ export function entitiesWire(entities: SketchEntity[], ids: string[], plane: Pla
|
||||
for (const id of ids) {
|
||||
const e = entities.find((x) => x.id === id);
|
||||
if (!e) throw new Error("A path curve was deleted");
|
||||
// A spline with points off the plane: through space, as it is drawn.
|
||||
const high = splineHeightSamples(e);
|
||||
if (high) {
|
||||
const flat = entityPolylines(e)[0] ?? [];
|
||||
const pts = flat.map((q, i): Vec3 => {
|
||||
const at = toWorld(plane, q);
|
||||
const h = high[Math.min(i, high.length - 1)];
|
||||
return [at[0] + plane.normal[0] * h, at[1] + plane.normal[1] * h, at[2] + plane.normal[2] * h];
|
||||
});
|
||||
let run = 0;
|
||||
for (let i = 1; i < pts.length; i++) run += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1], pts[i][2] - pts[i - 1][2]);
|
||||
if (pts.length >= 3 && run > 1e-9) {
|
||||
edges.push(makeBSplineApproximation(pts, { tolerance: Math.max(1e-6, run * 1e-6), degMax: 5, degMin: 3 }));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
for (const p of entityPrims(e)) {
|
||||
if (p.t === "line") edges.push(makeLine(toWorld(plane, p.a), toWorld(plane, p.b)));
|
||||
else if (p.t === "circle" && isClosedPrim(p)) edges.push(makeCircle(p.r, toWorld(plane, p.c), plane.normal));
|
||||
@@ -61,9 +77,21 @@ export function entitiesWire(entities: SketchEntity[], ids: string[], plane: Pla
|
||||
else edges.push(exactSpline(p, 0, 1, plane) ?? bspline(Array.from({ length: 65 }, (_, i) => evalPrim(p, i / 64)), plane));
|
||||
}
|
||||
}
|
||||
return assembleWire(endToEnd(edges));
|
||||
return pathOf(endToEnd(edges));
|
||||
}
|
||||
|
||||
/** A path's curves as one wire - a gap in it said "Failed to build the wire, disconnected wire". */
|
||||
export function pathOf(edges: Edge[]): Wire {
|
||||
try {
|
||||
return assembleWire(edges);
|
||||
} catch (e) {
|
||||
if (/disconnected/i.test(String((e as Error)?.message ?? e))) throw new Error(PATH_GAP);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export const PATH_GAP = "The path's curves don't join end to end - tap a curve again to leave it out, or pick ones that meet";
|
||||
|
||||
/**
|
||||
* Path curves in the order they run, whatever order they were picked or drawn
|
||||
* in: a fillet's arc is added after the two lines it joins, and the wire was
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
|
||||
import { cast, draw, getOC, makeCompound, makeLine, makeVertex, type Drawing, type Edge, type Face, type Shape3D } from "replicad";
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { cross, dist, dot, len, norm, scale, sub } from "../geom";
|
||||
import { add, cross, dist, dot, len, norm, scale, sub } from "../geom";
|
||||
import { cylinderOf } from "./faceEdit";
|
||||
import { measureVolume } from "./ocFree";
|
||||
import { measureVolume, quickVolume } from "./ocFree";
|
||||
|
||||
const tup = (v: { toTuple(): number[] }) => v.toTuple() as Vec3;
|
||||
|
||||
@@ -95,10 +95,24 @@ function seen(e: Edge, o: Vec3, n: Vec3, body: Shape3D, eps: number): boolean {
|
||||
const seg = makeLine(q, pp);
|
||||
const ds = new oc.BRepExtrema_DistShapeShape(seg.wrapped, body.wrapped);
|
||||
try {
|
||||
return ds.IsDone() && ds.Value() > eps * 0.05;
|
||||
if (!(ds.IsDone() && ds.Value() > eps * 0.05)) return false;
|
||||
} finally {
|
||||
ds.delete();
|
||||
}
|
||||
// Run all the way inside the body, it's hidden too: the distance measured is
|
||||
// to the faces round it, not 0 (a circle drawn on a block's top went through
|
||||
// onto its bottom). Its middle inside, then.
|
||||
const mid = makeVertex(scale(add(q, pp), 0.5));
|
||||
const at = new oc.BRepExtrema_DistShapeShape();
|
||||
try {
|
||||
at.LoadS1(body.wrapped);
|
||||
at.LoadS2(mid.wrapped);
|
||||
at.Perform();
|
||||
return !(at.IsDone() && at.InnerSolution());
|
||||
} finally {
|
||||
at.delete();
|
||||
mid.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** The body's faces split along edges lying on them (one solid still). */
|
||||
@@ -155,11 +169,20 @@ export function wrapOnto(body: Shape3D, round: Face, src: Src, height: number):
|
||||
// The plane's nearest point to the axis: where the wrap starts.
|
||||
let R0 = sub(o, Loc);
|
||||
R0 = sub(R0, scale(Z, dot(R0, Z)));
|
||||
if (len(R0) < 1e-9) R0 = n;
|
||||
// (Straight out from the axis to the plane, along its normal: not towards
|
||||
// the first shape, or a word centred on a mug's far side came out started
|
||||
// from its first letter's place, a quarter of the way round.)
|
||||
const side = dot(R0, n);
|
||||
if (Math.abs(side) > 1e-9) R0 = scale(n, Math.sign(side));
|
||||
else if (len(R0) < 1e-9) R0 = n;
|
||||
R0 = norm(R0);
|
||||
const T = cross(Z, R0);
|
||||
const theta0 = (Math.atan2(dot(R0, Y), dot(R0, X)) + 2 * Math.PI) % (2 * Math.PI);
|
||||
const map = (p: Vec3): [number, number] => [r * theta0 + dot(sub(p, Loc), T), dot(sub(p, Loc), Z)];
|
||||
// Seen from outside the face, as it can only be read: a sketch facing in
|
||||
// towards the axis (drawn on a plane through the far side, looking out from
|
||||
// inside) is turned round, or its letters came out back to front.
|
||||
const across = dot(n, R0) < 0 ? -1 : 1;
|
||||
const map = (p: Vec3): [number, number] => [r * theta0 + across * dot(sub(p, Loc), T), dot(sub(p, Loc), Z)];
|
||||
|
||||
const solids: Shape3D[] = [];
|
||||
for (const { face } of src) {
|
||||
@@ -235,7 +258,7 @@ function thicken(face: Face, height: number, cy: { s: number }): Shape3D {
|
||||
th.MakeThickSolidBySimple(face.wrapped, k);
|
||||
if (!th.IsDone()) return null;
|
||||
let s = cast(th.Shape()) as Shape3D;
|
||||
if (measureVolume(s) < 0) s = cast(s.wrapped.Reversed()) as Shape3D;
|
||||
if (quickVolume(s) < 0) s = cast(s.wrapped.Reversed()) as Shape3D;
|
||||
return s;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -2,6 +2,7 @@ import "./style.css";
|
||||
import { App } from "./app";
|
||||
import { outerScrollbars } from "./ui/scrollbars";
|
||||
import { installDebug } from "./debug";
|
||||
import { keepPageSteady } from "./ui/steady";
|
||||
|
||||
// Update reloads with ?v=<time> so no stored copy is used; once loaded, the
|
||||
// address is plain again (it's what people copy to share the app).
|
||||
@@ -13,6 +14,9 @@ import { installDebug } from "./debug";
|
||||
}
|
||||
}
|
||||
|
||||
// The page itself never scrolls (a phone pushing it along for a keyboard that does not come).
|
||||
keepPageSteady();
|
||||
|
||||
// Scroll bars outside the windows, only while scrolling.
|
||||
outerScrollbars();
|
||||
|
||||
|
||||
@@ -50,6 +50,127 @@ export interface Settings {
|
||||
showHints: boolean;
|
||||
/** Offline mode: the app's files are kept on this device (More → Offline mode). */
|
||||
offline: boolean;
|
||||
/**
|
||||
* The sentence bar: a line at the bottom that says what is picked and what
|
||||
* can be done with it. Always on - it is the only way to the tools (kept as a
|
||||
* setting for the code that asks).
|
||||
*/
|
||||
sentence: boolean;
|
||||
/**
|
||||
* Direct touch: what is picked is dragged by itself, not only by its arrow
|
||||
* or dot - a face pulled, a shape pulled up, an edge rounded - and a finger
|
||||
* pressed and held on one picks it and pulls in the same touch. Always on
|
||||
* (kept as a setting for the code that asks).
|
||||
*/
|
||||
direct: boolean;
|
||||
/**
|
||||
* Which mouse drags turn, move and zoom the view (Settings > Mouse): the app's own way, or the way of another
|
||||
* CAD program, for hands used to it (see MOUSE_PRESETS). In all of them the wheel zooms, Alt + left drag turns,
|
||||
* and a right drag turns too unless the preset uses it for something else.
|
||||
*/
|
||||
mouse: string;
|
||||
/** The wheel rolled forward zooms out (it zooms in otherwise). */
|
||||
wheelReverse: boolean;
|
||||
}
|
||||
|
||||
export type MouseNav = "orbit" | "pan" | "zoom";
|
||||
|
||||
/**
|
||||
* A way of working the view with a mouse. `middle` and `right`: what a drag with that button does, by the keys
|
||||
* held (`plain`, `shift`, `ctrl`, `both` for Ctrl + Shift; one not given falls back to `plain`). `chord`: what
|
||||
* the middle button's drag becomes while another button is held with it (CATIA, NX, FreeCAD).
|
||||
*/
|
||||
export interface MousePreset {
|
||||
id: string;
|
||||
/** The programs that work this way (the row in Settings). */
|
||||
apps: string;
|
||||
/** What it does, in words. */
|
||||
text: string;
|
||||
middle: { plain: MouseNav; shift?: MouseNav; ctrl?: MouseNav; both?: MouseNav };
|
||||
right?: { shift?: MouseNav; ctrl?: MouseNav };
|
||||
chord?: { left?: MouseNav; right?: MouseNav };
|
||||
}
|
||||
|
||||
/**
|
||||
* The presets. Asked for: "it should have controls presets from all major CAD apps". Each as its program's own
|
||||
* help gives it (2026-11); programs that work the same way share a row. The wheel's way round is its own switch
|
||||
* (programs differ, and each lets it be turned over).
|
||||
*/
|
||||
export const MOUSE_PRESETS: MousePreset[] = [
|
||||
{
|
||||
id: "default",
|
||||
apps: "superGeometry, Onshape, Tinkercad",
|
||||
text: "Right drag turns the view. Middle drag moves it (also Shift or Ctrl + right drag).",
|
||||
middle: { plain: "pan" },
|
||||
right: { shift: "pan", ctrl: "pan" },
|
||||
},
|
||||
{
|
||||
id: "fusion",
|
||||
apps: "Fusion, Inventor, Revit, AutoCAD",
|
||||
text: "Shift + middle drag turns the view. Middle drag moves it. Ctrl + Shift + middle drag zooms.",
|
||||
middle: { plain: "pan", shift: "orbit", both: "zoom" },
|
||||
right: { shift: "pan" },
|
||||
},
|
||||
{
|
||||
id: "solidworks",
|
||||
apps: "SolidWorks",
|
||||
text: "Middle drag turns the view. Ctrl + middle drag moves it. Shift + middle drag zooms.",
|
||||
middle: { plain: "orbit", ctrl: "pan", shift: "zoom" },
|
||||
right: { shift: "pan" },
|
||||
},
|
||||
{
|
||||
id: "creo",
|
||||
apps: "Creo, Solid Edge, Blender, SketchUp",
|
||||
text: "Middle drag turns the view. Shift + middle drag moves it. Ctrl + middle drag zooms.",
|
||||
middle: { plain: "orbit", shift: "pan", ctrl: "zoom" },
|
||||
right: { shift: "pan" },
|
||||
},
|
||||
{
|
||||
id: "nx",
|
||||
apps: "NX",
|
||||
text: "Middle drag turns the view. Middle + right drag (or Shift + middle) moves it. Middle + left drag (or Ctrl + middle) zooms.",
|
||||
middle: { plain: "orbit", shift: "pan", ctrl: "zoom" },
|
||||
right: { shift: "pan" },
|
||||
chord: { right: "pan", left: "zoom" },
|
||||
},
|
||||
{
|
||||
id: "catia",
|
||||
apps: "CATIA, FreeCAD",
|
||||
text: "Middle drag moves the view. Hold the middle button and press the left or right one too: the drag turns it. Ctrl + middle drag zooms.",
|
||||
middle: { plain: "pan", ctrl: "zoom" },
|
||||
right: { shift: "pan" },
|
||||
chord: { left: "orbit", right: "orbit" },
|
||||
},
|
||||
{
|
||||
id: "rhino",
|
||||
apps: "Rhino",
|
||||
text: "Right drag turns the view. Shift + right drag moves it. Ctrl + right drag zooms. Middle drag moves it too.",
|
||||
middle: { plain: "pan" },
|
||||
right: { shift: "pan", ctrl: "zoom" },
|
||||
},
|
||||
];
|
||||
|
||||
/** The preset in use (one not known - an older setting - is the app's own). */
|
||||
export function mousePreset(id: string): MousePreset {
|
||||
return MOUSE_PRESETS.find((m) => m.id === id) ?? MOUSE_PRESETS[0];
|
||||
}
|
||||
|
||||
/** What a mouse press on the view does to the view, in a preset: null, nothing (the press is for the tools). */
|
||||
export function mouseDrag(id: string, button: number, keys: { shift: boolean; ctrl: boolean; alt: boolean }): MouseNav | "right" | null {
|
||||
const preset = mousePreset(id);
|
||||
if (button === 0) return keys.alt ? "orbit" : null;
|
||||
// The right button: a drag turns the view, a click is the right-click (told apart as it moves) - with a key, what the preset says.
|
||||
if (button === 2) return (keys.ctrl ? preset.right?.ctrl : keys.shift ? preset.right?.shift : undefined) ?? "right";
|
||||
if (button !== 1) return null;
|
||||
const m = preset.middle;
|
||||
return (keys.ctrl && keys.shift ? (m.both ?? m.ctrl ?? m.shift) : keys.ctrl ? m.ctrl : keys.shift ? m.shift : undefined) ?? m.plain;
|
||||
}
|
||||
|
||||
/** A middle drag while other buttons are held with it (`buttons` as a pointer event gives them): what it becomes, or null. */
|
||||
export function mouseChord(id: string, buttons: number): MouseNav | null {
|
||||
const chord = mousePreset(id).chord;
|
||||
if (!chord || !(buttons & 4)) return null;
|
||||
return (buttons & 1 ? chord.left : undefined) ?? (buttons & 2 ? chord.right : undefined) ?? null;
|
||||
}
|
||||
|
||||
const DEFAULTS: Settings = {
|
||||
@@ -81,7 +202,11 @@ const DEFAULTS: Settings = {
|
||||
numpad: isTouchDevice,
|
||||
showHints: true,
|
||||
offline: false,
|
||||
version: 4,
|
||||
sentence: true,
|
||||
direct: true,
|
||||
mouse: "default",
|
||||
wheelReverse: false,
|
||||
version: 5,
|
||||
};
|
||||
|
||||
type Listener = (s: Settings) => void;
|
||||
@@ -105,6 +230,10 @@ class SettingsStore {
|
||||
if ((saved.version ?? 1) < 3) this.value = { ...this.value, numpad: isTouchDevice, version: 3 };
|
||||
// v4: the Constraints column starts closed (it got in the way; the Constraints button opens it).
|
||||
if ((saved.version ?? 1) < 4) this.value = { ...this.value, showConstraints: false, version: 4 };
|
||||
// The sentence bar is the only way to the tools (its switch in More is gone): on for everyone.
|
||||
this.value.sentence = true;
|
||||
// Direct touch is how the app is worked too (it had a switch in More for a while: one saved as off is on again).
|
||||
this.value.direct = true;
|
||||
}
|
||||
|
||||
set<K extends keyof Settings>(key: K, v: Settings[K]): void {
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
// from wandering (so the result is the smallest change that satisfies them).
|
||||
|
||||
import type { ConstraintType, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../doc/types";
|
||||
import { arcFrom3, entityCorners } from "./curves";
|
||||
import { arcFrom3, entityCorners, entityPolylines } from "./curves";
|
||||
import { mirrorXf, offsetEntity, transformEntity } from "./edit";
|
||||
|
||||
// ------------------------------------------------------------- parameters
|
||||
|
||||
@@ -36,18 +37,28 @@ function params(e: SketchEntity): number[] {
|
||||
}
|
||||
}
|
||||
|
||||
/** Length per unit of each parameter (1 for coordinates, the radius for angles). */
|
||||
function pullScale(e: SketchEntity, p: number[]): number[] {
|
||||
/**
|
||||
* A shape with a size of its own (a rectangle, an ellipse, a polygon) keeps it sooner than its place: asked to bring
|
||||
* a corner somewhere, it goes there - it is not squashed towards it. (Each counted the same, a rectangle whose corner
|
||||
* was put on a point 60 away came out 0.00001 tall, and an ellipse flat.)
|
||||
*/
|
||||
const STIFF = 4;
|
||||
|
||||
/**
|
||||
* Length per unit of each parameter (1 for coordinates, the radius for angles). `stiff`: how much sooner a shape
|
||||
* keeps its size and its way round than its place (1 while it is dragged: a corner pulled is the shape pulled about).
|
||||
*/
|
||||
function pullScale(e: SketchEntity, p: number[], stiff: number): number[] {
|
||||
const r = (v: number) => Math.max(Math.abs(v), 1e-9);
|
||||
switch (e.kind) {
|
||||
case "arc":
|
||||
return p.length === 5 ? [1, 1, 1, r(p[2]), r(p[2])] : p.map(() => 1);
|
||||
return p.length === 5 ? [1, 1, stiff, stiff * r(p[2]), stiff * r(p[2])] : p.map(() => 1);
|
||||
case "ellipse":
|
||||
return [1, 1, 1, 1, r(Math.max(e.rx, e.ry))];
|
||||
return [1, 1, stiff, stiff, r(Math.max(e.rx, e.ry))];
|
||||
case "rect":
|
||||
return [1, 1, 1, 1, r(Math.hypot(e.w, e.h) / 2)];
|
||||
return [1, 1, stiff, stiff, r(Math.hypot(e.w, e.h) / 2)];
|
||||
case "polygon":
|
||||
return [1, 1, 1, r(e.radius)];
|
||||
return [1, 1, stiff, r(e.radius)];
|
||||
default:
|
||||
return p.map(() => 1);
|
||||
}
|
||||
@@ -90,12 +101,25 @@ export function pointsOf(e: SketchEntity): { p: string; at: Vec2 }[] {
|
||||
return [{ p: "a", at: e.a }, { p: "b", at: e.b }, ...(c ? [{ p: "c", at: c.c }] : [])];
|
||||
}
|
||||
case "circle":
|
||||
case "ellipse":
|
||||
return [{ p: "c", at: e.center }];
|
||||
case "ellipse": {
|
||||
if (e.sweep === undefined) return [{ p: "c", at: e.center }];
|
||||
// Part of an ellipse: its two ends too.
|
||||
const at = (t: number): Vec2 => {
|
||||
const x = e.rx * Math.cos(t);
|
||||
const y = e.ry * Math.sin(t);
|
||||
return [e.center[0] + x * Math.cos(e.rotation) - y * Math.sin(e.rotation), e.center[1] + x * Math.sin(e.rotation) + y * Math.cos(e.rotation)];
|
||||
};
|
||||
return [{ p: "a", at: at(e.a0 ?? 0) }, { p: "b", at: at((e.a0 ?? 0) + e.sweep) }, { p: "c", at: e.center }];
|
||||
}
|
||||
case "rect":
|
||||
case "polygon":
|
||||
return [{ p: "c", at: e.center }, ...entityCorners(e).map((at, i) => ({ p: `k${i}`, at }))];
|
||||
case "spline":
|
||||
// A curve that follows a body's edge (Project): its two ends, as the edge has - the points between are the
|
||||
// edge's shape, made again whenever the body changes, and not there to pick, snap to or drag.
|
||||
if (e.id.startsWith(LINKED) && !e.closed && e.points.length > 2) return [{ p: "k0", at: e.points[0] }, { p: `k${e.points.length - 1}`, at: e.points[e.points.length - 1] }];
|
||||
return e.points.map((at, i) => ({ p: `k${i}`, at }));
|
||||
case "polyline":
|
||||
return e.points.map((at, i) => ({ p: `k${i}`, at }));
|
||||
}
|
||||
@@ -172,7 +196,7 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
|
||||
if (a && b) return [a[0] - b[0], a[1] - b[1]];
|
||||
// Point on a curve.
|
||||
const e = E(0);
|
||||
if (a && e) return [distToEntity(a, e)];
|
||||
if (a && e) return distToEntity(a, e);
|
||||
return [];
|
||||
}
|
||||
case "horizontal":
|
||||
@@ -210,8 +234,21 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
|
||||
if (line && round) return [distPointLine(round.c, line.a, line.b) - round.r];
|
||||
if (r1 && r2) {
|
||||
const d = Math.hypot(r1.c[0] - r2.c[0], r1.c[1] - r2.c[1]);
|
||||
// External tangency unless one contains the other.
|
||||
return [Math.min(Math.abs(d - (r1.r + r2.r)), Math.abs(d - Math.abs(r1.r - r2.r)))];
|
||||
// Touching from outside, or one inside the other: whichever is nearer. (With its sign: the smaller of the two
|
||||
// sizes has a kink right at the answer, and the last of the way there was crept.)
|
||||
const out = d - (r1.r + r2.r);
|
||||
const ins = d - Math.abs(r1.r - r2.r);
|
||||
return [Math.abs(out) < Math.abs(ins) ? out : ins];
|
||||
}
|
||||
// A line and an ellipse: the line is as far from the centre as the ellipse reaches that way.
|
||||
const ell = e1.kind === "ellipse" ? e1 : e2.kind === "ellipse" ? e2 : null;
|
||||
if (line && ell) {
|
||||
const l = Math.hypot(line.b[0] - line.a[0], line.b[1] - line.a[1]) || 1;
|
||||
const n: Vec2 = [(line.b[1] - line.a[1]) / l, -(line.b[0] - line.a[0]) / l];
|
||||
const cs = Math.cos(ell.rotation);
|
||||
const sn = Math.sin(ell.rotation);
|
||||
const reach = Math.hypot(ell.rx * (n[0] * cs + n[1] * sn), ell.ry * (-n[0] * sn + n[1] * cs));
|
||||
return [distPointLine(ell.center, line.a, line.b) - reach];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -259,6 +296,37 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
|
||||
if (o.kind === "ellipse" && k.kind === "ellipse") out.push(k.rx - o.rx, k.ry - o.ry);
|
||||
return out;
|
||||
}
|
||||
case "follow": {
|
||||
// A copy made from another curve - its offset, its mirror image: it is that, of the original as it is now.
|
||||
// (An offset or a mirrored copy was a curve of its own from the moment it was made: the original given
|
||||
// another size - a dimension typed, a variable changed - the copy stayed as it had been.)
|
||||
const o = E(0);
|
||||
const k = E(1);
|
||||
const how = c.how;
|
||||
if (!o || !k || !how) return [];
|
||||
const want = how.mirror ? transformEntity(o, mirrorXf(how.mirror[0], how.mirror[1])) : how.offset !== undefined ? offsetEntity(o, how.offset) : null;
|
||||
if (!want) return [];
|
||||
if (how.loose) {
|
||||
// A piece of an offset outline: on the original's offset (its ends are its neighbours' business).
|
||||
if (want.kind === "line" && k.kind === "line") return [distPointLineSigned(k.a, want.a, want.b), distPointLineSigned(k.b, want.a, want.b)];
|
||||
if (want.kind === "arc" && k.kind === "arc") {
|
||||
const w = arcFrom3(want.a, want.m, want.b);
|
||||
return w ? [k.a, k.m, k.b].map((p) => Math.hypot(p[0] - w.c[0], p[1] - w.c[1]) - w.r) : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (want.kind !== k.kind) return [];
|
||||
const out: number[] = [];
|
||||
for (const q of pointsOf(want)) {
|
||||
const w = pointOf(k, q.p);
|
||||
if (!w) return [];
|
||||
out.push(w[0] - q.at[0], w[1] - q.at[1]);
|
||||
}
|
||||
if (want.kind === "arc" && k.kind === "arc") out.push(k.m[0] - want.m[0], k.m[1] - want.m[1]);
|
||||
if ((want.kind === "circle" || want.kind === "polygon") && (k.kind === "circle" || k.kind === "polygon")) out.push(k.radius - want.radius);
|
||||
if (want.kind === "ellipse" && k.kind === "ellipse") out.push(k.rx - want.rx, k.ry - want.ry, wrap(k.rotation - want.rotation) * Math.max(want.rx, want.ry));
|
||||
return out;
|
||||
}
|
||||
case "distance": {
|
||||
if (c.value === undefined) return [];
|
||||
// Point to line: perpendicular distance.
|
||||
@@ -267,6 +335,17 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
|
||||
const l = E(0);
|
||||
return p && l?.kind === "line" ? [distPointLine(p, l.a, l.b) - c.value] : [];
|
||||
}
|
||||
// Line to line: they run the same way, that far apart (the second's middle from the first).
|
||||
if (!c.pts?.length && c.curves?.length === 2) {
|
||||
const [l, m] = [E(0), E(1)];
|
||||
if (l?.kind !== "line" || m?.kind !== "line") return [];
|
||||
const [d1, d2] = [dirOf(l), dirOf(m)];
|
||||
if (!d1 || !d2) return [];
|
||||
const mid: Vec2 = [(m.a[0] + m.b[0]) / 2, (m.a[1] + m.b[1]) / 2];
|
||||
const len = Math.hypot(m.b[0] - m.a[0], m.b[1] - m.a[1]) || 1;
|
||||
// (The turn as a length - the second line's end off the first's way - so it weighs as the distance does.)
|
||||
return [distPointLine(mid, l.a, l.b) - c.value, (d1[0] * d2[1] - d1[1] * d2[0]) * len];
|
||||
}
|
||||
const [a, b] = (c.pts ?? []).map(P);
|
||||
return a && b ? [Math.hypot(a[0] - b[0], a[1] - b[1]) - c.value] : [];
|
||||
}
|
||||
@@ -309,11 +388,48 @@ function distPointLineSigned(p: Vec2, a: Vec2, b: Vec2): number {
|
||||
return ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / l;
|
||||
}
|
||||
|
||||
function distToEntity(p: Vec2, e: SketchEntity): number {
|
||||
if (e.kind === "line") return distPointLineSigned(p, e.a, e.b);
|
||||
function distToEntity(p: Vec2, e: SketchEntity): number[] {
|
||||
if (e.kind === "line") return [distPointLineSigned(p, e.a, e.b)];
|
||||
const r = roundOf(e);
|
||||
if (r) return Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r;
|
||||
return 0;
|
||||
if (r) return [Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r];
|
||||
if (e.kind === "ellipse") {
|
||||
// In the ellipse's own frame, how far out the point is as a share of the way to it (1: on it).
|
||||
const dx = p[0] - e.center[0];
|
||||
const dy = p[1] - e.center[1];
|
||||
const cs = Math.cos(e.rotation);
|
||||
const sn = Math.sin(e.rotation);
|
||||
const k = Math.hypot((dx * cs + dy * sn) / Math.max(e.rx, 1e-12), (-dx * sn + dy * cs) / Math.max(e.ry, 1e-12));
|
||||
return [(k - 1) * Math.min(e.rx, e.ry)];
|
||||
}
|
||||
// A rectangle, a polygon, a polyline, a spline: from the nearest place on it (a spline: as it is drawn) to the
|
||||
// point, across and up. Two numbers that change evenly as the point goes round a corner, so it gets there from
|
||||
// anywhere and the last of the way is not crept. (It was 0 for all of these: a point "put on" a rectangle's edge
|
||||
// was taken and stayed where it was.)
|
||||
const runs: Vec2[][] = e.kind === "rect" || e.kind === "polygon" ? [closedRun(entityCorners(e))] : e.kind === "polyline" ? [e.closed ? closedRun(e.points) : e.points] : entityPolylines(e);
|
||||
let best = Infinity;
|
||||
let out = [0, 0];
|
||||
for (const run of runs)
|
||||
for (let i = 0; i + 1 < run.length; i++) {
|
||||
const a = run[i];
|
||||
const b = run[i + 1];
|
||||
const ux = b[0] - a[0];
|
||||
const uy = b[1] - a[1];
|
||||
const l2 = ux * ux + uy * uy;
|
||||
if (l2 < 1e-24) continue;
|
||||
const s = ((p[0] - a[0]) * ux + (p[1] - a[1]) * uy) / l2;
|
||||
const c = Math.max(0, Math.min(1, s));
|
||||
const vx = p[0] - a[0] - c * ux;
|
||||
const vy = p[1] - a[1] - c * uy;
|
||||
const d = Math.hypot(vx, vy);
|
||||
if (d >= best) continue;
|
||||
best = d;
|
||||
out = [vx, vy];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function closedRun(pts: Vec2[]): Vec2[] {
|
||||
return pts.length ? [...pts, pts[0]] : pts;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ solver
|
||||
@@ -417,9 +533,44 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
|
||||
const p = params(e);
|
||||
offsets.push(x0.length);
|
||||
counts.push(p.length);
|
||||
per.push(...pullScale(e, p));
|
||||
per.push(...pullScale(e, p, opts.drag?.length ? 1 : STIFF));
|
||||
x0.push(...p);
|
||||
}
|
||||
// A line asked to lie a way it is far from (Vertical on one nearly level; an angle 130 degrees off): turned there
|
||||
// about its middle first, its length kept. Left to the steps alone it got there by shrinking - shorter is the
|
||||
// shortest way to "upright" - and a line given a far angle ended a speck.
|
||||
if (!opts.drag?.length) {
|
||||
const at = new Map(movers.map((e, i) => [e.id, i]));
|
||||
for (const c of live) {
|
||||
const pair = (c.type === "parallel" || c.type === "perpendicular") && c.curves?.length === 2;
|
||||
// (Parallel, Perpendicular: the second line is the one turned - the first if only that one may move.)
|
||||
const which = pair ? (at.has(c.curves![1]) ? 1 : 0) : 0;
|
||||
const i = (pair || c.curves?.length === 1) && !c.pts?.length ? at.get(c.curves![which]) : undefined;
|
||||
const e = i === undefined ? undefined : movers[i];
|
||||
if (i === undefined || e?.kind !== "line") continue;
|
||||
const now = Math.atan2(e.b[1] - e.a[1], e.b[0] - e.a[0]);
|
||||
let want: number | null = null;
|
||||
if (pair) {
|
||||
const o = entities.find((x) => x.id === c.curves![1 - which]);
|
||||
if (o?.kind !== "line") continue;
|
||||
const base = Math.atan2(o.b[1] - o.a[1], o.b[0] - o.a[0]) + (c.type === "perpendicular" ? Math.PI / 2 : 0);
|
||||
// (Either way along it will do: the nearer.)
|
||||
want = Math.abs(wrap(base - now)) <= Math.PI / 2 ? base : base + Math.PI;
|
||||
}
|
||||
if (c.type === "dim" && c.prop === "angle" && c.value !== undefined) want = (c.value * Math.PI) / 180;
|
||||
else if (c.type === "horizontal") want = Math.abs(wrap(now)) < Math.PI / 2 ? 0 : Math.PI;
|
||||
else if (c.type === "vertical") want = wrap(now) > 0 ? Math.PI / 2 : -Math.PI / 2;
|
||||
if (want === null || Math.abs(wrap(want - now)) < Math.PI / 6) continue;
|
||||
const o = offsets[i];
|
||||
const mx = (e.a[0] + e.b[0]) / 2;
|
||||
const my = (e.a[1] + e.b[1]) / 2;
|
||||
const h = Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1]) / 2;
|
||||
x0[o] = mx - h * Math.cos(want);
|
||||
x0[o + 1] = my - h * Math.sin(want);
|
||||
x0[o + 2] = mx + h * Math.cos(want);
|
||||
x0[o + 3] = my + h * Math.sin(want);
|
||||
}
|
||||
}
|
||||
const byId = new Map(entities.map((e) => [e.id, e]));
|
||||
const build = (x: number[]) => {
|
||||
const m = new Map(byId);
|
||||
@@ -496,7 +647,7 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
|
||||
// (The pull pass only has to get near: once a step gains next to nothing
|
||||
// it stops - it used to run all 30 steps every frame, as the pull never
|
||||
// reaches zero; the exact pass stops once the constraints are met.)
|
||||
xs = lm(xs, 1e-3, true, t, Math.min(30, it), 1e-6, false, 1e-7);
|
||||
xs = lm(xs, 1e-7, true, t, Math.min(30, it), 1e-6, false, 1e-7);
|
||||
xs = lm(xs, 1e-8, false, t, it, 1e-10, true, 1e-9);
|
||||
} else {
|
||||
// A noticeable pull first (smallest change), then almost none (exact constraints).
|
||||
@@ -541,6 +692,16 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
|
||||
const xg = gradually(1 / 16, 60);
|
||||
if (xg && errorAt(xg) <= Math.max(errorAt(xs), tol)) xs = xg;
|
||||
}
|
||||
// Float noise off the answer (a height typed as 93 solved to 92.999999999999,
|
||||
// then shown, saved and built so): each value a hair off a clean one is put
|
||||
// on it, when that keeps the constraints as well met.
|
||||
if (!drags.length) {
|
||||
const clean = xs.map((v) => {
|
||||
const r = Math.round(v * 1e9) / 1e9;
|
||||
return r !== v && Math.abs(r - v) < 1e-10 * Math.max(1, Math.abs(v)) ? r : v;
|
||||
});
|
||||
if (clean.some((v, i) => v !== xs[i]) && errorAt(clean) <= Math.max(errorAt(xs), tol)) xs = clean;
|
||||
}
|
||||
const m = build(xs);
|
||||
const error = errorAt(xs);
|
||||
return { entities: entities.map((e) => m.get(e.id) ?? e), error, ok: error < 1e-6 * Math.max(1, scale) };
|
||||
@@ -642,8 +803,15 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So
|
||||
for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) A[b][a] = A[a][b];
|
||||
let improved = false;
|
||||
let gain = 0;
|
||||
// Damped the same in every direction (each parameter in its own length): the step is then the shortest one
|
||||
// that does it. Damped by each parameter's own share (Marquardt's way), a sketch with room to spare - most
|
||||
// are - stepped furthest in the direction that helped least: a line given a length drew its ends together
|
||||
// sideways until it stood upright, and stopped there, the length not met.
|
||||
let mean = 0;
|
||||
for (let i = 0; i < n; i++) mean += A[i][i] / (per[i] * per[i]);
|
||||
mean = mean / Math.max(1, n) || 1;
|
||||
for (let tries = 0; tries < 8; tries++) {
|
||||
const diag = A.map((rowA, i) => rowA[i] * (1 + lambda) + 1e-12);
|
||||
const diag = A.map((rowA, i) => rowA[i] + lambda * mean * per[i] * per[i] + 1e-12);
|
||||
let dx = solveSPD(A, diag, g);
|
||||
if (!dx) {
|
||||
const M = A.map((rowA, i) => rowA.map((v, j) => (i === j ? diag[i] : v)));
|
||||
@@ -931,7 +1099,9 @@ export function applicable(type: ConstraintType, pts: PointRef[], curves: Sketch
|
||||
case "equal":
|
||||
return curves.length === 2 && (lines.length === 2 || rounds.length === 2);
|
||||
case "tangent":
|
||||
return curves.length === 2 && rounds.length >= 1;
|
||||
// A circle or an arc with a line or another of them; a line with an ellipse. (It was offered for a circle with
|
||||
// anything - a rectangle, a spline, an ellipse - and taken, and did nothing.)
|
||||
return curves.length === 2 && (rounds.length === 2 || (rounds.length === 1 && lines.length === 1) || (lines.length === 1 && curves.some((e) => e.kind === "ellipse")));
|
||||
case "concentric":
|
||||
return curves.length === 2 && curves.every((e) => e.kind !== "line" && e.kind !== "spline" && e.kind !== "polyline");
|
||||
case "midpoint":
|
||||
@@ -939,7 +1109,7 @@ export function applicable(type: ConstraintType, pts: PointRef[], curves: Sketch
|
||||
case "symmetric":
|
||||
return pts.length === 2 && lines.length === 1 && curves.length === 1;
|
||||
case "distance":
|
||||
return (pts.length === 2 && !curves.length) || (pts.length === 1 && lines.length === 1 && curves.length === 1);
|
||||
return (pts.length === 2 && !curves.length) || (pts.length === 1 && lines.length === 1 && curves.length === 1) || (!pts.length && lines.length === 2 && curves.length === 2);
|
||||
case "fix":
|
||||
// Points, or whole curves (all their points).
|
||||
return pts.length >= 1 || curves.length >= 1;
|
||||
@@ -1144,6 +1314,7 @@ export function constraintName(c: SketchConstraint): string {
|
||||
if (c.type === "dim") return `${c.prop === "angle" ? "angle" : (c.prop ?? "size")} dimension`;
|
||||
if (c.type === "fix") return "lock";
|
||||
if (c.type === "pattern") return "pattern link";
|
||||
if (c.type === "follow") return c.how?.mirror ? "mirror link" : "offset link";
|
||||
return c.type;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
// Every sketch entity is broken into primitives (line / circular arc /
|
||||
// elliptical arc / spline) that can be evaluated at a parameter t ∈ [0, 1].
|
||||
|
||||
import type { SketchEntity, Vec2 } from "../doc/types";
|
||||
import type { PlaneDef, SketchEntity, Vec2, Vec3 } from "../doc/types";
|
||||
import { toWorld } from "../geom";
|
||||
|
||||
export type Prim =
|
||||
| { t: "line"; a: Vec2; b: Vec2; src: string }
|
||||
@@ -82,7 +83,7 @@ export function entityPrims(e: SketchEntity): Prim[] {
|
||||
case "circle":
|
||||
return [{ t: "circle", c: e.center, r: e.radius, a0: 0, sweep: TAU, src }];
|
||||
case "ellipse":
|
||||
return [{ t: "ellipse", c: e.center, rx: e.rx, ry: e.ry, rot: e.rotation, a0: 0, sweep: TAU, src }];
|
||||
return [{ t: "ellipse", c: e.center, rx: e.rx, ry: e.ry, rot: e.rotation, a0: e.sweep === undefined ? 0 : (e.a0 ?? 0), sweep: e.sweep ?? TAU, src }];
|
||||
case "spline":
|
||||
return [{ t: "spline", pts: splinePoints(e.points, e.closed, e.mode), closed: e.closed && e.points.length > 2, src, ...(e.points.length > 2 ? { ctrl: { points: e.points, closed: e.closed, mode: e.mode } } : {}) }];
|
||||
case "rect":
|
||||
@@ -120,6 +121,39 @@ export function entityCorners(e: Extract<SketchEntity, { kind: "rect" | "polygon
|
||||
] as Vec2[]).map(([x, y]) => [e.center[0] + x * c - y * s, e.center[1] + x * s + y * c] as Vec2);
|
||||
}
|
||||
|
||||
/** A spline's heights off its sketch's plane, one for each of its points - null when it is flat (or they don't fit its points). */
|
||||
export function splineHeights(e: SketchEntity): number[] | null {
|
||||
if (e.kind !== "spline" || !e.z || e.z.length !== e.points.length || !e.z.some((v) => Math.abs(v) > 1e-12)) return null;
|
||||
return e.z;
|
||||
}
|
||||
|
||||
/**
|
||||
* The height at each point of the spline's drawn polyline (entityPolylines' own points, in step with them): the
|
||||
* heights of its points run through the same curve as their places. Null for a flat one.
|
||||
*/
|
||||
export function splineHeightSamples(e: SketchEntity): number[] | null {
|
||||
const z = splineHeights(e);
|
||||
if (!z || e.kind !== "spline") return null;
|
||||
return splinePoints(z.map((v): Vec2 => [v, 0]), e.closed && e.points.length > 2, e.mode).map((p) => p[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
* An entity's drawn polylines where they are in space: on the sketch's plane - and a spline with points off the
|
||||
* plane up where it runs. (What picks a place on a curve - a plane on it, a preview along it - goes by this, not by
|
||||
* the curve's shadow on the plane.)
|
||||
*/
|
||||
export function entityWorldPolylines(e: SketchEntity, plane: PlaneDef): Vec3[][] {
|
||||
const high = splineHeightSamples(e);
|
||||
const n = plane.normal;
|
||||
return entityPolylines(e).map((poly) =>
|
||||
poly.map((q, i) => {
|
||||
const at = toWorld(plane, q);
|
||||
const h = high ? (high[Math.min(i, high.length - 1)] ?? 0) : 0;
|
||||
return h ? ([at[0] + n[0] * h, at[1] + n[1] * h, at[2] + n[2] * h] as Vec3) : at;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Dense polyline for drawing an entity. */
|
||||
export function entityPolylines(e: SketchEntity): Vec2[][] {
|
||||
return entityPrims(e).map((p) => samplePrim(p, 0, 1));
|
||||
|
||||
@@ -5,7 +5,8 @@ import type { OutlineOffset, PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec
|
||||
import { roundSig, toPlane, toWorld } from "../geom";
|
||||
import type { Arrangement, Region } from "./regions";
|
||||
import { constraintError, pointOf, pointsOf, refsOf, solve } from "./constraints";
|
||||
import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, type Prim } from "./curves";
|
||||
import { fitSpline } from "./freehand";
|
||||
import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, splineHeights, splineHeightSamples, type Prim } from "./curves";
|
||||
|
||||
export function uid(): string {
|
||||
return Math.random().toString(36).slice(2, 10);
|
||||
@@ -52,9 +53,11 @@ export function transformEntity(e: SketchEntity, xf: Xf, newId = false): SketchE
|
||||
case "circle":
|
||||
return { ...base, kind: "circle", center: xf(e.center), radius: e.radius * k };
|
||||
case "ellipse":
|
||||
return { ...base, kind: "ellipse", center: xf(e.center), rx: e.rx * k, ry: e.ry * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot };
|
||||
// (Part of an ellipse, mirrored: it runs the other way round from the other side of its axis.)
|
||||
return { ...base, kind: "ellipse", center: xf(e.center), rx: e.rx * k, ry: e.ry * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot, ...(e.sweep === undefined ? {} : { a0: mirrored ? -(e.a0 ?? 0) : (e.a0 ?? 0), sweep: mirrored ? -e.sweep : e.sweep }) };
|
||||
case "spline":
|
||||
return { ...base, kind: "spline", points: e.points.map(xf), closed: e.closed, mode: e.mode };
|
||||
// (Moved, turned or mirrored in the plane, its points stay as far off it; scaled, that much nearer or further.)
|
||||
return { ...base, kind: "spline", points: e.points.map(xf), closed: e.closed, mode: e.mode, ...(e.z ? { z: e.z.map((v) => v * k) } : {}) };
|
||||
case "rect":
|
||||
return { ...base, kind: "rect", center: xf(e.center), w: e.w * k, h: e.h * k, rotation: mirrored ? rot - e.rotation : e.rotation + rot };
|
||||
case "polygon": {
|
||||
@@ -83,7 +86,8 @@ export function guidePoints(e: SketchEntity): { p: Vec2; kind: "end" | "mid" | "
|
||||
case "circle":
|
||||
case "ellipse":
|
||||
out.push({ p: e.center, kind: "center" });
|
||||
for (const p of entityPrims(e)) for (const t of [0, 0.25, 0.5, 0.75]) out.push({ p: evalPrim(p, t), kind: "end" });
|
||||
// (Part of an ellipse: its two ends and its middle.)
|
||||
for (const p of entityPrims(e)) for (const t of e.kind === "ellipse" && e.sweep !== undefined ? [0, 0.5, 1] : [0, 0.25, 0.5, 0.75]) out.push({ p: evalPrim(p, t), kind: "end" });
|
||||
break;
|
||||
case "spline":
|
||||
e.points.forEach((p) => out.push({ p, kind: "end" }));
|
||||
@@ -166,7 +170,7 @@ export function explodeJoined(
|
||||
}
|
||||
|
||||
/** Parameters where other entities cross primitive `p`. */
|
||||
function crossings(p: Prim, others: Prim[]): number[] {
|
||||
export function crossings(p: Prim, others: Prim[]): number[] {
|
||||
const ts: number[] = [];
|
||||
const n = Math.max(primSegments(p), 1) * 4;
|
||||
const A = Array.from({ length: n + 1 }, (_, i) => evalPrim(p, i / n));
|
||||
@@ -307,7 +311,7 @@ export function trim(entities: SketchEntity[], id: string, at: Vec2): SketchEnti
|
||||
}
|
||||
|
||||
/** Entity for part [t0, t1] of a primitive (t may exceed 1 for closed curves). */
|
||||
function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity {
|
||||
export function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity {
|
||||
const at = (t: number) => evalPrim(p, isClosedPrim(p) && p.t !== "spline" ? t : Math.min(1, t > 1 ? t - 1 : t));
|
||||
if (p.t === "line") return { id: uid(), kind: "line", a: at(t0), b: at(t1), construction };
|
||||
if (p.t === "circle") return { id: uid(), kind: "arc", a: at(t0), m: at((t0 + t1) / 2), b: at(t1), construction };
|
||||
@@ -380,7 +384,7 @@ export function splineEnds(e: SketchEntity): [Vec2, Vec2] | null {
|
||||
function reverseIf(e: SketchEntity, rev: boolean): SketchEntity {
|
||||
if (!rev) return e;
|
||||
if (e.kind === "line" || e.kind === "arc") return { ...e, a: e.b, b: e.a } as SketchEntity;
|
||||
if (e.kind === "spline") return { ...e, points: [...e.points].reverse() };
|
||||
if (e.kind === "spline") return { ...e, points: [...e.points].reverse(), ...(e.z ? { z: [...e.z].reverse() } : {}) };
|
||||
return e;
|
||||
}
|
||||
|
||||
@@ -450,6 +454,7 @@ function moveEnd(e: SketchEntity, end: "a" | "b", to: Vec2): SketchEntity {
|
||||
// The end fit point moves there.
|
||||
const pts = [...e.points];
|
||||
pts[end === "a" ? 0 : pts.length - 1] = to;
|
||||
// (Its heights stay with its points: the spread above keeps them.)
|
||||
return { ...e, points: pts };
|
||||
}
|
||||
if (e.kind !== "arc") return e;
|
||||
@@ -655,6 +660,10 @@ export function splitAny(entities: SketchEntity[], id: string, at: Vec2, step: n
|
||||
pts = e.points;
|
||||
closed = e.closed;
|
||||
mode = e.mode;
|
||||
} else if (e.sweep !== undefined) {
|
||||
// Part of an ellipse: an open spline through 13 of its points.
|
||||
pts = Array.from({ length: 13 }, (_, i) => evalPrim(prim, i / 12));
|
||||
closed = false;
|
||||
} else {
|
||||
pts = Array.from({ length: 12 }, (_, i) => evalPrim(prim, i / 12));
|
||||
closed = true;
|
||||
@@ -663,15 +672,21 @@ export function splitAny(entities: SketchEntity[], id: string, at: Vec2, step: n
|
||||
const T = closestOnPrim(prim, P).t;
|
||||
const spans = closed ? pts.length : pts.length - 1;
|
||||
const s = Math.max(0, Math.min(spans - 1, Math.floor(T * spans + 1e-9)));
|
||||
// A spline with points off the plane: each piece keeps its points' heights, and the new end is as high as the
|
||||
// curve is there. (The pieces came out flat on the plane.)
|
||||
const z = splineHeights(e);
|
||||
const high = z ? splineHeightSamples(e) : null;
|
||||
const zP = high ? (high[Math.max(0, Math.min(high.length - 1, Math.round(T * (high.length - 1))))] ?? 0) : 0;
|
||||
const up = (list: number[]) => (z ? { z: list } : {});
|
||||
if (closed) {
|
||||
// A closed loop opens up at that point (one piece, both ends there).
|
||||
const ring = [...pts.slice(s + 1), ...pts.slice(0, s + 1)];
|
||||
const open: SketchEntity = { id, kind: "spline", points: [P, ...ring, P], closed: false, mode, construction: e.construction };
|
||||
const open: SketchEntity = { id, kind: "spline", points: [P, ...ring, P], closed: false, mode, construction: e.construction, ...up(z ? [zP, ...z.slice(s + 1), ...z.slice(0, s + 1), zP] : []) };
|
||||
return { entities: entities.map((x) => (x.id === id ? open : x)), parts: [id], exploded: true };
|
||||
}
|
||||
const n = newId();
|
||||
const first: SketchEntity = { id, kind: "spline", points: [...pts.slice(0, s + 1), P], closed: false, mode, construction: e.construction };
|
||||
const second: SketchEntity = { id: n, kind: "spline", points: [P, ...pts.slice(s + 1)], closed: false, mode, construction: e.construction };
|
||||
const first: SketchEntity = { id, kind: "spline", points: [...pts.slice(0, s + 1), P], closed: false, mode, construction: e.construction, ...up(z ? [...z.slice(0, s + 1), zP] : []) };
|
||||
const second: SketchEntity = { id: n, kind: "spline", points: [P, ...pts.slice(s + 1)], closed: false, mode, construction: e.construction, ...up(z ? [zP, ...z.slice(s + 1)] : []) };
|
||||
return { entities: entities.flatMap((x) => (x.id === id ? [first, second] : [x])), parts: [id, n], exploded: false };
|
||||
}
|
||||
return null;
|
||||
@@ -1036,7 +1051,7 @@ export function offsetEntity(e: SketchEntity, d: number): SketchEntity | null {
|
||||
case "circle":
|
||||
return e.radius + d > 0 ? { ...base, kind: "circle", center: e.center, radius: e.radius + d } : null;
|
||||
case "ellipse":
|
||||
return e.rx + d > 0 && e.ry + d > 0 ? { ...base, kind: "ellipse", center: e.center, rx: e.rx + d, ry: e.ry + d, rotation: e.rotation } : null;
|
||||
return e.rx + d > 0 && e.ry + d > 0 ? { ...base, kind: "ellipse", center: e.center, rx: e.rx + d, ry: e.ry + d, rotation: e.rotation, ...(e.sweep === undefined ? {} : { a0: e.a0 ?? 0, sweep: e.sweep }) } : null;
|
||||
case "rect":
|
||||
return e.w + 2 * d > 0 && e.h + 2 * d > 0 ? { ...base, kind: "rect", center: e.center, w: e.w + 2 * d, h: e.h + 2 * d, rotation: e.rotation } : null;
|
||||
case "polygon": {
|
||||
@@ -1073,9 +1088,13 @@ export function offsetEntity(e: SketchEntity, d: number): SketchEntity | null {
|
||||
// Outward for CCW closed curves = to the right of travel.
|
||||
return [p[0] + (ty / L) * d * sign * (closed ? 1 : -1), p[1] - (tx / L) * d * sign * (closed ? 1 : -1)] as Vec2;
|
||||
});
|
||||
// Enough fit points to follow the curve closely (four per original span).
|
||||
const n = Math.max(24, (e.kind === "spline" ? e.points.length : 6) * 4 + 1);
|
||||
return e.kind === "spline" ? { ...base, kind: "spline", points: thin(closed ? out.slice(0, -1) : out, n), closed, mode: "fit" } : { ...base, kind: "polyline", points: out, closed };
|
||||
if (e.kind !== "spline") return { ...base, kind: "polyline", points: out, closed };
|
||||
// As few fit points as follow the curve closely (within a five-thousandth of its size): it was four per span of
|
||||
// the original, so the offset of a curve projected from an edge - 24 points, out of sight - came out a row of 97 dots.
|
||||
const xs = out.map((q) => q[0]);
|
||||
const ys = out.map((q) => q[1]);
|
||||
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
|
||||
return { ...base, kind: "spline", points: fitSpline(closed ? out.slice(0, -1) : out, closed, Math.max(size * 2e-4, 1e-9)), closed, mode: "fit" };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1228,7 +1247,18 @@ const unit = (a: Vec2): Vec2 => {
|
||||
* A 3D polyline (e.g. a body edge) flattened onto the sketch plane, as the
|
||||
* simplest matching entity: line, circle, arc or spline.
|
||||
*/
|
||||
export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string): SketchEntity | null {
|
||||
/**
|
||||
* (A curved edge that is no circle is a spline through 24 of its points: as
|
||||
* close to the edge as that gets. A curve that follows its edge keeps that -
|
||||
* only its two ends show (`pointsOf`). `lean`: a free copy, which is the
|
||||
* user's to shape - a whole ellipse as an ellipse, anything else with as few
|
||||
* points as hold it within a two-thousandth of its size, not a row of 24 dots
|
||||
* to drag one by one. And a round edge seen at a slant - part of a circle or
|
||||
* of an ellipse - is part of an ellipse, exactly, with its two ends: `conic`
|
||||
* false keeps the spline, for a curve of an older project made as one, which
|
||||
* may have sizes tied to its points.)
|
||||
*/
|
||||
export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string, lean = false, conic = true): SketchEntity | null {
|
||||
const pts = dedupe(pts3.map((p) => toPlane(plane, p)));
|
||||
if (pts.length < 2) return null;
|
||||
const a = pts[0];
|
||||
@@ -1245,8 +1275,207 @@ export function projectPolyline(pts3: Vec3[], plane: PlaneDef, type: string): Sk
|
||||
if (ok) return closed ? { id: uid(), kind: "circle", center: c.c, radius: c.r } : { id: uid(), kind: "arc", a, m, b };
|
||||
}
|
||||
}
|
||||
const fit = thin(closed ? pts.slice(0, -1) : pts, 24);
|
||||
return { id: uid(), kind: "spline", points: fit, closed, mode: "fit" };
|
||||
const run = closed ? pts.slice(0, -1) : pts;
|
||||
if (conic && !closed && (type === "CIRCLE" || type === "ELLIPSE") && run.length >= 7) {
|
||||
const xs = pts.map((p) => p[0]);
|
||||
const ys = pts.map((p) => p[1]);
|
||||
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
|
||||
const el = fitEllipse(run);
|
||||
// (Only when every point is on it: a short, nearly straight piece can be fitted by ellipses that are nothing like it.)
|
||||
if (el && run.every((p) => offEllipse(p, el) < size * 1e-6) && Math.max(el.rx, el.ry) < size * 50) {
|
||||
const at = (p: Vec2) => {
|
||||
const dx = p[0] - el.c[0];
|
||||
const dy = p[1] - el.c[1];
|
||||
return Math.atan2((-dx * Math.sin(el.rot) + dy * Math.cos(el.rot)) / el.ry, (dx * Math.cos(el.rot) + dy * Math.sin(el.rot)) / el.rx);
|
||||
};
|
||||
// Which way round it goes: the way that passes its middle point.
|
||||
const turn = (from: number, to: number) => ((((to - from) % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI));
|
||||
const a0 = at(a);
|
||||
const toMid = turn(a0, at(run[Math.floor(run.length / 2)]));
|
||||
const toEnd = turn(a0, at(b));
|
||||
const sweep = toMid <= toEnd ? toEnd : toEnd - 2 * Math.PI;
|
||||
if (Math.abs(sweep) > 1e-6) return { id: uid(), kind: "ellipse", center: el.c, rx: el.rx, ry: el.ry, rotation: el.rot, a0, sweep };
|
||||
}
|
||||
}
|
||||
if (lean) {
|
||||
const xs = pts.map((p) => p[0]);
|
||||
const ys = pts.map((p) => p[1]);
|
||||
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
|
||||
// A circle seen at a slant, an ellipse: the ellipse itself.
|
||||
if (closed && run.length >= 6) {
|
||||
const el = fitEllipse(run);
|
||||
if (el && run.every((p) => offEllipse(p, el) < size * 1e-5)) return { id: uid(), kind: "ellipse", center: el.c, rx: el.rx, ry: el.ry, rotation: el.rot };
|
||||
}
|
||||
// Within a two-thousandth of its size of the edge (0.025 on a curve 50 long).
|
||||
const tol = Math.max(size * 5e-4, 1e-9);
|
||||
const ctrl = closed ? null : fitControl(run, tol);
|
||||
if (ctrl) return { id: uid(), kind: "spline", points: ctrl, closed: false, mode: "control" };
|
||||
return { id: uid(), kind: "spline", points: fitSpline(run, closed, tol), closed, mode: "fit" };
|
||||
}
|
||||
return { id: uid(), kind: "spline", points: thin(run, 24), closed, mode: "fit" };
|
||||
}
|
||||
|
||||
/** A spline with only the points it needs (one that followed an edge and was unlinked: its 24 become the user's to shape). */
|
||||
export function leanSpline<E extends SketchEntity>(e: E): E {
|
||||
if (e.kind !== "spline" || e.mode !== "fit" || e.points.length < 7) return e;
|
||||
const xs = e.points.map((p) => p[0]);
|
||||
const ys = e.points.map((p) => p[1]);
|
||||
const size = Math.hypot(Math.max(...xs) - Math.min(...xs), Math.max(...ys) - Math.min(...ys));
|
||||
return { ...e, points: fitSpline(e.points, e.closed, Math.max(size * 5e-4, 1e-9)) };
|
||||
}
|
||||
|
||||
/** Solve m (n rows of n + 1: the last column the right side) in place; null when it has no one answer. */
|
||||
function solveRows(m: number[][]): number[] | null {
|
||||
const n = m.length;
|
||||
for (let i = 0; i < n; i++) {
|
||||
let best = i;
|
||||
for (let r = i + 1; r < n; r++) if (Math.abs(m[r][i]) > Math.abs(m[best][i])) best = r;
|
||||
if (Math.abs(m[best][i]) < 1e-12) return null;
|
||||
[m[i], m[best]] = [m[best], m[i]];
|
||||
for (let r = 0; r < n; r++) {
|
||||
if (r === i) continue;
|
||||
const f = m[r][i] / m[i][i];
|
||||
for (let j = i; j <= n; j++) m[r][j] -= f * m[i][j];
|
||||
}
|
||||
}
|
||||
return m.map((row, i) => row[n] / row[i]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The fewest control points of an open spline (the sketch's own kind: a
|
||||
* uniform cubic B-spline that starts and ends on its first and last point)
|
||||
* that keep it within `tol` of the points: its two ends where the curve's
|
||||
* are, the handles between fitted (least squares, each point's place along
|
||||
* the curve put right and fitted again). Null when even twelve don't hold it.
|
||||
*/
|
||||
function fitControl(run: Vec2[], tol: number): Vec2[] | null {
|
||||
const n = run.length;
|
||||
if (n < 4) return null;
|
||||
const A = run[0];
|
||||
const Z = run[n - 1];
|
||||
// Where each point is along the curve, 0 to 1, by the way gone.
|
||||
const way = [0];
|
||||
for (let i = 1; i < n; i++) way.push(way[i - 1] + Math.hypot(run[i][0] - run[i - 1][0], run[i][1] - run[i - 1][1]));
|
||||
if (!(way[n - 1] > 0)) return null;
|
||||
const start = way.map((w) => w / way[n - 1]);
|
||||
/** How much of each control point a place along the curve is made of (the mirrored ones past the ends folded in). */
|
||||
const weights = (m: number, at: number): number[] => {
|
||||
const spans = m - 1;
|
||||
const s = Math.min(spans - 1e-12, Math.max(0, at * spans));
|
||||
const k = Math.min(spans - 1, Math.floor(s));
|
||||
const u = s - k;
|
||||
const u2 = u * u;
|
||||
const u3 = u2 * u;
|
||||
const b = [(1 - 3 * u + 3 * u2 - u3) / 6, (4 - 6 * u2 + 3 * u3) / 6, (1 + 3 * u + 3 * u2 - 3 * u3) / 6, u3 / 6];
|
||||
const w = new Array<number>(m).fill(0);
|
||||
for (let j = 0; j < 4; j++) {
|
||||
const i = k - 1 + j;
|
||||
if (i < 0) (w[0] += 2 * b[j]), (w[1] -= b[j]);
|
||||
else if (i > m - 1) (w[m - 1] += 2 * b[j]), (w[m - 2] -= b[j]);
|
||||
else w[i] += b[j];
|
||||
}
|
||||
return w;
|
||||
};
|
||||
const at = (P: Vec2[], x: number): Vec2 => {
|
||||
const w = weights(P.length, x);
|
||||
return [w.reduce((s, c, i) => s + c * P[i][0], 0), w.reduce((s, c, i) => s + c * P[i][1], 0)];
|
||||
};
|
||||
for (let m = 3; m <= 12 && m < n; m++) {
|
||||
let ts = start.slice();
|
||||
let P: Vec2[] | null = null;
|
||||
for (let round = 0; round < 4; round++) {
|
||||
// The handles (all but the two ends), least squares.
|
||||
const q = m - 2;
|
||||
const mx = Array.from({ length: q }, () => new Array<number>(q + 1).fill(0));
|
||||
const my = Array.from({ length: q }, () => new Array<number>(q + 1).fill(0));
|
||||
for (let j = 0; j < n; j++) {
|
||||
const w = weights(m, ts[j]);
|
||||
const rx = run[j][0] - w[0] * A[0] - w[m - 1] * Z[0];
|
||||
const ry = run[j][1] - w[0] * A[1] - w[m - 1] * Z[1];
|
||||
for (let a = 0; a < q; a++) {
|
||||
for (let b = 0; b < q; b++) {
|
||||
mx[a][b] += w[a + 1] * w[b + 1];
|
||||
my[a][b] += w[a + 1] * w[b + 1];
|
||||
}
|
||||
mx[a][q] += w[a + 1] * rx;
|
||||
my[a][q] += w[a + 1] * ry;
|
||||
}
|
||||
}
|
||||
const xs = solveRows(mx);
|
||||
const ys = solveRows(my);
|
||||
if (!xs || !ys) break;
|
||||
P = [A, ...xs.map((x, i): Vec2 => [x, ys[i]]), Z];
|
||||
// Each point's place along this curve, put right: the nearest of a fine walk along it, near where it was.
|
||||
const fine = 24 * (m - 1);
|
||||
const walk = Array.from({ length: fine + 1 }, (_, i) => at(P!, i / fine));
|
||||
let worst = 0;
|
||||
const next = ts.slice();
|
||||
for (let j = 1; j < n - 1; j++) {
|
||||
const mid = Math.round(ts[j] * fine);
|
||||
let best = Infinity;
|
||||
let where = ts[j];
|
||||
for (let i = Math.max(1, mid - 24); i <= Math.min(fine, mid + 24); i++) {
|
||||
// (To the piece of the walk, not just its corners.)
|
||||
const a = walk[i - 1];
|
||||
const b = walk[i];
|
||||
const dx = b[0] - a[0];
|
||||
const dy = b[1] - a[1];
|
||||
const f = Math.max(0, Math.min(1, ((run[j][0] - a[0]) * dx + (run[j][1] - a[1]) * dy) / (dx * dx + dy * dy || 1)));
|
||||
const d = Math.hypot(run[j][0] - a[0] - f * dx, run[j][1] - a[1] - f * dy);
|
||||
if (d < best) (best = d), (where = (i - 1 + f) / fine);
|
||||
}
|
||||
next[j] = where;
|
||||
worst = Math.max(worst, best);
|
||||
}
|
||||
if (worst <= tol) return P;
|
||||
ts = next;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The ellipse through these points (a conic fitted to them, least squares), or null when they are not on one. */
|
||||
function fitEllipse(pts: Vec2[]): { c: Vec2; rx: number; ry: number; rot: number } | null {
|
||||
const n = pts.length;
|
||||
const mx = pts.reduce((s, p) => s + p[0], 0) / n;
|
||||
const my = pts.reduce((s, p) => s + p[1], 0) / n;
|
||||
const k = Math.max(...pts.map((p) => Math.hypot(p[0] - mx, p[1] - my))) || 1;
|
||||
// A x² + B xy + C y² + D x + E y = 1, about their middle and at their own size (so the numbers stay tame).
|
||||
const m = Array.from({ length: 5 }, () => new Array<number>(6).fill(0));
|
||||
for (const p of pts) {
|
||||
const x = (p[0] - mx) / k;
|
||||
const y = (p[1] - my) / k;
|
||||
const row = [x * x, x * y, y * y, x, y];
|
||||
for (let i = 0; i < 5; i++) {
|
||||
for (let j = 0; j < 5; j++) m[i][j] += row[i] * row[j];
|
||||
m[i][5] += row[i];
|
||||
}
|
||||
}
|
||||
const sol = solveRows(m);
|
||||
if (!sol) return null;
|
||||
const [A, B, C, D, E] = sol;
|
||||
const det = 4 * A * C - B * B;
|
||||
if (!(det > 1e-12)) return null;
|
||||
const cx = (B * E - 2 * C * D) / det;
|
||||
const cy = (B * D - 2 * A * E) / det;
|
||||
const f = A * cx * cx + B * cx * cy + C * cy * cy + D * cx + E * cy - 1;
|
||||
const rot = 0.5 * Math.atan2(B, A - C);
|
||||
const cos = Math.cos(rot);
|
||||
const sin = Math.sin(rot);
|
||||
const along = A * cos * cos + B * cos * sin + C * sin * sin;
|
||||
const across = A * sin * sin - B * cos * sin + C * cos * cos;
|
||||
if (!(-f / along > 0) || !(-f / across > 0)) return null;
|
||||
return { c: [mx + cx * k, my + cy * k], rx: Math.sqrt(-f / along) * k, ry: Math.sqrt(-f / across) * k, rot };
|
||||
}
|
||||
|
||||
/** About how far a point is from an ellipse (exact on it, near enough close by). */
|
||||
function offEllipse(p: Vec2, el: { c: Vec2; rx: number; ry: number; rot: number }): number {
|
||||
const dx = p[0] - el.c[0];
|
||||
const dy = p[1] - el.c[1];
|
||||
const x = dx * Math.cos(el.rot) + dy * Math.sin(el.rot);
|
||||
const y = -dx * Math.sin(el.rot) + dy * Math.cos(el.rot);
|
||||
const r = Math.hypot(x / el.rx, y / el.ry);
|
||||
return Math.abs(r - 1) * Math.min(el.rx, el.ry);
|
||||
}
|
||||
|
||||
function dedupe(pts: Vec2[]): Vec2[] {
|
||||
@@ -1457,6 +1686,9 @@ export function carryConstraints(before: SketchEntity[], after: SketchEntity[],
|
||||
};
|
||||
const out: SketchConstraint[] = [];
|
||||
for (const c of cs) {
|
||||
// A copy that follows its original (an offset, a mirror image), one of the two cut or reshaped here: it is its
|
||||
// own curve from now on - held to being the copy, a trimmed offset would be pulled back to its whole length.
|
||||
if (c.type === "follow" && (c.curves ?? []).some((id) => old.get(id) !== now.get(id))) continue;
|
||||
let ok = true;
|
||||
const pts = c.pts?.map((r) => {
|
||||
const was = old.get(r.e);
|
||||
@@ -1593,7 +1825,7 @@ export function outlineOffsetCurves(boundary: SketchEntity[], links: OutlineOffs
|
||||
}
|
||||
if (!seed) continue;
|
||||
let made: SketchEntity[] = [];
|
||||
if (seed.kind === "line" || seed.kind === "arc" || (seed.kind === "spline" && !seed.closed)) made = offsetChain(boundary, seed.id, o.distance)?.slice(boundary.length) ?? [];
|
||||
if (!o.single && (seed.kind === "line" || seed.kind === "arc" || (seed.kind === "spline" && !seed.closed))) made = offsetChain(boundary, seed.id, o.distance)?.slice(boundary.length) ?? [];
|
||||
else {
|
||||
const one = offsetEntity(seed, o.distance);
|
||||
if (one) made = [one];
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
// Fill Pattern: a closed shape of a sketch filled with a pattern of curves - lines from edge to edge (straight,
|
||||
// crossed, zigzag, waves) or small shapes inside it (dots, a honeycomb, squares, diamonds). The pattern's curves
|
||||
// are curves of the sketch like any other, so the strips and cells they make can be extruded or cut: a texture on
|
||||
// a model. (Asked for: "a new tool in sketch mode named fill pattern ... different line patterns that you can only
|
||||
// put in closed shapes that go from edges to edges ... very useful when I want different textures on my models.
|
||||
// Also I should be able to change the space between lines, or distance between shapes".)
|
||||
|
||||
import type { SketchEntity, SketchFill, Vec2 } from "../doc/types";
|
||||
import { arcFrom3, entityCorners, entityPrims, evalPrim, pointInPoly, type Prim } from "./curves";
|
||||
import { crossings, pieceEntity } from "./edit";
|
||||
import { arrangement, type Region } from "./regions";
|
||||
|
||||
/** The patterns, in the order they are offered. `lines`: whether it runs edge to edge (else: shapes inside). */
|
||||
export const FILL_KINDS: { id: SketchFill["kind"]; label: string; lines: boolean; sized: boolean }[] = [
|
||||
{ id: "lines", label: "Lines", lines: true, sized: false },
|
||||
{ id: "cross", label: "Crossed lines", lines: true, sized: false },
|
||||
{ id: "zigzag", label: "Zigzag", lines: true, sized: true },
|
||||
{ id: "waves", label: "Waves", lines: true, sized: true },
|
||||
{ id: "dots", label: "Dots", lines: false, sized: true },
|
||||
{ id: "hex", label: "Honeycomb", lines: false, sized: true },
|
||||
{ id: "squares", label: "Squares", lines: false, sized: true },
|
||||
{ id: "diamonds", label: "Diamonds", lines: false, sized: true },
|
||||
];
|
||||
|
||||
/** A fill's curves are named for it: "fp-<fill>-<n>". */
|
||||
export const FILL_PREFIX = "fp-";
|
||||
export const fillOf = (entityId: string): string | null => (entityId.startsWith(FILL_PREFIX) ? entityId.slice(FILL_PREFIX.length, entityId.lastIndexOf("-")) : null);
|
||||
/** The sketch's own curves: all but the ones fills made. */
|
||||
export const withoutFills = (entities: SketchEntity[]): SketchEntity[] => entities.filter((e) => !e.id.startsWith(FILL_PREFIX));
|
||||
|
||||
/** No more curves than this in one fill (a spacing typed a hundred times too small). */
|
||||
export const FILL_MOST = 2500;
|
||||
|
||||
const inRegion = (r: Region, q: Vec2): boolean => pointInPoly(q, r.outer.poly) && !r.holes.some((h) => pointInPoly(q, h.poly));
|
||||
|
||||
/** The closed shape a point is in (the smallest, where shapes are one in another): null on none. */
|
||||
export function fillRegion(entities: SketchEntity[], at: Vec2): Region | null {
|
||||
const regions = arrangement(withoutFills(entities)).regions.filter((r) => inRegion(r, at));
|
||||
return regions.sort((a, b) => a.area - b.area)[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The curves of one fill, for the sketch as it is (its own curves; other fills' are left out). Null: no closed
|
||||
* shape there. `tooMany`: the spacing gives more curves than a sketch should hold - none made.
|
||||
*/
|
||||
export function fillCurves(entities: SketchEntity[], fill: SketchFill): { curves: SketchEntity[]; tooMany?: boolean } | null {
|
||||
const own = withoutFills(entities);
|
||||
const region = fillRegion(own, fill.at);
|
||||
if (!region) return null;
|
||||
const around = new Set(region.curves);
|
||||
const edge: Prim[] = own.filter((e) => around.has(e.id) && !e.construction).flatMap(entityPrims);
|
||||
const kind = FILL_KINDS.find((k) => k.id === fill.kind) ?? FILL_KINDS[0];
|
||||
const out: SketchEntity[] = [];
|
||||
const name = () => `${FILL_PREFIX}${fill.id}-${out.length}`;
|
||||
const th = (fill.angle * Math.PI) / 180;
|
||||
const d: Vec2 = [Math.cos(th), Math.sin(th)];
|
||||
const n: Vec2 = [-d[1], d[0]];
|
||||
// The shape's reach along the pattern's own two ways, and its middle there.
|
||||
const along = region.outer.poly.map((p) => p[0] * d[0] + p[1] * d[1]);
|
||||
const across = region.outer.poly.map((p) => p[0] * n[0] + p[1] * n[1]);
|
||||
const [a0, a1, c0, c1] = [Math.min(...along), Math.max(...along), Math.min(...across), Math.max(...across)];
|
||||
const mid: Vec2 = [(a0 + a1) / 2, (c0 + c1) / 2];
|
||||
const at = (u: number, v: number): Vec2 => [d[0] * u + n[0] * v, d[1] * u + n[1] * v];
|
||||
const reach = Math.hypot(a1 - a0, c1 - c0);
|
||||
const step = Math.max(1e-6, Math.abs(fill.spacing));
|
||||
const size = Math.max(1e-6, Math.abs(fill.size));
|
||||
|
||||
/** The parts of a curve that are inside the shape, each from edge to edge. */
|
||||
const clipped = (p: Prim): boolean => {
|
||||
const ts = [0, ...crossings(p, edge), 1].filter((t, i, all) => i === 0 || t - all[i - 1] > 1e-7);
|
||||
for (let i = 0; i + 1 < ts.length; i++) {
|
||||
if (!inRegion(region, evalPrim(p, (ts[i] + ts[i + 1]) / 2))) continue;
|
||||
if (out.length >= FILL_MOST) return false;
|
||||
out.push({ ...pieceEntity(p, ts[i], ts[i + 1]), id: name() } as SketchEntity);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
if (kind.lines) {
|
||||
// Rows `step` apart, the middle one through the shape's middle; cross: the same again, square to them.
|
||||
for (const turn of fill.kind === "cross" ? [0, 1] : [0]) {
|
||||
const [u0, u1, v0, v1, um, vm] = turn ? [c0, c1, -a1, -a0, mid[1], -mid[0]] : [a0, a1, c0, c1, mid[0], mid[1]];
|
||||
const P = (u: number, v: number): Vec2 => (turn ? at(-v, u) : at(u, v));
|
||||
const pad = reach * 0.01 + 1e-3;
|
||||
const rows = Math.ceil((v1 - v0) / step / 2) + 1;
|
||||
if (rows * 2 > FILL_MOST) return { curves: [], tooMany: true };
|
||||
for (let k = -rows; k <= rows; k++) {
|
||||
const v = vm + k * step;
|
||||
// (Zigzag and waves swing `size` either side of their row.)
|
||||
const swing = fill.kind === "zigzag" || fill.kind === "waves" ? size / 2 : 0;
|
||||
if (v + swing <= v0 || v - swing >= v1) continue;
|
||||
if (fill.kind === "lines" || fill.kind === "cross") {
|
||||
if (!clipped({ t: "line", a: P(u0 - pad, v), b: P(u1 + pad, v), src: "" })) return { curves: [], tooMany: true };
|
||||
continue;
|
||||
}
|
||||
// A tooth or a wave every `size` along the row, up then down, starting a whole number of them from the middle.
|
||||
const first = um - Math.ceil((um - u0 + pad) / size) * size;
|
||||
const teeth = Math.ceil((u1 + pad - first) / size);
|
||||
if (teeth * rows > FILL_MOST * 4) return { curves: [], tooMany: true };
|
||||
for (let j = 0; j < teeth; j++) {
|
||||
const up = (Math.round((first - um) / size) + j) % 2 === 0 ? 1 : -1;
|
||||
const [x0, x1] = [first + j * size, first + (j + 1) * size];
|
||||
let prim: Prim;
|
||||
if (fill.kind === "zigzag") prim = { t: "line", a: P(x0, v - (up * size) / 2), b: P(x1, v + (up * size) / 2), src: "" };
|
||||
else {
|
||||
const arc = arcFrom3(P(x0, v), P((x0 + x1) / 2, v + up * size * 0.3), P(x1, v));
|
||||
if (!arc) continue;
|
||||
prim = { t: "circle", c: arc.c, r: arc.r, a0: arc.a0, sweep: arc.sweep, src: "" };
|
||||
}
|
||||
if (!clipped(prim)) return { curves: [], tooMany: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
return { curves: out };
|
||||
}
|
||||
|
||||
// Shapes: `size` across, `step` between one and the next, in rows - every other row half a step along for dots,
|
||||
// the honeycomb and diamonds. Only those wholly inside the shape.
|
||||
const pitch = size + step;
|
||||
const stagger = fill.kind !== "squares";
|
||||
const rowGap = fill.kind === "squares" ? pitch : fill.kind === "diamonds" ? pitch / 2 : (pitch * Math.sqrt(3)) / 2;
|
||||
const rows = Math.ceil((c1 - c0) / rowGap / 2) + 1;
|
||||
const cols = Math.ceil((a1 - a0) / pitch / 2) + 1;
|
||||
if ((2 * rows + 1) * (2 * cols + 1) > FILL_MOST * 6) return { curves: [], tooMany: true };
|
||||
for (let r = -rows; r <= rows; r++) {
|
||||
for (let c = -cols; c <= cols; c++) {
|
||||
const u = mid[0] + c * pitch + (stagger && r % 2 !== 0 ? pitch / 2 : 0);
|
||||
const v = mid[1] + r * rowGap;
|
||||
const centre = at(u, v);
|
||||
let e: SketchEntity;
|
||||
let rim: Vec2[];
|
||||
if (fill.kind === "dots") {
|
||||
e = { id: "", kind: "circle", center: centre, radius: size / 2 } as SketchEntity;
|
||||
rim = Array.from({ length: 16 }, (_, i) => [centre[0] + (size / 2) * Math.cos((i * Math.PI) / 8), centre[1] + (size / 2) * Math.sin((i * Math.PI) / 8)] as Vec2);
|
||||
} else {
|
||||
// (Honeycomb: `size` across its flats, a flat towards its neighbours in the row. Squares: `size` a side.
|
||||
// Diamonds: `size` from point to point.)
|
||||
const [sides, radius, turn] = fill.kind === "hex" ? [6, size / Math.sqrt(3), th] : fill.kind === "squares" ? [4, size / Math.SQRT2, th + Math.PI / 4] : [4, size / 2, th];
|
||||
const poly = { id: "", kind: "polygon" as const, center: centre, radius, sides, angle: turn };
|
||||
e = poly as SketchEntity;
|
||||
const corners = entityCorners(poly as Extract<SketchEntity, { kind: "polygon" }>);
|
||||
rim = corners.flatMap((p, i) => {
|
||||
const q = corners[(i + 1) % corners.length];
|
||||
return [p, [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2] as Vec2];
|
||||
});
|
||||
}
|
||||
if (!rim.every((p) => inRegion(region, p))) continue;
|
||||
// (All its points inside, and its outline crossing nothing: not across a thin neck of the shape.)
|
||||
if (entityPrims(e).some((p) => crossings(p, edge).length)) continue;
|
||||
if (out.length >= FILL_MOST) return { curves: [], tooMany: true };
|
||||
out.push({ ...e, id: name() });
|
||||
}
|
||||
}
|
||||
return { curves: out };
|
||||
}
|
||||
|
||||
/**
|
||||
* The sketch's curves with every fill's made again for the shapes as they are now (a shape changed size: its
|
||||
* pattern follows). A fill whose shape is gone keeps the curves it had; curves of a fill that is no more go.
|
||||
*/
|
||||
export function refill(entities: SketchEntity[], fills: SketchFill[] | undefined): SketchEntity[] {
|
||||
const own = withoutFills(entities);
|
||||
if (!fills?.length) return own.length === entities.length ? entities : own;
|
||||
const made: SketchEntity[] = [];
|
||||
for (const f of fills) {
|
||||
const got = fillCurves(own, f);
|
||||
if (got && !got.tooMany) made.push(...got.curves);
|
||||
else made.push(...entities.filter((e) => fillOf(e.id) === f.id));
|
||||
}
|
||||
return [...own, ...made];
|
||||
}
|
||||
@@ -305,9 +305,6 @@ export function simplifyStroke(raw: Vec2[], tol: number, closeTol = tol * 6): Fr
|
||||
return { pieces, closed: closed && pieces.length > 0 };
|
||||
}
|
||||
|
||||
export function startOf(e: FreehandPiece): Vec2 {
|
||||
return e.kind === "spline" ? e.points[0] : e.kind === "circle" ? e.center : e.a;
|
||||
}
|
||||
export function endOf(e: FreehandPiece): Vec2 {
|
||||
return e.kind === "spline" ? e.points[e.points.length - 1] : e.kind === "circle" ? e.center : e.b;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// A sketch pattern whose count is a variable (or a formula): kept with the sketch, so its copies are made again
|
||||
// when the count comes to another number - six holes round a circle become eight when "n" does. (A sketch pattern
|
||||
// was its copies and nothing more: the count could be typed once, and never follow anything.)
|
||||
//
|
||||
// The copies are curves of the sketch, each tied to its original by the same "pattern" link a plain pattern's
|
||||
// copies have - named for their pattern, "rp-<pattern>-<copy>-<curve>", their links "rpc-...".
|
||||
|
||||
import type { SketchConstraint, SketchEntity, SketchRepeat } from "../doc/types";
|
||||
import { rotateXf, transformEntity, translateXf } from "./edit";
|
||||
|
||||
export const REPEAT_PREFIX = "rp-";
|
||||
const LINK_PREFIX = "rpc-";
|
||||
/** No more copies than this from one pattern (a count that came to thousands by a slip). */
|
||||
export const REPEAT_MOST = 500;
|
||||
|
||||
const mine = (id: string, r: SketchRepeat) => id.startsWith(`${REPEAT_PREFIX}${r.id}-`) || id.startsWith(`${LINK_PREFIX}${r.id}-`);
|
||||
|
||||
/** How many times the pattern's curves are there now, the originals counted (1: no copies). */
|
||||
export function repeatCountNow(entities: SketchEntity[], r: SketchRepeat): number {
|
||||
const copies = new Set(entities.filter((e) => mine(e.id, r)).map((e) => e.id.slice(`${REPEAT_PREFIX}${r.id}-`.length).split("-")[0]));
|
||||
return copies.size + 1;
|
||||
}
|
||||
|
||||
/** The pattern's copies and their links, for its originals as they are now. */
|
||||
export function repeatCurves(entities: SketchEntity[], r: SketchRepeat): { curves: SketchEntity[]; links: SketchConstraint[] } {
|
||||
const src = r.src.map((id) => entities.find((e) => e.id === id)).filter((e): e is SketchEntity => !!e);
|
||||
const n = Math.max(1, Math.min(REPEAT_MOST, Math.round(r.count)));
|
||||
const curves: SketchEntity[] = [];
|
||||
const links: SketchConstraint[] = [];
|
||||
const full = Math.abs(Math.abs(r.angle ?? 0) - 360) < 1e-6;
|
||||
const turn = (r.angle ?? 0) / (full ? n : Math.max(1, n - 1));
|
||||
for (let k = 1; k < n; k++) {
|
||||
src.forEach((e, i) => {
|
||||
const id = `${REPEAT_PREFIX}${r.id}-${k}-${i}`;
|
||||
const xf = r.kind === "linear" ? translateXf(r.step![0] * k, r.step![1] * k) : rotateXf(r.at!, (turn * k * Math.PI) / 180);
|
||||
curves.push({ ...transformEntity(e, xf, true), id });
|
||||
const base = { id: `${LINK_PREFIX}${r.id}-${k}-${i}`, type: "pattern" as const, curves: [e.id, id] };
|
||||
links.push(r.kind === "linear" ? { ...base, at: [r.step![0] * k, r.step![1] * k] } : { ...base, turn: true, at: r.at!, value: turn * k });
|
||||
});
|
||||
}
|
||||
return { curves, links };
|
||||
}
|
||||
|
||||
/**
|
||||
* The sketch's curves and constraints with each pattern's copies as many as its count says. A pattern whose copies
|
||||
* are that many already is left as it is (its copies follow their originals by their links); one whose originals
|
||||
* are all gone goes, its copies staying as plain curves. Null: nothing to change.
|
||||
*/
|
||||
export function applyRepeats(entities: SketchEntity[], constraints: SketchConstraint[], repeats: SketchRepeat[] | undefined, force = false): { entities: SketchEntity[]; constraints: SketchConstraint[] } | null {
|
||||
if (!repeats?.length) return null;
|
||||
let changed = false;
|
||||
for (const r of repeats) {
|
||||
const want = Math.max(1, Math.min(REPEAT_MOST, Math.round(r.count)));
|
||||
if (!force && repeatCountNow(entities, r) === want) continue;
|
||||
if (!r.src.some((id) => entities.some((e) => e.id === id))) continue;
|
||||
const base = entities.filter((e) => !mine(e.id, r));
|
||||
const made = repeatCurves(base, r);
|
||||
entities = [...base, ...made.curves];
|
||||
const gone = (c: SketchConstraint) => mine(c.id, r) || [...(c.curves ?? []), ...(c.pts ?? []).map((q) => q.e)].some((id) => mine(id, r) && !made.curves.some((e) => e.id === id));
|
||||
constraints = [...constraints.filter((c) => !gone(c)), ...made.links];
|
||||
changed = true;
|
||||
}
|
||||
return changed ? { entities, constraints } : null;
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { BufferGeometry, ConeGeometry, Group, Line, LineBasicMaterial, LineDashe
|
||||
import { mergingCommits } from "../doc/store";
|
||||
import type { PinDef, Vec3 } from "../doc/types";
|
||||
import { el } from "../ui/ui";
|
||||
import { numpadInput, openNumpad } from "../ui/numpad";
|
||||
import { numpadInput, openNumpad, typingInto } from "../ui/numpad";
|
||||
import { settings } from "../settings";
|
||||
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
|
||||
import type { Viewport } from "../view/viewport";
|
||||
@@ -103,6 +103,13 @@ export interface DimWidgetOptions {
|
||||
angle?: boolean;
|
||||
/** No dimension line (just the box, e.g. at the corner between two lines). */
|
||||
noLine?: boolean;
|
||||
/**
|
||||
* The face the value belongs to, by its outward normal: seen from behind,
|
||||
* the box steps aside (the value is in the tool's card then). It sat over
|
||||
* whatever is in front of that face: a funnel's spout end, tapped from
|
||||
* below to open it too, went to Shell's thickness box on the top face.
|
||||
*/
|
||||
facing?: Vec3;
|
||||
/** Variables to choose from (a ƒx menu before the pin): the value becomes that variable. */
|
||||
variables?: string[];
|
||||
onVariable?(name: string): void;
|
||||
@@ -121,6 +128,7 @@ export class DimWidget {
|
||||
private boxAt: "middle" | "side" | "beyond" | "clear";
|
||||
private boxGap: number;
|
||||
private dir?: Vec3;
|
||||
private facing?: Vec3;
|
||||
private hook = () => this.layout();
|
||||
|
||||
constructor(
|
||||
@@ -131,6 +139,7 @@ export class DimWidget {
|
||||
this.boxAt = opts.boxAt ?? "middle";
|
||||
this.boxGap = opts.boxGap ?? 0;
|
||||
this.dir = opts.dir;
|
||||
this.facing = opts.facing;
|
||||
view.overlay.add(this.line.group);
|
||||
if (opts.modes) {
|
||||
const sel = document.createElement("select");
|
||||
@@ -235,7 +244,7 @@ export class DimWidget {
|
||||
}
|
||||
|
||||
setValue(v: number): void {
|
||||
if (document.activeElement !== this.input) this.input.value = this.show(v);
|
||||
if (!typingInto(this.input)) this.input.value = this.show(v);
|
||||
this.box.classList.remove("typing", "invalid");
|
||||
}
|
||||
|
||||
@@ -292,6 +301,16 @@ export class DimWidget {
|
||||
s = [s[0] + n[0] * k, s[1] + n[1] * k];
|
||||
}
|
||||
}
|
||||
// Its face turned away (seen from behind): out of the way - and out of
|
||||
// the numpad's hands (on a phone it has it from the start), the value
|
||||
// then typed in the tool's card.
|
||||
if (s && this.facing) {
|
||||
const v = this.view.cam.viewDir();
|
||||
if (v.x * this.facing[0] + v.y * this.facing[1] + v.z * this.facing[2] > 0.05) {
|
||||
s = null;
|
||||
if (this.input === document.activeElement) this.input.blur();
|
||||
}
|
||||
}
|
||||
this.box.hidden = !s;
|
||||
// The dimension on screen (the tool's options card keeps off it).
|
||||
if (sa && sb) this.box.dataset.seg = `${Math.round(sa[0])},${Math.round(sa[1])},${Math.round(sb[0])},${Math.round(sb[1])}`;
|
||||
@@ -320,8 +339,8 @@ export class DimWidget {
|
||||
|
||||
/** A screen point moved (if needed) so a box of these half sizes is on screen and off the open side panels. */
|
||||
/** The side panels' and the tool card's places, measured at most every 120 ms (not per box per frame). */
|
||||
let freeCache: { t: number; sides: DOMRect[]; panel: DOMRect | null } | null = null;
|
||||
function freeAreas(): { sides: DOMRect[]; panel: DOMRect | null } {
|
||||
let freeCache: { t: number; sides: DOMRect[]; panel: DOMRect | null; low: DOMRect[] } | null = null;
|
||||
function freeAreas(): { sides: DOMRect[]; panel: DOMRect | null; low: DOMRect[] } {
|
||||
const now = performance.now();
|
||||
if (freeCache && now - freeCache.t < 120) return freeCache;
|
||||
const sides: DOMRect[] = [];
|
||||
@@ -331,11 +350,20 @@ function freeAreas(): { sides: DOMRect[]; panel: DOMRect | null } {
|
||||
}
|
||||
const p = document.getElementById("panel");
|
||||
const panel = document.documentElement.dataset.screen === "phone" && p && !p.hidden && p.offsetHeight ? p.getBoundingClientRect() : null;
|
||||
freeCache = { t: now, sides, panel };
|
||||
// What sits along the bottom - the line with its tools, and on a phone undo and the guide text over it: a value
|
||||
// box stays above them (pulled down into a cut on a phone, the box sat on the guide text).
|
||||
const low: DOMRect[] = [];
|
||||
for (const id of ["sentence", "undo-dock", "hint"]) {
|
||||
const e = document.getElementById(id);
|
||||
const r = e && !e.hidden && e.offsetHeight && getComputedStyle(e).visibility !== "hidden" ? e.getBoundingClientRect() : null;
|
||||
if (r && r.top > window.innerHeight * 0.5) low.push(r);
|
||||
}
|
||||
low.sort((a, b) => b.top - a.top);
|
||||
freeCache = { t: now, sides, panel, low };
|
||||
return freeCache;
|
||||
}
|
||||
|
||||
function clampToFree(s: [number, number], hw: number, hh: number): [number, number] {
|
||||
export function clampToFree(s: [number, number], hw: number, hh: number): [number, number] {
|
||||
let left = 8;
|
||||
let right = window.innerWidth - 8;
|
||||
const free = freeAreas();
|
||||
@@ -352,6 +380,7 @@ function clampToFree(s: [number, number], hw: number, hh: number): [number, numb
|
||||
const r = free.panel;
|
||||
if (x + hw > r.left - 6 && x - hw < r.right + 6 && y + hh > r.top - 6) y = Math.max(52 + hh, r.top - 8 - hh);
|
||||
}
|
||||
for (const r of free.low) if (x + hw > r.left - 6 && x - hw < r.right + 6 && y + hh > r.top - 6 && y - hh < r.bottom + 6) y = Math.max(52 + hh, r.top - 8 - hh);
|
||||
return [x, y];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
// More ways to make a construction axis, each from what it says:
|
||||
// Point to Point – through two points of the model.
|
||||
// Intersection of 2 Planes – where two planes or flat faces cross.
|
||||
// (Square to a face, along an edge and the middle of a cylinder or cone are
|
||||
// one tap each: started from the wheel with the pick, see app.ts.)
|
||||
// The axis is worked out from the picks and kept, like the planes.
|
||||
|
||||
import type { AxisFeature, AxisKind, PlaneDef, Vec3 } from "../doc/types";
|
||||
import { add, cross, dot, len, norm, scale, sub } from "../geom";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
import { FeatureOp } from "./featureOp";
|
||||
import { roundAxis } from "./select";
|
||||
import { planeSlot, pointSlot } from "./slots";
|
||||
import type { AppContext } from "./tool";
|
||||
|
||||
abstract class AxisFromPicks extends FeatureOp<AxisFeature> {
|
||||
readonly id = "axis";
|
||||
constructor(app: AppContext, label: string, kind: AxisKind) {
|
||||
super(app, { ...app.store.newIdentity("axis", label), type: "axis", origin: [0, 0, 0], dir: [0, 0, 1], kind });
|
||||
}
|
||||
/** The axis the picks make (null: not yet / they don't make one). */
|
||||
protected abstract make(): { origin: Vec3; dir: Vec3 } | null;
|
||||
protected sync(): void {
|
||||
const a = this.make();
|
||||
if (a) (this.feature.origin = a.origin), (this.feature.dir = a.dir);
|
||||
}
|
||||
protected ready(): boolean {
|
||||
return super.ready() && !!this.make();
|
||||
}
|
||||
protected items(): PanelItem[] {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export class TwoPointAxisOp extends AxisFromPicks {
|
||||
private pts: (Vec3 | null)[] = [null, null];
|
||||
constructor(app: AppContext) {
|
||||
super(app, "Axis Point to Point", "2pt");
|
||||
this.slots = ["First point", "Second point"].map((l, i) => pointSlot(app, l, () => this.pts[i], (p) => ((this.pts[i] = p), this.sync())));
|
||||
this.finishWhenPicked = true;
|
||||
}
|
||||
protected make(): { origin: Vec3; dir: Vec3 } | null {
|
||||
const [a, b] = this.pts;
|
||||
if (!a || !b || len(sub(b, a)) < 1e-9) return null;
|
||||
return { origin: a, dir: norm(sub(b, a)) };
|
||||
}
|
||||
protected hint(): string {
|
||||
const [a, b] = this.pts;
|
||||
return a && b && !this.make() ? "⚠ The two points are the same - pick another" : "Tap two points (corners, points on edges or in sketches): the axis goes through both.";
|
||||
}
|
||||
}
|
||||
|
||||
export class PlanesAxisOp extends AxisFromPicks {
|
||||
private a: PlaneDef | null = null;
|
||||
private b: PlaneDef | null = null;
|
||||
constructor(app: AppContext) {
|
||||
super(app, "Axis 2 Planes", "planes");
|
||||
this.slots = [
|
||||
planeSlot(app, "First plane", () => this.a, (p) => ((this.a = p), this.sync())),
|
||||
planeSlot(app, "Second plane", () => this.b, (p) => ((this.b = p), this.sync())),
|
||||
];
|
||||
this.finishWhenPicked = true;
|
||||
}
|
||||
protected make(): { origin: Vec3; dir: Vec3 } | null {
|
||||
return this.a && this.b ? planesMeet(this.a, this.b) : null;
|
||||
}
|
||||
protected hint(): string {
|
||||
return this.a && this.b && !this.make() ? "⚠ The two planes are parallel - they never cross. Pick another" : "Tap two planes or flat faces: the axis goes where they cross.";
|
||||
}
|
||||
}
|
||||
|
||||
/** Where two planes cross: the line, through the point of it nearest the middle of their origins. */
|
||||
export function planesMeet(a: PlaneDef, b: PlaneDef): { origin: Vec3; dir: Vec3 } | null {
|
||||
const n1 = norm(a.normal);
|
||||
const n2 = norm(b.normal);
|
||||
const d = cross(n1, n2);
|
||||
if (len(d) < 1e-6) return null;
|
||||
const dir = norm(d);
|
||||
// A point on both: x = q + s n1 + t n2, with n1·x = n1·a.origin and n2·x = n2·b.origin, q the middle.
|
||||
const q = scale(add(a.origin, b.origin), 0.5);
|
||||
const r1 = dot(n1, sub(a.origin, q));
|
||||
const r2 = dot(n2, sub(b.origin, q));
|
||||
const c = dot(n1, n2);
|
||||
const det = 1 - c * c;
|
||||
const s = (r1 - c * r2) / det;
|
||||
const t = (r2 - c * r1) / det;
|
||||
return { origin: add(q, add(scale(n1, s), scale(n2, t))), dir };
|
||||
}
|
||||
|
||||
/**
|
||||
* The middle line of a round face - a cylinder (or a hole), a cone (a
|
||||
* countersink, a taper) - from its mesh: every normal on it is at the same
|
||||
* angle to the axis, and every normal line goes through the axis.
|
||||
*/
|
||||
export function surfaceAxis(app: AppContext, body: string, face: number): { origin: Vec3; dir: Vec3 } | null {
|
||||
const round = roundAxis(app, body, face);
|
||||
if (round) return round;
|
||||
const b = app.view.body(body);
|
||||
const info = b?.faces[face];
|
||||
const g = b?.faceGroups.find((x) => x.face === face);
|
||||
if (!b || !info || !g || g.count < 3 || !["CONE", "CYLINDRE", "REVOLUTION_SURFACE", "TORUS", "SPHERE"].includes(info.type)) return null;
|
||||
const at = (A: ArrayLike<number>, i: number): Vec3 => [A[3 * i], A[3 * i + 1], A[3 * i + 2]];
|
||||
const idx = [...new Set(Array.from(b.indices.subarray(g.start, g.start + g.count)))];
|
||||
const ns = idx.map((i) => norm(at(b.normals, i)));
|
||||
const ps = idx.map((i) => at(b.positions, i));
|
||||
// The axis: the way the normals don't spread (their spread's least direction).
|
||||
const m = scale(ns.reduce(add, [0, 0, 0] as Vec3), 1 / ns.length);
|
||||
const C = [0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
for (const n of ns) {
|
||||
const v = sub(n, m);
|
||||
for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) C[r * 3 + c] += v[r] * v[c];
|
||||
}
|
||||
const tr = C[0] + C[4] + C[8];
|
||||
if (tr < 1e-6 * ns.length) return null; // all the normals one way: a sliver, nothing to go by
|
||||
// Power steps on (tr·I − C): its biggest is C's least.
|
||||
let d: Vec3 = norm(cross(ns[0], ns[ns.length >> 1]));
|
||||
if (len(d) < 0.5) d = [0.577, 0.577, 0.577];
|
||||
for (let k = 0; k < 60; k++) {
|
||||
const nd: Vec3 = [0, 1, 2].map((r) => tr * d[r] - (C[r * 3] * d[0] + C[r * 3 + 1] * d[1] + C[r * 3 + 2] * d[2])) as Vec3;
|
||||
if (len(nd) < 1e-12) return null;
|
||||
d = norm(nd);
|
||||
}
|
||||
// The point on the axis: nearest every normal line, across the axis.
|
||||
const A = [0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||||
const rhs: Vec3 = [0, 0, 0];
|
||||
for (let i = 0; i < ns.length; i++) {
|
||||
const u0 = sub(ns[i], scale(d, dot(ns[i], d)));
|
||||
if (len(u0) < 1e-6) continue;
|
||||
const u = norm(u0);
|
||||
for (let r = 0; r < 3; r++)
|
||||
for (let c = 0; c < 3; c++) {
|
||||
const M = (r === c ? 1 : 0) - u[r] * u[c] - d[r] * d[c];
|
||||
A[r * 3 + c] += M;
|
||||
rhs[r] += M * ps[i][c];
|
||||
}
|
||||
}
|
||||
// (Along the axis it is free: held at the face's middle.)
|
||||
for (let r = 0; r < 3; r++) for (let c = 0; c < 3; c++) A[r * 3 + c] += d[r] * d[c] * ns.length;
|
||||
for (let r = 0; r < 3; r++) rhs[r] += d[r] * dot(d, info.center) * ns.length;
|
||||
const o = solve3(A, rhs);
|
||||
return o && { origin: o, dir: d };
|
||||
}
|
||||
|
||||
function solve3(A: number[], b: Vec3): Vec3 | null {
|
||||
const det = (m: number[]) => m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
|
||||
const D = det(A);
|
||||
if (Math.abs(D) < 1e-12) return null;
|
||||
const col = (k: number) => A.map((v, i) => (i % 3 === k ? b[Math.floor(i / 3)] : v));
|
||||
return [det(col(0)) / D, det(col(1)) / D, det(col(2)) / D];
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
// change it with (−), picked in turn; keep either side if wanted.
|
||||
|
||||
import type { BooleanFeature, Vec3 } from "../doc/types";
|
||||
import { add, scale } from "../geom";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
import { DimWidget } from "./annotate";
|
||||
import { FeatureOp, type Slot } from "./featureOp";
|
||||
import { bodyCenter } from "./ops";
|
||||
import type { AppContext } from "./tool";
|
||||
@@ -60,8 +62,13 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
|
||||
this.slots = [targetSlot, toolsSlot];
|
||||
}
|
||||
|
||||
/** Names seen (while its preview is being made, a body can be missing from the list). */
|
||||
private names = new Map<string, string>();
|
||||
|
||||
private nameOf(id: string): string {
|
||||
return this.app.store.doc.names?.[id] ?? this.app.view.bodyList.find((b) => b.id === id)?.name ?? "Body";
|
||||
const name = this.app.store.doc.names?.[id] ?? this.app.view.bodyList.find((b) => b.id === id)?.name ?? this.names.get(id);
|
||||
if (name) this.names.set(id, name);
|
||||
return name ?? "Body";
|
||||
}
|
||||
|
||||
protected hint(): string {
|
||||
@@ -70,10 +77,43 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
|
||||
: "Tap a body, then the bodies it overlaps. Only the part they share is kept.";
|
||||
}
|
||||
|
||||
/** Which bodies give way to the clearance, named after the bodies picked. */
|
||||
private sides(): { id: string; label: string }[] {
|
||||
const t = this.feature.tools;
|
||||
return [
|
||||
{ id: "body", label: this.feature.target ? this.nameOf(this.feature.target) : "Body" },
|
||||
{ id: "tools", label: t.length === 1 ? this.nameOf(t[0]) : "The others" },
|
||||
{ id: "all", label: t.length > 1 ? "All" : "Both" },
|
||||
];
|
||||
}
|
||||
|
||||
private setSide(id: string): void {
|
||||
this.feature.cutFrom = id === "body" ? undefined : (id as "tools" | "all");
|
||||
this.render();
|
||||
this.update();
|
||||
}
|
||||
|
||||
private setClearance(v: number): void {
|
||||
if (!(v >= 0)) return;
|
||||
this.feature.clearance = v || undefined;
|
||||
this.app.ui.updatePanelValues([v]);
|
||||
this.dim?.setValue(v);
|
||||
this.update();
|
||||
}
|
||||
|
||||
protected items(): PanelItem[] {
|
||||
const f = this.feature;
|
||||
const sub = f.op === "subtract";
|
||||
const gap: PanelItem[] = sub
|
||||
? [
|
||||
{ ...this.num("Clearance", "clearance", "length", { min: 0, onInput: (v) => this.setClearance(v), inBox: true }), value: f.clearance ?? 0 } as PanelItem,
|
||||
{ type: "choice", label: "Cut from", options: this.sides(), value: f.cutFrom ?? "body", onChange: (id) => this.setSide(id) },
|
||||
]
|
||||
: [];
|
||||
// The others give way (or all do): every body stays, changed.
|
||||
if (sub && f.cutFrom) return gap;
|
||||
return [
|
||||
...gap,
|
||||
{ type: "toggle", label: "Keep modified body", value: !!f.keepTarget, onChange: (v) => ((f.keepTarget = v || undefined), this.render(), this.update()) },
|
||||
{ type: "toggle", label: sub ? "Keep subtracted bodies" : "Keep intersecting bodies", value: !!f.keepTools, onChange: (v) => ((f.keepTools = v || undefined), this.render(), this.update()) },
|
||||
];
|
||||
@@ -86,39 +126,135 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
|
||||
}
|
||||
|
||||
exit(): void {
|
||||
this.dim?.dispose();
|
||||
this.dim = null;
|
||||
this.app.view.frameHooks.delete(this.hook);
|
||||
for (const m of this.marks) m.remove();
|
||||
this.marks = [];
|
||||
super.exit();
|
||||
}
|
||||
|
||||
/** The clearance, typed between the body and the first body it's subtracted with. */
|
||||
private dim: DimWidget | null = null;
|
||||
/** The names in its drop-down (made again when the bodies picked change). */
|
||||
private dimSides = "";
|
||||
|
||||
protected onDraftChanged(): void {
|
||||
this.placeMarks();
|
||||
const f = this.feature;
|
||||
const a = this.centers.get(f.target), b = f.tools[0] ? this.centers.get(f.tools[0]) : undefined;
|
||||
const sides = this.sides();
|
||||
const key = JSON.stringify(sides);
|
||||
if (f.op !== "subtract" || !a || !b || key !== this.dimSides) {
|
||||
this.dim?.dispose();
|
||||
this.dim = null;
|
||||
}
|
||||
if (f.op !== "subtract" || !a || !b) return;
|
||||
this.dimSides = key;
|
||||
this.dim ??= new DimWidget(this.app.view, {
|
||||
noLine: true,
|
||||
value: f.clearance ?? 0,
|
||||
modes: sides,
|
||||
mode: f.cutFrom ?? "body",
|
||||
onMode: (id) => this.setSide(id),
|
||||
onInput: (v, text) => {
|
||||
if (!(v >= 0)) return;
|
||||
this.typedInto("clearance", text);
|
||||
this.setClearance(v);
|
||||
},
|
||||
onCommit: () => this.done(),
|
||||
});
|
||||
const [p, q] = this.boxAt(scale(add(a, b), 0.5));
|
||||
this.boxPoint = p;
|
||||
this.dim.set(p, q);
|
||||
this.dim.setMode(f.cutFrom ?? "body");
|
||||
this.dim.setValue(f.clearance ?? 0);
|
||||
// (The signs again, clear of the box just made.)
|
||||
this.placeMarks();
|
||||
}
|
||||
|
||||
/**
|
||||
* The sign on `body` turned the other way: a "−" body becomes the one
|
||||
* changed, the one that was takes its place among the others; the "+" body
|
||||
* swaps with the first of the others.
|
||||
*/
|
||||
private swap(body: string): void {
|
||||
const f = this.feature;
|
||||
if (!f.target || !f.tools.length) return;
|
||||
const other = body === f.target ? f.tools[0] : body;
|
||||
if (!f.tools.includes(other)) return;
|
||||
f.tools = f.tools.map((t) => (t === other ? f.target : t));
|
||||
f.target = other;
|
||||
f.whole = undefined;
|
||||
this.render();
|
||||
this.update();
|
||||
this.placeMarks();
|
||||
}
|
||||
|
||||
/** "+" on the body that's changed, "−" on each body it's changed with. */
|
||||
/**
|
||||
* Where the clearance box goes: between the two bodies, or - when that's
|
||||
* over a body (a tray's middle, its pockets still to be tapped) - further
|
||||
* down the screen, clear of them. (It sat on the pockets; its number pad,
|
||||
* opened by a tap meant for one, covered half the tray.)
|
||||
*/
|
||||
private boxPoint: Vec3 | null = null;
|
||||
|
||||
private boxAt(mid: Vec3): [Vec3, Vec3] {
|
||||
const view = this.app.view;
|
||||
const s = view.toScreen(mid);
|
||||
if (!s) return [mid, mid];
|
||||
const over = (y: number) => [-90, 0, 90].some((dx) => view.pick(s[0] + dx, y, { edgeTolPx: 24, planes: false }));
|
||||
if (!over(s[1])) return [mid, mid];
|
||||
let y = s[1];
|
||||
while (y < view.height - 160 && over(y)) y += 20;
|
||||
if (over(y)) return [mid, mid];
|
||||
const w = view.worldUnder(s[0], y).toArray() as Vec3;
|
||||
return [w, w];
|
||||
}
|
||||
|
||||
private placeMarks(): void {
|
||||
const want: [string, string][] = [];
|
||||
if (this.feature.target) want.push([this.feature.target, "+"]);
|
||||
for (const t of this.feature.tools) want.push([t, "−"]);
|
||||
// Many taken away (eight pockets out of a tray): only the first keeps its
|
||||
// sign - the rest, pushed aside to clear each other, landed on bodies still
|
||||
// to be tapped, and a tap meant for a pocket swapped the tray out instead.
|
||||
for (const t of this.feature.tools.length > 2 ? this.feature.tools.slice(0, 1) : this.feature.tools) want.push([t, "−"]);
|
||||
while (this.marks.length > want.length) this.marks.pop()!.remove();
|
||||
while (this.marks.length < want.length) {
|
||||
const m = document.createElement("div");
|
||||
m.className = "bool-mark";
|
||||
// A tap on a sign turns it the other way round: picked in the wrong order, fixed in one tap.
|
||||
m.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
m.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
if (m.dataset.body) this.swap(m.dataset.body);
|
||||
});
|
||||
document.body.append(m);
|
||||
this.marks.push(m);
|
||||
}
|
||||
const r = this.app.view.canvas.getBoundingClientRect();
|
||||
// (Bodies sharing a middle - a peg through a plate - get their signs side by side, each one tappable.)
|
||||
const placed: [number, number][] = [];
|
||||
// (And clear of the clearance's box, which sits between the first two bodies.)
|
||||
const a = this.centers.get(this.feature.target), b = this.feature.tools[0] ? this.centers.get(this.feature.tools[0]) : undefined;
|
||||
const box = this.dim && a && b ? this.app.view.toScreen(this.boxPoint ?? scale(add(a, b), 0.5)) : null;
|
||||
want.forEach(([body, sign], i) => {
|
||||
const m = this.marks[i];
|
||||
m.title = sign === "+" ? "Changed" : "Changed with";
|
||||
m.dataset.body = body;
|
||||
m.title = sign === "+" ? "Changed - tap to change it with this one instead" : "Changed with - tap to change this one instead";
|
||||
m.classList.toggle("minus", sign !== "+");
|
||||
// (Where the body was: in the preview a subtracted body is used up.)
|
||||
if (this.app.view.bodyList.some((b) => b.id === body)) this.centers.set(body, bodyCenter(this.app, [body]));
|
||||
const at = this.centers.get(body);
|
||||
const c = at ? this.app.view.toScreen(at) : null;
|
||||
m.hidden = !c;
|
||||
if (c) m.style.transform = `translate(${Math.round(r.left + c[0] - 14)}px, ${Math.round(r.top + c[1] - 14)}px)`;
|
||||
if (!c) return;
|
||||
let x = c[0], y = c[1];
|
||||
if (box && Math.abs(box[0] - x) < 100 && Math.abs(box[1] - y) < 36) y = box[1] - 36;
|
||||
while (placed.some(([px, py]) => Math.abs(px - x) < 30 && Math.abs(py - y) < 30)) x += 32;
|
||||
placed.push([x, y]);
|
||||
m.style.transform = `translate(${Math.round(r.left + x - 14)}px, ${Math.round(r.top + y - 14)}px)`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,9 +83,21 @@ export class DragTyping {
|
||||
(this.boxEl.querySelector(".dim-unit") as HTMLElement).textContent = unit;
|
||||
if (document.activeElement !== this.boxInput) this.boxInput!.value = value.replace(/\s*(mm|cm|m|in|ft|°|")$/, "").replace(/^×/, "");
|
||||
const r = this.app.view.canvas.getBoundingClientRect();
|
||||
this.boxEl.style.left = `${Math.round(r.left + p.x + 22)}px`;
|
||||
this.boxEl.style.top = `${Math.round(r.top + p.y + 16)}px`;
|
||||
this.boxEl.hidden = false;
|
||||
// Below right of the finger - or left of it / above it where that runs off
|
||||
// the screen (a face pushed out at a phone's right edge had its box at
|
||||
// x 387 on a 375 screen: there, but not to be tapped).
|
||||
const w = this.boxEl.offsetWidth;
|
||||
const h = this.boxEl.offsetHeight;
|
||||
const M = 8;
|
||||
let x = r.left + p.x + 22;
|
||||
let y = r.top + p.y + 16;
|
||||
if (x + w > innerWidth - M) x = r.left + p.x - 22 - w;
|
||||
if (y + h > innerHeight - M) y = r.top + p.y - 16 - h;
|
||||
x = Math.max(M, Math.min(x, innerWidth - M - w));
|
||||
y = Math.max(M, Math.min(y, innerHeight - M - h));
|
||||
this.boxEl.style.left = `${Math.round(x)}px`;
|
||||
this.boxEl.style.top = `${Math.round(y)}px`;
|
||||
this.app.ui.setLabel(0, 0, null);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
// edges, and the rest of the body, don't move.
|
||||
|
||||
import type { FaceFreeformFeature, FaceRef, Vec3 } from "../doc/types";
|
||||
import { FreeformTool, layFaceCage } from "./freeform";
|
||||
import { editedStep } from "../doc/freeformEdits";
|
||||
import { facesNormal } from "../freeform/faceGrid";
|
||||
import { faceStepNormal, FreeformTool, layFaceCage, type EditKeep } from "./freeform";
|
||||
import { faceRefOf, type AppContext, type Sel, type Tool } from "./tool";
|
||||
|
||||
/** The triangles of face `i` of a body as shown (the cage goes only where the face is). */
|
||||
@@ -19,6 +21,51 @@ function faceTriangles(app: AppContext, body: string, i: number): [Vec3, Vec3, V
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Do the faces (each as its triangles) all hang together, each sharing an edge with another? */
|
||||
function joined(faces: [Vec3, Vec3, Vec3][][]): boolean {
|
||||
const key = (p: Vec3) => p.map((x) => Math.round(x * 1e4)).join(",");
|
||||
const edgesOf = (tris: [Vec3, Vec3, Vec3][]) => {
|
||||
const s = new Set<string>();
|
||||
for (const t of tris)
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const a = key(t[k]);
|
||||
const b = key(t[(k + 1) % 3]);
|
||||
s.add(a < b ? `${a}|${b}` : `${b}|${a}`);
|
||||
}
|
||||
return s;
|
||||
};
|
||||
const sets = faces.map(edgesOf);
|
||||
const reached = new Set([0]);
|
||||
for (let grew = true; grew; ) {
|
||||
grew = false;
|
||||
for (let i = 0; i < sets.length; i++) {
|
||||
if (reached.has(i)) continue;
|
||||
if ([...reached].some((j) => [...sets[i]].some((e) => sets[j].has(e)))) (reached.add(i), (grew = true));
|
||||
}
|
||||
}
|
||||
return reached.size === sets.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* A Freeform Face step (as its edits leave it) whose surface on the picked
|
||||
* faces' body shares an edge with them, and that surface's triangles.
|
||||
*/
|
||||
function touchedStep(app: AppContext, picked: Extract<Sel, { kind: "face" }>[]): { step: FaceFreeformFeature; tris: [Vec3, Vec3, Vec3][] } | null {
|
||||
const body = picked[0].body;
|
||||
if (picked.some((p) => p.body !== body)) return null;
|
||||
const faces = app.view.body(body)?.faces ?? [];
|
||||
const mine = new Set(picked.map((p) => p.face));
|
||||
const steps = [...new Set(faces.flatMap((f, k) => (f.step && !mine.has(k) ? [f.step] : [])))];
|
||||
const pickedTris = picked.map((p) => faceTriangles(app, body, p.face));
|
||||
for (const id of steps) {
|
||||
const s = editedStep<FaceFreeformFeature>(app.store.features, id);
|
||||
if (s?.type !== "faceFreeform" || s.face.body !== body) continue;
|
||||
const tris = faces.flatMap((f, k) => (f.step === id && !mine.has(k) ? faceTriangles(app, body, k) : []));
|
||||
if (tris.length && joined([tris, ...pickedTris])) return { step: s, tris };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The face most like a saved one (facing the same way, its middle nearest), or -1. */
|
||||
function nearestFace(faces: { center: Vec3; normal: Vec3 }[], ref: FaceRef): number {
|
||||
let best = -1;
|
||||
@@ -36,29 +83,53 @@ function nearestFace(faces: { center: Vec3; normal: Vec3 }[], ref: FaceRef): num
|
||||
* `existing`, a Freeform Face step to change (its face found on the body by
|
||||
* the step that made it). Null (after saying why) when no cage fits the face.
|
||||
*/
|
||||
export function faceFreeformTool(app: AppContext, face: Extract<Sel, { kind: "face" }> | null, existing?: FaceFreeformFeature): Tool | null {
|
||||
export function faceFreeformTool(app: AppContext, face: Extract<Sel, { kind: "face" }> | Extract<Sel, { kind: "face" }>[] | null, existing?: FaceFreeformFeature, keep?: EditKeep): Tool | null {
|
||||
if (existing) {
|
||||
const faces = app.view.body(existing.face.body)?.faces ?? [];
|
||||
let i = faces.findIndex((f) => f.step === existing.id);
|
||||
// The step didn't work (so its face isn't there): the flat face it was made on.
|
||||
if (i < 0) i = nearestFace(faces, existing.face);
|
||||
// (Several faces made one: the surface may be in pieces, all made by the step.)
|
||||
let at = faces.flatMap((f, k) => (f.step === existing.id ? [k] : []));
|
||||
if (!existing.more?.length) at = at.slice(0, 1);
|
||||
// The step didn't work (so its face isn't there): the flat faces it was made on.
|
||||
if (!at.length) at = [existing.face, ...(existing.more ?? [])].map((r) => nearestFace(faces, r)).filter((k) => k >= 0);
|
||||
// (Over a face already shaped the cage is laid on its outline, which is the flat face's.)
|
||||
const tris = i >= 0 ? faceTriangles(app, existing.face.body, i) : [];
|
||||
const tris = at.flatMap((k) => faceTriangles(app, existing.face.body, k));
|
||||
const feature = structuredClone(existing);
|
||||
if (!feature.cage?.verts?.length) {
|
||||
// Made before faces had cages: a fresh one over it.
|
||||
const laid = layFaceCage(tris, feature.face.center, feature.face.normal, 5);
|
||||
const laid = layFaceCage(tris, feature.face.center, faceStepNormal(feature), 5, !!feature.more?.length);
|
||||
if (!laid) return (app.ui.toast("This face's outline won't take a grid - pick it again with Freeform Face"), null);
|
||||
feature.cage = laid.cage;
|
||||
feature.grid = laid.n;
|
||||
}
|
||||
return new FreeformTool(app, { face: { feature, existing: true, tris } });
|
||||
return new FreeformTool(app, { face: { feature, existing: true, tris, keep } });
|
||||
}
|
||||
const ref = face && (faceRefOf(app, face) as FaceRef | null);
|
||||
if (!face || !ref) return null;
|
||||
const tris = faceTriangles(app, face.body, face.face);
|
||||
const laid = layFaceCage(tris, ref.center, ref.normal, 5);
|
||||
if (!laid) return (app.ui.toast("This face's outline won't take a grid (too small, or too odd a shape)"), null);
|
||||
const feature: FaceFreeformFeature = { ...app.store.newIdentity("faceFreeform"), type: "faceFreeform", face: ref, cage: laid.cage, grid: laid.n };
|
||||
const picked = !face ? [] : Array.isArray(face) ? face : [face];
|
||||
const refs = picked.map((s) => faceRefOf(app, s) as FaceRef | null);
|
||||
if (!picked.length || refs.some((r) => !r)) return null;
|
||||
const [ref, ...more] = refs as FaceRef[];
|
||||
const tris = picked.flatMap((s) => faceTriangles(app, s.body, s.face));
|
||||
// Several faces: they must touch, one after another (a grid can't jump a gap).
|
||||
if (more.length && !joined(picked.map((s) => faceTriangles(app, s.body, s.face)))) return (app.ui.toast("Pick faces that touch each other - side by side, sharing an edge"), null);
|
||||
// Touching a surface a Freeform Face step made on the same body: that step
|
||||
// grows to take these faces in - one surface, no edge where they meet (an
|
||||
// Edit Freeform step in History: delete it and they are apart again).
|
||||
const grow = touchedStep(app, picked);
|
||||
if (grow) {
|
||||
const s = grow.step;
|
||||
const all: FaceRef[] = [...(s.more ?? []), ...(refs as FaceRef[])];
|
||||
const feature: FaceFreeformFeature = { ...structuredClone(s), more: all };
|
||||
const both = [...grow.tris, ...tris];
|
||||
// (Laid over the surface as it is shaped now and the new faces: what was shaped stays so, near enough.)
|
||||
const laid = layFaceCage(both, s.face.center, faceStepNormal(feature), Math.max(5, s.grid ?? 5), true);
|
||||
if (!laid) return (app.ui.toast("These faces won't take one grid with the freeform beside them (seen together they fold back over each other)"), null);
|
||||
feature.cage = laid.cage;
|
||||
feature.grid = laid.n;
|
||||
app.ui.toast(`Joined to ${s.name}: one smooth surface`);
|
||||
return new FreeformTool(app, { face: { feature, existing: true, tris: both } });
|
||||
}
|
||||
const normal = more.length ? facesNormal([ref.normal, ...more.map((m) => m.normal)]) : ref.normal;
|
||||
const laid = layFaceCage(tris, ref.center, normal, 5, more.length > 0);
|
||||
if (!laid) return (app.ui.toast(more.length ? "These faces won't take one grid (seen together they fold back over each other) - pick fewer" : "This face's outline won't take a grid (too small, or too odd a shape)"), null);
|
||||
const feature: FaceFreeformFeature = { ...app.store.newIdentity("faceFreeform"), type: "faceFreeform", face: ref, ...(more.length ? { more } : {}), cage: laid.cage, grid: laid.n };
|
||||
return new FreeformTool(app, { face: { feature, existing: false, tris } });
|
||||
}
|
||||
|
||||
@@ -90,9 +90,98 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
this.render();
|
||||
this.update();
|
||||
this.app.ui.focusPanel();
|
||||
this.steps = [JSON.stringify(this.feature)];
|
||||
this.redos = [];
|
||||
window.addEventListener("pointerdown", this.onDown, true);
|
||||
window.addEventListener("pointerup", this.onUp, true);
|
||||
window.addEventListener("pointercancel", this.onUp, true);
|
||||
}
|
||||
|
||||
// ---- Undo inside the tool
|
||||
// Each change made while the tool is open - a drag of its handle, a value typed, an option chosen, something more
|
||||
// picked - is a step of its own that Undo takes back, one at a time, and Redo puts back (asked for: "when I ...
|
||||
// select a vertex and I move it around, and I hit undo, that undo should change the last modification, not go back
|
||||
// to the extruding action or the one before entirely ... I want full history control"). Undo used to close the tool,
|
||||
// throwing all of it away, and then take back the step before it as well. With nothing left to take back in the
|
||||
// tool, Undo closes it (nothing made); the next Undo is the project's.
|
||||
private steps: string[] = [];
|
||||
private redos: string[] = [];
|
||||
private held = false;
|
||||
private settle = 0;
|
||||
private restoring = false;
|
||||
private onDown = (): void => void (this.held = true);
|
||||
private onUp = (): void => {
|
||||
this.held = false;
|
||||
// (After the tool's own handlers for this lift have run.)
|
||||
window.setTimeout(() => this.record(), 0);
|
||||
};
|
||||
|
||||
/** What the draft is now, as a step - if it differs from the last one. */
|
||||
private record(): void {
|
||||
if (this.restoring || !this.steps.length) return;
|
||||
const now = JSON.stringify(this.feature);
|
||||
if (now === this.steps[this.steps.length - 1]) return;
|
||||
this.steps.push(now);
|
||||
if (this.steps.length > 100) this.steps.shift();
|
||||
this.redos = [];
|
||||
(this.app as AppContext & { refreshUndo?(): void }).refreshUndo?.();
|
||||
}
|
||||
|
||||
/** The draft changed: a step once the drag ends, or once typing stops for a moment (digit by digit is one step). */
|
||||
private noteChange(): void {
|
||||
if (this.restoring || this.held) return;
|
||||
clearTimeout(this.settle);
|
||||
this.settle = window.setTimeout(() => this.record(), 450);
|
||||
}
|
||||
|
||||
/** The draft put back to a step (in place: the window's parts and the handles hold on to it). */
|
||||
private restore(step: string): void {
|
||||
this.restoring = true;
|
||||
try {
|
||||
const f = this.feature as unknown as Record<string, unknown>;
|
||||
for (const k of Object.keys(f)) delete f[k];
|
||||
Object.assign(f, JSON.parse(step));
|
||||
this.restored();
|
||||
this.render();
|
||||
this.update();
|
||||
} finally {
|
||||
this.restoring = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** After Undo / Redo put the draft back: for a tool that keeps something beside the draft in step with it. */
|
||||
protected restored(): void {}
|
||||
|
||||
get canUndo(): boolean {
|
||||
return true;
|
||||
}
|
||||
get canRedo(): boolean {
|
||||
return this.redos.length > 0;
|
||||
}
|
||||
undo(): boolean {
|
||||
clearTimeout(this.settle);
|
||||
this.record();
|
||||
if (this.steps.length < 2) {
|
||||
this.cancel();
|
||||
return true;
|
||||
}
|
||||
this.redos.push(this.steps.pop()!);
|
||||
this.restore(this.steps[this.steps.length - 1]);
|
||||
return true;
|
||||
}
|
||||
redo(): boolean {
|
||||
const next = this.redos.pop();
|
||||
if (!next) return false;
|
||||
this.steps.push(next);
|
||||
this.restore(next);
|
||||
return true;
|
||||
}
|
||||
|
||||
exit(): void {
|
||||
clearTimeout(this.settle);
|
||||
window.removeEventListener("pointerdown", this.onDown, true);
|
||||
window.removeEventListener("pointerup", this.onUp, true);
|
||||
window.removeEventListener("pointercancel", this.onUp, true);
|
||||
this.app.view.setOriginPlanesVisible(false);
|
||||
this.app.ui.showPanel(null);
|
||||
this.app.ui.setHint(null);
|
||||
@@ -147,13 +236,23 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A tap on a body the step waiting can't use (a mirror's plane, a ball tapped): true if the tool took it some other way. */
|
||||
protected otherBody(_body: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** After regionTap changed the profile (e.g. Extrude moves its arrow). */
|
||||
protected regionsChanged(): void {}
|
||||
|
||||
tap(p: ToolPointer): void {
|
||||
const slot = this.slots[this.active];
|
||||
const h = this.lastHover;
|
||||
const hit = h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6 ? h.hit : this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}) });
|
||||
let hit = h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6 ? h.hit : this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}) });
|
||||
// Not what this step is making (its preview): what's under it. (A Fill's
|
||||
// last boundary curve, tapped once the loop closed, took the edge of the
|
||||
// surface just made on it instead.)
|
||||
const mine = (b: string) => b === this.feature.id || b.startsWith(`${this.feature.id}:`);
|
||||
if (hit && "body" in hit && hit.body && mine(hit.body)) hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...(slot?.pick ?? {}), bodies: false });
|
||||
if (this.moreRegions && (!slot || !hit || hit.kind === "plane" || hit.kind === "profile") && this.regionTap(p)) return;
|
||||
// Tapping empty space ends the tool: keep the result if it's complete.
|
||||
if (!hit) {
|
||||
@@ -167,6 +266,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
const body = "body" in hit ? hit.body : null;
|
||||
if (!slot.accept(hit) && !(body && this.app.view.facesAt(p.x, p.y).some((f) => f.kind === "face" && f.body !== body && slot.accept(f)))) {
|
||||
if (this.moreRegions && this.regionTap(p)) return;
|
||||
if (body && !mine(body) && this.otherBody(body)) return;
|
||||
if (slot.rejectHint) this.app.ui.toast(slot.rejectHint);
|
||||
return;
|
||||
}
|
||||
@@ -176,6 +276,24 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
this.update();
|
||||
}
|
||||
|
||||
/**
|
||||
* A body tapped in Items: the slot waiting takes it, as a tap on it in the
|
||||
* view would. (Six pegs inside a pulley's web, to subtract, can't be tapped
|
||||
* there - and the tap in Items put Subtract away and selected the body.)
|
||||
*/
|
||||
pickBody(id: string): boolean {
|
||||
const slot = this.slots[this.active];
|
||||
if (!slot || !slot.accept({ kind: "body", body: id, point: [0, 0, 0] } as unknown as PickHit)) return false;
|
||||
if (!slot.multi) this.active = this.slots.findIndex((s, i) => i > this.active && !s.filled());
|
||||
this.render();
|
||||
if (this.finishWhenPicked && this.ready()) {
|
||||
void this.finishIfOk();
|
||||
return true;
|
||||
}
|
||||
this.update();
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Nothing left to set once the picks are made (e.g. Replace Face): the last pick finishes. */
|
||||
protected finishWhenPicked = false;
|
||||
|
||||
@@ -240,7 +358,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
this.app.setSelection(this.slots.flatMap((s) => s.shows?.() ?? []));
|
||||
}
|
||||
|
||||
private setHint(): void {
|
||||
protected setHint(): void {
|
||||
const slot = this.slots[this.active];
|
||||
const text = this.error ? `⚠ ${this.error}` : slot && !slot.filled() ? `${slot.label}: ${slot.describe()}` : this.hint();
|
||||
this.app.ui.setHint(text);
|
||||
@@ -257,6 +375,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
/** Re-run the preview with the current draft. */
|
||||
protected update(): void {
|
||||
this.onDraftChanged();
|
||||
this.noteChange();
|
||||
const ready = this.ready();
|
||||
const base = this.app.store.features;
|
||||
// (The steps that aren't the project's own: the draft, or what a tool puts in its place.)
|
||||
@@ -281,9 +400,18 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
shown(r);
|
||||
this.error = r?.errors.find((e) => e.featureId === this.feature.id)?.message ?? null;
|
||||
this.setHint();
|
||||
// What the step notes about itself (it cut where Add may have been
|
||||
// meant, a piece left off): said while it's being made, not only on
|
||||
// its History row, out of sight on a phone. Once per new note.
|
||||
const note = r ? (r.notes?.find((n) => n.featureId === this.feature.id)?.message ?? null) : this.noted;
|
||||
if (note && note !== this.noted && !this.error) this.app.ui.toast(note);
|
||||
this.noted = note;
|
||||
});
|
||||
}
|
||||
|
||||
/** The note the last preview had for this step (said once). */
|
||||
private noted: string | null = null;
|
||||
|
||||
/** Hook for handles etc. */
|
||||
protected onDraftChanged(): void {}
|
||||
|
||||
|
||||
@@ -11,8 +11,9 @@
|
||||
import { Box3, BufferAttribute, BufferGeometry, DoubleSide, Sprite, LineBasicMaterial, LineSegments, type Material, Mesh, MeshBasicMaterial, MeshStandardMaterial, Points, Raycaster, Vector2, Vector3 } from "three";
|
||||
import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";
|
||||
import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js";
|
||||
import type { FaceFreeformFeature, Feature, FreeformFeature, PlaneDef, TransformFeature, Vec3 } from "../doc/types";
|
||||
import { faceCage } from "../freeform/faceGrid";
|
||||
import type { FaceFreeformFeature, Feature, FreeformEditFeature, FreeformFeature, PlaneDef, TransformFeature, Vec3 } from "../doc/types";
|
||||
import { faceCage, facesNormal, liftOnto, onCorners, toFaces } from "../freeform/faceGrid";
|
||||
import { carryCreases, edgeLoopOf, removeEdgeLoop, withCreases } from "../freeform/cage";
|
||||
import { applyPlan, archBridge, planeCage, borderChains, cachedPlan, planIndices, smoothNormals, type SubdivPlan, bridgeChains, bridgeFaces, moveTurnScale, shapeCage, sweepFace, type Chain, boundaryEdges, bridgeLoops, cageEdgeKey, extendBorder, cageEdges, deleteFaces, extrudeFaces, fillHole, holeLoops, insertEdgeLoop, insetFaces, isClosed, primitiveCage, refineCage, selfCrossings, subdivide, type Cage, type CagePrimitive } from "../freeform/cage";
|
||||
import { add, cross, dot, len, niceStep, norm, scale, sub, xDirFor } from "../geom";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
@@ -21,7 +22,7 @@ import type { ToolPointer } from "../view/input";
|
||||
import { dotMaterial, planeMarkMaterial, PLANE_MARK_SIZE } from "../view/viewport";
|
||||
import { isCoarse, screenClass } from "../device";
|
||||
import { DragTyping, type DragTypingTarget } from "./dragTyping";
|
||||
import { Gimbal, GIMBAL_AXES, type GimbalPart } from "./gimbal";
|
||||
import { Gimbal, GIMBAL_AXES, SCALE_PARTS, type GimbalPart } from "./gimbal";
|
||||
import { axisDrag } from "./handles";
|
||||
import { FillToPlaneOp } from "./ops";
|
||||
import type { AppContext, Sel, Tool } from "./tool";
|
||||
@@ -35,7 +36,7 @@ type Pick = { kind: "vert"; i: number } | { kind: "edge"; e: [number, number] }
|
||||
* Re-made from `base` on every slider move; the next tap or step keeps it.
|
||||
*/
|
||||
type Live =
|
||||
| { kind: "shape"; prim: "box" | "cylinder" | "sphere"; size: Vec3; rows: number }
|
||||
| { kind: "shape"; prim: "box" | "cylinder" | "sphere" | "torus"; size: Vec3; rows: number }
|
||||
/** A new flat surface on the plane picked: its width, depth and faces in the card. */
|
||||
| { kind: "sheet"; size: [number, number]; rows: number; at: Vec3; x: Vec3; y: Vec3; n: Vec3 }
|
||||
| { kind: "sweep"; base: Cage; face: number; steps: number; length: number; bend: number; taper: number; size: number }
|
||||
@@ -53,20 +54,43 @@ export interface FaceShaping {
|
||||
/** Editing a step already in History (else a new one). */
|
||||
existing: boolean;
|
||||
tris: [Vec3, Vec3, Vec3][];
|
||||
/** How an edit is kept (see FreeformTool's `keep`). */
|
||||
keep?: EditKeep;
|
||||
}
|
||||
|
||||
/**
|
||||
* A cage `n` across over a face's triangles (relative to `center`) - or, if
|
||||
* the face's outline won't take that many, the nearest coarser preset.
|
||||
* How Done keeps an edit of a freeform made earlier: as a new Edit Freeform
|
||||
* step in History (the default), into an Edit Freeform step opened from
|
||||
* History (`edit`: its id), or into the step itself (`inPlace`: the step
|
||||
* opened from History).
|
||||
*/
|
||||
export function layFaceCage(tris: [Vec3, Vec3, Vec3][], center: Vec3, normal: Vec3, n: number): { cage: Cage; n: number } | null {
|
||||
export type EditKeep = { edit?: string; inPlace?: boolean };
|
||||
|
||||
/**
|
||||
* A cage `n` across over a face's triangles (relative to `center`) - or, if
|
||||
* the face's outline won't take that many, the nearest coarser preset. Over
|
||||
* several faces side by side: laid seen along `normal` (their middle way), then
|
||||
* put down onto them - where they meet, the cage bends, and the smooth surface
|
||||
* through it rounds the corner off.
|
||||
*/
|
||||
export function layFaceCage(tris: [Vec3, Vec3, Vec3][], center: Vec3, normal: Vec3, n: number, several = false): { cage: Cage; n: number } | null {
|
||||
for (const k of FACE_GRIDS.filter((g) => g <= n).reverse()) {
|
||||
const cage = faceCage(tris, center, normal, k);
|
||||
if (cage) return { cage, n: k };
|
||||
if (cage) return { cage: several ? onCorners(liftOnto(cage, center, normal, tris), center, tris) : cage, n: k };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The way a Freeform Face step's faces face (one face: its normal; several: the middle of theirs). */
|
||||
export function faceStepNormal(f: FaceFreeformFeature): Vec3 {
|
||||
return f.more?.length ? facesNormal([f.face.normal, ...f.more.map((m) => m.normal)]) : norm(f.face.normal);
|
||||
}
|
||||
|
||||
/** "Pick in a box" (a finger draws the box): on until switched off. */
|
||||
let boxByFinger = false;
|
||||
/** Soft: how far round the picked points a move reaches (0: not at all). Kept for the next shape. */
|
||||
let softRadius = 0;
|
||||
|
||||
export class FreeformTool implements Tool {
|
||||
readonly id = "freeform";
|
||||
private cage: Cage;
|
||||
@@ -74,10 +98,20 @@ export class FreeformTool implements Tool {
|
||||
private picks: Pick[] = [];
|
||||
private hovered: Pick | null = null;
|
||||
private gimbal: Gimbal | null = null;
|
||||
private dragging: { part: GimbalPart; from: ToolPointer; base: Vec3[]; center: Vec3; d: Vec3; ang: number } | null = null;
|
||||
private dragging: { part: GimbalPart; from: ToolPointer; base: Vec3[]; center: Vec3; d: Vec3; ang: number; k: Vec3; r0: number; along?: Vec3; soft?: Map<number, number> } | null = null;
|
||||
/** What the gimbal up now is for (Move, Turn or Scale: its handles are that one's). */
|
||||
private gimbalFor = "";
|
||||
private typing: DragTyping;
|
||||
/** The card's exact values: what they act on (Move, Turn, Scale), and the points as they were before typing. */
|
||||
private xform: "move" | "turn" | "scale" = "move";
|
||||
private xform: "move" | "turn" | "scale" | "place" = "move";
|
||||
/**
|
||||
* A finger drawing a box picks the points inside it (seen through: the
|
||||
* ones behind too) - a whole slice of a shape in one go from a side view.
|
||||
* Off, a finger orbits as usual. (Kept on for the next shape.)
|
||||
*/
|
||||
get boxByFinger(): boolean {
|
||||
return boxByFinger;
|
||||
}
|
||||
private fieldBase: Map<number, Vec3> | null = null;
|
||||
private fieldVals = [0, 0, 0, 1];
|
||||
private live: Live | null = null;
|
||||
@@ -115,6 +149,8 @@ export class FreeformTool implements Tool {
|
||||
* apart while picking. Hidden behind the surface where it turns away.
|
||||
*/
|
||||
private faceEdges: LineSegments2;
|
||||
/** The cage's sharp edges, drawn over its lines. */
|
||||
private creaseLines: LineSegments2;
|
||||
/** Which surface points the face outlines join (pairs), for the layout shown. */
|
||||
private faceEdgeIdx: Uint32Array = new Uint32Array(0);
|
||||
/**
|
||||
@@ -149,21 +185,22 @@ export class FreeformTool implements Tool {
|
||||
|
||||
constructor(
|
||||
private app: AppContext,
|
||||
from: { primitive: CagePrimitive } | { feature: FreeformFeature } | { face: FaceShaping },
|
||||
from: { primitive: CagePrimitive } | { feature: FreeformFeature; keep?: EditKeep } | { face: FaceShaping },
|
||||
) {
|
||||
this.keep = ("keep" in from ? from.keep : "face" in from ? from.face.keep : undefined) ?? {};
|
||||
if ("face" in from) {
|
||||
this.face = from.face;
|
||||
const f = from.face.feature;
|
||||
this.cage = { faces: structuredClone(f.cage.faces), verts: f.cage.verts.map((v) => add(f.face.center, v)) };
|
||||
this.surfaceSheet = true;
|
||||
const n = norm(f.face.normal);
|
||||
const n = faceStepNormal(f);
|
||||
const u = xDirFor(n);
|
||||
this.axes = [u, norm(cross(n, u)), n];
|
||||
} else if ("feature" in from) {
|
||||
this.existing = from.feature;
|
||||
this.place = placementOf(app.store.features, from.feature.id);
|
||||
const c = structuredClone(from.feature.cage);
|
||||
this.cage = { faces: c.faces, verts: c.verts.map(this.place.fwd) };
|
||||
this.cage = { faces: c.faces, verts: c.verts.map(this.place.fwd), ...(c.creases ? { creases: c.creases } : {}) };
|
||||
this.surfaceSheet = !!from.feature.surface;
|
||||
this.thickness = from.feature.thickness ?? 0;
|
||||
this.thickSide = from.feature.thickSide ?? "up";
|
||||
@@ -184,6 +221,9 @@ export class FreeformTool implements Tool {
|
||||
this.marks = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(SEL, 4, false));
|
||||
this.hoverMarks = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(HOVER, 2.5, false));
|
||||
this.faceEdges = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(0x2f3b52, 1.6, true));
|
||||
this.creaseLines = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(0xff8a3d, 3.2, true));
|
||||
this.creaseLines.renderOrder = 12;
|
||||
this.creaseLines.visible = false;
|
||||
this.markFill.renderOrder = 67;
|
||||
// Zoom to fit frames the cage being shaped (its points: the smooth shape lies inside them).
|
||||
this.dots.userData.fit = true;
|
||||
@@ -196,8 +236,28 @@ export class FreeformTool implements Tool {
|
||||
for (const o of [this.markDots, this.hoverDots]) o.renderOrder = 71;
|
||||
}
|
||||
|
||||
private keep: EditKeep;
|
||||
|
||||
get editingId(): string | undefined {
|
||||
return this.existing?.id ?? (this.face?.existing ? this.face.feature.id : undefined);
|
||||
return this.keep.edit ?? this.existing?.id ?? (this.face?.existing ? this.face.feature.id : undefined);
|
||||
}
|
||||
|
||||
/** The edit of a step made earlier, kept as `keep` says. */
|
||||
private saveEdit(target: string, patch: FreeformEditFeature["patch"]): void {
|
||||
const store = this.app.store;
|
||||
if (this.keep.edit) store.update(this.keep.edit, { patch } as Partial<FreeformEditFeature>);
|
||||
else if (this.keep.inPlace) store.update(target, patch as Partial<FreeformFeature>);
|
||||
else store.add({ ...store.newIdentity("freeformEdit"), type: "freeformEdit", target, patch });
|
||||
}
|
||||
|
||||
/** The steps as they would be with this edit kept (for a preview). */
|
||||
private withEdit(target: string, patch: FreeformEditFeature["patch"]): Feature[] {
|
||||
const list = [...this.app.store.features];
|
||||
const at = (id: string) => list.findIndex((x) => x.id === id);
|
||||
if (this.keep.edit && at(this.keep.edit) >= 0) list[at(this.keep.edit)] = { ...(list[at(this.keep.edit)] as FreeformEditFeature), patch };
|
||||
else if (this.keep.inPlace && at(target) >= 0) list[at(target)] = { ...list[at(target)], ...patch } as Feature;
|
||||
else list.push({ id: "freeform-edit-draft", name: "Edit Freeform", type: "freeformEdit", target, patch } as FreeformEditFeature);
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -218,6 +278,7 @@ export class FreeformTool implements Tool {
|
||||
if (this.sym) queueMicrotask(() => this.drawSymPlane());
|
||||
this.symMark.renderOrder = 72;
|
||||
this.symMark.visible = false;
|
||||
view.overlay.add(this.creaseLines);
|
||||
view.overlay.add(this.symPlane, this.symMark, this.surface, this.faceEdges, this.backLines, this.backDots, this.lines, this.dots, this.markFill, this.marks, this.markDots, this.hoverMarks, this.hoverDots);
|
||||
// Editing an existing freeform: hide its finished body while the cage is out.
|
||||
if (this.existing) view.setHidden(new Set([...this.app.store.doc.hidden, this.existing.id]));
|
||||
@@ -258,8 +319,9 @@ export class FreeformTool implements Tool {
|
||||
// A new box, cylinder or sphere: its size and rows in the card first.
|
||||
if (!this.existing && this.primKind && this.primKind !== "plane") {
|
||||
const prim = this.primKind;
|
||||
this.live = { kind: "shape", prim, size: [40, 40, 40], rows: prim === "sphere" ? 2 : 2 };
|
||||
this.cage = shapeCage(prim, [40, 40, 40], 2);
|
||||
const size: Vec3 = prim === "torus" ? [40, 40, 12] : [40, 40, 40];
|
||||
this.live = { kind: "shape", prim, size, rows: 2 };
|
||||
this.cage = shapeCage(prim, size, 2);
|
||||
}
|
||||
this.rebuild();
|
||||
// A new shape inside another body (or a flat surface, which you'll want to place first): move it as a whole first.
|
||||
@@ -306,6 +368,7 @@ export class FreeformTool implements Tool {
|
||||
// (A sprite's geometry is shared by every sprite: only taken off, not disposed.)
|
||||
view.overlay.remove(this.symMark);
|
||||
view.overlay.remove(this.faceEdges);
|
||||
view.overlay.remove(this.creaseLines);
|
||||
// (They share the front pass's points and lines: disposed with those.)
|
||||
view.overlay.remove(this.backLines, this.backDots);
|
||||
for (const o of [this.symPlane, this.surface, this.lines, this.dots, this.markFill, this.marks, this.markDots, this.hoverMarks, this.hoverDots]) {
|
||||
@@ -319,7 +382,7 @@ export class FreeformTool implements Tool {
|
||||
this.app.ui.setHint(null);
|
||||
this.app.ui.setLabel(0, 0, null);
|
||||
this.typing.hideBox();
|
||||
for (const o of [this.marks, this.hoverMarks, this.faceEdges]) {
|
||||
for (const o of [this.marks, this.hoverMarks, this.faceEdges, this.creaseLines]) {
|
||||
o.geometry.dispose();
|
||||
view.releaseLineMaterial(o.material);
|
||||
}
|
||||
@@ -341,8 +404,8 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
if (this.placing) return this.app.ui.setHint("First drag the arrows to put it in place. Then tap its points, edges or faces to shape it.");
|
||||
// A phone has no Shift: there every tap adds, a second tap drops it.
|
||||
if (this.live && this.live.kind !== "shape" && this.live.kind !== "sheet") return this.app.ui.setHint("Shape it with the sliders in the card. Tap the model to keep it.");
|
||||
if (this.live) return this.app.ui.setHint("Set the size and rows in the card, then tap faces to shape it.");
|
||||
if (this.live && this.live.kind !== "shape" && this.live.kind !== "sheet") return this.app.ui.setHint("Shape it with its values on the line at the bottom. Tap the model to keep it.");
|
||||
if (this.live) return this.app.ui.setHint("Set the size and rows on the line at the bottom, then tap faces to shape it.");
|
||||
const more = isCoarse ? "Tap more to add; tap a face again for the one behind it" : "Shift+tap adds; click a face again for the one behind it";
|
||||
this.app.ui.setHint(
|
||||
this.picks.length
|
||||
@@ -359,8 +422,12 @@ export class FreeformTool implements Tool {
|
||||
this.fieldBase = null;
|
||||
// Nothing moved yet: no offset, no turn - and every scale factor 1 (0 flattened the points).
|
||||
this.fieldVals = this.xform === "scale" ? [1, 1, 1, 1] : [0, 0, 0, 1];
|
||||
items.push({ type: "choice", options: [{ id: "move", label: "Move" }, { id: "turn", label: "Turn" }, { id: "scale", label: "Scale" }], value: this.xform, onChange: (v) => ((this.xform = v as typeof this.xform), this.panel()) });
|
||||
if (this.xform === "scale") {
|
||||
items.push({ type: "choice", options: [{ id: "move", label: "Move" }, { id: "turn", label: "Turn" }, { id: "scale", label: "Scale" }, { id: "place", label: "Place at" }], value: this.xform, onChange: (v) => ((this.xform = v as typeof this.xform), this.panel(), this.placeGimbal()) });
|
||||
if (this.xform === "place") {
|
||||
// Where the picked points are (their middle), to type where they should be: X, Y and Z from the origin.
|
||||
const at = this.centroid(this.selectedVerts());
|
||||
for (const [k, a] of ["X", "Y", "Z"].entries()) items.push({ type: "number", label: a, value: Math.round(at[k] * 1000) / 1000, kind: "length", onInput: (v) => this.placeAt(k, v) });
|
||||
} else if (this.xform === "scale") {
|
||||
items.push({ type: "number", label: "All", value: 1, kind: "number", min: 0.01, onInput: (v) => this.setField(3, v) });
|
||||
for (const [k, a] of ["X", "Y", "Z"].entries()) items.push({ type: "number", label: a, value: 1, kind: "number", min: 0.01, onInput: (v) => this.setField(k, v) });
|
||||
} else {
|
||||
@@ -368,6 +435,23 @@ export class FreeformTool implements Tool {
|
||||
for (const [k, a] of ["X", "Y", "Z"].entries()) items.push({ type: "number", label: turn ? `${a}°` : `Δ${a}`, value: 0, kind: turn ? "angle" : "length", onInput: (v) => this.setField(k, v) });
|
||||
}
|
||||
}
|
||||
// Soft: the points round the picked ones go along with a move, less the further off they are - a bump raised
|
||||
// by one point, not a spike. (0: only what is picked moves.)
|
||||
if (n && !this.face && (!this.live || this.live.kind === "shape" || this.live.kind === "sheet") && (this.xform === "move" || this.xform === "place"))
|
||||
items.push({ type: "number", label: "Soft", value: softRadius, kind: "length", min: 0, onInput: (v) => (softRadius = Math.max(0, v)) });
|
||||
// A phone has no mouse to draw a box round the points: a finger draws it while this is on.
|
||||
if (isCoarse && !this.placing && (!this.live || this.live.kind === "shape" || this.live.kind === "sheet"))
|
||||
items.push({
|
||||
type: "toggle",
|
||||
label: "Pick in a box",
|
||||
value: this.boxByFinger,
|
||||
onChange: (on) => {
|
||||
boxByFinger = on;
|
||||
// (Its switch on the line shows how it is now: it was read once, and stayed as it was however it was set.)
|
||||
this.panel();
|
||||
this.app.ui.setHint(on ? "Draw a box with your finger round the points to pick (the ones behind are picked too). Two fingers still move the view." : "A finger turns the view again.");
|
||||
},
|
||||
});
|
||||
if (this.face) return this.facePanel(items);
|
||||
if (!this.live && !this.placing) {
|
||||
items.push({
|
||||
@@ -395,7 +479,10 @@ export class FreeformTool implements Tool {
|
||||
},
|
||||
});
|
||||
if (this.symPicking) {
|
||||
const mid = this.centroid(this.cage.verts.map((_, i) => i));
|
||||
// (The middle of its size, not of its points: more detail on one side - an inset face - pulled the mirror
|
||||
// towards it, and nothing on the two sides matched.)
|
||||
const vs = this.cage.verts;
|
||||
const mid = [0, 1, 2].map((k) => (Math.min(...vs.map((v) => v[k])) + Math.max(...vs.map((v) => v[k]))) / 2) as Vec3;
|
||||
items.push({ type: "choice", label: "Mirror across", options: [{ id: "x", label: "X" }, { id: "y", label: "Y" }, { id: "z", label: "Z" }], value: "", onChange: (k) => this.setSymmetry(mid, k === "x" ? [1, 0, 0] : k === "y" ? [0, 1, 0] : [0, 0, 1]) });
|
||||
}
|
||||
}
|
||||
@@ -424,14 +511,64 @@ export class FreeformTool implements Tool {
|
||||
if (faces === 2 && !this.placing) items.push({ type: "button", label: "Bridge faces", icon: "loft", onClick: () => this.bridgeSelectedFaces() });
|
||||
// One edge picked: a new loop of points across the faces it runs through.
|
||||
const edges = this.picks.filter((p) => p.kind === "edge");
|
||||
if (edges.length === 1 && !faces && !this.placing) items.push({ type: "button", label: "Add edge loop", icon: "splitLine", onClick: () => this.addEdgeLoop(edges[0].e) });
|
||||
// Edges picked: made sharp - the surface keeps a crease along them instead of rounding over - or smooth again.
|
||||
if (edges.length && !faces && !this.placing && !this.face) {
|
||||
const key = (e: [number, number]) => cageEdgeKey(e[0], e[1]);
|
||||
const sharp = new Set((this.cage.creases ?? []).map(key));
|
||||
const picked = edges.map((p) => (p as Extract<Pick, { kind: "edge" }>).e);
|
||||
const allSharp = picked.every((e) => sharp.has(key(e)));
|
||||
const many = picked.length > 1;
|
||||
items.push({
|
||||
type: "button",
|
||||
label: allSharp ? (many ? "Smooth edges" : "Smooth edge") : many ? "Sharp edges" : "Sharp edge",
|
||||
icon: "chamfer",
|
||||
onClick: () => {
|
||||
const drop = new Set(picked.map(key));
|
||||
this.setCreases(allSharp ? (this.cage.creases ?? []).filter((e) => !drop.has(key(e))) : [...(this.cage.creases ?? []), ...picked]);
|
||||
this.app.ui.toast(allSharp ? "Smooth again" : "Sharp: the surface keeps a crease along it (shown orange)");
|
||||
},
|
||||
});
|
||||
// (One edge: the whole loop it is part of, in one tap.)
|
||||
if (!many) {
|
||||
const loop = edgeLoopOf(this.cage, picked[0][0], picked[0][1], true) ?? [];
|
||||
if (loop.length > 1) {
|
||||
const loopSharp = loop.every((e) => sharp.has(key(e)));
|
||||
items.push({
|
||||
type: "button",
|
||||
label: loopSharp ? "Smooth loop" : "Sharp loop",
|
||||
icon: "chamfer",
|
||||
onClick: () => {
|
||||
const drop = new Set(loop.map(key));
|
||||
this.setCreases(loopSharp ? (this.cage.creases ?? []).filter((e) => !drop.has(key(e))) : [...(this.cage.creases ?? []), ...loop]);
|
||||
this.app.ui.toast(loopSharp ? "Smooth again" : `Sharp all the way along (${loop.length} edges)`);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (edges.length === 1 && !faces && !this.placing) {
|
||||
items.push({ type: "button", label: "Add edge loop", icon: "splitLine", onClick: () => this.addEdgeLoop(edges[0].e) });
|
||||
// (The other way: the loop this edge is part of taken out, the faces either side of it made one.)
|
||||
if (removeEdgeLoop(this.cage, edges[0].e[0], edges[0].e[1]))
|
||||
items.push({
|
||||
type: "button",
|
||||
label: "Remove edge loop",
|
||||
icon: "trash",
|
||||
onClick: () => {
|
||||
const r = removeEdgeLoop(this.cage, edges[0].e[0], edges[0].e[1]);
|
||||
if (!r) return this.app.ui.toast("That loop cannot be taken out");
|
||||
this.changeCage(r, []);
|
||||
this.app.ui.toast("Edge loop removed - the faces either side of it are one");
|
||||
},
|
||||
});
|
||||
}
|
||||
// Rim edges of holes picked: one hole → Fill, two facing holes → Bridge.
|
||||
// (Not while the whole shape is being placed: then every point is picked.)
|
||||
const loops = this.placing ? [] : this.pickedLoops();
|
||||
if (loops.length === 1) items.push({ type: "button", label: "Fill hole", icon: "fill", onClick: () => this.fillHoles(loops) });
|
||||
if (loops.length === 2) items.push({ type: "button", label: "Bridge holes", icon: "loft", onClick: () => this.fillHoles(loops) });
|
||||
// Two runs of border edges (two edges, two rows): a strip of faces between them.
|
||||
else {
|
||||
{
|
||||
const runs = this.placing ? [] : this.pickedRuns();
|
||||
if (runs.length === 2 && !runs.every((r) => r.closed)) items.push({ type: "button", label: "Connect edges", icon: "loft", onClick: () => this.connectRuns(runs) });
|
||||
}
|
||||
@@ -439,7 +576,13 @@ export class FreeformTool implements Tool {
|
||||
if (!isClosed(this.cage)) {
|
||||
items.push(
|
||||
{ type: "number", label: "Thickness", value: this.thickness, kind: "length", min: 0, onInput: (v) => ((this.thickness = Math.max(0, v)), this.panelHint()) },
|
||||
{ type: "choice", options: [{ id: "up", label: "Up" }, { id: "down", label: "Down" }, { id: "both", label: "Symmetric" }], value: this.thickSide, onChange: (v) => ((this.thickSide = v as typeof this.thickSide), this.panel()) },
|
||||
{ type: "choice", options: [{ id: "up", label: "Up" }, { id: "down", label: "Down" }, { id: "both", label: "Symmetric" }], value: this.thickSide, onChange: (v) => {
|
||||
this.thickSide = v as typeof this.thickSide;
|
||||
// A side picked with no thickness yet makes it solid (2 thick), not nothing.
|
||||
if (!(this.thickness > 0)) this.thickness = 2;
|
||||
this.panel();
|
||||
},
|
||||
},
|
||||
// Or solid down to a plane (no thickness): finish the surface, then pick the plane.
|
||||
{
|
||||
type: "button",
|
||||
@@ -478,7 +621,7 @@ export class FreeformTool implements Tool {
|
||||
options: FACE_GRIDS.map((n) => ({ id: String(n), label: String(n) })),
|
||||
value: String(f.feature.grid ?? ""),
|
||||
onChange: (v) => {
|
||||
const laid = layFaceCage(f.tris, f.feature.face.center, f.feature.face.normal, Number(v));
|
||||
const laid = layFaceCage(f.tris, f.feature.face.center, faceStepNormal(f.feature), Number(v), !!f.feature.more?.length);
|
||||
if (!laid) return this.app.ui.toast("This face's outline won't take a grid that fine");
|
||||
const moved = !this.flat();
|
||||
f.feature.grid = laid.n;
|
||||
@@ -507,6 +650,12 @@ export class FreeformTool implements Tool {
|
||||
/** Is every cage point still on the face's plane (nothing shaped)? */
|
||||
private flat(): boolean {
|
||||
const f = this.face!.feature.face;
|
||||
// Several faces (a new step): every point still on them.
|
||||
const more = this.face!.feature.more;
|
||||
if (more?.length) {
|
||||
const n = faceStepNormal(this.face!.feature);
|
||||
return !this.face!.existing && this.cage.verts.every((v) => Math.abs(toFaces(v, n, this.face!.tris) ?? 1) < 1e-6);
|
||||
}
|
||||
return this.cage.verts.every((v) => Math.abs(dot(sub(v, f.center), f.normal)) < 1e-9);
|
||||
}
|
||||
|
||||
@@ -519,9 +668,8 @@ export class FreeformTool implements Tool {
|
||||
/** The body previewed with the face shaped as the cage is now. */
|
||||
private previewFace(): void {
|
||||
const draft = this.faceDraft();
|
||||
const list = [...this.app.store.features];
|
||||
const k = list.findIndex((x) => x.id === draft.id);
|
||||
if (k >= 0) list[k] = draft;
|
||||
let list = [...this.app.store.features];
|
||||
if (this.face?.existing) list = this.withEdit(draft.id, { cage: draft.cage, grid: draft.grid, ...(draft.more ? { more: draft.more } : {}) });
|
||||
else list.push(draft);
|
||||
void this.app.preview(list).then((r) => {
|
||||
if (!r || this.gone) return;
|
||||
@@ -539,8 +687,17 @@ export class FreeformTool implements Tool {
|
||||
private pickedLoops(): number[][] {
|
||||
const verts = new Set(this.selectedVerts());
|
||||
const chosen = new Set<string>();
|
||||
for (const [a, b] of boundaryEdges(this.cage)) if (verts.has(a) && verts.has(b)) chosen.add(cageEdgeKey(a, b));
|
||||
return chosen.size ? holeLoops(this.cage, chosen) : [];
|
||||
const border = boundaryEdges(this.cage);
|
||||
for (const [a, b] of border) if (verts.has(a) && verts.has(b)) chosen.add(cageEdgeKey(a, b));
|
||||
if (!chosen.size) return [];
|
||||
// One edge of a hole's rim is enough: the hole is the whole rim it is on. (It took every edge of the rim picked,
|
||||
// which nothing said - one edge tapped offered only Add edge loop.)
|
||||
// (A hole, not a sheet's own outline: that is most of the sheet's points, and "filling" it would lay a second
|
||||
// face over the whole sheet. An outline with every edge picked is still taken, as before.)
|
||||
const exact = holeLoops(this.cage, chosen);
|
||||
const all = holeLoops(this.cage, new Set(border.map(([a, b]) => cageEdgeKey(a, b))));
|
||||
const whole = all.filter((loop) => loop.length * 2 <= this.cage.verts.length && loop.some((a, k) => chosen.has(cageEdgeKey(a, loop[(k + 1) % loop.length]))));
|
||||
return [...whole, ...exact.filter((l) => !whole.some((w) => w.length === l.length && w.every((x) => l.includes(x))))];
|
||||
}
|
||||
|
||||
/** Picked border edges grouped into runs (edges picked, or the points along them). */
|
||||
@@ -559,7 +716,7 @@ export class FreeformTool implements Tool {
|
||||
const next = bridgeChains(this.cage, runs[0], runs[1]);
|
||||
if (!next) return this.app.ui.toast("These edges can't be connected (they touch each other)");
|
||||
this.remember();
|
||||
this.cage = next;
|
||||
this.cage = carryCreases(this.cage, next);
|
||||
this.picks = [];
|
||||
this.rebuild();
|
||||
this.selectionChanged();
|
||||
@@ -569,7 +726,7 @@ export class FreeformTool implements Tool {
|
||||
/** A cage change: the new cage, what's picked after it, and a fresh preview. */
|
||||
private changeCage(next: Cage, picks: Pick[]): void {
|
||||
this.remember();
|
||||
this.cage = next;
|
||||
this.cage = carryCreases(this.cage, next);
|
||||
this.picks = picks;
|
||||
this.rebuild();
|
||||
this.selectionChanged();
|
||||
@@ -595,7 +752,7 @@ export class FreeformTool implements Tool {
|
||||
const q = this.cage.faces[picked[0]].map((v) => this.cage.verts[v]);
|
||||
const size = (len(sub(q[0], q[2])) + len(sub(q[1], q[3]))) / 2 / Math.SQRT2;
|
||||
this.startLive({ kind: "sweep", base: this.cage, face: picked[0], steps: 4, length: Math.round(size * 2), bend: 0, taper: 1, size });
|
||||
this.app.ui.toast("Pulled out - Length, Bend and Taper in the card shape it (a spout: bend it up)");
|
||||
this.app.ui.toast("Pulled out - Length, Bend and Taper on the line at the bottom shape it (a spout: bend it up)");
|
||||
return;
|
||||
}
|
||||
const out = extrudeFaces(this.cage, this.pickedFaces(), this.edgeSize() * 0.4);
|
||||
@@ -634,7 +791,7 @@ export class FreeformTool implements Tool {
|
||||
// Facing each other (a tunnel): straight across.
|
||||
const same = dot(this.faceNormalOf(a), this.faceNormalOf(b)) > 0.3;
|
||||
this.startLive({ kind: "bridge", base: this.cage, fa: a, fb: b, arch: same ? Math.round(span * 0.9) : 0, segments: same ? 6 : 1, span });
|
||||
this.app.ui.toast(same ? "Bridged into a handle - Arch in the card sets how far it reaches out" : "Bridged - the two faces are joined by a tube");
|
||||
this.app.ui.toast(same ? "Bridged into a handle - Arch on the line at the bottom sets how far it reaches out" : "Bridged - the two faces are joined by a tube");
|
||||
}
|
||||
|
||||
private faceNormalOf(f: number): Vec3 {
|
||||
@@ -681,7 +838,8 @@ export class FreeformTool implements Tool {
|
||||
if (!next) this.app.ui.toast("That would twist the handle - try less arch or more segments");
|
||||
}
|
||||
if (!next) return false;
|
||||
this.cage = next;
|
||||
// (A live step is made again from the cage it began on: that one's sharp edges, each time.)
|
||||
this.cage = "base" in l ? carryCreases(l.base, next) : next;
|
||||
this.picks = picks;
|
||||
this.rebuild();
|
||||
this.placeGimbal();
|
||||
@@ -711,7 +869,6 @@ export class FreeformTool implements Tool {
|
||||
private liveItems(): PanelItem[] {
|
||||
const l = this.live;
|
||||
if (!l) return [];
|
||||
const mm = (v: number) => fmtLen(v);
|
||||
if (l.kind === "sheet")
|
||||
return [
|
||||
{ type: "number", label: "Width", value: l.size[0], kind: "length", min: 0.01, onInput: (v) => (this.setLive({ size: [v, l.size[1]] as unknown as Vec3 }), this.frameSoon()) },
|
||||
@@ -735,7 +892,11 @@ export class FreeformTool implements Tool {
|
||||
{ type: "number", label: round ? "Diameter" : "Width", value: l.size[0], kind: "length", min: 0.01, onInput: (v) => (this.setLive({ size: round ? [v, v, l.prim === "sphere" ? v : l.size[2]] : [v, l.size[1], l.size[2]] }), this.frameSoon()) },
|
||||
];
|
||||
if (l.prim === "box") out.push({ type: "number", label: "Depth", value: l.size[1], kind: "length", min: 0.01, onInput: (v) => (this.setLive({ size: [l.size[0], v, l.size[2]] }), this.frameSoon()) });
|
||||
if (l.prim !== "sphere") {
|
||||
// A ring: how thick its tube is, and how many faces round the tube.
|
||||
if (l.prim === "torus") {
|
||||
out.push({ type: "number", label: "Thickness", value: l.size[2], kind: "length", min: 0.01, onInput: (v) => (this.setLive({ size: [l.size[0], l.size[1], Math.min(v, l.size[0] * 0.98)] }), this.frameSoon()) });
|
||||
out.push({ type: "slider", label: "Rows", value: l.rows, min: 2, max: 6, step: 1, onInput: (v) => this.setLive({ rows: v }) });
|
||||
} else if (l.prim !== "sphere") {
|
||||
out.push({ type: "number", label: "Height", value: l.size[2], kind: "length", min: 0.01, onInput: (v) => (this.setLive({ size: [l.size[0], l.size[1], v] }), this.frameSoon()) });
|
||||
out.push({ type: "slider", label: l.prim === "box" ? "Faces" : "Rows", value: l.rows, min: 1, max: 8, step: 1, onInput: (v) => this.setLive({ rows: v }) });
|
||||
}
|
||||
@@ -743,14 +904,17 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
if (l.kind === "sweep")
|
||||
return [
|
||||
{ type: "slider", label: "Length", value: l.length, min: Math.max(1, Math.round(l.size * 0.2)), max: Math.round(l.size * 10), step: 1, show: mm, onInput: (v) => this.setLive({ length: v }) },
|
||||
// (A length like any other: typed and shown in the unit in use. As a slider it was typed in millimetres
|
||||
// whatever the unit, and stopped at ten times the face's size.)
|
||||
{ type: "number", label: "Length", value: l.length, kind: "length", min: 0.01, onInput: (v) => this.setLive({ length: v }) },
|
||||
{ type: "slider", label: "Bend", value: l.bend, min: -150, max: 150, step: 1, show: (v) => `${v}°`, onInput: (v) => this.setLive({ bend: v }) },
|
||||
{ type: "slider", label: "Taper", value: l.taper, min: 0.2, max: 2.5, step: 0.05, show: (v) => `${v.toFixed(2)}×`, onInput: (v) => this.setLive({ taper: v }) },
|
||||
{ type: "slider", label: "Steps", value: l.steps, min: 1, max: 12, step: 1, onInput: (v) => this.setLive({ steps: v }) },
|
||||
];
|
||||
if (l.kind === "inset") return [{ type: "slider", label: "Inset", value: l.amount, min: 0.05, max: 0.9, step: 0.01, show: (v) => `${Math.round(v * 100)}%`, onInput: (v) => this.setLive({ amount: v }) }];
|
||||
// (In percent, as it is shown: typed as a number it was taken as a fraction - 40 gave 90 %, the most there is.)
|
||||
if (l.kind === "inset") return [{ type: "slider", label: "Inset", value: Math.round(l.amount * 100), min: 5, max: 90, step: 1, show: (v) => `${Math.round(v)}%`, onInput: (v) => this.setLive({ amount: v / 100 }) }];
|
||||
return [
|
||||
{ type: "slider", label: "Arch", value: l.arch, min: 0, max: Math.round(l.span * 3), step: 1, show: mm, onInput: (v) => this.setLive({ arch: v, segments: v > 0 && l.segments < 2 ? 6 : l.segments }) },
|
||||
{ type: "number", label: "Arch", value: l.arch, kind: "length", min: 0, onInput: (v) => this.setLive({ arch: v, segments: v > 0 && l.segments < 2 ? 6 : l.segments }) },
|
||||
{ type: "slider", label: "Segments", value: l.segments, min: 1, max: 12, step: 1, onInput: (v) => this.setLive({ segments: v }) },
|
||||
];
|
||||
}
|
||||
@@ -762,6 +926,7 @@ export class FreeformTool implements Tool {
|
||||
this.remember();
|
||||
this.cage = deleteFaces(this.cage, faces);
|
||||
this.picks = [];
|
||||
this.hovered = null;
|
||||
this.rebuild();
|
||||
this.selectionChanged();
|
||||
this.panelHint();
|
||||
@@ -798,7 +963,7 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
if (!next) return this.app.ui.toast(loops.length === 2 ? "Bridging needs two holes with the same number of edges" : "That hole can't be filled");
|
||||
this.remember();
|
||||
this.cage = next;
|
||||
this.cage = carryCreases(this.cage, next);
|
||||
this.picks = [];
|
||||
this.rebuild();
|
||||
this.selectionChanged();
|
||||
@@ -958,7 +1123,7 @@ export class FreeformTool implements Tool {
|
||||
this.setSymmetry(scale(add(a, b), 0.5), sub(b, a));
|
||||
return;
|
||||
}
|
||||
return this.app.ui.toast("Tap a cage edge (the mirror goes across its middle), or pick X / Y / Z in the card");
|
||||
return this.app.ui.toast("Tap a cage edge (the mirror goes across its middle), or pick X / Y / Z under Symmetry on the line at the bottom");
|
||||
}
|
||||
if (this.choosingPlane) {
|
||||
const at = this.planeAt(p);
|
||||
@@ -1066,7 +1231,11 @@ export class FreeformTool implements Tool {
|
||||
this.gimbal = null;
|
||||
return;
|
||||
}
|
||||
this.gimbal ??= new Gimbal(this.app.view, { axes: this.axes });
|
||||
// Move: the arrows and planes; Turn: the rings; Scale: the cube-ended handles and the middle.
|
||||
if (this.gimbal && this.gimbalFor !== this.xform) (this.gimbal.dispose(), (this.gimbal = null));
|
||||
this.gimbalFor = this.xform;
|
||||
const parts = this.xform === "turn" ? (q: GimbalPart) => q.kind === "ring" : this.xform === "scale" ? SCALE_PARTS : (q: GimbalPart) => q.kind !== "ring";
|
||||
this.gimbal ??= new Gimbal(this.app.view, { axes: this.axes, parts, cubes: this.xform === "scale" });
|
||||
this.gimbal.setCenter(this.centroid(ids));
|
||||
}
|
||||
|
||||
@@ -1109,11 +1278,33 @@ export class FreeformTool implements Tool {
|
||||
const center = part.kind === "ring" && ids.length === 1 ? this.centroid(this.cage.verts.map((_, i) => i)) : this.gimbal.origin;
|
||||
this.remember();
|
||||
this.fieldBase = null;
|
||||
this.dragging = { part, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center, d: [0, 0, 0], ang: 0 };
|
||||
// (Scale: the press's distance from the middle on screen is "as it is" for this drag.)
|
||||
const c = this.app.view.toScreen(this.gimbal.origin);
|
||||
const r0 = c ? Math.max(24, Math.hypot(p.x - c[0], p.y - c[1])) : 60;
|
||||
this.dragging = { part, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center, d: [0, 0, 0], ang: 0, k: [1, 1, 1], r0, soft: this.softWeights(ids, this.cage.verts) };
|
||||
this.gimbal.setHot(part);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A picked face pressed and dragged by itself (not by the gimbal): pushed in
|
||||
* or pulled out along its own normal - several picked: along their average.
|
||||
* (As everywhere else on the model: the thing picked is dragged.)
|
||||
*/
|
||||
dragStart(p: ToolPointer): boolean {
|
||||
if (this.dragging || this.choosingPlane || this.symPicking || this.placing || (this.live && this.live.kind !== "shape" && this.live.kind !== "sheet")) return false;
|
||||
const hit = this.pickAt(p);
|
||||
const faces = this.picks.filter((x): x is Extract<Pick, { kind: "face" }> => x.kind === "face");
|
||||
if (hit?.kind !== "face" || !faces.some((x) => x.f === hit.f)) return false;
|
||||
const n = norm(faces.reduce((s, x) => add(s, this.faceNormalOf(x.f)), [0, 0, 0] as Vec3));
|
||||
if (len(n) < 0.5) return false;
|
||||
const ids = this.selectedVerts();
|
||||
this.remember();
|
||||
this.fieldBase = null;
|
||||
this.dragging = { part: { kind: "axis", i: 2 }, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center: this.centroid(ids), d: [0, 0, 0], ang: 0, k: [1, 1, 1], r0: 60, along: n, soft: this.softWeights(ids, this.cage.verts) };
|
||||
return true;
|
||||
}
|
||||
|
||||
drag(p: ToolPointer): void {
|
||||
const dr = this.dragging;
|
||||
if (!dr) return;
|
||||
@@ -1123,6 +1314,21 @@ export class FreeformTool implements Tool {
|
||||
const step = niceStep(view.cam.worldPerPixel(view.height) * 4);
|
||||
const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step);
|
||||
const part = dr.part;
|
||||
if (dr.along) {
|
||||
const d = snap(axisDrag(view, dr.center, dr.along, dr.from, p));
|
||||
this.apply(scale(dr.along, d), 0);
|
||||
this.boxAt(p, fmtLen(d));
|
||||
return;
|
||||
}
|
||||
if (this.xform === "scale" && (part.kind === "axis" || part.kind === "center")) {
|
||||
const c = view.toScreen(dr.center);
|
||||
if (!c) return;
|
||||
let f = part.kind === "axis" ? (dr.r0 + axisDrag(view, dr.center, this.axes[part.i], dr.from, p) / view.cam.worldPerPixel(view.height)) / dr.r0 : Math.hypot(p.x - c[0], p.y - c[1]) / dr.r0;
|
||||
f = Math.max(0.01, p.shift ? f : Math.round(f * 100) / 100);
|
||||
this.scaleBy(part.kind === "axis" ? ([0, 1, 2].map((i) => (i === part.i ? f : 1)) as Vec3) : [f, f, f]);
|
||||
this.boxAt(p, `×${f.toFixed(2)}`);
|
||||
return;
|
||||
}
|
||||
if (part.kind === "axis") {
|
||||
const dir = this.axes[part.i];
|
||||
const d = snap(axisDrag(view, dr.center, dir, dr.from, p));
|
||||
@@ -1151,6 +1357,21 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
}
|
||||
|
||||
/** Scale the selected points from where the drag began, about the gimbal's middle, by k along its three axes. */
|
||||
private scaleBy(k: Vec3): void {
|
||||
const dr = this.dragging;
|
||||
if (!dr) return;
|
||||
dr.k = k;
|
||||
const ids = this.selectedVerts();
|
||||
for (const i of ids) {
|
||||
const v = sub(dr.base[i], dr.center);
|
||||
this.cage.verts[i] = this.axes.reduce((q, a, j) => add(q, scale(a, dot(v, a) * k[j])), dr.center);
|
||||
}
|
||||
this.mirrorMoved(ids);
|
||||
this.gimbal?.setCenter(this.centroid(ids));
|
||||
this.rebuild();
|
||||
}
|
||||
|
||||
/** Move the selected points from where the drag began: translate d, then turn `deg` about the gimbal axis. */
|
||||
private apply(d: Vec3, deg: number): void {
|
||||
const dr = this.dragging;
|
||||
@@ -1170,7 +1391,9 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
this.cage.verts[i] = add(q, d);
|
||||
}
|
||||
this.mirrorMoved(ids);
|
||||
// (The points round them go along with a move, by their share - not with a turn.)
|
||||
const soft = dr.soft?.size && !deg ? this.softened(dr.soft, d, dr.base) : [];
|
||||
this.mirrorMoved([...ids, ...soft]);
|
||||
this.gimbal?.setCenter(this.centroid(ids));
|
||||
this.rebuild();
|
||||
}
|
||||
@@ -1258,7 +1481,7 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
|
||||
up(): void {
|
||||
const moved = !!this.dragging && (len(this.dragging.d) > 0 || this.dragging.ang !== 0);
|
||||
const moved = !!this.dragging && (len(this.dragging.d) > 0 || this.dragging.ang !== 0 || this.dragging.k.some((x) => x !== 1));
|
||||
const from = this.dragging?.from;
|
||||
// A press on the gimbal that moved nothing isn't a step to undo…
|
||||
if (this.dragging && !moved) (this.past.pop(), this.app.refreshUndo());
|
||||
@@ -1296,6 +1519,13 @@ export class FreeformTool implements Tool {
|
||||
if (!dr) return null;
|
||||
const part = dr.part;
|
||||
const dragDir = norm(dr.d);
|
||||
if (this.xform === "scale" && (part.kind === "axis" || part.kind === "center"))
|
||||
return {
|
||||
kind: "number",
|
||||
apply: (v) => v > 0 && this.scaleBy(part.kind === "axis" ? ([0, 1, 2].map((i) => (i === part.i ? v : 1)) as Vec3) : [v, v, v]),
|
||||
commit: () => this.up(),
|
||||
cancel: () => this.scaleBy([1, 1, 1]),
|
||||
};
|
||||
return {
|
||||
kind: part.kind === "ring" ? "angle" : "length",
|
||||
apply: (v) => {
|
||||
@@ -1330,12 +1560,68 @@ export class FreeformTool implements Tool {
|
||||
if (!this.fieldBase) {
|
||||
this.remember();
|
||||
this.fieldBase = new Map(ids.map((i) => [i, [...this.cage.verts[i]] as Vec3]));
|
||||
this.fieldSoft = this.softWeights(ids, this.cage.verts);
|
||||
this.fieldSoftBase = this.cage.verts.map((p) => [...p] as Vec3);
|
||||
}
|
||||
this.fieldVals[k] = v;
|
||||
if (this.xform === "place") return;
|
||||
const base = [...this.fieldBase];
|
||||
const moved = moveTurnScale(base.map(([, p]) => p), this.xform, this.fieldVals as [number, number, number, number]);
|
||||
base.forEach(([i], n) => (this.cage.verts[i] = moved[n]));
|
||||
this.mirrorMoved(base.map(([i]) => i));
|
||||
const soft = this.xform === "move" ? this.softened(this.fieldSoft, [this.fieldVals[0], this.fieldVals[1], this.fieldVals[2]]) : [];
|
||||
this.mirrorMoved([...base.map(([i]) => i), ...soft]);
|
||||
this.rebuild();
|
||||
this.placeGimbal();
|
||||
}
|
||||
|
||||
/** The cage's sharp edges set to these (a step to undo). */
|
||||
private setCreases(list: [number, number][]): void {
|
||||
this.remember();
|
||||
this.cage = withCreases(this.cage, list);
|
||||
this.rebuild();
|
||||
this.panel();
|
||||
}
|
||||
|
||||
/** The points round the picked ones that go along with a move, each with how much of it (see Soft). */
|
||||
private fieldSoft = new Map<number, number>();
|
||||
private fieldSoftBase: Vec3[] = [];
|
||||
|
||||
/** How much of a move each unpicked point within the Soft distance of a picked one takes: 1 beside it, 0 at that distance. */
|
||||
private softWeights(ids: number[], verts: Vec3[]): Map<number, number> {
|
||||
const out = new Map<number, number>();
|
||||
if (!(softRadius > 0) || this.face) return out;
|
||||
const picked = new Set(ids);
|
||||
for (let j = 0; j < verts.length; j++) {
|
||||
if (picked.has(j)) continue;
|
||||
let d = Infinity;
|
||||
for (const i of ids) d = Math.min(d, len(sub(verts[j], verts[i])));
|
||||
if (d >= softRadius) continue;
|
||||
const u = 1 - (d / softRadius) ** 2;
|
||||
out.set(j, u * u);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Move the soft points by their share of `d` from where they were; those moved. */
|
||||
private softened(weights: Map<number, number>, d: Vec3, base: Vec3[] = this.fieldSoftBase): number[] {
|
||||
for (const [j, w] of weights) if (base[j]) this.cage.verts[j] = add(base[j], scale(d, w));
|
||||
return [...weights.keys()];
|
||||
}
|
||||
|
||||
/** The picked points put where their middle is at `v` on axis `k` (X, Y or Z from the origin). */
|
||||
private placeAt(k: number, v: number): void {
|
||||
const ids = this.selectedVerts();
|
||||
if (!ids.length || !Number.isFinite(v)) return;
|
||||
if (!this.fieldBase) {
|
||||
this.remember();
|
||||
this.fieldBase = new Map(ids.map((i) => [i, [...this.cage.verts[i]] as Vec3]));
|
||||
}
|
||||
const d: Vec3 = [0, 0, 0];
|
||||
d[k] = v - this.centroid(ids)[k];
|
||||
for (const i of ids) this.cage.verts[i] = add(this.cage.verts[i], d);
|
||||
const soft = this.softWeights(ids, this.cage.verts);
|
||||
for (const [j, w] of soft) this.cage.verts[j] = add(this.cage.verts[j], scale(d, w));
|
||||
this.mirrorMoved([...ids, ...soft.keys()]);
|
||||
this.rebuild();
|
||||
this.placeGimbal();
|
||||
}
|
||||
@@ -1451,14 +1737,17 @@ export class FreeformTool implements Tool {
|
||||
const seg = (ps: Pick[]) =>
|
||||
ps.flatMap((p) => {
|
||||
const V = this.cage.verts;
|
||||
if (p.kind === "edge") return [...V[p.e[0]], ...V[p.e[1]]];
|
||||
// (A pick of a part the cage no longer has - a face just deleted: nothing to mark.)
|
||||
if (p.kind === "edge") return V[p.e[0]] && V[p.e[1]] ? [...V[p.e[0]], ...V[p.e[1]]] : [];
|
||||
if (p.kind === "face") {
|
||||
const f = this.cage.faces[p.f];
|
||||
if (!f) return [];
|
||||
return f.flatMap((i, k) => [...V[i], ...V[f[(k + 1) % 4]]]);
|
||||
}
|
||||
return [];
|
||||
});
|
||||
const pts = (ps: Pick[]) => ps.flatMap((p) => (p.kind === "vert" ? [...this.cage.verts[p.i]] : []));
|
||||
const pts = (ps: Pick[]) => ps.flatMap((p) => (p.kind === "vert" && this.cage.verts[p.i] ? [...this.cage.verts[p.i]] : []));
|
||||
setLines(this.creaseLines, (this.cage.creases ?? []).flatMap(([a, b]) => (this.cage.verts[a] && this.cage.verts[b] ? [...this.cage.verts[a], ...this.cage.verts[b]] : [])));
|
||||
setLines(this.marks, seg(this.picks));
|
||||
setPositions(this.markDots, pts(this.picks));
|
||||
const h = this.hovered ? [this.hovered] : [];
|
||||
@@ -1466,7 +1755,7 @@ export class FreeformTool implements Tool {
|
||||
setPositions(this.hoverDots, pts(h));
|
||||
// Picked faces filled (two triangles each).
|
||||
const fill = this.picks.flatMap((p) => {
|
||||
if (p.kind !== "face") return [];
|
||||
if (p.kind !== "face" || !this.cage.faces[p.f]) return [];
|
||||
const [a, b, c, d] = this.cage.faces[p.f].map((i) => this.cage.verts[i]);
|
||||
return [...a, ...b, ...c, ...a, ...c, ...d];
|
||||
});
|
||||
@@ -1518,13 +1807,13 @@ export class FreeformTool implements Tool {
|
||||
}
|
||||
const f = this.faceDraft();
|
||||
// A new step that shapes nothing: no step at all.
|
||||
if (this.face.existing) this.app.store.update(f.id, { cage: f.cage, grid: f.grid } as Partial<FaceFreeformFeature>);
|
||||
else if (!this.flat()) this.app.store.add(f);
|
||||
if (this.face.existing) this.saveEdit(f.id, { cage: f.cage, grid: f.grid, ...(f.more ? { more: f.more } : {}) });
|
||||
else if (!this.flat() || f.more?.length) this.app.store.add(f); // (several faces: made one smooth surface even as laid)
|
||||
this.app.setTool(null);
|
||||
return f.face.body;
|
||||
}
|
||||
// Stored where it was made: later move steps in History still apply on top.
|
||||
const cage = { faces: structuredClone(this.cage.faces), verts: this.cage.verts.map(this.place.inv) };
|
||||
const cage = { faces: structuredClone(this.cage.faces), verts: this.cage.verts.map(this.place.inv), ...(this.cage.creases?.length ? { creases: structuredClone(this.cage.creases) } : {}) };
|
||||
const open = !isClosed(cage);
|
||||
const symmetry = this.sym ? (() => {
|
||||
const o = this.place.inv(this.sym!.origin);
|
||||
@@ -1534,12 +1823,14 @@ export class FreeformTool implements Tool {
|
||||
let id: string;
|
||||
if (this.existing) {
|
||||
id = this.existing.id;
|
||||
this.app.store.update(id, { cage, ...extra } as Partial<FreeformFeature>);
|
||||
this.saveEdit(id, { cage, ...extra });
|
||||
} else {
|
||||
const f: FreeformFeature = { ...this.app.store.newIdentity("freeform", isClosed(cage) ? "Freeform" : "Freeform surface"), type: "freeform", cage, ...extra };
|
||||
this.app.store.add(f);
|
||||
id = f.id;
|
||||
}
|
||||
// Left open with no thickness: a surface, which nothing solid can be done with - said as it is made, with the ways on.
|
||||
if (open && !(this.thickness > 0)) this.app.ui.toast("This is an open surface, not a solid yet. Edit Freeform to give it a Thickness or fill its hole - or Fill to Plane.");
|
||||
this.app.setTool(null);
|
||||
return id;
|
||||
}
|
||||
@@ -1585,6 +1876,7 @@ export class FreeformTool implements Tool {
|
||||
if (doomed.size >= this.cage.faces.length) return this.app.ui.toast("At least one face has to stay");
|
||||
this.cage = deleteFaces(this.cage, [...doomed]);
|
||||
this.picks = [];
|
||||
this.hovered = null;
|
||||
this.rebuild();
|
||||
this.selectionChanged();
|
||||
this.app.ui.toast("The shape is no longer closed: give it a Thickness to make a solid, or Done for a surface.");
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
// A look ahead, drawn on the model in dashed yellow: what a tool would do to
|
||||
// what is picked, shown while the pointer is over the tool (before anything
|
||||
// is started) - a face's outline lifted for Extrude, the lines a round would
|
||||
// run between for Fillet, a row of boxes for a pattern. Nothing is computed
|
||||
// by the kernel for it: it is a sketch of the change, from what the view
|
||||
// already has, so it comes up at once.
|
||||
|
||||
import { BufferGeometry, Float32BufferAttribute, LineDashedMaterial, LineSegments } from "three";
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { add, cross, dot, len, norm, scale, sub, toWorld } from "../geom";
|
||||
import { entityPolylines } from "../sketch/curves";
|
||||
import type { Viewport } from "../view/viewport";
|
||||
import { edgesOfFace, sourceFrame, sourcesOf, type AppContext, type Sel } from "./tool";
|
||||
|
||||
const YELLOW = 0xffd23a;
|
||||
|
||||
/** Line segments (pairs of points, flat) in dashed yellow, over everything. Dashes keep their size on screen. */
|
||||
export class Ghost {
|
||||
private mat = new LineDashedMaterial({ color: YELLOW, depthTest: false, transparent: true, opacity: 0.95, dashSize: 1, gapSize: 1 });
|
||||
private line = new LineSegments(new BufferGeometry(), this.mat);
|
||||
private wpp = 0;
|
||||
private onFrame = () => this.dashes();
|
||||
|
||||
constructor(private view: Viewport, segs: number[]) {
|
||||
this.line.renderOrder = 48;
|
||||
this.line.frustumCulled = false;
|
||||
this.line.geometry.setAttribute("position", new Float32BufferAttribute(segs, 3));
|
||||
this.line.computeLineDistances();
|
||||
this.dashes();
|
||||
view.overlay.add(this.line);
|
||||
view.frameHooks.add(this.onFrame);
|
||||
view.helpers.add(this);
|
||||
view.requestRender();
|
||||
}
|
||||
|
||||
private dashes(): void {
|
||||
const w = this.view.cam.worldPerPixel(this.view.height);
|
||||
if (Math.abs(w - this.wpp) < this.wpp * 0.02) return;
|
||||
this.wpp = w;
|
||||
this.mat.dashSize = w * 7;
|
||||
this.mat.gapSize = w * 5;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.view.helpers.delete(this);
|
||||
this.view.frameHooks.delete(this.onFrame);
|
||||
this.view.overlay.remove(this.line);
|
||||
this.line.geometry.dispose();
|
||||
this.mat.dispose();
|
||||
this.view.requestRender();
|
||||
}
|
||||
}
|
||||
|
||||
type Segs = number[];
|
||||
const seg = (out: Segs, a: Vec3, b: Vec3) => void out.push(a[0], a[1], a[2], b[0], b[1], b[2]);
|
||||
const moved = (segs: Segs, v: Vec3): Segs => segs.map((x, i) => x + v[i % 3]);
|
||||
|
||||
/** The outline of a body's face, as the view drew its edges. */
|
||||
function faceOutline(app: AppContext, body: string, face: number): Segs {
|
||||
const m = app.view.body(body);
|
||||
if (!m) return [];
|
||||
const out: Segs = [];
|
||||
const of = new Set(edgesOfFace(app, body, face));
|
||||
for (const g of m.edgeGroups) if (of.has(g.edge)) for (let j = g.start * 3; j < (g.start + g.count) * 3; j++) out.push(m.edgePositions[j]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The box round some bodies: its twelve edges, and its middle. */
|
||||
export function bodiesBox(app: AppContext, ids: string[]): { lo: Vec3; hi: Vec3; mid: Vec3; segs: Segs } | null {
|
||||
const lo: Vec3 = [Infinity, Infinity, Infinity];
|
||||
const hi: Vec3 = [-Infinity, -Infinity, -Infinity];
|
||||
for (const id of ids) {
|
||||
const p = app.view.body(id)?.positions;
|
||||
if (!p) continue;
|
||||
for (let i = 0; i < p.length; i++) {
|
||||
const k = i % 3;
|
||||
if (p[i] < lo[k]) lo[k] = p[i];
|
||||
if (p[i] > hi[k]) hi[k] = p[i];
|
||||
}
|
||||
}
|
||||
if (!Number.isFinite(lo[0])) return null;
|
||||
const c = (i: number): Vec3 => [i & 1 ? hi[0] : lo[0], i & 2 ? hi[1] : lo[1], i & 4 ? hi[2] : lo[2]];
|
||||
const segs: Segs = [];
|
||||
for (const [a, b] of [[0, 1], [2, 3], [4, 5], [6, 7], [0, 2], [1, 3], [4, 6], [5, 7], [0, 4], [1, 5], [2, 6], [3, 7]]) seg(segs, c(a), c(b));
|
||||
return { lo, hi, mid: scale(add(lo, hi), 0.5), segs };
|
||||
}
|
||||
|
||||
/** A row of copies: the bodies' box again and again along `dir`, and the line they go along. */
|
||||
export function rowGhost(app: AppContext, ids: string[], dir: Vec3, spacing: number, count: number): Segs {
|
||||
const box = bodiesBox(app, ids);
|
||||
if (!box) return [];
|
||||
const d = norm(dir);
|
||||
const out: Segs = [];
|
||||
for (let k = 1; k < count; k++) out.push(...moved(box.segs, scale(d, spacing * k)));
|
||||
seg(out, box.mid, add(box.mid, scale(d, spacing * (count - 1))));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A ring of copies: the bodies' box turned about the axis, and the circle its middle goes round. */
|
||||
export function ringGhost(app: AppContext, ids: string[], axis: { origin: Vec3; dir: Vec3 }, angle: number, count: number): Segs {
|
||||
const box = bodiesBox(app, ids);
|
||||
if (!box) return [];
|
||||
const d = norm(axis.dir);
|
||||
const turn = (p: Vec3, deg: number): Vec3 => {
|
||||
const a = (deg * Math.PI) / 180;
|
||||
const v = sub(p, axis.origin);
|
||||
const along = scale(d, dot(v, d));
|
||||
const flat = sub(v, along);
|
||||
return add(axis.origin, add(along, add(scale(flat, Math.cos(a)), scale(cross(d, flat), Math.sin(a)))));
|
||||
};
|
||||
const full = Math.abs(Math.abs(angle) - 360) < 1e-6;
|
||||
const step = angle / (full ? count : Math.max(1, count - 1));
|
||||
const out: Segs = [];
|
||||
for (let k = 1; k < count; k++) for (let i = 0; i < box.segs.length; i += 3) out.push(...turn([box.segs[i], box.segs[i + 1], box.segs[i + 2]], step * k));
|
||||
// (The circle: only where the bodies are off the axis.)
|
||||
if (len(sub(box.mid, turn(box.mid, 180))) > 1e-6) for (let k = 0; k < 48; k++) seg(out, turn(box.mid, (angle * k) / 48), turn(box.mid, (angle * (k + 1)) / 48));
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the tool `id` would do to what is picked, as dashed lines - or nothing,
|
||||
* where there is no telling picture of it (most tools: those say what they do
|
||||
* by name).
|
||||
*/
|
||||
export function peekSegs(app: AppContext, id: string, sel: Sel[]): Segs {
|
||||
const s = sel[0];
|
||||
if (!s) return [];
|
||||
const out: Segs = [];
|
||||
if (s.kind === "face" && (id === "extrude" || id === "offsetFace" || id === "offset" || id === "shell" || id === "thicken")) {
|
||||
const f = app.view.body(s.body)?.faces[s.face];
|
||||
if (!f) return [];
|
||||
const outline = faceOutline(app, s.body, s.face);
|
||||
// (Out by about a third of the face's size; Shell: in, by a wall.)
|
||||
const d = Math.sqrt(f.area) * (id === "shell" ? -0.12 : 0.35);
|
||||
const v = scale(f.normal, d);
|
||||
out.push(...moved(outline, v));
|
||||
// (Up from the outline's corners - every few points of a round one.)
|
||||
const stride = Math.max(1, Math.floor(outline.length / 6 / 12));
|
||||
for (let i = 0; i < outline.length; i += 6 * stride) seg(out, [outline[i], outline[i + 1], outline[i + 2]], add([outline[i], outline[i + 1], outline[i + 2]], v));
|
||||
return out;
|
||||
}
|
||||
if (s.kind === "profile" && (id === "extrude" || id === "revolve")) {
|
||||
if (id !== "extrude") return [];
|
||||
const src = sourcesOf(app, sel)[0];
|
||||
const plane = app.sketchPlane(s.sketch);
|
||||
if (!src || !plane) return [];
|
||||
const fr = sourceFrame(app, src);
|
||||
const flat: Segs = [];
|
||||
for (const e of app.sketchCurves(s.sketch)) {
|
||||
if (e.construction) continue;
|
||||
for (const poly of entityPolylines(e)) for (let i = 0; i + 1 < poly.length; i++) seg(flat, toWorld(plane, poly[i]), toWorld(plane, poly[i + 1]));
|
||||
}
|
||||
let size = 0;
|
||||
for (let i = 0; i < flat.length; i += 3) size = Math.max(size, len(sub([flat[i], flat[i + 1], flat[i + 2]], fr.base)));
|
||||
const v = scale(fr.normal, Math.max(size * 0.6, 1e-3));
|
||||
out.push(...moved(flat, v));
|
||||
const stride = Math.max(1, Math.floor(flat.length / 6 / 12));
|
||||
for (let i = 0; i < flat.length; i += 6 * stride) seg(out, [flat[i], flat[i + 1], flat[i + 2]], add([flat[i], flat[i + 1], flat[i + 2]], v));
|
||||
return out;
|
||||
}
|
||||
if (s.kind === "edge" && (id === "fillet" || id === "chamfer")) {
|
||||
const m = app.view.body(s.body);
|
||||
if (!m || m.faces.length > 400) return [];
|
||||
for (const one of sel) {
|
||||
if (one.kind !== "edge" || one.body !== s.body) continue;
|
||||
const e = m.edges[one.edge];
|
||||
if (!e || e.type !== "LINE") continue;
|
||||
// The two flat faces the edge is between, and the way into each from the edge.
|
||||
const into: Vec3[] = [];
|
||||
for (let f = 0; f < m.faces.length && into.length < 2; f++) {
|
||||
const face = m.faces[f];
|
||||
if (!face.plane || Math.abs(dot(face.normal, e.dir)) > 1e-3 || Math.abs(dot(sub(e.mid, face.center), face.normal)) > 1e-4) continue;
|
||||
if (!edgesOfFace(app, s.body, f).includes(one.edge)) continue;
|
||||
const side = norm(cross(face.normal, e.dir));
|
||||
into.push(dot(side, sub(face.center, e.mid)) < 0 ? scale(side, -1) : side);
|
||||
}
|
||||
if (into.length < 2) continue;
|
||||
const r = Math.min(e.length * 0.25, Math.sqrt(Math.min(...m.faces.map((x) => x.area))) * 0.5);
|
||||
const a = (p: Vec3) => add(p, scale(into[0], r));
|
||||
const b = (p: Vec3) => add(p, scale(into[1], r));
|
||||
seg(out, a(e.start), a(e.end));
|
||||
seg(out, b(e.start), b(e.end));
|
||||
for (const p of [e.start, e.end]) {
|
||||
if (id === "chamfer") seg(out, a(p), b(p));
|
||||
else {
|
||||
// (The round's end: from one line to the other, bowed towards the edge.)
|
||||
const q = (t: number): Vec3 => add(add(scale(a(p), (1 - t) * (1 - t)), scale(p, 2 * t * (1 - t) * 0.83 + 0)), add(scale(add(a(p), b(p)), t * (1 - t) * 0.17), scale(b(p), t * t)));
|
||||
for (let k = 0; k < 8; k++) seg(out, q(k / 8), q((k + 1) / 8));
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (s.kind === "body" && (id === "patl" || id === "patc")) {
|
||||
const ids = sel.flatMap((x) => (x.kind === "body" ? [x.body] : []));
|
||||
const box = bodiesBox(app, ids);
|
||||
if (!box) return [];
|
||||
if (id === "patl") return rowGhost(app, ids, [1, 0, 0], (box.hi[0] - box.lo[0]) * 1.5 || 10, 3);
|
||||
return ringGhost(app, ids, { origin: [0, 0, 0], dir: [0, 0, 1] }, 360, 6);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -8,7 +8,11 @@ import type { ToolPointer } from "../view/input";
|
||||
// Amber, so a handle never disappears against the blue of a selection.
|
||||
const COLOR = 0xffa31a;
|
||||
const HOT = 0xffd27a;
|
||||
const ARROW_PX = 84;
|
||||
// (Slim and short: a line with a dark edge under it, so it reads over a lit face and over the grid alike, and a
|
||||
// head sized for a finger whatever the arrow's length.)
|
||||
const ARROW_PX = 64;
|
||||
const HEAD_PX = 70;
|
||||
const EDGE = 0x15171b;
|
||||
|
||||
/**
|
||||
* A drag handle drawn at constant screen size: an arrow along a direction, or a
|
||||
@@ -23,16 +27,26 @@ export class Handle {
|
||||
private mat = new MeshBasicMaterial({ color: COLOR, depthTest: false, transparent: true });
|
||||
private head: Mesh;
|
||||
private shaft: LineSegments2 | null = null;
|
||||
/** The dark edge under the shaft. */
|
||||
private under: LineSegments2 | null = null;
|
||||
private underMat: ReturnType<Viewport["lineMaterial"]> | null = null;
|
||||
private lineMat;
|
||||
private onFrame = () => this.layout();
|
||||
|
||||
constructor(private view: Viewport, readonly shape: "arrow" | "dot") {
|
||||
this.lineMat = view.lineMaterial(COLOR, 4);
|
||||
/** `px`: how long an arrow is on screen (a pair back to back - a double arrow - is drawn shorter). */
|
||||
constructor(private view: Viewport, readonly shape: "arrow" | "dot", private px = ARROW_PX) {
|
||||
this.lineMat = view.lineMaterial(COLOR, 3);
|
||||
this.lineMat.transparent = true;
|
||||
this.head = new Mesh(shape === "arrow" ? new ConeGeometry(0.11, 0.3, 20) : new SphereGeometry(0.12, 20, 12), this.mat);
|
||||
this.head = new Mesh(shape === "arrow" ? new ConeGeometry(0.095, 0.3, 24) : new SphereGeometry(0.1, 20, 12), this.mat);
|
||||
this.head.renderOrder = 50;
|
||||
this.group.add(this.head);
|
||||
if (shape === "arrow") {
|
||||
this.underMat = view.lineMaterial(EDGE, 6);
|
||||
this.underMat.transparent = true;
|
||||
this.underMat.opacity = 0.55;
|
||||
this.under = new LineSegments2(new LineSegmentsGeometry(), this.underMat);
|
||||
this.under.renderOrder = 49;
|
||||
this.group.add(this.under);
|
||||
this.shaft = new LineSegments2(new LineSegmentsGeometry(), this.lineMat);
|
||||
this.shaft.renderOrder = 50;
|
||||
this.group.add(this.shaft);
|
||||
@@ -51,7 +65,7 @@ export class Handle {
|
||||
this.mat.color.setHex(on ? HOT : COLOR);
|
||||
if (this.shaft) {
|
||||
this.view.releaseLineMaterial(this.lineMat);
|
||||
this.lineMat = this.view.lineMaterial(on ? HOT : COLOR, on ? 6 : 4);
|
||||
this.lineMat = this.view.lineMaterial(on ? HOT : COLOR, on ? 4.5 : 3);
|
||||
this.lineMat.transparent = true;
|
||||
this.shaft.material = this.lineMat;
|
||||
}
|
||||
@@ -90,16 +104,18 @@ export class Handle {
|
||||
this.view.overlay.remove(this.group);
|
||||
this.head.geometry.dispose();
|
||||
this.shaft?.geometry.dispose();
|
||||
this.under?.geometry.dispose();
|
||||
if (this.underMat) this.view.releaseLineMaterial(this.underMat);
|
||||
this.view.releaseLineMaterial(this.lineMat);
|
||||
this.view.requestRender();
|
||||
}
|
||||
|
||||
private size(): number {
|
||||
return this.view.cam.worldPerPixel(this.view.height) * ARROW_PX;
|
||||
return this.view.cam.worldPerPixel(this.view.height) * this.px;
|
||||
}
|
||||
|
||||
private headScale(): number {
|
||||
return this.size() * (this.hot ? 1.45 : 1);
|
||||
return this.view.cam.worldPerPixel(this.view.height) * HEAD_PX * (this.hot ? 1.3 : 1);
|
||||
}
|
||||
|
||||
private tip(): Vector3 {
|
||||
@@ -113,8 +129,14 @@ export class Handle {
|
||||
const tip = this.tip();
|
||||
this.head.position.copy(tip);
|
||||
this.head.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), this.dir);
|
||||
const start = this.base.clone().addScaledVector(this.dir, s * 0.12);
|
||||
(this.shaft!.geometry as LineSegmentsGeometry).setPositions([...start.toArray(), ...tip.toArray()]);
|
||||
// (From a little off its foot to the head's base; the head's point is the arrow's tip.)
|
||||
const h = this.headScale() * 0.3;
|
||||
this.head.position.copy(tip).addScaledVector(this.dir, -h / 2);
|
||||
const start = this.base.clone().addScaledVector(this.dir, Math.min(s * 0.12, Math.max(0, s - h)));
|
||||
const end = this.base.clone().addScaledVector(this.dir, Math.max(0, s - h));
|
||||
const at = [...start.toArray(), ...end.toArray()];
|
||||
(this.shaft!.geometry as LineSegmentsGeometry).setPositions(at);
|
||||
(this.under!.geometry as LineSegmentsGeometry).setPositions(at);
|
||||
} else {
|
||||
this.head.position.copy(this.base);
|
||||
}
|
||||
|
||||
@@ -154,7 +154,14 @@ export class MeasureTool implements Tool {
|
||||
if (s.kind === "face") {
|
||||
const f = b.faces[s.face];
|
||||
const pts = facePoints(b, s.face);
|
||||
const rows = [{ name: `Surface area · ${niceType(f.type)}`, value: fmtArea(f.area), at: f.center }];
|
||||
const rows: Row[] = [{ name: `Surface area · ${niceType(f.type)}`, value: fmtArea(f.area), at: f.center }];
|
||||
// A round face (a shaft, a hole): its diameter, pinned as a line straight across it.
|
||||
if (f.round) {
|
||||
const r = f.round.r;
|
||||
const across = acrossCylinder(b, s.face, r, f.round.hole, f.center);
|
||||
rows.push({ name: f.round.hole ? "Diameter · hole" : "Diameter", value: `Ø ${fmtLen(2 * r)}`, at: across?.mid ?? f.center, ...(across ? { a: across.a, b: across.b } : {}) });
|
||||
rows.push({ name: "Radius", value: `R ${fmtLen(r)}`, at: across?.b ?? f.center, ...(across ? { a: across.mid, b: across.b } : {}) });
|
||||
}
|
||||
return { rows, anchor: f.center, points: pts, dir: f.plane ? f.normal : undefined };
|
||||
}
|
||||
if (s.kind === "edge") {
|
||||
@@ -211,6 +218,44 @@ function edgePoints(b: BodyMesh, edge: number): Vec3[] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A line straight across a round face, through its axis, level with the
|
||||
* middle of the face: its ends on the surface (null where the face's own
|
||||
* normals can't tell the axis).
|
||||
*/
|
||||
function acrossCylinder(b: BodyMesh, face: number, r: number, hole: boolean, center: Vec3): { a: Vec3; b: Vec3; mid: Vec3 } | null {
|
||||
const g = b.faceGroups.find((x) => x.face === face);
|
||||
if (!g || !g.count) return null;
|
||||
const at = (i: number): { p: Vec3; n: Vec3 } => {
|
||||
const v = b.indices[i] * 3;
|
||||
return { p: [b.positions[v], b.positions[v + 1], b.positions[v + 2]], n: [b.normals[v], b.normals[v + 1], b.normals[v + 2]] };
|
||||
};
|
||||
const first = at(g.start);
|
||||
// The surface's normals all stand square to the axis: two far apart give it.
|
||||
let axis: Vec3 | null = null;
|
||||
let best = 0.2;
|
||||
for (let i = g.start; i < g.start + g.count; i++) {
|
||||
const c = cross(first.n, at(i).n);
|
||||
const l = len(c);
|
||||
if (l > best) {
|
||||
best = l;
|
||||
axis = [c[0] / l, c[1] / l, c[2] / l];
|
||||
}
|
||||
}
|
||||
if (!axis) return null;
|
||||
// (A hole's surface faces its axis, a shaft's away from it.)
|
||||
const k = hole ? r : -r;
|
||||
const onAxis: Vec3 = [first.p[0] + first.n[0] * k, first.p[1] + first.n[1] * k, first.p[2] + first.n[2] * k];
|
||||
const t = dot(sub(center, onAxis), axis);
|
||||
const mid: Vec3 = [onAxis[0] + axis[0] * t, onAxis[1] + axis[1] * t, onAxis[2] + axis[2] * t];
|
||||
const side = dot(first.n, axis);
|
||||
const u0: Vec3 = [first.n[0] - axis[0] * side, first.n[1] - axis[1] * side, first.n[2] - axis[2] * side];
|
||||
const ul = len(u0);
|
||||
if (ul < 1e-9) return null;
|
||||
const u: Vec3 = [u0[0] / ul, u0[1] / ul, u0[2] / ul];
|
||||
return { a: [mid[0] - u[0] * r, mid[1] - u[1] * r, mid[2] - u[2] * r], b: [mid[0] + u[0] * r, mid[1] + u[1] * r, mid[2] + u[2] * r], mid };
|
||||
}
|
||||
|
||||
function closestPair(a: Vec3[], b: Vec3[]): { d: number; p: Vec3; q: Vec3 } {
|
||||
let best = { d: Infinity, p: a[0], q: b[0] };
|
||||
const step = (n: number) => Math.max(1, Math.floor(n / 600));
|
||||
@@ -255,5 +300,5 @@ function fmtVolume(mm3: number): string {
|
||||
}
|
||||
|
||||
function niceType(t: string): string {
|
||||
return t.toLowerCase().replace(/_/g, " ").replace("bspline", "free-form");
|
||||
return t.toLowerCase().replace(/_/g, " ").replace("bspline", "free-form").replace("cylindre", "cylinder");
|
||||
}
|
||||
|
||||
@@ -7,9 +7,14 @@
|
||||
|
||||
import type { PlaneDef, SketchFeature, Vec3 } from "../doc/types";
|
||||
import type { BodyMesh } from "../kernel/protocol";
|
||||
import { len, roundSig, sub } from "../geom";
|
||||
import { add, dot, len, niceStep, norm, roundSig, scale, sub } from "../geom";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
import { fmtLen } from "../units";
|
||||
import type { ToolPointer } from "../view/input";
|
||||
import { DimWidget } from "./annotate";
|
||||
import { DragTyping } from "./dragTyping";
|
||||
import { FeatureOp, type Slot } from "./featureOp";
|
||||
import { axisDrag, Handle } from "./handles";
|
||||
import { offsetLineOnFace } from "./offsetEdgeGeom";
|
||||
import { faceRefOf, type AppContext, type Sel } from "./tool";
|
||||
|
||||
@@ -36,6 +41,13 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
|
||||
private typed = false;
|
||||
/** Why there's no line (the edge across the face, the line off it). */
|
||||
private problem: string | null = null;
|
||||
/** The line as it is now, in the world (the arrow sits on its middle). */
|
||||
private line: { a: Vec3; b: Vec3 } | null = null;
|
||||
/** A double arrow on the line, dragged to set how far from the edge it runs; the distance in a box beside it. */
|
||||
private arrows: [Handle, Handle] | null = null;
|
||||
private dim: DimWidget | null = null;
|
||||
private dragging: { from: ToolPointer; d0: number; foot: Vec3; out: Vec3 } | null = null;
|
||||
private typing = new DragTyping(this.app);
|
||||
|
||||
/** Started from an edge (Offset Edge) or from the face (Offset from Edge): the other is tapped next. */
|
||||
constructor(app: AppContext, start?: { body: string; edge: number }, onFace?: { body: string; face: number }) {
|
||||
@@ -95,6 +107,7 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
|
||||
/** The line from the picks and the distance, into the sketch. */
|
||||
private sync(): void {
|
||||
this.problem = null;
|
||||
this.line = null;
|
||||
if (!this.edge || !this.face) return;
|
||||
const l = offsetLineOnFace(this.face.body, this.face.face, this.face.plane, this.edge.start, this.edge.end, this.distance);
|
||||
if (typeof l === "string") {
|
||||
@@ -103,6 +116,107 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
|
||||
return;
|
||||
}
|
||||
this.feature.entities = [{ id: "offset", kind: "line", a: l.a2, b: l.b2 }];
|
||||
this.line = { a: l.a, b: l.b };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the line's middle is measured from on the edge, and the way a
|
||||
* bigger distance goes (across the face, away from the edge).
|
||||
*/
|
||||
private frame(): { foot: Vec3; out: Vec3 } | null {
|
||||
if (!this.edge || !this.face || !this.line) return null;
|
||||
const n = norm(this.face.plane.normal);
|
||||
const flat = (p: Vec3): Vec3 => sub(p, scale(n, dot(sub(p, this.face!.plane.origin), n)));
|
||||
const e0 = flat(this.edge.start);
|
||||
const along = norm(sub(flat(this.edge.end), e0));
|
||||
const mid = scale(add(this.line.a, this.line.b), 0.5);
|
||||
const foot = add(e0, scale(along, dot(sub(mid, e0), along)));
|
||||
const w = sub(mid, foot);
|
||||
if (len(w) < 1e-9 || !this.distance) return null;
|
||||
return { foot, out: scale(norm(w), Math.sign(this.distance)) };
|
||||
}
|
||||
|
||||
private setDistance(v: number): void {
|
||||
this.typed = true;
|
||||
this.distance = v;
|
||||
this.sync();
|
||||
this.app.ui.updatePanelValues([v]);
|
||||
this.dim?.setValue(v);
|
||||
this.update();
|
||||
}
|
||||
|
||||
/** The double arrow and the value box come up once there is a line. */
|
||||
protected onDraftChanged(): void {
|
||||
const fr = this.dragging ?? this.frame();
|
||||
if (!fr || !this.line) {
|
||||
// (Dragged off the face: they stay where they were, to drag back.)
|
||||
if (!this.dragging) this.dropGrip();
|
||||
return;
|
||||
}
|
||||
if (!this.arrows) {
|
||||
this.arrows = [new Handle(this.app.view, "arrow", 34), new Handle(this.app.view, "arrow", 34)];
|
||||
this.dim = new DimWidget(this.app.view, { boxAt: "beyond", boxGap: 96, dir: fr.out, value: this.distance, onInput: (v) => this.setDistance(v), onCommit: () => this.done() });
|
||||
}
|
||||
const mid = scale(add(this.line.a, this.line.b), 0.5);
|
||||
this.arrows[0].set(mid, fr.out);
|
||||
this.arrows[1].set(mid, scale(fr.out, -1));
|
||||
this.dim!.set(fr.foot, mid);
|
||||
this.dim!.setValue(this.distance);
|
||||
}
|
||||
|
||||
private dropGrip(): void {
|
||||
this.arrows?.forEach((h) => h.dispose());
|
||||
this.arrows = null;
|
||||
this.dim?.dispose();
|
||||
this.dim = null;
|
||||
}
|
||||
|
||||
exit(): void {
|
||||
this.dropGrip();
|
||||
super.exit();
|
||||
}
|
||||
|
||||
hover(p: ToolPointer | null): void {
|
||||
const on = !!p && !!this.arrows && (!!this.dragging || this.arrows.some((h) => h.hit(p)));
|
||||
this.arrows?.forEach((h) => h.setHot(on));
|
||||
if (!on) super.hover(p);
|
||||
}
|
||||
|
||||
down(p: ToolPointer): boolean {
|
||||
const fr = this.frame();
|
||||
if (!fr || !this.arrows?.some((h) => h.hit(p))) return false;
|
||||
this.dragging = { from: p, d0: this.distance, ...fr };
|
||||
return true;
|
||||
}
|
||||
|
||||
drag(p: ToolPointer): void {
|
||||
const dr = this.dragging;
|
||||
if (!dr) return;
|
||||
this.typing.track(p);
|
||||
if (this.typing.active) return;
|
||||
const raw = dr.d0 + axisDrag(this.app.view, add(dr.foot, scale(dr.out, dr.d0)), dr.out, dr.from, p);
|
||||
const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4);
|
||||
this.setDistance(Math.round(raw / step) * step);
|
||||
this.app.ui.setLabel(p.x, p.y, `${fmtLen(this.distance)} · type a value`);
|
||||
}
|
||||
|
||||
up(): void {
|
||||
this.dragging = null;
|
||||
this.typing.reset();
|
||||
this.app.ui.setLabel(0, 0, null);
|
||||
this.arrows?.forEach((h) => h.setHot(false));
|
||||
this.onDraftChanged();
|
||||
}
|
||||
|
||||
dragKey(e: KeyboardEvent): boolean {
|
||||
const dr = this.dragging;
|
||||
if (!dr) return false;
|
||||
return this.typing.key(e, {
|
||||
kind: "length",
|
||||
apply: (v) => this.setDistance(v),
|
||||
commit: () => ((this.dragging = null), this.done()),
|
||||
cancel: () => this.setDistance(dr.d0),
|
||||
});
|
||||
}
|
||||
|
||||
protected ready(): boolean {
|
||||
@@ -120,6 +234,7 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
|
||||
this.typed = true;
|
||||
this.distance = v;
|
||||
this.sync();
|
||||
this.dim?.setValue(v);
|
||||
this.update();
|
||||
},
|
||||
},
|
||||
@@ -130,6 +245,6 @@ export class OffsetEdgeOp extends FeatureOp<SketchFeature> {
|
||||
if (this.problem) return `⚠ ${this.problem}`;
|
||||
if (!this.edge) return this.face ? "Tap a straight edge: the line on this face runs alongside it." : "Tap a straight edge: the line runs alongside it.";
|
||||
if (!this.face) return "Tap the flat face to draw the line on.";
|
||||
return "The line runs across the face beside the edge. Type how far from the edge (negative: the other side).";
|
||||
return "The line runs across the face beside the edge. Drag the double arrow, or type, to set how far from the edge (negative: the other side).";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Vector3 } from "three";
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { el } from "../ui/ui";
|
||||
import { numpadInput } from "../ui/numpad";
|
||||
import { selectAll } from "../ui/textField";
|
||||
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
|
||||
import type { Viewport } from "../view/viewport";
|
||||
|
||||
@@ -65,7 +66,7 @@ export class PatternBox {
|
||||
document.body.append(this.box);
|
||||
view.frameHooks.add(this.hook);
|
||||
view.helpers.add(this);
|
||||
setTimeout(() => (this.count.focus(), this.count.select()), 0);
|
||||
setTimeout(() => (this.count.focus(), selectAll(this.count)), 0);
|
||||
}
|
||||
|
||||
/** Where the box sits (a world point, e.g. the arrow's tip). */
|
||||
|
||||
@@ -9,8 +9,7 @@
|
||||
import { Vector3 } from "three";
|
||||
import type { PlaneDef, PlaneFeature, PlaneKind, Vec3 } from "../doc/types";
|
||||
import { add, cross, dot, len, norm, scale, sub, xDirFor } from "../geom";
|
||||
import { entityPolylines } from "../sketch/curves";
|
||||
import { sketchToWorld } from "../view/viewport";
|
||||
import { entityWorldPolylines } from "../sketch/curves";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
import type { PickHit } from "../view/viewport";
|
||||
import { FeatureOp, type Slot } from "./featureOp";
|
||||
@@ -80,8 +79,9 @@ function curvePick(app: AppContext, hit: PickHit): CurvePick | null {
|
||||
const plane = app.sketchPlane(hit.sketch);
|
||||
const e = app.sketchCurves(hit.sketch).find((x) => x.id === hit.entity);
|
||||
if (!plane || !e) return null;
|
||||
for (const poly of entityPolylines(e)) {
|
||||
const pts = poly.map((q) => sketchToWorld(plane, q).toArray() as Vec3);
|
||||
// (Where the curve is in space: a spline with points off its plane is picked up there, and the plane put on it
|
||||
// is square to it there - it was put on the curve's shadow, off the curve and askew to it.)
|
||||
for (const pts of entityWorldPolylines(e, plane)) {
|
||||
const near = nearestOnPolyline(pts, hit.point);
|
||||
if (near) return { ...near, line: e.kind === "line" ? [pts[0], pts[pts.length - 1]] : undefined, sel: { kind: "curve", sketch: hit.sketch, entity: hit.entity } };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
// Quick actions: a short row of round buttons right beside whatever is
|
||||
// picked - on the model a face, an edge, a point, a body, a sketch's shape, a
|
||||
// plane, an axis, an image; in a sketch its curves and points - with the two
|
||||
// tools most likely next for it (a flat face: Sketch, Move; a round one:
|
||||
// Thread, Fillet; an edge: Chamfer, Move; a body: Fillet, Mirror; a sketch's
|
||||
// curves: Construction, Delete). The most likely of all already has its handle
|
||||
// on it (a face's arrow, an edge's fillet dot, a gimbal): these are the next
|
||||
// ones. On the model the row ends with Delete and More, which opens every
|
||||
// other tool the pick has (Shell among them); they are the very tools the line
|
||||
// at the bottom offers for the pick (the same ToolItems).
|
||||
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { icons } from "../ui/icons";
|
||||
import type { ToolItem } from "../ui/ui";
|
||||
import type { Viewport } from "../view/viewport";
|
||||
import { clampToFree } from "./annotate";
|
||||
|
||||
/** By kind of pick: the tools to offer, best first (the first two there are and can be used now). */
|
||||
export const QUICK = {
|
||||
// (A freeform surface's face: Edit Freeform first - shaping it again is what it is for.)
|
||||
face: ["editFreeform", "thread", "sketch", "move", "fillet", "thicken"],
|
||||
// (Fillet first, before Chamfer - asked for: "when I select an edge, I also want the fillet tool icon ... before
|
||||
// chamfer". Its dot is on the edge to drag as well.)
|
||||
edge: ["fillet", "chamfer", "move", "thread", "connect"],
|
||||
vertex: ["moveVertex", "delete"],
|
||||
// (A body that is, or began as, a freeform: Edit Freeform first - asked for: "when I double click a freeform body,
|
||||
// I want the edit freeform button there".)
|
||||
body: ["editFreeform", "fillet", "mirror"],
|
||||
profile: ["extrude", "revolve"],
|
||||
plane: ["sketch", "plane"],
|
||||
axis: ["delete"],
|
||||
image: ["scale", "delete"],
|
||||
// In a sketch: its picked curves and points (the sketch tool's own buttons).
|
||||
curve: ["construction", "delete"],
|
||||
point: ["delete"],
|
||||
} satisfies Record<string, string[]>;
|
||||
|
||||
export type QuickKind = keyof typeof QUICK;
|
||||
|
||||
export interface QuickPlace {
|
||||
/** The pick's outward normal (a face's, a shape's): they go the other way from its arrow on the screen. */
|
||||
facing?: Vec3;
|
||||
/** Turned away (seen from behind): hidden (a body's face; a sketch's shape is seen from both sides). */
|
||||
hideBack?: boolean;
|
||||
/** How far from the point (px): further for a gimbal round it. */
|
||||
gap?: number;
|
||||
}
|
||||
|
||||
/** At most this many: only the important things (the rest is under More at the row's end). */
|
||||
const MOST = 2;
|
||||
/**
|
||||
* An edge has three: Fillet, Chamfer and Move/Rotate Edge (asked for: "if I select an edge I want the move and
|
||||
* rotate edge icon there"). Move/Rotate Edge is for one straight edge: with a curved one, or several, it is not
|
||||
* offered and the row is the two.
|
||||
*/
|
||||
const MOST_OF: Partial<Record<QuickKind, number>> = { edge: 3 };
|
||||
|
||||
export class QuickActions {
|
||||
private readonly box = document.createElement("div");
|
||||
private readonly hook = () => this.layout();
|
||||
|
||||
/** `items`: what the pick offers (the wheel's own list, its kinds' items too); `at`: the point it is shown beside. */
|
||||
static show(view: Viewport, kind: QuickKind, items: ToolItem[], at: Vec3, place: QuickPlace = {}, all = false): QuickActions | null {
|
||||
const byId = new Map<string, ToolItem>();
|
||||
const walk = (its: ToolItem[]) => {
|
||||
for (const it of its) {
|
||||
if (!byId.has(it.id)) byId.set(it.id, it);
|
||||
if (it.children?.length) walk(it.children);
|
||||
}
|
||||
};
|
||||
walk(items);
|
||||
const picked = (QUICK[kind] as readonly string[]).map((id) => byId.get(id)).filter((it): it is ToolItem => !!it && !it.disabled && !!it.run && (!it.beta || it.id === "editFreeform")).slice(0, MOST_OF[kind] ?? MOST);
|
||||
if (!all) return picked.length ? new QuickActions(view, picked, at, place) : null;
|
||||
// On the model: Delete beside them, and a last button that opens every other tool the pick has (asked for: "I
|
||||
// also want to have other tools there that could be used on that element. And also delete"). The few most likely
|
||||
// stay the row; the rest come up under it only when asked for, so nothing is crowded.
|
||||
const usable = (it: ToolItem | undefined): it is ToolItem => !!it && !it.disabled && !!it.run;
|
||||
const del = [byId.get("delete"), byId.get("deleteBody")].find(usable);
|
||||
const row = del && !picked.includes(del) ? [...picked, del] : picked;
|
||||
const rest: ToolItem[] = [];
|
||||
// (Beside a corner, not Move/Rotate Body: it moves the whole body, which is not what a corner was picked for -
|
||||
// asked for: "it doesn't make sense to be there". It is still under Transform on the line.)
|
||||
const skip = new Set(["deselect", "reveal", "color", "opacity", "material", "wholePattern", ...(kind === "vertex" ? ["move"] : [])]);
|
||||
const gather = (its: ToolItem[]) => {
|
||||
for (const it of its) {
|
||||
if (!it.label || it.id.startsWith("---") || skip.has(it.id) || it.disabled) continue;
|
||||
// (A tool that starts by itself is one button, its kinds a tap further inside it; a bare group is its tools.)
|
||||
if (it.run) {
|
||||
if (!row.includes(it) && !rest.some((r) => r.label === it.label) && !row.some((r) => r.label === it.label)) rest.push(it);
|
||||
} else if (it.children?.length) gather(it.children);
|
||||
}
|
||||
};
|
||||
gather(items);
|
||||
// (Just one more: it is a button of the row, before Delete - a More that opens a single button is a tap wasted.)
|
||||
if (rest.length === 1) {
|
||||
const one = rest.pop()!;
|
||||
row.splice(del && row.includes(del) ? row.indexOf(del) : row.length, 0, one);
|
||||
}
|
||||
return row.length || rest.length ? new QuickActions(view, row, at, place, rest) : null;
|
||||
}
|
||||
|
||||
/** These very buttons (a tool's own choices, the one in use lit), beside `at`. */
|
||||
static of(view: Viewport, items: ToolItem[], at: Vec3, place: QuickPlace = {}): QuickActions {
|
||||
return new QuickActions(view, items, at, place);
|
||||
}
|
||||
|
||||
private readonly facing?: Vec3;
|
||||
|
||||
private constructor(
|
||||
private readonly view: Viewport,
|
||||
items: ToolItem[],
|
||||
private readonly at: Vec3,
|
||||
private readonly place: QuickPlace,
|
||||
rest: ToolItem[] = [],
|
||||
) {
|
||||
this.facing = place.facing;
|
||||
this.box.className = "quick-actions";
|
||||
const button = (it: ToolItem) => {
|
||||
const b = document.createElement("button");
|
||||
b.className = `quick-action${it.active ? " on" : ""}${it.id === "delete" || it.id === "deleteBody" ? " danger" : ""}`;
|
||||
b.title = it.shortcut ? `${it.label} (${it.shortcut})` : it.label;
|
||||
b.setAttribute("aria-label", it.label);
|
||||
const icon = icons[it.icon as keyof typeof icons];
|
||||
b.innerHTML = `${icon ?? ""}<span>${shortName(it.label)}</span>`;
|
||||
b.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
it.run?.();
|
||||
});
|
||||
return b;
|
||||
};
|
||||
const row = document.createElement("div");
|
||||
row.className = "quick-row";
|
||||
for (const it of items) row.append(button(it));
|
||||
this.box.append(row);
|
||||
if (rest.length) {
|
||||
// The rest of what the pick offers: under the row, opened by its last button (and shut by it again).
|
||||
const more = document.createElement("button");
|
||||
more.className = "quick-action quick-more";
|
||||
more.title = "Every other tool for this";
|
||||
more.setAttribute("aria-label", "More tools for this");
|
||||
more.innerHTML = `${icons.more ?? ""}<span>More</span>`;
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "quick-rest";
|
||||
grid.hidden = true;
|
||||
for (const it of rest) grid.append(button(it));
|
||||
more.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
grid.hidden = !grid.hidden;
|
||||
more.classList.toggle("on", !grid.hidden);
|
||||
this.layout();
|
||||
});
|
||||
row.append(more);
|
||||
this.box.append(grid);
|
||||
}
|
||||
// A press on them is theirs: never a pick on the model behind, nor the view turning.
|
||||
this.box.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
document.body.append(this.box);
|
||||
view.frameHooks.add(this.hook);
|
||||
this.layout();
|
||||
}
|
||||
|
||||
/** Below the point, clear of the handle on it (moved on with the view: only when the view is drawn again). */
|
||||
private layout(): void {
|
||||
const s = this.view.toScreen(this.at);
|
||||
let shown = !!s;
|
||||
if (s && this.facing && this.place.hideBack !== false) {
|
||||
const v = this.view.cam.viewDir();
|
||||
if (v.x * this.facing[0] + v.y * this.facing[1] + v.z * this.facing[2] > 0.05) shown = false;
|
||||
}
|
||||
this.box.hidden = !shown;
|
||||
if (!s || !shown) return;
|
||||
const hw = this.box.offsetWidth / 2;
|
||||
const hh = this.box.offsetHeight / 2;
|
||||
// (A face's arrow points out along its normal: they go the other way on the screen, not under it.)
|
||||
const first: [number, number][] = [];
|
||||
if (this.facing) {
|
||||
const k = this.view.cam.worldPerPixel(this.view.height) * 60;
|
||||
const tip = this.view.toScreen([this.at[0] + this.facing[0] * k, this.at[1] + this.facing[1] * k, this.at[2] + this.facing[2] * k]);
|
||||
const dx = tip ? s[0] - tip[0] : 0;
|
||||
const dy = tip ? s[1] - tip[1] : 0;
|
||||
const l = Math.hypot(dx, dy);
|
||||
if (l > 8) {
|
||||
const d = Math.abs((dx / l) * hw) + Math.abs((dy / l) * hh) + (this.place.gap ?? 34);
|
||||
first.push([s[0] + (dx / l) * d, s[1] + (dy / l) * d]);
|
||||
}
|
||||
}
|
||||
const g = this.place.gap ?? 46;
|
||||
const spots: [number, number][] = [
|
||||
...first,
|
||||
[s[0], s[1] + g + hh],
|
||||
[s[0], s[1] - g - hh],
|
||||
[s[0] - g - hw, s[1]],
|
||||
[s[0] + g + hw, s[1]],
|
||||
].map((p) => clampToFree(p as [number, number], hw, hh));
|
||||
// (Nor under a value box on the model - an extrude's distance, beside its arrow.)
|
||||
const boxes = [...document.querySelectorAll<HTMLElement>(".dim-widget")].map((b) => b.getBoundingClientRect()).filter((r) => r.width > 0);
|
||||
const clear = ([x, y]: [number, number]) => !boxes.some((r) => x + hw + 6 > r.left && x - hw - 6 < r.right && y + hh + 6 > r.top && y - hh - 6 < r.bottom);
|
||||
const [x, y] = spots.find(clear) ?? spots[0];
|
||||
this.box.style.transform = `translate(${Math.round(x - hw)}px, ${Math.round(y - hh)}px)`;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.view.frameHooks.delete(this.hook);
|
||||
this.box.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/** A short name under the icon ("Move/Rotate Edge" → "Move"). */
|
||||
function shortName(label: string): string {
|
||||
const s = label.replace(/…$/, "").split(/[/ –]/)[0];
|
||||
return s.length > 12 ? s.slice(0, 11) + "…" : s;
|
||||
}
|
||||
@@ -107,7 +107,7 @@ export class SectionTool implements Tool {
|
||||
},
|
||||
},
|
||||
{ type: "button", label: "Normal to Section", icon: "normal", onClick: () => this.lookAtCut() },
|
||||
{ type: "button", label: "Place Plane", icon: "plane", onClick: () => this.placePlane() },
|
||||
{ type: "button", label: "Add Plane", icon: "plane", onClick: () => this.placePlane() },
|
||||
],
|
||||
actions: [{ id: "delete", label: "Delete Section", icon: "trash", run: () => (this.app.setSection(null), this.handle?.dispose(), (this.handle = null), this.askForPlane()) }],
|
||||
onDone: () => this.app.setTool(null),
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { AssemblyTool } from "../assembly/assemblyTool";
|
||||
import { QuickActions, type QuickKind, type QuickPlace } from "./quickActions";
|
||||
import { circleAxis } from "./slots";
|
||||
import { isTouchDevice } from "../device";
|
||||
import { BODY_COLORS, BODY_OPACITY, bodyColor } from "../doc/types";
|
||||
import type { DeleteGeomFeature, EdgeLink, FreeformFeature, EdgeRef, ExtrudeSource, FaceRef, ImageFeature, PlaneDef, PlaneFeature, SketchFeature, Vec3 } from "../doc/types";
|
||||
import { peekSegs } from "./ghost";
|
||||
import { settings } from "../settings";
|
||||
import { BODY_COLORS, BODY_OPACITY, DEFAULT_BODY_COLOR, bodyColor } from "../doc/types";
|
||||
import type { DeleteGeomFeature, EdgeLink, FaceFreeformFeature, FreeformFeature, EdgeRef, ExtrudeSource, FaceRef, ImageFeature, PlaneDef, PlaneFeature, SketchFeature, Vec3 } from "../doc/types";
|
||||
import { editedStep } from "../doc/freeformEdits";
|
||||
import { arrangement } from "../sketch/regions";
|
||||
import { projectPolyline, uid } from "../sketch/edit";
|
||||
import type { MenuRow, ToolItem } from "../ui/ui";
|
||||
@@ -21,6 +26,7 @@ import { OffsetEdgeOp } from "./offsetEdge";
|
||||
import { faceFreeformTool } from "./faceFreeform";
|
||||
import { AxisOp, bodyCenter as centerOf, ConnectOp, EdgeOp, ExtrudeOp, FillToPlaneOp, ImageOp, LoftOp, MoveFaceOp, PlaneMoveOp, PlaneOp, planeAxes, ReplaceFaceOp, ScaleFaceOp, ScaleOp, ScaleRefOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./ops";
|
||||
import { SketchTool, type SketchKind } from "./sketch";
|
||||
import { SectionTool, type SectionHost } from "./section";
|
||||
import { BooleanOp } from "./booleanOp";
|
||||
import { pickColor } from "../ui/colorPicker";
|
||||
import { BimTool } from "../bim/bimTool";
|
||||
@@ -30,7 +36,8 @@ import { ImprintOp, ProjectSketchOp, WrapOp } from "./wrapOps";
|
||||
import { materialOf } from "../bim/materials";
|
||||
import { bodiesOf, edgeRefOf, faceRefOf, hitToSel, oppositeFace, sameSel, sourceFrame, sourcesOf, viewMenu, type AppContext, type Sel, type Tool } from "./tool";
|
||||
|
||||
const SOON = "Coming soon";
|
||||
/** How see-through an opacity is, as the Transparency list names it ("40%"). */
|
||||
const seeThrough = (opacity: number) => `${Math.round((1 - opacity) * 100)}%`;
|
||||
|
||||
/**
|
||||
* The default tool. Tap things to select them; the selection decides which
|
||||
@@ -41,6 +48,8 @@ export class SelectTool implements Tool {
|
||||
private handle: Handle | null = null;
|
||||
private handleAction: (() => Tool) | null = null;
|
||||
private gimbal: Gimbal | null = null;
|
||||
/** The next tools for what's picked, as buttons beside it. */
|
||||
private quick: QuickActions | null = null;
|
||||
private copyToggle: CopyToggle | null = null;
|
||||
private dim: DimWidget | null = null;
|
||||
/** A tool chosen with nothing selected waits for the selection. */
|
||||
@@ -53,6 +62,8 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
|
||||
exit(): void {
|
||||
// Another tool started: a tool that was waiting for a pick (Plane's Offset Plane) waits no more.
|
||||
this.pending = null;
|
||||
this.clearHandle();
|
||||
this.app.ui.setHint(null);
|
||||
this.app.setHover(null);
|
||||
@@ -69,9 +80,17 @@ export class SelectTool implements Tool {
|
||||
return this.app.setHover(null);
|
||||
}
|
||||
this.app.view.canvas.style.cursor = "";
|
||||
// Over the section's cut face: a tap there brings the cut's arrow and buttons.
|
||||
if (this.onCut(p)) {
|
||||
this.app.view.canvas.style.cursor = "pointer";
|
||||
this.lastHover = null;
|
||||
return this.app.setHover(null);
|
||||
}
|
||||
const hit = this.pickAt(p);
|
||||
this.lastHover = { x: p.x, y: p.y, hit };
|
||||
this.app.setHover(hitToSel(hit));
|
||||
// Direct touch: over what is picked and can be dragged by itself, the pointer says so.
|
||||
if ((this.handleAction || (this.gimbal && this.app.selection[0]?.kind === "body")) && this.onPick(p, hit)) this.app.view.canvas.style.cursor = "grab";
|
||||
}
|
||||
|
||||
/** What the last hover highlighted, and where: tapping there selects exactly that. */
|
||||
@@ -94,6 +113,12 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
|
||||
dragStart(p: ToolPointer): boolean {
|
||||
// Direct touch: a picked body dragged by itself slides over the floor.
|
||||
if (this.gimbal && !this.gimbal.hit(p) && this.app.selection[0]?.kind === "body" && this.onPick(p)) {
|
||||
const op = new TransformOp(this.app, "move", bodiesOf(this.app.selection), undefined, undefined, copyMode.on).grabAnywhere();
|
||||
this.app.setTool(op);
|
||||
return op.down(p);
|
||||
}
|
||||
if (this.gimbal?.hit(p)) {
|
||||
const s = this.app.selection[0];
|
||||
const img = s?.kind === "image" ? this.app.store.find<ImageFeature>(s.id) : undefined;
|
||||
@@ -113,12 +138,41 @@ export class SelectTool implements Tool {
|
||||
this.app.setTool(op);
|
||||
return op.down(p);
|
||||
}
|
||||
if (!this.handle?.hit(p) || !this.handleAction) return false;
|
||||
if (!this.handleAction) return false;
|
||||
// Direct touch: the picked face, shape or edge dragged by itself is its arrow or dot dragged.
|
||||
const direct = !this.handle?.hit(p) && this.onPick(p);
|
||||
if (!this.handle?.hit(p) && !direct) return false;
|
||||
const op = this.handleAction();
|
||||
if (direct) (op as { grabAnywhere?(): unknown }).grabAnywhere?.();
|
||||
this.app.setTool(op);
|
||||
return op.down?.(p) ?? false;
|
||||
}
|
||||
|
||||
/** Direct touch is on and the press is on what is picked (the thing its arrow or dot is for). */
|
||||
private onPick(p: ToolPointer, hit: ReturnType<SelectTool["pickAt"]> = this.pickAt(p)): boolean {
|
||||
if (!settings.value.direct || this.pending || p.shift) return false;
|
||||
const picked = (s: Sel | null) => !!s && this.app.selection.some((x) => sameSel(x, s) || (x.kind === "body" && "body" in s && s.body === x.body && s.kind !== "vertex"));
|
||||
if (picked(hitToSel(hit))) return true;
|
||||
// (Only a sketch's shape can lie over the pick: anything else under the press is what it is.)
|
||||
if (hit && hit.kind !== "profile" && hit.kind !== "curve") return false;
|
||||
// (A face or body picked that has a sketch lying on it: the press is on it all the same.)
|
||||
return (this.app.selection[0]?.kind === "face" || this.app.selection[0]?.kind === "body") && picked(hitToSel(this.app.view.pick(p.x, p.y, { profiles: false, planes: false, axes: false, curves: false, edgeTolPx: p.tol })));
|
||||
}
|
||||
|
||||
/**
|
||||
* A finger held still on a face, a sketch's shape or an edge (direct
|
||||
* touch): it is picked, and - where the pick has something to drag - the
|
||||
* same touch goes on to drag it. (Else the hold is the menu, as before.)
|
||||
*/
|
||||
grab(p: ToolPointer): boolean {
|
||||
if (!settings.value.direct || this.pending) return false;
|
||||
if (this.gimbal?.hit(p) || this.handle?.hit(p)) return false;
|
||||
const s = hitToSel(this.pickAt(p));
|
||||
if (!s || (s.kind !== "face" && s.kind !== "profile" && s.kind !== "edge")) return false;
|
||||
if (!this.app.selection.some((x) => sameSel(x, s))) this.app.setSelection([s]);
|
||||
return !!this.handleAction;
|
||||
}
|
||||
|
||||
/** Sketch curves win near them; a face outline copied into a sketch ("bnd-…") is the body's edge. */
|
||||
private pickAt(p: ToolPointer) {
|
||||
const hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, curves: true });
|
||||
@@ -137,10 +191,37 @@ export class SelectTool implements Tool {
|
||||
/** Chosen from the list of overlapping faces: the next tap's hit. */
|
||||
private chosenHit: ReturnType<SelectTool["pickAt"]> | null = null;
|
||||
|
||||
/** On the section's cut face (with nothing waiting for a pick): a tap there is the section's. */
|
||||
private onCut(p: ToolPointer): boolean {
|
||||
return !this.pending && !!(this.app as AppContext & Partial<SectionHost>).section && !!this.app.view.cutAt(p.x, p.y);
|
||||
}
|
||||
|
||||
tap(p: ToolPointer, count: number): void {
|
||||
// The cut face of a section: its arrow to move the cut, and its buttons (Add Plane, Flip...).
|
||||
if (!p.add && this.onCut(p)) {
|
||||
this.app.setSelection([]);
|
||||
return this.app.setTool(new SectionTool(this.app as AppContext & SectionHost));
|
||||
}
|
||||
this.pick(p, count);
|
||||
}
|
||||
|
||||
/** What's picked, as rows of the Items list: bodies, planes, axes, images, sketches. */
|
||||
private pickedIds(): string[] {
|
||||
return [...new Set(this.app.selection.flatMap((s) => (s.kind === "body" || s.kind === "face" || s.kind === "edge" || s.kind === "vertex" ? [s.body] : s.kind === "plane" || s.kind === "axis" || s.kind === "image" ? [s.id] : s.kind === "curve" || s.kind === "point" || s.kind === "profile" ? [s.sketch] : [])))];
|
||||
}
|
||||
|
||||
/** A tap on the model. False when it only put up the list of overlapping faces (the tap comes again from there). */
|
||||
private pick(p: ToolPointer, count: number): boolean {
|
||||
const forced = this.chosenHit;
|
||||
this.chosenHit = null;
|
||||
let hit = forced ?? this.tapHit(p);
|
||||
// Waiting for edges (Fillet, Chamfer): a corner within a finger's reach
|
||||
// isn't one - the edge under the finger is (a slot's rim, tapped from the
|
||||
// top, gave the corner of the wheel standing in it). So for a shape or a
|
||||
// face (Extrude): a keyway's box drawn across a bore gave the corner on
|
||||
// the bore's seam, which Extrude can't take.
|
||||
const wants = this.pending?.accepts;
|
||||
if (!forced && hit?.kind === "vertex" && wants && !wants.includes("vertex") && (wants.includes("edge") || wants.includes("face") || wants.includes("profile"))) hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, vertices: false }) ?? hit;
|
||||
// Faces of several bodies in the same place (a bolt flush with the flange
|
||||
// it cuts): which one, from a list by the pointer.
|
||||
if (!forced && hit?.kind === "face" && count < 2 && !this.app.view.selectThrough) {
|
||||
@@ -159,9 +240,16 @@ export class SelectTool implements Tool {
|
||||
},
|
||||
})),
|
||||
);
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// A sketch's shape too narrow where it was tapped to tap without its outline (the frame round a face left by a
|
||||
// small offset of its edge): the tap is the shape - its line, the body's edge beside it or the face under it
|
||||
// took it every time, on any screen. (A double tap on its line still opens the sketch.)
|
||||
if (!forced && count < 2 && !this.app.view.selectThrough && hit && (hit.kind === "curve" || hit.kind === "point" || hit.kind === "edge" || hit.kind === "vertex" || hit.kind === "face") && (!this.pending || this.pending.accepts.includes("profile"))) {
|
||||
const thin = this.app.view.thinProfileNear(p.x, p.y, p.tol);
|
||||
if (thin) hit = thin;
|
||||
}
|
||||
// A finger on a thin shape (a ruler's tick, a letter) is always on its
|
||||
// outline too: one tap takes the shape under it (to extrude); a double
|
||||
// tap opens the sketch to edit. (A mouse can aim for one or the other.)
|
||||
@@ -172,6 +260,13 @@ export class SelectTool implements Tool {
|
||||
// the middle of the circle to sweep along opened its sketch instead.
|
||||
if (under?.kind === "profile") hit = under;
|
||||
}
|
||||
// A double tap on a sketch's line opens its sketch, even where the line
|
||||
// lies on a body (a sketch drawn on a face: its corner or the face won
|
||||
// the pick, and the double tap took the whole body instead).
|
||||
if (count >= 2 && !forced && !this.pending && (hit?.kind === "vertex" || hit?.kind === "edge" || hit?.kind === "face" || hit?.kind === "profile")) {
|
||||
const line = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, curves: true, vertices: false, edges: false, profiles: false, planes: false, axes: false });
|
||||
if (line?.kind === "curve" || line?.kind === "point") hit = line;
|
||||
}
|
||||
// Tapping a line/curve/point of a finished sketch opens it for editing, with that piece selected.
|
||||
if ((hit?.kind === "curve" || hit?.kind === "point") && !this.pending) {
|
||||
const tool = new SketchTool(this.app, { sketchId: hit.sketch });
|
||||
@@ -179,25 +274,36 @@ export class SelectTool implements Tool {
|
||||
this.app.setTool(tool);
|
||||
if (hit.kind === "curve") tool.preselect([hit.entity]);
|
||||
else tool.preselect([], [{ e: hit.entity, p: hit.p }]);
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
// Where the tap was: Edit Freeform picks the cage element there.
|
||||
this.lastTap = p;
|
||||
let s = hitToSel(hit);
|
||||
const sel = this.app.selection;
|
||||
if (!s) return this.app.setSelection([]);
|
||||
// Double tap selects the whole body.
|
||||
if (count >= 2 && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex")) s = { kind: "body", body: s.body };
|
||||
// With bodies selected, tapping another body adds it (Union/Subtract need two).
|
||||
if (sel[0]?.kind === "body" && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex") && (p.add || !sel.some((x) => x.kind === "body" && x.body === (s as { body: string }).body))) {
|
||||
s = { kind: "body", body: s.body };
|
||||
if (!s) {
|
||||
this.app.setSelection([]);
|
||||
return true;
|
||||
}
|
||||
if (sel.length && sel[0].kind === s.kind) {
|
||||
const i = sel.findIndex((x) => sameSel(x, s!));
|
||||
if (i >= 0 && count < 2) this.app.setSelection(sel.filter((_, j) => j !== i));
|
||||
else if (i < 0) this.app.setSelection(p.add || sel[0].kind !== "vertex" ? [...sel, s] : [s]);
|
||||
} else {
|
||||
// Double tap selects the whole body (what its first tap picked there gives way to it).
|
||||
const whole = count >= 2 && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex");
|
||||
if (whole) s = { kind: "body", body: (s as { body: string }).body };
|
||||
// With bodies selected, tapping another body adds it (Union/Subtract need
|
||||
// two) - and tapping a picked body anywhere lets it go.
|
||||
if (sel[0]?.kind === "body" && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex")) s = { kind: "body", body: s.body };
|
||||
if (this.pending && (!sel.length || sel[0].kind !== s.kind)) {
|
||||
// A tool waiting for its pick: what's tapped is the pick.
|
||||
this.app.setSelection([s]);
|
||||
} else if (whole) {
|
||||
const b = (s as { body: string }).body;
|
||||
this.app.setSelection([...sel.filter((x) => !("body" in x && x.body === b)), s]);
|
||||
} else {
|
||||
// Each tap adds to what is picked, whatever it is (a face, then an edge, then a plane); a tap on a picked one
|
||||
// lets that one go; a tap on nothing lets them all go. (Asked for: "I don't like that now I have to click the
|
||||
// + icon after I select to add another one ... I should just be able to select another to add to the
|
||||
// selection. If I want to deselect an element from the selection, I can just click on that element again".
|
||||
// A tap had picked that thing alone, with a + on the line - or Shift - to add.)
|
||||
const i = sel.findIndex((x) => sameSel(x, s!));
|
||||
this.app.setSelection(i >= 0 ? sel.filter((_, j) => j !== i) : [...sel, s]);
|
||||
}
|
||||
// Waiting for a body, and a corner of one was tapped (an STL's faces meet
|
||||
// in corners everywhere): that body is the pick.
|
||||
@@ -205,19 +311,24 @@ export class SelectTool implements Tool {
|
||||
s = { kind: "body", body: s.body };
|
||||
this.app.setSelection([s]);
|
||||
}
|
||||
// Fillet or Chamfer waiting, and a round face's seam tapped: nothing to
|
||||
// round there - said, and still waiting (it took the wait, and the next
|
||||
// edge tapped was only picked: a fillet's dot on a chamfer).
|
||||
if (this.pending && /^(Fillet|Chamfer)$/.test(this.pending.label) && s.kind === "edge" && this.app.view.body(s.body)?.edges[s.edge]?.seam) {
|
||||
this.app.setSelection([]);
|
||||
this.app.ui.toast("That line is a seam - where a round face starts and ends, no corner there to round or chamfer. Tap a real edge.");
|
||||
return true;
|
||||
}
|
||||
if (this.pending && this.pending.accepts.includes(s.kind)) {
|
||||
const run = this.pending.run;
|
||||
this.pending = null;
|
||||
run();
|
||||
return;
|
||||
}
|
||||
// A shape's region tapped (not added with Shift/Ctrl): its extrude arrow is
|
||||
// ready - at 0, so nothing is made until the arrow is dragged (or a value typed).
|
||||
const now = this.app.selection;
|
||||
if (s.kind === "profile" && !p.add && count < 2 && now.length && now.every((x) => x.kind === "profile") && now.some((x) => sameSel(x, s!))) {
|
||||
const src = sourcesOf(this.app, now)[0];
|
||||
if (src) this.app.setTool(new ExtrudeOp(this.app, src, undefined, "auto", { distance: 0 }).markTapped());
|
||||
return true;
|
||||
}
|
||||
// (A shape's region tapped is picked, like anything else: its arrow to drag and its tools beside it - Extrude,
|
||||
// Revolve, Delete and the rest. It went straight into Extrude, which showed the arrow alone; asked for: "I want
|
||||
// them to appear from the first click". Extrude still starts by dragging the arrow or the shape, or typing a size.)
|
||||
return true;
|
||||
}
|
||||
|
||||
/** What a box takes (Tab while dragging cycles; B, F, E pick one, A all). */
|
||||
@@ -305,11 +416,24 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
}
|
||||
}
|
||||
// No body in the box: the closed shapes of the sketches in it (an imported drawing's hundreds of shapes,
|
||||
// picked one tap at a time before - "I tried click drag release around them all").
|
||||
if (kind === "all" && !picked.length) for (const pr of view.profileList()) if (takes(pr.points.length, (i) => pr.points[i])) picked.push({ kind: "profile", sketch: pr.sketch, region: pr.region });
|
||||
const k = picked[0]?.kind ?? (kind === "all" ? "body" : kind);
|
||||
const base = add ? this.app.selection.filter((s) => s.kind === k) : [];
|
||||
this.app.setSelection([...base, ...picked.filter((s) => !base.some((x) => sameSel(x, s)))]);
|
||||
}
|
||||
|
||||
/** Ctrl + A: every body shown; with no bodies, every closed shape of the sketches shown. */
|
||||
selectAll(): boolean {
|
||||
const view = this.app.view;
|
||||
const bodies: Sel[] = view.bodyList.filter((b) => !view.isHidden(b.id)).map((b) => ({ kind: "body", body: b.id }));
|
||||
const all: Sel[] = bodies.length ? bodies : view.profileList().map((pr) => ({ kind: "profile", sketch: pr.sketch, region: pr.region }));
|
||||
if (!all.length) return false;
|
||||
this.app.setSelection(all);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Keys while a box is being dragged: which kind it takes. */
|
||||
dragKey(e: KeyboardEvent): boolean {
|
||||
if (!this.boxing) return false;
|
||||
@@ -347,7 +471,7 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
if (rows[rows.length - 1] === "-") rows.pop();
|
||||
// Where it is in the Items list.
|
||||
const ids = [...new Set(this.app.selection.flatMap((s) => (s.kind === "body" || s.kind === "face" || s.kind === "edge" || s.kind === "vertex" ? [s.body] : s.kind === "plane" || s.kind === "axis" || s.kind === "image" ? [s.id] : s.kind === "curve" || s.kind === "point" || s.kind === "profile" ? [s.sketch] : [])))];
|
||||
const ids = this.pickedIds();
|
||||
if (ids.length) rows.push("-", { label: "Reveal in Items", run: () => this.app.revealInItems(ids) });
|
||||
}
|
||||
viewMenu(this.app, p.x, p.y, rows);
|
||||
@@ -375,14 +499,14 @@ export class SelectTool implements Tool {
|
||||
// left); edges: the fillet radius. The tool armed on tap takes the value.
|
||||
if (!e.ctrlKey && !e.metaKey && !e.altKey && /^[0-9.]$/.test(e.key) && sel.length) {
|
||||
const first = sel[0];
|
||||
if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.freeformOf(first.body)) {
|
||||
if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.sheetFreeform(first.body)) {
|
||||
const src = sourcesOf(this.app, sel)[0];
|
||||
if (src) {
|
||||
this.app.setTool(new ExtrudeOp(this.app, src, undefined, "auto", { typed: e.key }));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (first.kind === "edge" && sel.every((x) => x.kind === "edge") && !this.freeformOf(first.body)) {
|
||||
if (first.kind === "edge" && sel.every((x) => x.kind === "edge") && !this.sheetFreeform(first.body)) {
|
||||
const refs = this.edgeRefs();
|
||||
if (refs.length) {
|
||||
this.app.setTool(new EdgeOp(this.app, "fillet", refs.map((r) => ({ ...r })), undefined, undefined, e.key));
|
||||
@@ -402,26 +526,37 @@ export class SelectTool implements Tool {
|
||||
|
||||
/** Re-derive tools and handle from the current selection. */
|
||||
refresh(): void {
|
||||
if (!this.app.selection.length) this.adding = false;
|
||||
this.clearHandle();
|
||||
// Whatever an earlier tool left on screen goes too (no ghost arrows or dots).
|
||||
this.app.view.clearHelpers([]);
|
||||
const sel = this.app.selection;
|
||||
this.app.ui.setTools(sel.length ? this.actions() : this.app.mainTools());
|
||||
const items = sel.length ? this.actions() : this.app.mainTools();
|
||||
this.app.ui.setTools(items);
|
||||
this.app.ui.setBottom(this.app.bottomTools());
|
||||
// (First the quick buttons: the guide says when there are some.)
|
||||
if (sel[0]) this.showQuick(items);
|
||||
this.app.ui.setHint(
|
||||
this.pending
|
||||
? `${this.pending.label}: tap ${this.pending.accepts.map((k) => withArticle(label({ kind: k } as Sel, 1))).join(" or ")}`
|
||||
: sel.length === 0
|
||||
? this.app.store.features.length
|
||||
? "Pick a tool, or tap the model to select part of it."
|
||||
: "Tap Sketch to start: draw a shape, then pull it into 3D."
|
||||
? this.app.firstShape()
|
||||
? "Your shape is ready: tap it, then drag its arrow up."
|
||||
: this.app.store.features.length
|
||||
? "Tap part of the model: the line at the bottom shows what you can do with it. Or pick a tool there first."
|
||||
: "Tap Sketch to start: draw a shape, then pull it into 3D."
|
||||
: this.armedHint(),
|
||||
);
|
||||
const first = sel[0];
|
||||
if (!first) return;
|
||||
// (Picks of different kinds: no one handle is for all of them.)
|
||||
if (!first || sel.some((x) => x.kind !== first.kind)) return;
|
||||
// The most likely next step gets a handle.
|
||||
// Several picked: the handle is on the one picked last - where the hand and the eye are (asked for: "I want the
|
||||
// arrow / fillet or chamfer circle ... to appear on the last element I selected. Now it stays on the first one
|
||||
// and I have to navigate back to it"). The tool started from it works from there too.
|
||||
const lastFirst = sel.length > 1 ? [sel[sel.length - 1], ...sel.slice(0, -1)] : sel;
|
||||
if (first.kind === "profile") {
|
||||
const src = sourcesOf(this.app, sel)[0];
|
||||
const src = sourcesOf(this.app, lastFirst)[0];
|
||||
if (src) this.showHandle(sourceFrame(this.app, src), "arrow", () => new ExtrudeOp(this.app, src));
|
||||
} else if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type)) {
|
||||
// Flat and round faces: drag the arrow to offset (round faces change radius).
|
||||
@@ -440,8 +575,8 @@ export class SelectTool implements Tool {
|
||||
this.copyToggle = new CopyToggle(this.app.view, () => g.origin);
|
||||
} else if (first.kind === "vertex" && sel.length === 1) {
|
||||
const v = this.app.view.vertexOf(first.body, first.vertex);
|
||||
// A freeform's points are moved in Edit Freeform, so no gimbal here.
|
||||
if (v && !this.freeformOf(first.body)) {
|
||||
// (A freeform left as an open surface: its points are moved in Edit Freeform, so no gimbal here.)
|
||||
if (v && !this.sheetFreeform(first.body)) {
|
||||
this.gimbal = new Gimbal(this.app.view);
|
||||
this.gimbal.setCenter(v);
|
||||
}
|
||||
@@ -462,12 +597,13 @@ export class SelectTool implements Tool {
|
||||
this.copyToggle = new CopyToggle(this.app.view, () => g.origin);
|
||||
}
|
||||
} else if (first.kind === "edge") {
|
||||
const e = this.edgeRefs()[0];
|
||||
const all = this.edgeRefs();
|
||||
const e = all[all.length - 1];
|
||||
// An edge's most likely next step is rounding it: the fillet's dot is
|
||||
// ready to drag, and a number typed is the radius. Moving a straight
|
||||
// edge (its faces tilt to follow) is Move/Rotate Edge (M) in the list.
|
||||
// (A freeform's edges get neither: its shape comes from the cage.)
|
||||
if (e && !this.freeformOf(first.body)) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", this.edgeRefs()).grabFromEdge());
|
||||
if (e && !this.sheetFreeform(first.body)) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", [e, ...all.slice(0, -1)]).grabFromEdge());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -475,20 +611,24 @@ export class SelectTool implements Tool {
|
||||
* What the tool armed by this selection does, and how to use it right
|
||||
* away (drag its handle, or just type the value). Other tools: the list.
|
||||
*/
|
||||
/** What the pick is ready for, in one line: its handle, then the other tools (the round buttons beside it when there are). */
|
||||
private armedHint(): string {
|
||||
const sel = this.app.selection;
|
||||
const sel = this.picks;
|
||||
const first = sel[0];
|
||||
const n = sel.length;
|
||||
const touch = isTouchDevice;
|
||||
const more = touch ? "tap" : "click";
|
||||
if (first.kind === "profile") return `Extrude: drag the arrow or type a height. ${cap(more)} more shapes to add them, or pick another tool.`;
|
||||
if (first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.freeformOf(first.body)) {
|
||||
return "Offset Face: drag the arrow or type a size to move the face in or out. Or pick another tool.";
|
||||
}
|
||||
if (first.kind === "face" && n === 2 && sel[1].kind === "face") return "The distance between the two faces is shown. Pick a tool for them.";
|
||||
if (first.kind === "edge" && !this.freeformOf(first.body)) return `Fillet: drag the dot or type a radius to round ${n > 1 ? "the edges" : "the edge"}. ${cap(more)} more edges to add them.`;
|
||||
if (first.kind === "body") return `Move/Rotate: drag the arrows or the arcs. ${cap(more)} another body to add it.`;
|
||||
return `${n} ${label(first, n)} selected. Pick a tool for ${n > 1 ? "them" : "it"}, or ${more} more to add.`;
|
||||
const tap = isTouchDevice ? "tap" : "click";
|
||||
const or = this.quick ? `or ${tap} a button beside it` : "or pick a tool";
|
||||
const direct = settings.value.direct;
|
||||
if (direct && first.kind === "profile") return `Drag the shape (or its arrow) to pull it into 3D, ${or}.`;
|
||||
if (direct && first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.sheetFreeform(first.body)) return `Drag the face (or its arrow) to push or pull it, ${or}.`;
|
||||
if (direct && first.kind === "edge" && !this.sheetFreeform(first.body)) return `Drag ${n > 1 ? "an edge" : "the edge"} (or its dot) to round ${n > 1 ? "them" : "it"}, ${or}.`;
|
||||
if (direct && first.kind === "body") return `Drag it to slide it over the floor, or its arrows and arcs to move and turn it, ${or}.`;
|
||||
if (first.kind === "profile") return `Drag the arrow to extrude, ${or}.`;
|
||||
if (first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.sheetFreeform(first.body)) return `Drag the arrow to move the face, ${or}.`;
|
||||
if (first.kind === "face" && n === 2 && sel[1].kind === "face") return "The distance between the faces is shown. Pick a tool for them.";
|
||||
if (first.kind === "edge" && !this.sheetFreeform(first.body)) return `Drag the dot to round ${n > 1 ? "the edges" : "the edge"}, ${or}.`;
|
||||
if (first.kind === "body") return `Drag the arrows or arcs to move it, ${or}.`;
|
||||
return this.quick ? `${cap(tap)} a button beside it, or pick a tool on the line at the bottom.` : `Pick a tool for ${n > 1 ? "them" : "it"}, or ${tap} another to add it (${tap} a picked one to let it go).`;
|
||||
}
|
||||
|
||||
/** Called by the app when a top-level tool needs a selection first. */
|
||||
@@ -506,6 +646,19 @@ export class SelectTool implements Tool {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Each tap adds to the pick (the + beside its name is on): off again once nothing is picked. */
|
||||
adding = false;
|
||||
|
||||
/** The tool started with nothing picked that is waiting for its pick now (the sentence bar says so over the line), and letting it go. */
|
||||
get waiting(): string | null {
|
||||
return this.pending?.label ?? null;
|
||||
}
|
||||
stopWaiting(): void {
|
||||
if (!this.pending) return;
|
||||
this.pending = null;
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
waitFor(label: string, accepts: Sel["kind"][], run: () => void): void {
|
||||
this.pending = { label, accepts, run };
|
||||
this.app.setSelection([]);
|
||||
@@ -515,20 +668,36 @@ export class SelectTool implements Tool {
|
||||
|
||||
/** The list for what's picked, its groups apart with a dim line. */
|
||||
private actions(): ToolItem[] {
|
||||
return withGroups(this.actionList());
|
||||
// Each tool that has a telling picture of what it would do to the pick shows it while the pointer is over it.
|
||||
const sel = this.picks;
|
||||
const look = (items: ToolItem[]): ToolItem[] =>
|
||||
items.map((it) => ({ ...it, peek: () => peekSegs(this.app, it.id, sel), ...(it.children ? { children: look(it.children) } : {}) }));
|
||||
return withGroups(look(this.actionList()));
|
||||
}
|
||||
|
||||
/**
|
||||
* What the tools are for: everything picked - or, picks of different kinds
|
||||
* (a face, then an edge), the ones of the kind picked last.
|
||||
*/
|
||||
private get picks(): Sel[] {
|
||||
const sel = this.app.selection;
|
||||
const k = sel[sel.length - 1]?.kind;
|
||||
return sel.every((x) => x.kind === k) ? sel : sel.filter((x) => x.kind === k);
|
||||
}
|
||||
|
||||
private actionList(): ToolItem[] {
|
||||
const sel = this.app.selection;
|
||||
const all = this.app.selection;
|
||||
const sel = this.picks;
|
||||
if (!sel.length) return [];
|
||||
const head: ToolItem[] = [{ id: "deselect", label: "Deselect All", icon: "deselect", shortcut: "Esc", sub: `${sel.length} ${label(sel[0], sel.length)}`, run: () => this.app.setSelection([]) }];
|
||||
const mixed = all.length > sel.length;
|
||||
const head: ToolItem[] = [{ id: "deselect", label: "Deselect All", icon: "deselect", shortcut: "Esc", sub: mixed ? `${all.length} items` : `${sel.length} ${label(sel[0], sel.length)}`, run: () => this.app.setSelection([]) }];
|
||||
// A freeform body (or a face/edge/point of one): open its cage, picking the spot that was tapped.
|
||||
const first = sel[0];
|
||||
const ffBody = "body" in first ? first.body : "";
|
||||
const ff = ffBody ? this.freeformOf(ffBody) : undefined;
|
||||
// Editing a copy: it becomes its own freeform first (unless it is linked).
|
||||
const own = () => this.ownFreeform(ffBody) ?? ff!;
|
||||
if (ff?.type === "freeform") head.push({ id: "editFreeform", label: "Edit Freeform", icon: "freeform", shortcut: "F2", run: () => this.editFreeform(own()) });
|
||||
if (ff?.type === "freeform") head.push({ id: "editFreeform", label: "Edit Freeform", icon: "editFreeform", shortcut: "F2", run: () => this.editFreeform(own()) });
|
||||
// Border edges of open freeforms (one surface or two): connect them with new faces.
|
||||
const edgeSel = sel.filter((x): x is Extract<Sel, { kind: "edge" }> => x.kind === "edge");
|
||||
if (edgeSel.length >= 2 && edgeSel.length === sel.length) {
|
||||
@@ -537,7 +706,7 @@ export class SelectTool implements Tool {
|
||||
const f = this.freeformOf(b);
|
||||
return !!f && !isClosed(f.cage);
|
||||
});
|
||||
if (open && bodies.length <= 2) head.push({ id: "connect", label: "Connect", icon: "loft", sub: bodies.length === 2 ? "Join the two surfaces" : "New faces between the edges", run: () => this.connectEdges(edgeSel) });
|
||||
if (open && bodies.length <= 2) head.push({ id: "connect", label: "Connect", icon: "connect", sub: bodies.length === 2 ? "Join the two surfaces" : "New faces between the edges", run: () => this.connectEdges(edgeSel) });
|
||||
}
|
||||
// An open freeform (faces deleted, or a surface): close a hole, or give it a thickness.
|
||||
if (ff?.type === "freeform" && !isClosed(ff.cage)) {
|
||||
@@ -557,9 +726,9 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
head.push({ id: "thicken", label: "Thickness…", icon: "shell", run: () => this.app.setTool(new FreeformTool(this.app, { feature: own() })) });
|
||||
}
|
||||
// A face, edge or point of a freeform: its shape comes from the cage -
|
||||
// fillet, chamfer, offset face… don't apply (they were listed all the same).
|
||||
if (ff?.type === "freeform" && (first.kind === "face" || first.kind === "edge" || first.kind === "vertex")) {
|
||||
// A face, edge or point of a freeform left as an open surface: its shape comes from the cage - fillet, chamfer,
|
||||
// offset face... don't apply. (A finished freeform solid has every tool a body has: it was held to these few.)
|
||||
if (ff?.type === "freeform" && this.sheetFreeform(ffBody) && (first.kind === "face" || first.kind === "edge" || first.kind === "vertex")) {
|
||||
const bodies = bodiesOf(sel);
|
||||
const app = this.app;
|
||||
return [
|
||||
@@ -590,10 +759,10 @@ export class SelectTool implements Tool {
|
||||
const pivot = this.app.view.vertexOf(s.body, s.vertex);
|
||||
const at = sel.flatMap((x) => (x.kind === "vertex" && x.body === s.body ? [this.app.view.vertexOf(x.body, x.vertex)!].filter(Boolean) : []));
|
||||
// A freeform's points move in Edit Freeform (at the top of this list), not here.
|
||||
const isFreeform = !!ff && ff.type === "freeform";
|
||||
const isFreeform = this.sheetFreeform(s.body);
|
||||
return [
|
||||
...head,
|
||||
...(isFreeform ? [] : [{ id: "moveVertex", label: "Move Vertex", icon: "move" as const, shortcut: "M", active: true, disabled: !pivot, run: () => pivot && this.app.setTool(new MoveFaceOp(this.app, { vertex: { body: s.body, at: pivot } })) }]),
|
||||
...(isFreeform ? [] : [{ id: "moveVertex", label: "Move Vertex", icon: "point" as const, shortcut: "M", active: true, disabled: !pivot, run: () => pivot && this.app.setTool(new MoveFaceOp(this.app, { vertex: { body: s.body, at: pivot } })) }]),
|
||||
{ id: "move", label: "Move/Rotate Body", icon: "move", run: () => this.app.setTool(new TransformOp(this.app, "move", bodies, undefined, pivot)) },
|
||||
{ id: "delete", label: "Delete Vertex", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { vertices: at }) },
|
||||
];
|
||||
@@ -615,7 +784,7 @@ export class SelectTool implements Tool {
|
||||
|
||||
private profileActions(): ToolItem[] {
|
||||
const app = this.app;
|
||||
const sel = app.selection;
|
||||
const sel = this.picks;
|
||||
const src = sourcesOf(app, sel)[0] as Extract<ExtrudeSource, { kind: "profile" }> | undefined;
|
||||
const sketchId = (sel[0] as Extract<Sel, { kind: "profile" }>).sketch;
|
||||
const plane = app.sketchPlane(sketchId);
|
||||
@@ -630,8 +799,8 @@ export class SelectTool implements Tool {
|
||||
{ id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: inSketch("patternLinear") },
|
||||
{ id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: inSketch("patternCircular") },
|
||||
// Starts at the last distance used (the preview shows at once: Enter keeps it).
|
||||
{ id: "extrude", label: "Extrude", icon: "extrude", shortcut: "E", active: true, run: () => src && app.setTool(new ExtrudeOp(app, src, undefined, "auto", { distance: 0 })) },
|
||||
{ id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => frame && app.setTool(new AxisOp(app, frame.base, frame.normal)) },
|
||||
{ id: "extrude", label: "Extrude", icon: "extrude", shortcut: "E", active: true, pulse: app.firstShape(), run: () => src && app.setTool(new ExtrudeOp(app, src, undefined, "auto", { distance: 0 })) },
|
||||
{ id: "axis", label: "Axis – Perp. to Face", icon: "axisFace", run: () => frame && app.setTool(new AxisOp(app, frame.base, frame.normal, undefined, "face")) },
|
||||
{ id: "plane", label: "Plane – Offset", icon: "plane", run: () => plane && app.setTool(new PlaneOp(app, plane, undefined)) },
|
||||
{ id: "text", label: "Text", icon: "text", run: inSketch("text") },
|
||||
// In the sketch: the shape turns about a point you tap (not a 3D axis).
|
||||
@@ -653,7 +822,7 @@ export class SelectTool implements Tool {
|
||||
|
||||
private faceActions(): ToolItem[] {
|
||||
const app = this.app;
|
||||
const sel = app.selection;
|
||||
const sel = this.picks;
|
||||
const s = sel[0] as Extract<Sel, { kind: "face" }>;
|
||||
const info = app.view.body(s.body)?.faces[s.face];
|
||||
const flat = !!info?.plane;
|
||||
@@ -661,13 +830,21 @@ export class SelectTool implements Tool {
|
||||
const src = sourcesOf(app, sel)[0];
|
||||
const faceRefs = sel.flatMap((x) => (x.kind === "face" ? [faceRefOf(app, x)!] : []));
|
||||
const needFlat = { disabled: !flat || !one, why: "Needs one flat face" };
|
||||
const allFlat = sel.every((x) => x.kind === "face" && x.body === s.body && !!app.view.body(x.body)?.faces[x.face]?.plane);
|
||||
const freeFaces = { disabled: !allFlat, why: one ? "Needs a flat face" : "Needs flat faces of one body" };
|
||||
const ref = faceRefOf(app, s);
|
||||
const bodies = bodiesOf(sel);
|
||||
// (One round wall of a hole picked: a pattern started here repeats the hole.)
|
||||
const holeRef = one && info?.round?.hole && ref ? ref : undefined;
|
||||
// A round face: its axis (from its mesh).
|
||||
const axis = info?.round && one ? roundAxis(app, s.body, s.face) : null;
|
||||
// A face a Freeform Face step made: that step opens again to reshape it.
|
||||
const shaped = info?.step ? app.store.find(info.step) : undefined;
|
||||
const editFree: ToolItem[] = shaped?.type === "faceFreeform" && one ? [{ id: "editFreeform", label: "Edit Freeform", icon: "freeform", active: true, beta: true, run: () => app.editStep(shaped.id) }] : [];
|
||||
const editFree: ToolItem[] = shaped?.type === "faceFreeform" && one ? [{ id: "editFreeform", label: "Edit Freeform", icon: "editFreeform", active: true, beta: true, run: () => {
|
||||
// (A new Edit Freeform step in History, from the shape as its edits have left it.)
|
||||
const t = faceFreeformTool(app, null, editedStep<FaceFreeformFeature>(app.store.features, shaped.id));
|
||||
if (t) app.setTool(t);
|
||||
} }] : [];
|
||||
// What only a flat face can take (a sketch, an extrude, a plane on it) isn't
|
||||
// offered for a round or curved one at all, the way the body's tools aren't
|
||||
// offered for an edge: only what the face can do is listed.
|
||||
@@ -679,8 +856,13 @@ export class SelectTool implements Tool {
|
||||
{ id: "move", label: "Move/Rotate Face", icon: "moveFace", shortcut: "M", ...needFlat, run: () => ref && info?.plane && app.setTool(new MoveFaceOp(app, { face: ref, plane: info.plane })) },
|
||||
// Scales just this face, within its plane; the sides tilt to follow.
|
||||
{ id: "scale", label: "Scale Face", icon: "scale", ...needFlat, run: () => ref && info?.plane && app.setTool(new ScaleFaceOp(app, ref, info.plane)) },
|
||||
{ id: "align", label: "Align", icon: "align", disabled: true, why: SOON },
|
||||
{ id: "thread", label: "Thread", icon: "thread", disabled: !one || !info?.round, why: "Needs one round face (a shank or a hole)", run: () => app.startThread() },
|
||||
// Two faces, one on each of two bodies: the joint between the two (Assemblies opens with it made).
|
||||
(() => {
|
||||
const fs = this.picks.filter((p): p is Extract<Sel, { kind: "face" }> => p.kind === "face");
|
||||
const pair = this.picks.length === 2 && fs.length === 2 && fs[0].body !== fs[1].body;
|
||||
return { id: "joint", label: "Joint", icon: "assembly", disabled: !pair, why: "Needs a face on each of two parts", run: () => pair && app.setTool(new AssemblyTool(app, { a: fs[0], b: fs[1] })) } as ToolItem;
|
||||
})(),
|
||||
{ id: "offsetFace", label: "Offset Face", icon: "offsetFace", shortcut: "E", active: !editFree.length, disabled: !one || !offsettable(info?.type), why: "Needs one flat or round face", run: () => src && app.setTool(new ExtrudeOp(app, src)) },
|
||||
// A line on this face, parallel to an edge (tapped next): Offset Edge started from the face.
|
||||
{ id: "offsetFromEdge", label: "Offset from Edge", icon: "offsetEdge", ...needFlat, run: () => app.setTool(new OffsetEdgeOp(app, undefined, { body: s.body, face: s.face })) },
|
||||
@@ -689,20 +871,23 @@ export class SelectTool implements Tool {
|
||||
{ id: "extrude", label: "Extrude", icon: "extrude", ...needFlat, run: () => src && app.setTool(new ExtrudeOp(app, src, undefined, "new")) },
|
||||
{ id: "shell", label: "Shell", icon: "shell", run: () => app.setTool(new ShellOp(app, s.body, faceRefs)) },
|
||||
axis
|
||||
? { id: "axis", label: "Axis – Cylinder", icon: "axis", run: () => app.setTool(new AxisOp(app, axis.origin, axis.dir)) }
|
||||
: { id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => info && app.setTool(new AxisOp(app, info.center, info.normal)) },
|
||||
? { id: "axis", label: "Axis – Cylinder", icon: "axisRound", run: () => app.setTool(new AxisOp(app, axis.origin, axis.dir, undefined, "round")) }
|
||||
: { id: "axis", label: "Axis – Perp. to Face", icon: "axisFace", run: () => info && app.setTool(new AxisOp(app, info.center, info.normal, undefined, "face")) },
|
||||
{ id: "plane", label: "Plane – Offset", icon: "plane", ...needFlat, run: () => info?.plane && app.setTool(new PlaneOp(app, info.plane, faceRefOf(app, s)!)) },
|
||||
{ id: "loft", label: "Loft", icon: "loft", ...needFlat, run: () => app.setTool(new LoftOp(app, sourcesOf(app, sel).flatMap(splitRegions), sel)) },
|
||||
// The face made smooth: a grid of points over it to pull out or push in; its edges stay put.
|
||||
{ id: "faceFreeform", label: "Freeform Face", icon: "freeform", beta: true, ...needFlat, run: () => { const t = faceFreeformTool(app, s); if (t) app.setTool(t); } },
|
||||
// (Several flat faces of one body, side by side: one smooth surface over them all, no edge where they met.)
|
||||
{ id: "faceFreeform", label: "Freeform Face", icon: "faceFreeform", beta: true, ...freeFaces, run: () => { const t = faceFreeformTool(app, sel as Extract<Sel, { kind: "face" }>[]); if (t) app.setTool(t); } },
|
||||
// A smooth freeform bridge between two faces (the second tapped next when one is picked).
|
||||
{ id: "connect", label: "Connect", icon: "freeform", beta: true, disabled: sel.length > 2, why: "Needs two faces", run: () => app.setTool(new ConnectOp(app, sel)) },
|
||||
{ id: "connect", label: "Connect", icon: "connect", beta: true, disabled: sel.length > 2, why: "Needs two faces", run: () => app.setTool(new ConnectOp(app, sel)) },
|
||||
{ id: "split", label: "Split Body", icon: "split", disabled: !flat || app.view.bodyList.length < 2, why: "Needs another body to split", run: () => this.splitWith(info!.plane!, s.body) },
|
||||
{ id: "revolve", label: "Revolve", icon: "revolve", ...needFlat, run: () => src && app.setTool(new RevolveOp(app, src)) },
|
||||
{ id: "sweep", label: "Sweep", icon: "sweep", ...needFlat, run: () => src && app.setTool(new SweepOp(app, src)) },
|
||||
// The face's body moved, copied round or mirrored, without picking the body first.
|
||||
{ id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: () => app.setTool(new TransformOp(app, "linear", bodies)) },
|
||||
{ id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: () => app.setTool(new TransformOp(app, "circular", bodies)) },
|
||||
// (A hole's round wall: the pattern repeats the hole in its body - it copied the whole body, and there was no
|
||||
// way to repeat a hole.)
|
||||
{ id: "patl", label: "Pattern – Linear", icon: "patternLinear", ...(holeRef ? { sub: "repeats this hole" } : {}), run: () => app.setTool(new TransformOp(app, "linear", holeRef ? [s.body] : bodies, undefined, undefined, false, holeRef, holeRef ? info?.round?.r : undefined)) },
|
||||
{ id: "patc", label: "Pattern – Circular", icon: "patternCircular", ...(holeRef ? { sub: "repeats this hole" } : {}), run: () => app.setTool(new TransformOp(app, "circular", holeRef ? [s.body] : bodies, undefined, undefined, false, holeRef)) },
|
||||
{ id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) },
|
||||
{ id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) },
|
||||
{ id: "mirror", label: "Mirror", icon: "mirror", run: () => app.setTool(new TransformOp(app, "mirror", bodies)) },
|
||||
@@ -715,7 +900,7 @@ export class SelectTool implements Tool {
|
||||
|
||||
private edgeActions(): ToolItem[] {
|
||||
const app = this.app;
|
||||
const sel = app.selection;
|
||||
const sel = this.picks;
|
||||
const s = sel[0] as Extract<Sel, { kind: "edge" }>;
|
||||
const info = app.view.body(s.body)?.edges[s.edge];
|
||||
const bodies = bodiesOf(sel);
|
||||
@@ -724,7 +909,11 @@ export class SelectTool implements Tool {
|
||||
// view) and its list stays open - the selection's edge numbers then point at the preview's
|
||||
// edges, and "Drag / type" picked two other edges (rounding the valve's creases failed).
|
||||
const picked = this.edgeRefs();
|
||||
const refs = () => picked.map((r) => ({ ...r }));
|
||||
// (The edge picked last first: the tool's dot and its size are at that one.)
|
||||
const refs = () => {
|
||||
const all = picked.map((r) => ({ ...r }));
|
||||
return all.length > 1 ? [all[all.length - 1], ...all.slice(0, -1)] : all;
|
||||
};
|
||||
const ref = picked[0];
|
||||
// With variables defined, Fillet/Chamfer open a list: a free size, or one of the variables.
|
||||
const vars = app.store.doc.variables ?? [];
|
||||
@@ -752,13 +941,13 @@ export class SelectTool implements Tool {
|
||||
{
|
||||
id: "axis",
|
||||
label: info?.type === "CIRCLE" ? "Axis – Through Centre" : "Axis – Along Edge",
|
||||
icon: "axis",
|
||||
icon: info?.type === "CIRCLE" ? "axisRound" : "axisEdge",
|
||||
disabled: !straight && info?.type !== "CIRCLE",
|
||||
why: "Needs a straight or round edge",
|
||||
run: () => {
|
||||
if (!info) return;
|
||||
const ax = info.type === "CIRCLE" ? circleAxis(info.start, info.mid, info.end, info.dir) : { origin: info.start, dir: info.dir };
|
||||
if (ax) app.setTool(new AxisOp(app, ax.origin, ax.dir));
|
||||
if (ax) app.setTool(new AxisOp(app, ax.origin, ax.dir, undefined, info.type === "CIRCLE" ? "round" : "edge"));
|
||||
},
|
||||
},
|
||||
{ id: "planePerp", label: "Plane – Perp. to Edge", icon: "plane", run: () => info && app.setTool(new PlaneOp(app, { origin: info.mid, normal: info.dir, xDir: perpTo(info.dir) }, undefined)) },
|
||||
@@ -776,7 +965,7 @@ export class SelectTool implements Tool {
|
||||
|
||||
private bodyActions(): ToolItem[] {
|
||||
const app = this.app;
|
||||
const bodies = bodiesOf(app.selection);
|
||||
const bodies = bodiesOf(this.picks);
|
||||
const multi = bodies.length >= 2;
|
||||
// An open surface (it has open edges: a sheet, not a solid).
|
||||
const openSurface = bodies.length === 1 && !!app.view.bodyList.find((b) => b.id === bodies[0])?.openEdges?.length;
|
||||
@@ -848,16 +1037,18 @@ export class SelectTool implements Tool {
|
||||
label: c.name,
|
||||
icon: "color",
|
||||
swatch: c.hex,
|
||||
active: (bodyColor((app.store.doc.colors ?? {})[bodies[0]]) ?? BODY_COLORS[0].hex) === c.hex,
|
||||
active: bodyColor((app.store.doc.colors ?? {})[bodies[0]]) === c.hex,
|
||||
// (Tapped again while lit: back to the grey every body has to start with.)
|
||||
run: () =>
|
||||
app.store.commit((d) => {
|
||||
const colors = { ...(d.colors ?? {}) };
|
||||
for (const b of bodies) if (i === 0) delete colors[b];
|
||||
const off = bodies.every((b) => bodyColor(colors[b]) === c.hex);
|
||||
for (const b of bodies) if (off) delete colors[b];
|
||||
else colors[b] = c.hex;
|
||||
d.colors = colors;
|
||||
}),
|
||||
})),
|
||||
// Any colour (a dark lamp base, a brass shade): the ten soft ones
|
||||
// Any colour (a dark lamp base, a brass shade): the seven soft ones
|
||||
// couldn't give what a model made by code had.
|
||||
((): ToolItem => {
|
||||
const now = bodyColor((app.store.doc.colors ?? {})[bodies[0]]);
|
||||
@@ -876,7 +1067,7 @@ export class SelectTool implements Tool {
|
||||
d.colors = colors;
|
||||
};
|
||||
// One undo step for the whole pick: live while choosing, kept on Done.
|
||||
const hex = await pickColor("Custom colour", now ?? BODY_COLORS[0].hex, (h) => app.store.transient(write(h)));
|
||||
const hex = await pickColor("Custom colour", now ?? DEFAULT_BODY_COLOR, (h) => app.store.transient(write(h)));
|
||||
if (hex) app.store.commit(write(hex));
|
||||
else app.store.commit((d) => (d.colors = before));
|
||||
},
|
||||
@@ -890,9 +1081,10 @@ export class SelectTool implements Tool {
|
||||
// Next to Color: how see-through the body is.
|
||||
id: "opacity",
|
||||
label: "Transparency",
|
||||
inOrder: true,
|
||||
icon: "color",
|
||||
sub: BODY_OPACITY.find((o) => o.value === ((app.store.doc.opacity ?? {})[bodies[0]] ?? 1))?.name ?? "Solid",
|
||||
children: BODY_OPACITY.map((o, i) => ({
|
||||
sub: BODY_OPACITY.find((o) => o.value === ((app.store.doc.opacity ?? {})[bodies[0]] ?? 1))?.name ?? seeThrough((app.store.doc.opacity ?? {})[bodies[0]] ?? 1),
|
||||
children: [...BODY_OPACITY.map((o, i): ToolItem => ({
|
||||
id: `opacity-${i}`,
|
||||
label: o.name,
|
||||
icon: "color",
|
||||
@@ -905,6 +1097,34 @@ export class SelectTool implements Tool {
|
||||
d.opacity = op;
|
||||
}),
|
||||
})),
|
||||
// Any amount: typed in, as how see-through (40 = 40%).
|
||||
((): ToolItem => {
|
||||
const now = (app.store.doc.opacity ?? {})[bodies[0]] ?? 1;
|
||||
const custom = !BODY_OPACITY.some((o) => o.value === now);
|
||||
const put = (pct: number) =>
|
||||
app.store.commit((d) => {
|
||||
const v = Math.round(Math.min(95, Math.max(0, pct)));
|
||||
const op = { ...(d.opacity ?? {}) };
|
||||
for (const b of bodies) if (v <= 0) delete op[b];
|
||||
else op[b] = (100 - v) / 100;
|
||||
d.opacity = op;
|
||||
});
|
||||
const typed = String(Math.round((1 - now) * 100));
|
||||
return {
|
||||
id: "opacity-custom",
|
||||
label: "Custom…",
|
||||
icon: "numpad",
|
||||
...(custom ? { sub: seeThrough(now) } : {}),
|
||||
active: custom,
|
||||
value: { now: typed, put, int: true, min: 0, max: 95 },
|
||||
run: async () => {
|
||||
const r = await app.ui.dialog("Custom transparency", [{ key: "pct", label: "Transparency (%)", value: typed }]);
|
||||
const v = r ? parseFloat(r.pct) : NaN;
|
||||
if (Number.isFinite(v)) put(v);
|
||||
},
|
||||
};
|
||||
})(),
|
||||
],
|
||||
},
|
||||
{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => this.deleteBodies(bodies) },
|
||||
];
|
||||
@@ -912,7 +1132,7 @@ export class SelectTool implements Tool {
|
||||
|
||||
private planeActions(): ToolItem[] {
|
||||
const app = this.app;
|
||||
const s = app.selection[0] as Extract<Sel, { kind: "plane" }>;
|
||||
const s = this.picks[0] as Extract<Sel, { kind: "plane" }>;
|
||||
const plane = app.view.planeOf(s.id);
|
||||
const isFeature = !!app.store.find(s.id);
|
||||
return [
|
||||
@@ -925,7 +1145,7 @@ export class SelectTool implements Tool {
|
||||
|
||||
private axisActions(): ToolItem[] {
|
||||
const app = this.app;
|
||||
const s = app.selection[0] as Extract<Sel, { kind: "axis" }>;
|
||||
const s = this.picks[0] as Extract<Sel, { kind: "axis" }>;
|
||||
return [{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => (app.store.remove(s.id), app.setSelection([])) }];
|
||||
}
|
||||
|
||||
@@ -937,7 +1157,39 @@ export class SelectTool implements Tool {
|
||||
this.handleAction = action;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whatever is picked - a face, edge or point of a body (several of a kind:
|
||||
* beside the last), a body, a sketch's shape, a plane, an axis, an image -
|
||||
* its next tools as buttons beside it (QuickActions).
|
||||
*/
|
||||
private showQuick(items: ToolItem[]): void {
|
||||
const sel = this.picks;
|
||||
if (!sel.length || this.pending) return;
|
||||
const view = this.app.view;
|
||||
const s = sel[sel.length - 1];
|
||||
const show = (kind: QuickKind, at: Vec3 | undefined, place?: QuickPlace) => {
|
||||
if (at) this.quick = QuickActions.show(view, kind, items, at, place, true);
|
||||
};
|
||||
if (s.kind === "face") {
|
||||
const f = view.body(s.body)?.faces[s.face];
|
||||
if (f) show("face", f.center, f.plane ? { facing: f.normal } : {});
|
||||
} else if (s.kind === "edge") show("edge", view.body(s.body)?.edges[s.edge]?.mid);
|
||||
else if (s.kind === "vertex") show("vertex", view.vertexOf(s.body, s.vertex), { gap: 110 });
|
||||
else if (s.kind === "body") show("body", centerOf(this.app, bodiesOf(sel)), { gap: 120 });
|
||||
else if (s.kind === "profile") {
|
||||
const src = sourcesOf(this.app, [s])[0];
|
||||
const fr = src && sourceFrame(this.app, src);
|
||||
if (fr) show("profile", fr.base, { facing: fr.normal, hideBack: false });
|
||||
} else if (s.kind === "plane") {
|
||||
const pl = view.planeOf(s.id);
|
||||
show("plane", view.planeShownAt(s.id) ?? pl?.origin, { gap: 110 });
|
||||
} else if (s.kind === "axis") show("axis", view.axisOf(s.id)?.plane.origin, { gap: 40 });
|
||||
else if (s.kind === "image") show("image", this.app.store.find<ImageFeature>(s.id)?.plane.origin, { gap: 110 });
|
||||
}
|
||||
|
||||
private clearHandle(): void {
|
||||
this.quick?.dispose();
|
||||
this.quick = null;
|
||||
this.handle?.dispose();
|
||||
this.handle = null;
|
||||
this.handleAction = null;
|
||||
@@ -1017,7 +1269,7 @@ export class SelectTool implements Tool {
|
||||
/** Fillet/chamfer every edge round the selected faces: on a flat one's plane, or a round one's rims. */
|
||||
private edgesOfFaces(kind: "fillet" | "chamfer"): void {
|
||||
const refs: EdgeRef[] = [];
|
||||
for (const s of this.app.selection) {
|
||||
for (const s of this.picks) {
|
||||
if (s.kind !== "face") continue;
|
||||
const b = this.app.view.body(s.body);
|
||||
const f = b?.faces[s.face];
|
||||
@@ -1047,7 +1299,7 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
|
||||
private sketchOnFace(kind?: string): void {
|
||||
const s = this.app.selection[0] as Extract<Sel, { kind: "face" }>;
|
||||
const s = this.picks[0] as Extract<Sel, { kind: "face" }>;
|
||||
const info = this.app.view.body(s.body)?.faces[s.face];
|
||||
if (!info?.plane) return;
|
||||
const ref = faceRefOf(this.app, s)!;
|
||||
@@ -1061,7 +1313,7 @@ export class SelectTool implements Tool {
|
||||
/** The picked edges in a new sketch: on a flat face they all lie on, or else on the plane through them. */
|
||||
private projectEdges(): void {
|
||||
const app = this.app;
|
||||
const picked = app.selection.filter((x): x is Extract<Sel, { kind: "edge" }> => x.kind === "edge");
|
||||
const picked = this.picks.filter((x): x is Extract<Sel, { kind: "edge" }> => x.kind === "edge");
|
||||
const infos = picked.map((x) => ({ s: x, b: app.view.body(x.body), e: app.view.body(x.body)?.edges[x.edge] })).filter((x) => x.b && x.e);
|
||||
if (!infos.length) return;
|
||||
const pts = infos.flatMap((x) => [x.e!.start, x.e!.mid, x.e!.end]);
|
||||
@@ -1089,9 +1341,10 @@ export class SelectTool implements Tool {
|
||||
if (!g) return [];
|
||||
const ps: Vec3[] = [];
|
||||
for (let k = g.start; k < g.start + g.count; k++) if ((k - g.start) % 2 === 0 || k === g.start + g.count - 1) ps.push([b!.edgePositions[k * 3], b!.edgePositions[k * 3 + 1], b!.edgePositions[k * 3 + 2]]);
|
||||
const ent = projectPolyline(ps, plane!, e!.type);
|
||||
if (!ent) return [];
|
||||
const ref = edgeRefOf(app, s);
|
||||
// (A free copy - no steps to follow: with as few points as hold it.)
|
||||
const ent = projectPolyline(ps, plane!, e!.type, !ref?.steps?.length);
|
||||
if (!ent) return [];
|
||||
if (!ref?.steps?.length) return [ent];
|
||||
const id = `ref-${uid()}`;
|
||||
links.push({ id, edge: ref });
|
||||
@@ -1105,7 +1358,7 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
|
||||
private projectFace(then: string): void {
|
||||
const s = this.app.selection[0] as Extract<Sel, { kind: "face" }>;
|
||||
const s = this.picks[0] as Extract<Sel, { kind: "face" }>;
|
||||
const b = this.app.view.body(s.body);
|
||||
const f = b?.faces[s.face];
|
||||
if (!b || !f?.plane) return;
|
||||
@@ -1117,10 +1370,10 @@ export class SelectTool implements Tool {
|
||||
const g = b.edgeGroups.find((x) => x.edge === i)!;
|
||||
const pts: Vec3[] = [];
|
||||
for (let k = g.start; k < g.start + g.count; k++) if ((k - g.start) % 2 === 0 || k === g.start + g.count - 1) pts.push([b.edgePositions[k * 3], b.edgePositions[k * 3 + 1], b.edgePositions[k * 3 + 2]]);
|
||||
const ent = projectPolyline(pts, plane, e.type);
|
||||
if (!ent) return [];
|
||||
// Linked: it follows the face's edge when the body changes.
|
||||
const ref = edgeRefOf(this.app, { body: s.body, edge: i });
|
||||
const ent = projectPolyline(pts, plane, e.type, !ref?.steps?.length);
|
||||
if (!ent) return [];
|
||||
if (!ref?.steps?.length) return [ent];
|
||||
const id = `ref-${uid()}`;
|
||||
links.push({ id, edge: ref });
|
||||
@@ -1211,10 +1464,25 @@ export class SelectTool implements Tool {
|
||||
this.app.ui.toast("Connected - Thickness… makes it a solid");
|
||||
}
|
||||
|
||||
/**
|
||||
* A freeform that is still an open surface (faces deleted from it, or made as a surface): the one kind of freeform
|
||||
* body that isn't worked on like any other - no arrow to push its faces, no dot to round its edges, its points
|
||||
* moved in Edit Freeform. A finished freeform solid is a body like any other: every body tool is its too (asked
|
||||
* for: "a freeform body that is finished (not in freeform edit mode) should be treated like a regular body ... I
|
||||
* want to have access to normal body tools, to polish it even further"). Edit Freeform is still there for it -
|
||||
* beside the body when it is double tapped, and in History.
|
||||
*/
|
||||
private sheetFreeform(body: string): boolean {
|
||||
const live = freeformBodies(this.app.store.features).get(body)?.feature;
|
||||
if (!live) return false;
|
||||
const now = editedStep<FreeformFeature>(this.app.store.features, live.id) ?? live;
|
||||
return !isClosed(now.cage);
|
||||
}
|
||||
|
||||
/** The freeform a body is made from (its own, or the one a copy was made of). */
|
||||
private freeformOf(body: string): FreeformFeature | undefined {
|
||||
const f = this.app.store.find<FreeformFeature>(body);
|
||||
if (f?.type === "freeform") return f;
|
||||
if (f?.type === "freeform") return editedStep<FreeformFeature>(this.app.store.features, f.id);
|
||||
return freeformBodies(this.app.store.features).get(body)?.feature;
|
||||
}
|
||||
|
||||
@@ -1224,7 +1492,7 @@ export class SelectTool implements Tool {
|
||||
*/
|
||||
private ownFreeform(body: string): FreeformFeature | undefined {
|
||||
const f = this.app.store.find<FreeformFeature>(body);
|
||||
if (f?.type === "freeform") return f;
|
||||
if (f?.type === "freeform") return editedStep<FreeformFeature>(this.app.store.features, f.id);
|
||||
const id = this.app.store.newIdentity("freeform").id;
|
||||
const out = detachFreeformCopy(this.app.store.doc, body, id);
|
||||
if (!out) return freeformBodies(this.app.store.features).get(body)?.feature;
|
||||
@@ -1248,7 +1516,7 @@ export class SelectTool implements Tool {
|
||||
/** Delete faces/edges/vertices of one body; tells the user when it can't heal. */
|
||||
private deleteGeom(body: string, what: { faces?: FaceRef[]; edges?: EdgeRef[]; vertices?: Vec3[] }): void {
|
||||
// A freeform body: the cage loses the faces there, and stays open for a thickness.
|
||||
const ff = this.freeformOf(body) && this.ownFreeform(body);
|
||||
const ff = this.sheetFreeform(body) ? this.ownFreeform(body) : undefined;
|
||||
if (ff) {
|
||||
const tool = new FreeformTool(this.app, { feature: ff });
|
||||
this.app.setTool(tool);
|
||||
@@ -1275,7 +1543,7 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
|
||||
/** Loft wants one profile per section. */
|
||||
function splitRegions(s: ExtrudeSource): ExtrudeSource[] {
|
||||
export function splitRegions(s: ExtrudeSource): ExtrudeSource[] {
|
||||
return s.kind === "profile" ? s.regions.map((r) => ({ ...s, regions: [r] })) : [s];
|
||||
}
|
||||
|
||||
|
||||
@@ -40,13 +40,22 @@ const GLYPH: Partial<Record<ConstraintType, string>> = {
|
||||
};
|
||||
|
||||
/** Constraints for a button press, from the current selection (empty if it doesn't fit). */
|
||||
export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): SketchConstraint[] {
|
||||
export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[], all?: SketchEntity[]): SketchConstraint[] {
|
||||
if (type === "hv") {
|
||||
if (curves.length === 1 && curves[0].kind === "line" && !pts.length) {
|
||||
const l = curves[0];
|
||||
const horiz = Math.abs(l.b[0] - l.a[0]) >= Math.abs(l.b[1] - l.a[1]);
|
||||
return [{ id: uid(), type: horiz ? "horizontal" : "vertical", curves: [l.id] }];
|
||||
}
|
||||
// Two points (a circle's centre and a corner, two ends): level with each other, or one above the other -
|
||||
// whichever they are nearer to. (The solver had it; no button gave it.)
|
||||
if (pts.length === 2 && !curves.length && all) {
|
||||
const [a, b] = pts.map((r) => {
|
||||
const e = all.find((x) => x.id === r.e);
|
||||
return e ? pointOf(e, r.p) : null;
|
||||
});
|
||||
if (a && b && Math.hypot(a[0] - b[0], a[1] - b[1]) > 1e-9) return [{ id: uid(), type: Math.abs(b[0] - a[0]) >= Math.abs(b[1] - a[1]) ? "horizontal" : "vertical", pts }];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
if (!applicable(type, pts, curves)) return [];
|
||||
@@ -64,7 +73,7 @@ export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], c
|
||||
case "fix": {
|
||||
// Locking a curve holds all of its points (and a circle's size).
|
||||
const all = [...pts, ...curves.flatMap((e) => pointsOf(e).map((q) => ({ e: e.id, p: q.p })))];
|
||||
const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius }] : []));
|
||||
const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius, held: true }] : []));
|
||||
return [...all.map((p) => ({ id: uid(), type, pts: [p] })), ...sizes];
|
||||
}
|
||||
default:
|
||||
@@ -89,6 +98,16 @@ export function distanceOf(pts: PointRef[], curves: SketchEntity[], all: SketchE
|
||||
const dy = l.b[1] - l.a[1];
|
||||
return Math.abs((p[0] - l.a[0]) * dy - (p[1] - l.a[1]) * dx) / (Math.hypot(dx, dy) || 1);
|
||||
}
|
||||
// Two lines that run the same way (within a degree): how far apart they are - the second's middle from the first.
|
||||
// (Asked for: a distance between two lines. Two lines that cross have an angle between them, not a distance.)
|
||||
const m = curves[1];
|
||||
if (!pts.length && curves.length === 2 && l.kind === "line" && m.kind === "line") {
|
||||
const [dx, dy, ex, ey] = [l.b[0] - l.a[0], l.b[1] - l.a[1], m.b[0] - m.a[0], m.b[1] - m.a[1]];
|
||||
const [L, M] = [Math.hypot(dx, dy), Math.hypot(ex, ey)];
|
||||
if (!(L > 1e-12) || !(M > 1e-12) || Math.abs(dx * ey - dy * ex) / (L * M) > Math.sin(Math.PI / 180)) return null;
|
||||
const mid = [(m.a[0] + m.b[0]) / 2, (m.a[1] + m.b[1]) / 2];
|
||||
return Math.abs((mid[0] - l.a[0]) * dy - (mid[1] - l.a[1]) * dx) / L;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -103,6 +122,8 @@ export function existingConstraints(type: ConstraintType | "hv", constraints: Sk
|
||||
// A point counts as selected when it is, or when its curve is.
|
||||
const ptIn = (p: PointRef) => ptKeys.has(`${p.e}:${p.p}`) || ids.has(p.e);
|
||||
return constraints.filter((c) => {
|
||||
// (The size Lock put on a circle goes with its lock; it was left behind, and the circle unlocked kept its size.)
|
||||
if (type === "fix" && c.type === "dim" && c.held && c.curves?.length === 1 && ids.has(c.curves[0])) return true;
|
||||
if (!types.includes(c.type)) return false;
|
||||
const cv = c.curves ?? [];
|
||||
const cp = c.pts ?? [];
|
||||
@@ -113,10 +134,6 @@ export function existingConstraints(type: ConstraintType | "hv", constraints: Sk
|
||||
});
|
||||
}
|
||||
|
||||
export function buttonEnabled(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): boolean {
|
||||
return buildConstraints(type, pts, curves).length > 0;
|
||||
}
|
||||
|
||||
/** Upsert a driving dimension on one entity (length / radius / w / h / …). */
|
||||
export function setDim(list: SketchConstraint[], entity: string, prop: string, value: number, expr?: string | null): SketchConstraint[] {
|
||||
const i = list.findIndex((c) => c.type === "dim" && c.curves?.[0] === entity && c.curves.length === 1 && c.prop === prop);
|
||||
@@ -172,7 +189,7 @@ export class ConstraintGlyphs {
|
||||
const counts = new Map<string, number>();
|
||||
for (const c of constraints) {
|
||||
// (A pattern's copies have no badge each: there'd be one on every copy.)
|
||||
if (c.type === "pattern") continue;
|
||||
if (c.type === "pattern" || c.type === "follow") continue;
|
||||
// A mark only while everything it ties together is still drawn.
|
||||
if (![...(c.pts ?? []).map((p) => p.e), ...(c.curves ?? [])].every((id) => get(id))) continue;
|
||||
let at: Vec2 | null = null;
|
||||
@@ -271,6 +288,15 @@ export class ConstraintGlyphs {
|
||||
this.host.hidden = !on;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tapped to select (in the Select tool), or let through to the drawing under
|
||||
* them: a rectangle's width label under its edge took Mirror's tap on the
|
||||
* circle there, and the shapes picked so far were let go.
|
||||
*/
|
||||
setTappable(on: boolean): void {
|
||||
this.host.classList.toggle("passive", !on);
|
||||
}
|
||||
|
||||
private layout(): void {
|
||||
if (!this.plane) return;
|
||||
for (const it of this.items) {
|
||||
|
||||
@@ -33,6 +33,22 @@ export function axisSlot(app: AppContext, label: string, get: () => AxisRef | nu
|
||||
],
|
||||
shows: () => (shown ? [shown] : []),
|
||||
accept(hit) {
|
||||
// A point of a sketch (a short axis line is mostly its ends, and the
|
||||
// circle it halves has its own points on it): the sketch line through it.
|
||||
// (Tapped, it was taken for nothing - the Axis waited on.)
|
||||
if (hit.kind === "point") {
|
||||
const s = app.store.find<SketchFeature>(hit.sketch);
|
||||
const plane = app.sketchPlane(hit.sketch);
|
||||
if (!s || !plane) return false;
|
||||
const at = toPlane(plane, hit.point);
|
||||
const on = s.entities.find((e) => e.kind === "line" && closestOnPrim(entityPrims(e)[0], at).d < 1e-6 * Math.max(1, len(sub(toWorld(plane, e.b), toWorld(plane, e.a)))));
|
||||
if (!on || on.kind !== "line") return false;
|
||||
const a = toWorld(plane, on.a);
|
||||
set({ origin: a, dir: norm(sub(toWorld(plane, on.b), a)), ref: { kind: "sketchLine", sketch: s.id, entity: on.id } });
|
||||
name = "Sketch line";
|
||||
shown = { kind: "curve", sketch: s.id, entity: on.id } as Sel;
|
||||
return true;
|
||||
}
|
||||
if (hit.kind === "curve") {
|
||||
const s = app.store.find<SketchFeature>(hit.sketch);
|
||||
const e = s?.entities.find((x) => x.id === hit.entity);
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface Tool extends PointerHandler {
|
||||
exit?(): void;
|
||||
/** Return true when the key was handled. */
|
||||
key?(e: KeyboardEvent): boolean;
|
||||
/** Ctrl + A: pick everything the tool picks from. False: it has nothing of the kind. */
|
||||
selectAll?(): boolean;
|
||||
/** Keys typed while a drag is held (type an exact value; Enter finishes). */
|
||||
dragKey?(e: KeyboardEvent): boolean;
|
||||
/** Called after every regeneration (committed or preview). */
|
||||
@@ -63,6 +65,8 @@ export interface AppContext {
|
||||
/** A sketch's curves plus the outline of the face it sits on (what regions are made of). */
|
||||
sketchCurves(id: string): SketchEntity[];
|
||||
mainTools(): ToolItem[];
|
||||
/** The first model on its way: a shape drawn, nothing solid yet - Extrude is the next step (it pulses). */
|
||||
firstShape(): boolean;
|
||||
bottomTools(): ToolItem[];
|
||||
/** Pin a measurement in 3D (saved with the project). */
|
||||
addPin(pin: PinDef): void;
|
||||
@@ -150,6 +154,27 @@ app: AppContext, s: { body: string; edge: number }): EdgeRef | null {
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* The edges round a face (its outline and its holes'), by index: those whose
|
||||
* drawn points are all corners of its triangles (the face's mesh and the
|
||||
* edges' lines are cut from one tessellation, so they share their points).
|
||||
*/
|
||||
export function edgesOfFace(app: AppContext, body: string, face: number): number[] {
|
||||
const m = app.view.body(body);
|
||||
const g = m?.faceGroups.find((x) => x.face === face);
|
||||
if (!m || !g) return [];
|
||||
const key = (a: ArrayLike<number>, i: number) => `${Math.round(a[3 * i] * 1e4)},${Math.round(a[3 * i + 1] * 1e4)},${Math.round(a[3 * i + 2] * 1e4)}`;
|
||||
const corners = new Set<string>();
|
||||
for (let k = g.start; k < g.start + g.count; k++) corners.add(key(m.positions, m.indices[k]));
|
||||
return m.edgeGroups
|
||||
.filter((eg) => {
|
||||
if (!eg.count) return false;
|
||||
for (let j = eg.start; j < eg.start + eg.count; j++) if (!corners.has(key(m.edgePositions, j))) return false;
|
||||
return true;
|
||||
})
|
||||
.map((eg) => eg.edge);
|
||||
}
|
||||
|
||||
/** A selected profile or flat face as something extrude/revolve/… can use. */
|
||||
export function sourcesOf(app: AppContext, sel: Sel[]): ExtrudeSource[] {
|
||||
const out: ExtrudeSource[] = [];
|
||||
@@ -262,7 +287,20 @@ export function sourceFrame(app: AppContext, src: ExtrudeSource): { base: Vec3;
|
||||
/** Body that a source "sits on" (joins/cuts default to it). */
|
||||
export function targetOf(app: AppContext, src: ExtrudeSource): string | undefined {
|
||||
if (src.kind === "face") return src.face.body;
|
||||
return app.store.find<SketchFeature>(src.sketch)?.attachedTo?.body;
|
||||
const on = app.store.find<SketchFeature>(src.sketch)?.attachedTo?.body;
|
||||
if (on) return on;
|
||||
// Drawn on its own, but a body was made from the same region of it (a cookie
|
||||
// cutter's wall, 2 high with its flange, then taken on up to 15): that body.
|
||||
// Auto otherwise cut the region out of it, and what went past wasn't added.
|
||||
const key = (r: { c: number[]; k?: string[] }) => (r.k?.length ? [...r.k].sort().join("|") : r.c.map((v) => v.toFixed(3)).join(","));
|
||||
const mine = new Set(src.regions.map(key));
|
||||
for (const f of app.store.features) {
|
||||
if ((f.type !== "extrude" && f.type !== "revolve" && f.type !== "sweep") || f.source.kind !== "profile" || f.source.sketch !== src.sketch || f.mode === "cut" || f.mode === "intersect") continue;
|
||||
if (!f.source.regions.some((r) => mine.has(key(r)))) continue;
|
||||
const body = f.target ?? f.id;
|
||||
if (app.view.body(body)) return body;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Bodies referenced by the selection (faces/edges/vertices count for their body). */
|
||||
|
||||
@@ -12,6 +12,7 @@ import { mergingCommits } from "../doc/store";
|
||||
import type { Variable, Vec3 } from "../doc/types";
|
||||
import type { VarKind, VarTag } from "../doc/varAnchors";
|
||||
import { numpadInput, openNumpad } from "../ui/numpad";
|
||||
import { selectAll } from "../ui/textField";
|
||||
import { el } from "../ui/ui";
|
||||
import { bareExpr, toDisplay, trim, withUnitOf } from "../units";
|
||||
import type { Viewport } from "../view/viewport";
|
||||
@@ -168,7 +169,7 @@ export class VariableTags {
|
||||
this.showValue();
|
||||
this.layout();
|
||||
this.input.focus();
|
||||
this.input.select();
|
||||
selectAll(this.input);
|
||||
openNumpad(this.input);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
// Variables switched on (like Section View): the tags show in the view, and a
|
||||
// card with New Variable and the whole list. Tapping the view leaves the card;
|
||||
// the tags stay until Variables is tapped again (or Turn Off).
|
||||
// the tags stay until Variables is tapped again (or switched off in the card).
|
||||
|
||||
import { createVariable, editVariables } from "../io/insert";
|
||||
import { createVariable, editVariables, renameVariables } from "../io/insert";
|
||||
import type { AppContext, Tool } from "./tool";
|
||||
|
||||
export interface VariablesHost extends AppContext {
|
||||
/** Variables off: the tags go, and this card. */
|
||||
variablesOff(): void;
|
||||
/** The tags shown on the model (Variables on). */
|
||||
readonly varsOn: boolean;
|
||||
/** The tags on or off, the card staying. */
|
||||
showVariables(on: boolean): void;
|
||||
}
|
||||
|
||||
export class VariablesTool implements Tool {
|
||||
@@ -30,8 +34,11 @@ export class VariablesTool implements Tool {
|
||||
items: [
|
||||
{ type: "button", label: "New Variable", icon: "variableNew", primary: !n, onClick: () => void createVariable(this.app).then(() => this.showCard()) },
|
||||
...(n ? [{ type: "button" as const, label: `All Variables (${n})`, icon: "variable" as const, onClick: () => void editVariables(this.app).then(() => this.showCard()) }] : []),
|
||||
...(n ? [{ type: "button" as const, label: "Rename", icon: "variable" as const, onClick: () => void renameVariables(this.app).then(() => this.showCard()) }] : []),
|
||||
// On / off a tap each way: the tags on the model go and come back, the card stays.
|
||||
{ type: "toggle", label: "Variables", value: this.app.varsOn, onChange: (v) => (this.app.showVariables(v), this.showCard()) },
|
||||
],
|
||||
actions: [{ id: "off", label: "Turn Off", icon: "close", run: () => this.app.variablesOff() }],
|
||||
actions: [],
|
||||
onDone: () => this.leave(),
|
||||
});
|
||||
}
|
||||
@@ -47,7 +54,7 @@ export class VariablesTool implements Tool {
|
||||
* over nothing - it's off then.
|
||||
*/
|
||||
private leave(): void {
|
||||
if (this.app.store.doc.variables.length) this.app.setTool(null);
|
||||
if (this.app.store.doc.variables.length && this.app.varsOn) this.app.setTool(null);
|
||||
else this.app.variablesOff();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import type { EdgeRef, ExtrudeSource, FaceRef, ImprintFeature, PlaneDef, SketchFeature, WrapFeature } from "../doc/types";
|
||||
import { projectRegions } from "../sketch/edit";
|
||||
import { arrangement, resolveRegion, type Region } from "../sketch/regions";
|
||||
import { arrangement, materialRegions, regionRef, resolveRegion, type Region } from "../sketch/regions";
|
||||
import { planeSlot } from "./slots";
|
||||
import type { PanelItem } from "../ui/ui";
|
||||
import { FeatureOp, type Slot } from "./featureOp";
|
||||
@@ -31,6 +31,59 @@ function faceSlot(app: AppContext, label: string, get: () => FaceRef | null, set
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The sketch's shapes a step puts onto the body: more of them tapped, one
|
||||
* tapped again taken back out, or All (every shape drawn, letters with their
|
||||
* holes). Started from the menu, the first shape tapped was all it took: a
|
||||
* word wrapped round a mug came out as its first letter, a handle's second pad
|
||||
* was never drawn onto it.
|
||||
*/
|
||||
function shapesSlot(app: AppContext, get: () => ExtrudeSource | undefined, set: (s: ExtrudeSource) => void): Slot {
|
||||
const regionsOf = (sketch: string) => arrangement(app.sketchCurves(sketch)).regions;
|
||||
const same = (a: { c: number[] }, b: { c: number[] }) => Math.hypot(a.c[0] - b.c[0], a.c[1] - b.c[1]) < 1e-6;
|
||||
const count = () => {
|
||||
const s = get();
|
||||
return s?.kind === "profile" ? s.regions.length : 0;
|
||||
};
|
||||
return {
|
||||
label: "Shapes",
|
||||
multi: true,
|
||||
describe: () => (count() ? `${count()} shape${count() > 1 ? "s" : ""} - tap more` : "Tap the shapes"),
|
||||
filled: () => count() > 0,
|
||||
pick: { bodies: false, edges: false, vertices: false, planes: false, axes: false },
|
||||
shows: () => {
|
||||
const s = get();
|
||||
if (s?.kind !== "profile") return [];
|
||||
const all = regionsOf(s.sketch).map(regionRef);
|
||||
return s.regions.map((r) => ({ kind: "profile" as const, sketch: s.sketch, region: all.findIndex((x) => same(x, r)) })).filter((x) => x.region >= 0);
|
||||
},
|
||||
presets: [
|
||||
{
|
||||
label: "All",
|
||||
apply: () => {
|
||||
const s = get();
|
||||
if (s?.kind === "profile") set({ ...s, regions: materialRegions(arrangement(app.sketchCurves(s.sketch))).map(regionRef) });
|
||||
},
|
||||
},
|
||||
],
|
||||
accept(hit) {
|
||||
if (hit.kind !== "profile") return false;
|
||||
const r = regionsOf(hit.sketch)[hit.region];
|
||||
if (!r) return false;
|
||||
const ref = regionRef(r);
|
||||
const s = get();
|
||||
// (Another sketch's shape: that sketch's instead.)
|
||||
if (s?.kind !== "profile" || s.sketch !== hit.sketch) set({ kind: "profile", sketch: hit.sketch, regions: [ref] });
|
||||
else {
|
||||
const i = s.regions.findIndex((x) => same(x, ref));
|
||||
if (i >= 0 && s.regions.length === 1) return true;
|
||||
set({ ...s, regions: i >= 0 ? s.regions.filter((_, j) => j !== i) : [...s.regions, ref] });
|
||||
}
|
||||
return true;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Project as Edge. A sketch: its shapes drawn onto the body's faces seen from
|
||||
* it, along its normal. Edges: drawn onto a face picked next, along its normal.
|
||||
@@ -51,6 +104,7 @@ export class ImprintOp extends FeatureOp<ImprintFeature> {
|
||||
this.onto = f.face ?? null;
|
||||
if (f.source) {
|
||||
this.slots = [
|
||||
shapesSlot(app, () => f.source, (src) => (f.source = src)),
|
||||
faceSlot(
|
||||
app,
|
||||
"Onto body",
|
||||
@@ -96,6 +150,7 @@ export class WrapOp extends FeatureOp<WrapFeature> {
|
||||
const f = this.feature;
|
||||
this.onto = existing ? existing.face : null;
|
||||
this.slots = [
|
||||
shapesSlot(app, () => f.source, (src) => (f.source = src)),
|
||||
faceSlot(
|
||||
app,
|
||||
"Round face",
|
||||
|
||||
@@ -110,7 +110,7 @@ export function showAbout(): void {
|
||||
const back = el("div", "dialog-back");
|
||||
const box = el("div", "dialog about");
|
||||
const head = el("div", "library-head");
|
||||
head.append(el("div", "panel-title", "About supergeometry.app"));
|
||||
head.append(el("div", "panel-title", "About"));
|
||||
const closeBtn = el("button", "icon-btn library-close");
|
||||
closeBtn.type = "button";
|
||||
closeBtn.title = "Close";
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// as you go. Done keeps it; Cancel (or Esc, or a tap outside) puts it back.
|
||||
|
||||
import { el, textButton } from "./ui";
|
||||
import { textField } from "./textField";
|
||||
|
||||
type HSV = [number, number, number];
|
||||
|
||||
@@ -80,10 +81,7 @@ export function pickColor(title: string, start: string, live: (hex: string) => v
|
||||
|
||||
const row = el("div", "color-row");
|
||||
const preview = el("span", "swatch color-preview");
|
||||
const input = document.createElement("input");
|
||||
input.className = "color-hex";
|
||||
input.autocomplete = "off";
|
||||
input.spellcheck = false;
|
||||
const input = textField("color-hex");
|
||||
input.maxLength = 7;
|
||||
row.append(preview, input);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// so a command is found by its label there, and run as a tap would run it.
|
||||
|
||||
import { icons } from "./icons";
|
||||
import { caretAtEnd, caretToEnd, textField } from "./textField";
|
||||
import { el, type ToolItem } from "./ui";
|
||||
|
||||
export interface Listed {
|
||||
@@ -83,14 +84,11 @@ let openBox: HTMLElement | null = null;
|
||||
* closes. What the picked thing offers comes first.
|
||||
*/
|
||||
export function openCommandSearch(offered: () => ToolItem[], main: () => ToolItem[]): void {
|
||||
if (openBox) return void openBox.querySelector("input")?.focus();
|
||||
if (openBox) return void openBox.querySelector<HTMLElement>(".cmd-input")?.focus();
|
||||
const box = el("div", "cmd-search");
|
||||
const input = el("input", "cmd-input");
|
||||
input.type = "text";
|
||||
const input = textField("cmd-input");
|
||||
input.placeholder = "Search commands…";
|
||||
input.setAttribute("aria-label", "Search commands");
|
||||
input.autocomplete = "off";
|
||||
input.spellcheck = false;
|
||||
const list = el("div", "cmd-list");
|
||||
list.setAttribute("role", "listbox");
|
||||
box.append(input, list);
|
||||
@@ -179,9 +177,10 @@ export function openCommandSearch(offered: () => ToolItem[], main: () => ToolIte
|
||||
paint();
|
||||
}
|
||||
// → at the end of the text: the highlighted command's whole name.
|
||||
if (e.key === "ArrowRight" && input.selectionStart === input.value.length && shown[at]) {
|
||||
if (e.key === "ArrowRight" && caretAtEnd(input) && shown[at]) {
|
||||
e.preventDefault();
|
||||
input.value = shown[at].label;
|
||||
caretToEnd(input);
|
||||
filter();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import { icons } from "./icons";
|
||||
import { el, textButton } from "./ui";
|
||||
import { textField as typingBox } from "./textField";
|
||||
import { openSupport } from "./support";
|
||||
|
||||
export const SUBREDDIT = "supergeometry";
|
||||
@@ -34,7 +35,7 @@ export function deviceLine(): string {
|
||||
}
|
||||
|
||||
export function infoLine(): string {
|
||||
return `supergeometry.app ${__APP_VERSION__} · ${deviceLine()}`;
|
||||
return `superGeometry.app ${__APP_VERSION__} · ${deviceLine()}`;
|
||||
}
|
||||
|
||||
/** Reddit's "new text post" page for the subreddit, filled in. */
|
||||
@@ -72,15 +73,13 @@ export function showFeedback(): void {
|
||||
|
||||
const titleField = el("label", "dialog-field");
|
||||
titleField.append(el("span", "field-label", "Title"));
|
||||
const title = document.createElement("input");
|
||||
const title = typingBox();
|
||||
title.maxLength = 280;
|
||||
title.autocomplete = "off";
|
||||
titleField.append(title);
|
||||
|
||||
const textField = el("label", "dialog-field");
|
||||
textField.append(el("span", "field-label", "Description"));
|
||||
const text = document.createElement("textarea");
|
||||
text.rows = 6;
|
||||
const text = typingBox("", { multiline: true });
|
||||
text.maxLength = MAX_TEXT;
|
||||
textField.append(text);
|
||||
|
||||
|
||||
@@ -13,47 +13,52 @@ interface Entry {
|
||||
const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [
|
||||
{
|
||||
title: "Getting around",
|
||||
intro: "Drag with one finger or the left mouse button to turn the view, two fingers or the right button to move it, pinch or scroll to zoom. On touch screens, press and hold a tool to see its name - let go on it to use it, slide off to cancel. Esc steps back: first what's half done or picked, then the tool, then out of the sketch. Right-click (on touch screens and headsets: press and hold still) opens a menu by the pointer: a tool's Done and Cancel, what can be done with what's picked, and the view's switches.",
|
||||
intro: "Drag with one finger or the right mouse button to turn the view, two fingers or the middle button to move it, pinch or scroll to zoom (Settings → Mouse makes the mouse work as in another CAD program: Fusion, SolidWorks, Onshape, Creo, NX, CATIA, FreeCAD, Blender, Rhino and others). With a mouse, a left drag on empty space draws a box to select with (bodies; with none in it, the closed shapes of a sketch), and Ctrl + A picks everything. While a shape is drawn, type its sizes: a number, Tab for the next size, Enter or a click to place it - with a mouse they show in tags by the pointer. Esc steps back: first what's half done or picked, then the tool, then out of the sketch. Right-click (on touch screens and headsets: press and hold still on an empty spot) opens a menu by the pointer: a tool's Done and Cancel, what can be done with what's picked, and the view's switches. A list opened from the line at the bottom stays up while the view is turned, moved or zoomed.",
|
||||
items: [
|
||||
{ icon: "fit", name: "Fit", text: "Zooms so everything fits on screen (F)." },
|
||||
{ icon: "views", name: "View cube", text: "Tap a face of the cube for a straight-on view; ⟲ ⟳ at its top corners turn the view by 90°." },
|
||||
{ icon: "fit", name: "Fit", text: "Double-tap (or double-click) the view cube: zooms so everything fits on screen (F)." },
|
||||
{ icon: "views", name: "View cube", text: "Tap a face of the cube for a straight-on view; ⟲ ⟳ at its top corners turn the view by 90°. Double-tap it to fit everything on screen." },
|
||||
{ icon: "pivot", name: "Orbit centre", text: "The cube's bottom-left button: tap it, then tap a point - the view turns around that point. Fit resets it." },
|
||||
{ icon: "views", name: "Views & appearance", text: "The cube's bottom-right button opens (and closes) standard and saved views and the look of the view." },
|
||||
{ icon: "views", name: "Views", text: "The cube's bottom-right button opens (and closes) standard and saved views. How the view looks is under Display and Settings at the right edge." },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Top bar",
|
||||
title: "Top bar and the line at the bottom",
|
||||
items: [
|
||||
{ icon: "file", name: "File", text: "New, open and save projects (.super). Every project you work on is kept on this device: Open shows them as pictures - tap one to carry on, or Open file… for any .super file (each copy can be saved as a file or deleted there). New keeps the open one. Clearing the site's data in the browser deletes them, so save the ones that matter as files too. Export STL or 3MF for 3D printing, STEP for other CAD programs, DXF of a sketch (tap it in Items first) for laser cutters and CNC. The share mark next to each sends the file straight to another app (phones and tablets)." },
|
||||
{ icon: "body", name: "Items", text: "Every body, sketch, plane and image, with an eye to hide or show it. Each kind (Bodies, Sketches, Planes & axes, Images) folds away under its heading; a plane's icon shows how it was made. Group things into folders (Select, tick them, New folder); tick items all in one folder for New subfolder inside it. Remove takes ticked items out of their folder (one level up); Move, then tick a folder or subfolder, puts them in it. A tool waiting for a body takes one tapped here. What is selected in the view (a body double-clicked, a plane) lights up in the list." },
|
||||
{ icon: "more", name: "More", text: "Fullscreen (also in the window the app opens with), Update (loads the newest version - when one is out, More pulses and this item shows a pulsing NEW), this Help, Feedback (a bug report, suggestion or discussion, posted on r/supergeometry), About, and support links." },
|
||||
{ icon: "more", name: "More", text: "Fullscreen (also in the window the app opens with), Update (loads the newest version - when one is out, More pulses and this item shows NEW), this Help, Feedback (a bug report, suggestion or discussion, posted on r/supergeometry), About, and support links." },
|
||||
{ icon: "tools", name: "The line", text: "The line at the bottom is how every tool is reached. Tap part of the model (a face, an edge, a body, a sketch's shape): a tag over the line names what is picked, and the line shows the groups - Sketch, Freeform, Transform, Construct, Modify, Combine, Create - each a list: what can be done with that pick first, then the group's other tools in a quieter part (each of those asks for its own pick as it starts; with nothing picked: all the tools). The group whose list is open stays lit, and a list inside another says where it is (Transform › Pattern). More, at the end, holds only what is not on the line already: Insert, BIM, Section View, Measure, Variables, Print / Share, and the pick's own (Delete, Colour). Tap a tool and the line becomes its settings: tap a number to type it (or drag it sideways), tap a word to change it, tap the model to fill a blank. On a phone held upright a tool shows its size and what it still needs tapped; the rest is one word, Options. The tick finishes, the cross takes it back, the x on the tag lets go of the pick. With the pointer over a tool, some show in dashed yellow on the model what they would do (Extrude, Offset Face, Shell, Fillet, Chamfer, the patterns). At the right edge: Fit, Display and Settings (units & grid, snapping, the numpad, appearance)." },
|
||||
{ icon: "tools", name: "Tutorial", text: "More > Tutorial builds an M10 bolt and the nut that fits it with you, in their real sizes, one tap at a time, with tools from Sketch, Create, Modify and Combine: a rod, a hexagon head, chamfered edges, a thread, and a nut cut to fit with 0.2 mm of room so the printed pair turns. The screen is dimmed but for the spot to tap next, with a short sentence beside it; the shapes land exactly where they belong wherever in the lit spot you tap, the head's and the nut's thickness are set for you, and a size typed wrong is set right. It starts a new project (the one open is saved); Exit tutorial leaves it at any step. Where a tap lands inside the lit spot does not matter. At the end, New project starts one of your own (the bolt and nut stay in the list of projects). The first time the app is opened it is offered once the welcome window is closed." },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Making shapes (left column, nothing selected)",
|
||||
intro: "Most work starts with a sketch on a plane or a flat face, then Extrude or Revolve turns it into a solid body.",
|
||||
title: "Making shapes (nothing selected)",
|
||||
intro: "Most work starts with a sketch on a plane or a flat face, then Extrude or Revolve turns it into a solid body. Pick the thing first, then its tool, on the line at the bottom: Create (Extrude, Revolve, Sweep, Loft), Modify (Fillet, Chamfer, Shell, Offset Face, Offset Edge, Thread, Wrap & Emboss, and Fix › Fill, Fill to Plane, Repair Body), Combine (Union, Subtract, Intersect, Split Body), Transform (Move › Move/Rotate, Translate, Rotate Around Axis; Scale, Mirror, Pattern), Construct (Plane, Axis, Project as Edge), Freeform and Sketch. More, at the end of the line, has Insert, BIM, Section View, Measure, Variables and Print / Share. A tool started with nothing picked says what to tap. A new project opens straight in a sketch on the floor with Line on.",
|
||||
items: [
|
||||
{ icon: "sketch", name: "Sketch", text: "Pick a plane (tap it, or the XY floor / XZ front / YZ side buttons), one of your construction planes by name, or a flat face, then draw lines, arcs, circles, rectangles… In a straight-on view (Front, Top…) Sketch goes on the face you're looking at. Closed shapes become profiles you can extrude." },
|
||||
{ icon: "freeform", name: "Freeform", text: "Smooth organic shapes: start from a box, sphere, cylinder or plane (its size in the card) and pull its control points, edges and faces. Drag a box on empty space to pick the points inside. Cage tools: Extrude faces (Length, Bend, Taper, Steps - a spout in one go), Bridge two faces (a tube, or an arched handle), Inset, Add edge loop, Add detail. Symmetry mirrors every move across X / Y / Z, a tapped edge, or midway between two facing faces picked first; the plane is kept with the shape. A hole: tap its edge → Fill hole, or Thickness… for a solid wall. Points on an open border → Extend surface adds faces beyond them. Connect: pick border edges on one or two surfaces (Shift adds) - two edges get a face between them, two hole rims a tube." },
|
||||
{ icon: "extrude", name: "Extrude", text: "Pull a profile or a face straight out into a solid. Drag the arrow or type a distance; negative values cut. Running into another body cuts through it. Taper end % sizes the far end: 100 none, 50 half, 0 to a point (a spire, a cone) - type it, or press on the box and drag left / right. All shapes takes every shape of the sketch at once. A tapped shape shows Extrude's arrow, with Revolve, Sweep and Loft beside it in the column." },
|
||||
{ icon: "sketch", name: "Sketch", text: "Pick a plane (tap it, or the XY floor / XZ front / YZ side buttons), one of your construction planes by name, or a flat face, then draw lines, arcs, circles, rectangles… In a straight-on view (Front, Top…) Sketch goes on the face you're looking at. A new sketch starts with Line on. Closed shapes become profiles you can extrude: leave the sketch right after closing one and it is picked, the view turned so you can see it rise - drag the shape itself, or its arrow." },
|
||||
{ icon: "freeform", name: "Freeform", text: "Smooth organic shapes: start from a box, sphere, cylinder, torus or surface (its size on the line) and pull its control points, edges and faces. Drag a box on empty space to pick the points inside (on a touch screen, switch on Pick in a box first: a finger then draws the box, the points behind picked too - a whole slice from a side view). A picked face is pushed in or pulled out by dragging it. Move, Turn, Scale or Place at (the picked points put at an exact X, Y, Z); Soft makes the points round the picked ones follow a move, less the further off they are. Cage tools: Extrude faces (Length, Bend, Taper, Steps - a spout in one go), Bridge two faces (a tube, or an arched handle), Inset, Add edge loop and Remove edge loop, Add detail. Sharp edge (or Sharp loop) keeps a crease along the picked edges instead of rounding over - shown orange; Smooth edge takes it off. Symmetry mirrors every move across X / Y / Z, a tapped edge, or midway between two facing faces picked first; the plane is kept with the shape. A hole: tap one edge of its rim → Fill hole (two holes: Bridge holes), or Thickness… for a solid wall. Points on an open border → Extend surface adds faces beyond them. Connect: pick border edges on one or two surfaces (Shift adds) - two edges get a face between them, two hole rims a tube." },
|
||||
{ icon: "extrude", name: "Extrude", text: "Pull a profile or a face straight out into a solid: drag the arrow or type a distance. Operation (Auto, New body, Add, Cut, Intersect): Auto goes by direction - on a plane + is a new body and - a cut, on a face out adds and in cuts. From a face, round buttons beside it offer what that direction can do (out: Add, New body; in: Cut, Intersect, New body): the lit one is what it does, tap another to switch. Taper end % sizes the far end: 100 none, 50 half, 0 to a point (a spire, a cone) - type it, or press on the box and drag left / right. All shapes takes every shape of the sketch at once." },
|
||||
{ icon: "revolve", name: "Revolve", text: "Turn a profile around an axis (vases, wheels). Travel moves it along the axis while turning - with more than 360° that makes threads and springs." },
|
||||
{ icon: "sweep", name: "Sweep", text: "Move a profile along a path curve (pipes, handles). End size grows or shrinks it on the way: 2 ends twice as big, 0.5 half (a horn, a tapered handle). Twist turns it round the path as it goes (degrees from start to end: a twisted bar, a drill flute)." },
|
||||
{ icon: "loft", name: "Loft", text: "Blend between two or more profiles, e.g. a square into a circle. Closed loop goes on from the last back to the first (a ring, a handle). Add guide: a curve the body follows through the profiles (each one sitting across it)." },
|
||||
{ icon: "shell", name: "Shell", text: "Hollow a body out, leaving walls of the thickness you choose; picked faces become openings." },
|
||||
{ icon: "transform", name: "Transform", text: "Move/Rotate, Scale (all ways at once, along X / Y / Z only, or by reference: tap two points and type what their distance should be - in sketches too), Translate (from a point to a point - a corner, edge, face, sketch point, or the origin 0, 0, 0 where the axes cross), Mirror, Rotate Around Axis and Patterns (copies in a row or around a centre)." },
|
||||
{ icon: "union", name: "Union / Subtract / Intersect", text: "Combine bodies, cut one from another, or keep only where they overlap. Union needs the bodies to touch. Subtract / Intersect: tap the body to change (marked +), then the bodies to cut with (marked −); Keep modified body / Keep subtracted bodies leave copies. Two overlapping bodies picked: all three are in the list." },
|
||||
{ icon: "tools", name: "Tools", text: "Split Body (by a plane or face), Fill to Plane (an open freeform surface filled down to a plane becomes a solid), Thread (tap a round face or a hole's rim: ISO pitch, outside or inside, left-hand as an option), Repair Body (fixes an imported or broken body without changing its shape), Offset Face, Offset Edge (tap a straight edge, then a flat face: a line on that face parallel to the edge at the distance you type, running right across the face from edge to edge - it splits the face into shapes to extrude or cut; with a face selected it's Offset from Edge: tap the edge next)." },
|
||||
{ icon: "shell", name: "Shell", text: "Hollow a body out, leaving walls of the thickness you choose; picked faces become openings. Drag the arrow on the open face (into the body: thicker), or type." },
|
||||
{ icon: "transform", name: "Transform", text: "Move/Rotate, Scale (all ways at once, along X / Y / Z only, or by reference: tap two points and type what their distance should be - in sketches too), Translate (from a point to a point - a corner, edge, face, sketch point, or the origin 0, 0, 0 where the axes cross), Mirror, Rotate Around Axis and Patterns (copies in a row or around a centre). A row: point at an axis, an edge or a face to see the copies along it in dashed yellow, tap it, then drag the arrow on the first copy for the spacing. A ring: tap an axis, then drag the dot on the last copy round it for the angle. Count is a number on the line." },
|
||||
{ icon: "union", name: "Union / Subtract / Intersect", text: "Combine bodies, cut one from another, or keep only where they overlap. Union needs the bodies to touch. Subtract / Intersect: tap the body to change (marked +), then the bodies to cut with (marked −) - tap a sign to turn it the other way if you picked them in the wrong order; Keep modified body / Keep subtracted bodies leave copies. Subtract with a Clearance (type it in the box on the model) leaves that gap between them, for parts that must move or fit (print-in-place): cut from the body (a hole a little bigger than its peg), from the bodies it is subtracted with, or from both (half each - a peg through a plate becomes a pin in a hole). Two overlapping bodies picked: all three are in the list." },
|
||||
{ icon: "tools", name: "Split, Fill, Thread, Repair, Offset", text: "Split Body (by a plane or face), Fill to Plane (an open freeform surface filled down to a plane becomes a solid), Thread (tap a round face or a hole's rim: ISO pitch, outside or inside, left-hand as an option; free ends get a 45° lead-in), Repair Body (fixes an imported or broken body without changing its shape), Offset Face, Offset Edge (tap a straight edge, then a flat face: a line on that face parallel to the edge at the distance you drag with its double arrow or type, running right across the face from edge to edge - it splits the face into shapes to extrude or cut; with a face selected it's Offset from Edge: tap the edge next)." },
|
||||
{ icon: "patternLinear", name: "Pattern a hole, thread starts", text: "Tap the round wall of a hole, then Pattern - Linear or Circular: the hole is repeated in its body (the same depth), not the body copied. Thread has Starts: 1 is a bolt's thread; 2 to 8 are that many threads side by side, the crests still a pitch apart - a jar's lid, on in part of a turn." },
|
||||
{ icon: "construct", name: "Construct", text: "Helper planes - offset, midplane, through 3 points, on a curve, perpendicular to an edge, through an edge at an angle, parallel to a face - each with its own mark at a corner. Tap a plane you made: its gimbal moves it (the blue arrow changes its offset) or turns it; with Copy on beside it a drag makes a new plane, selected after so the next drag copies again; and axes (from a face or edge, or along X / Y / Z through a point you type)." },
|
||||
{ icon: "insert", name: "Insert", text: "Images to trace over (on the floor, front or side, at the X / Y you type), STEP/STL/SVG/DXF files." },
|
||||
{ icon: "insert", name: "Insert", text: "More › Insert. Image on plane: a picture to trace over (on the floor, front or side, at the X / Y you type). File: STEP, STL, OBJ, 3MF, DXF and SVG files. Project: another .super project's parts, brought into this one." },
|
||||
{ icon: "refImage", name: "Reference Image", text: "More › Insert › Reference Image: a picture in its own window over the model (under the buttons), to look at while you model. Drag it by its top bar or the picture, resize it from the corner, minimize it to its bar. Zoom the picture with the mouse wheel or a pinch; zoomed in, drag it to look about; double click or double tap to see it whole. More pictures are tabs along the top (+ adds one); drag a tab out to give it a window of its own, or onto another window's tabs to join them. They stay on this device until you close them, and are not part of the project." },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "With something selected",
|
||||
intro: "Tap a face, edge, corner or body: the left column shows only what can be done with it, in groups apart with a dim line. On touch screens every tap adds to the selection (tap again to drop it). The most likely tool is ready at once: a shape extrudes, a face offsets, an edge rounds, a body moves - drag its handle, or just type the value. Right-click (or press and hold) shows the same list by the pointer.",
|
||||
intro: "Tap a face, edge, corner or body: its most likely tool is ready at once (a shape extrudes, a face moves, an edge rounds, a body moves - drag its handle or type the value), the round buttons beside it hold the next two (a flat face Sketch and Move, a round one Thread and Fillet, an edge Fillet and Chamfer, a body Fillet and Mirror), then Delete, then More, which opens every other tool for that pick (Shell is there), and the line at the bottom has them all by group. Each tap adds to what is picked; a tap on a picked one lets it go, and a tap on nothing lets them all go. With a face, edge or corner picked, Whole body beside its name picks the body (a double tap on the model does too). Right-click shows the list by the pointer.",
|
||||
items: [
|
||||
{ icon: "offsetFace", name: "Face", text: "Drag the arrow to push/pull it (its neighbours follow), Move/Rotate it (every way, and turned about its normal), Scale it, Replace it with another face's plane, sketch on it, or delete it (the neighbours close up as if it was never there - fillets too)." },
|
||||
{ icon: "moveEdge", name: "Edge", text: "Fillet is ready: drag the dot outward to round, inward to bevel, or type the radius. Fillet can be Variable (a start and an end radius; Flip ends swaps them), sized by Chord width (straight across the round) instead of radius, Smooth (G2: the bend eases in from the faces, no line in reflections - straight edges between flat faces, and round edges of cylinders), and given a Corner setback (where three rounded edges meet they stop short and one smooth patch joins them). A round too big for a face beside it cuts on through that face's far edge, still exactly round. Chamfer can use two distances (Flip sides swaps them). Move/Rotate Edge (M) tilts the faces round a straight edge." },
|
||||
{ icon: "move", name: "Body", text: "The gimbal moves (arrows), slides (squares) and turns (rings) it. With Copy on, a drag makes a copy; the panel stays when you let go so you can type exact values. A copy is its own body; switch Link on to keep a freeform copy shaped like its original. A body of a pattern: Whole Pattern picks the rest." },
|
||||
{ icon: "offsetFace", name: "Face", text: "Drag the face itself, or its arrow, to push/pull it (its neighbours follow; on a touch screen press and hold a face, then pull, in one touch), Move/Rotate it (every way, and turned about its normal), Scale it, Replace it with another face's plane, sketch on it, or delete it (the neighbours close up as if it was never there - fillets too)." },
|
||||
{ icon: "moveEdge", name: "Edge", text: "Fillet is ready: drag the edge itself or its dot outward to round, inward to bevel, or type the radius. Fillet can be Variable (a start and an end radius; Flip ends swaps them), sized by Chord width (straight across the round) instead of radius, Smooth (G2: the bend eases in from the faces, no line in reflections - straight edges between flat faces, and round edges of cylinders), and given a Corner setback (where three rounded edges meet they stop short and one smooth patch joins them). A round too big for a face beside it cuts on through that face's far edge, still exactly round. Chamfer can use two distances (Flip sides swaps them). Move/Rotate Edge (M) tilts the faces round a straight edge." },
|
||||
{ icon: "move", name: "Body", text: "Drag the body itself to slide it over the floor. The gimbal moves (arrows), slides (squares) and turns (rings) it; drag the dot in its middle to move the point it turns about - it snaps to corners, edges and faces. With Copy on, a drag makes a copy; the panel stays when you let go so you can type exact values. A copy is its own body; switch Link on to keep a freeform copy shaped like its original. A body of a pattern: Whole Pattern picks the rest." },
|
||||
{ icon: "link", name: "Link (copies and patterns)", text: "With Copy on in Move/Rotate, Mirror or Scale - and in both Patterns - switch Link on: the copies and what they were made from then change together. Round an edge or cut a hole in any one of them and all the others get it too, each where it stands. Moving or turning one only moves that one; deleting one leaves the others. Off, each copy is a body of its own." },
|
||||
{ icon: "copy", name: "Sketch → Copy to Plane", text: "Tap a sketch region, then Copy to Plane: drag the blue arrow to a parallel plane (or red/green to slide it), or type the distance. Turn Copy off to move the sketch instead." },
|
||||
{ icon: "color", name: "Colour / Transparency", text: "Pick a colour for the selected bodies (or Custom… for any colour), and how see-through they are (Solid, 75%, 50%, 25%)." },
|
||||
],
|
||||
@@ -62,45 +67,56 @@ const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [
|
||||
title: "Values and cards",
|
||||
items: [
|
||||
{ icon: "numpad", name: "Value boxes", text: "Every drag shows a value box by the pointer that stays when you let go: tap it to type. Just type while dragging - it goes into that box. Press on a box and drag left or right to turn the value down or up like a wheel. The model follows each key as you type (one undo step for the whole value). On the numpad a minus stays when you type over a negative value; ⌫ first clears it all, sign too, to type it positive." },
|
||||
{ icon: "menu", name: "Tool cards", text: "A tool's values, its own actions and Cancel / Done, apart with dim lines. Drag the card (or the numpad) by its grip where you want it - remembered per screen type; double-tap the card's grip to fold it down to its name, and again to open it." },
|
||||
{ icon: "line", name: "Exact points on touch screens", text: "Right after the first tap of a line, rectangle, circle… the card has X / Y for that point; a line also takes Length and Angle, or Across and Up for a slope; an arc by centre takes the centre, Radius and the Start and End angles." },
|
||||
{ icon: "menu", name: "A tool's settings", text: "A tool's values and choices are the words on the line at the bottom while it is open, with Cancel and Done at its end; the number that is dragged is also in a box on the model. Drag the numpad by its grip where you want it - remembered per screen type." },
|
||||
{ icon: "line", name: "Exact points on touch screens", text: "Right after the first tap of a line, rectangle, circle… the line at the bottom has X / Y for that point; a line also takes Length and Angle, or Across and Up for a slope; an arc by centre takes the centre, Radius and the Start and End angles." },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "In a sketch",
|
||||
items: [
|
||||
{ icon: "line", name: "Line, Arc, Spline, Rectangle, Circle…", text: "Tap points to draw. Type a value while drawing (or use the numpad) to set an exact size. Arcs by 3 points or by centre; circles by centre, 2 or 3 points. Guides (on a curve, midpoints, extensions, parallel, perpendicular, crossings) are kept as constraints." },
|
||||
{ icon: "line", name: "Line, Arc, Spline, Rectangle, Circle…", text: "Under Draw on the line. A tool with more than one way (Circle: Center, 2 Points, 3 Points) shows them on the line the moment it is on. Tap points to draw; closing a shape ends the line. Type a value while drawing (or use the numpad) to set an exact size. Arcs by 3 points or by centre; circles by centre, 2 or 3 points. Guides (on a curve, midpoints, extensions, parallel, perpendicular, crossings) are kept as constraints." },
|
||||
{ icon: "spline", name: "Spline > Draw (freehand)", text: "Press and drag to draw, like a pencil (on touch: one finger draws, two move the view). When you let go the stroke is cleaned up into a few pieces: straight parts become lines, round parts arcs, the rest smooth curves through as few points as keep them within a couple of pixels of what you drew; sharp corners stay corners. End where you began to close it (a round loop becomes a circle), then extrude it like any shape. Starting or ending on a point joins it there." },
|
||||
{ icon: "project", name: "Project", text: "Copy body edges or curves of other sketches into this sketch. Or the other way: tap lines of this sketch, then a plane or flat face parallel to it - they're copied onto it as a new sketch." },
|
||||
{ icon: "offset", name: "Offset Edge", text: "A parallel copy of a curve (or a whole outline) at a distance. Tap empty space to finish." },
|
||||
{ icon: "project", name: "Project", text: "Copy body edges or curves of other sketches into this sketch (a round edge comes in as an arc, or seen at a slant as part of an ellipse - two ends, like the edge). Or the other way: tap lines of this sketch, then a plane or flat face parallel to it - they're copied onto it as a new sketch." },
|
||||
{ icon: "offset", name: "Offset Edge", text: "A parallel copy of a curve (or a whole outline) at a distance - or of a body's edge: tap the edge, and choose Edge (that one) or Chain (the whole outline of its face). What is offset stays lit; drag the double arrow on the new curve, or type, to set how far. Tap empty space to finish." },
|
||||
{ icon: "hatch", name: "Fill Pattern", text: "Fills a closed shape with a pattern: under Draw, then tap inside the shape. Lines, Crossed lines, Zigzag and Waves run from edge to edge; Dots, Honeycomb, Squares and Diamonds are small shapes kept inside it. Set the Spacing (or the Gap between shapes), the Size and the Angle, then Apply. The strips and cells are shapes of their own: exit the sketch and extrude or cut them for a texture. Tap a filled shape again to change its pattern or remove it; when the shape changes size, its pattern follows." },
|
||||
{ icon: "sketchFillet", name: "Fillet / Chamfer", text: "Round or bevel a corner: tap the corner itself (of a line chain, rectangle or polygon), or two lines or arcs that meet; tap the next corner to go on." },
|
||||
{ icon: "trim", name: "Trim / Join", text: "Cut away the piece of a curve between crossings (tap, or swipe across several) - or join two lines on the same axis." },
|
||||
{ icon: "mirror", name: "Mirror, Move/Rotate, Pattern", text: "Mirror the selected shapes across a line or an axis; Move/Rotate with its gimbal (turns about the selection's own centre); Rotate About turns the whole selection rigidly about a point you tap - an end, a midpoint or another shape's centre - so its own centre swings round that point (the dotted arc shows the path); Pattern in a row or round a centre." },
|
||||
{ icon: "variable", name: "A pattern that follows a count", text: "Type a variable or a formula as a sketch pattern's Count (n, or floor(len / 10 mm)): the pattern is kept with the sketch, and its copies are made again whenever the count comes to another number." },
|
||||
{ icon: "alignLine", name: "Align", text: "Move a line onto another line's axis; lines joined to it stretch along." },
|
||||
{ icon: "extend", name: "Extend", text: "Carry a line or arc on until it meets another curve." },
|
||||
{ icon: "spline", name: "A spline through space", text: "Tap a spline, then one of its points: the gimbal has a third arrow, off the plane. Turn the view and drag it (or type the point's Height) and that point leaves the sketch's plane - the curve runs through space, for a sweep's path or a loft's guide. Several of its points picked go together; Flat on the plane puts them back. Shapes to extrude, constraints and snapping go by its shadow on the plane." },
|
||||
{ icon: "constraints", name: "Picking in a sketch", text: "Tap a curve or a point; drag a box to pick everything it touches. A double tap on something drawn, with the sketch seen at a slant, turns the view to face it." },
|
||||
{ icon: "constraints", name: "Constraints", text: "Rules that keep the drawing in shape: horizontal, parallel, equal, a fixed distance… Tap a line, shape or point (or several): its card shows just the constraints that fit, one tap each; one already on is lit - tap it again to take it off. They show as small faint marks, a colour per kind; tap a mark to change or delete it. A new rule replaces the ones in its way (an old angle or parallel), and says which; locked points stay put. Dragging a point onto another joins them, and dragging a corner of a rectangle or polygon moves just that corner." },
|
||||
{ icon: "measure", name: "Distance between two lines", text: "Pick two lines that run the same way: the distance between them is in a box on the drawing. Type a value and Enter: they are held parallel and that far apart." },
|
||||
{ icon: "lineDashed", name: "Construction", text: "Helper lines that guide the drawing but don't make faces. Tap to switch the selection or new lines." },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Right column",
|
||||
title: "Settings, VR and History",
|
||||
items: [
|
||||
{ icon: "magnet", name: "Snapping", text: "What the pointer snaps to: grid, end and middle points, guide lines." },
|
||||
{ icon: "ruler", name: "Units & grid", text: "mm, cm, m, inch, foot; grid size; degree format." },
|
||||
{ icon: "numpad", name: "Numpad", text: "Tap to switch the on-screen numpad on or off: value boxes then open it instead of the keyboard. Typing replaces the value; ↵ applies it. ƒx adds + × / and your variables (tap one to type its name), and + New makes a variable from the value." },
|
||||
{ icon: "display", name: "Display", text: "Shaded, wireframe or X-ray; edges and hidden edges." },
|
||||
{ icon: "vr", name: "VR", text: "With a headset (its own browser, or a PC with one connected) the top bar shows Enter VR: your model stands in your room at real size, through the headset's cameras where it has them. Point the right hand at a table or the floor and pull the trigger to put it down there. Grip picks it up to move and turn it; both grips pulled apart or together size it (it stops at real size on the way). The scale over your left hand shows how big it is: 1:1 is real size, 2:1 twice as big, 1:2 half. A: real size or hand size. B: back in front of you. Y: X-Ray. Right stick: turn it, or size it. Left stick: raise or lower it. Hold X for the wheel (Real size, Hand size, Bring here, X-Ray, Edges, Exit): tilt the stick to a button and let go. On a phone or tablet the button says Enter AR (Chrome on Android): point it at the floor or a table and tap to put the model there, tap again to move it, pinch to size it and twist to turn it; Exit AR at the top. It's a viewer: edit on the screen." },
|
||||
{ icon: "camera", name: "Screenshot", text: "Save a picture of the view, marked faintly at the bottom right with the project's name, the isolated bodies (when isolating) and supergeometry.app." },
|
||||
{ icon: "history", name: "History", text: "Every step in order. Tap one to change it, hover to see what it works on, the eye switches it off, the bin deletes it (two taps, as in Items and the projects: the first turns it red). Select several (Ctrl/Shift+click) to group them: fold, rename, switch all off or on, ungroup. Ticked steps in a group: Ungroup (beside Group) takes just them out, in their own place in the timeline (a group they were in the middle of splits around them); a group's tick box ticks all its steps." },
|
||||
{ icon: "magnet", name: "Snapping", text: "In Settings (the gear at the right edge, which shows the unit in use). What the pointer snaps to: grid, end and middle points, guide lines." },
|
||||
{ icon: "ruler", name: "Units & grid", text: "In Settings. mm, cm, m, inch, foot; grid size; degree format." },
|
||||
{ icon: "numpad", name: "Numpad", text: "In Settings: switch the on-screen numpad on or off: value boxes then open it instead of the keyboard. Typing replaces the value; ↵ applies it. ƒx adds + × / and your variables (tap one to type its name), and + New makes a variable from the value." },
|
||||
{ icon: "display", name: "Display", text: "At the right edge. Shaded, wireframe or X-ray; edges and hidden edges; zebra stripes and a curvature map." },
|
||||
{ icon: "eye", name: "Appearance", text: "In Settings. Animated camera, orthographic or perspective, the grid and the world axes." },
|
||||
{ icon: "vr", name: "VR", text: "In a headset's own browser the top bar shows Enter VR (VR is only there, not on a computer): your model stands in your room at real size, through the headset's cameras where it has them. Point the right hand at a table or the floor and pull the trigger to put it down there. Grip picks it up to move and turn it; both grips pulled apart or together size it (it stops at real size on the way). The scale over your left hand shows how big it is: 1:1 is real size, 2:1 twice as big, 1:2 half. A: real size or hand size. B: back in front of you. Y: X-Ray. Right stick: turn it, or size it. Left stick: raise or lower it. Hold X for the wheel (Real size, Hand size, Bring here, X-Ray, Edges, Exit): tilt the stick to a button and let go. On a phone or tablet the button says Enter AR (Chrome on Android): point it at the floor or a table and tap to put the model there, tap again to move it, pinch to size it and twist to turn it; Exit AR at the top. It's a viewer: edit on the screen." },
|
||||
{ icon: "camera", name: "Screenshot", text: "Picture, in Print / Share (under More): save a picture of the view, marked faintly at the bottom right with the project's name, the isolated bodies (when isolating) and superGeometry.app." },
|
||||
{ icon: "history", name: "History", text: "History in the top bar: every step in order. Tap one to change it, hover to see what it works on, the eye switches it off, the bin deletes it (two taps, as in Items and the projects: the first turns it red). Select several (Ctrl/Shift+click) to group them: fold, rename, switch all off or on, ungroup. Ticked steps in a group: Ungroup (beside Group) takes just them out, in their own place in the timeline (a group they were in the middle of splits around them); a group's tick box ticks all its steps." },
|
||||
],
|
||||
},
|
||||
{
|
||||
title: "Bottom left",
|
||||
title: "Undo, and the view's tools",
|
||||
items: [
|
||||
{ icon: "undo", name: "Undo / Redo", text: "Step back and forward (Ctrl Z / Ctrl Y)." },
|
||||
{ icon: "section", name: "Section View", text: "Cut the view open to see inside - the cut shows as a solid face with a thick outline; tap again to hide it (it's remembered). Place Plane in its card puts a construction plane where the cut is." },
|
||||
{ icon: "isolate", name: "At the left edge", text: "Isolate, Measure and Section are always there, at the middle of the left edge - each lit while it is on, a tap switches it off again. Isolate shows only what is picked (tap a body, face or edge first). Variables and Print / Share are under More." },
|
||||
{ icon: "section", name: "Section View", text: "Cut the view open to see inside - the cut shows as a solid face with a thick outline; tap again to hide it (it's remembered). With a cut on, tap the cut face itself: its arrow comes up to move the cut, and its buttons on the line at the bottom - Add Plane puts a construction plane where the cut is, Flip, Section only, 2D section." },
|
||||
{ icon: "measure", name: "Measure", text: "Distances, angles and sizes between anything you tap; pin them to keep them on screen." },
|
||||
{ icon: "variable", name: "Variables", text: "Named sizes like wall = 3, to use in any field (wall * 2). Tap to switch on: a tag shows where each acts on the model (↔ length, ∠ angle, # number). Tap a tag to type its value or a formula, or drag the value - the model follows; lines show what it's made from and what uses it. Tap again to switch off." },
|
||||
{ icon: "variable", name: "Variables", text: "Named sizes like wall = 3, to use in any field (wall * 2). Tap to switch on: a tag shows where each acts on the model (↔ length, ∠ angle, # number). Tap a tag to type its value or a formula, or drag the value - the model follows; lines show what it's made from and what uses it. Tap again to switch off. A size on the line that follows a variable says so (od / 2 = 60 mm): tap it to type another formula, or ƒx beside the box to pick a variable. Formulas take + - * / ^ and brackets, units (2 in + 5 mm), sqrt, abs, sin, cos, tan (degrees), asin, acos, atan, floor, ceil, round, min and max - floor(length / pitch) is how many fit. Changing the project's unit changes no size: plain numbers in formulas are given the unit they were typed in." },
|
||||
{ icon: "variable", name: "Rename a variable", text: "Variables > Rename: type a new name over an old one. Everything that uses it - other variables, sizes, sketch dimensions, a pattern's count - says the new name, and nothing changes size." },
|
||||
{ icon: "isolate", name: "Print / Share", text: "Says whether the model is fit to print - each body closed and solid, or what is wrong with it and where to mend it - its size, and the files to take it away as: 3MF or STL for printing, STEP for other CAD programs, Picture for a PNG of the view." },
|
||||
{ icon: "views", name: "Drawings", text: "Pick a body, then More › Create Drawing: a sheet with its views, overall sizes, item numbers and title block. Tools are on the left (Views, Dimensions, Centrelines, Note, Image); the sheet's settings on the right under Properties. A dimension, a note, a picture or an item number moves when you drag it - with a tool still on, too - and stays on the paper; the arrows nudge what is picked (Shift: further). Tap a view for its handle and scale. Double-tap a note or a dimension to change its text; a picked note has A− and A+ for the size of its letters; a moved item number has Put back. Esc puts the tool down, then lets go of the pick, then leaves the drawing." },
|
||||
{ icon: "assembly", name: "Assemblies", text: "More › BIM › Assemblies (still being tried out). The parts stay where you modelled them: a joint only says how two of them move. Add joint, tap a face on each part, and the kind is read off the faces - two round faces on one axis, or two flat faces one above the other: a Hinge (a Screw, of the thread's pitch, when one part is threaded); two flat faces side by side: a Slide along the first one's normal; anything else: Fixed. Change the Type whenever you like. Drag a part to move it by its joint, or type its Angle or Distance; Limits keep it between two values; Flip turns the joint's line round. Follows makes a joint go with another by a Ratio (a gear: minus the ratio of the teeth). Explode pulls the parts apart along their joints. Stop on contact: a dragged part goes only as far as it can before it runs into another (parts that touch, or sit in each other with a hair of play, are let be; so is what was in each other when the drag began; walls thinner than half a millimetre are not felt). Stands still says which part doesn't move. Two faces picked on two parts have Joint among their tools as well. Moving is a pose, not a change to the model, and it is kept with the project: the parts stay as you left them after OK, and Assemblies opens with them that way. While something is picked or a tool is open the parts are shown where they were modelled (a tool's arrows and sizes are there), and go back to their pose after. Home puts every part where it was modelled. Exports, measurements and drawings use the modelled position. A thread's own faces can be tapped for a joint as well as round and flat ones. No weight or forces; parts go through each other unless Stop on contact is on." },
|
||||
{ icon: "isolate", name: "Isolate", text: "Show only the selected bodies (and sketches drawn on their faces - tap a shape on one to extrude, offset... it); tap again to show everything." },
|
||||
],
|
||||
},
|
||||
@@ -112,7 +128,7 @@ export class HelpPanel {
|
||||
constructor() {
|
||||
this.el.hidden = true;
|
||||
const head = el("div", "help-head");
|
||||
head.append(el("h2", "", "How supergeometry.app works"));
|
||||
head.append(el("h2", "", "How superGeometry.app works"));
|
||||
const close = el("button", "icon-btn help-close");
|
||||
close.innerHTML = icons.close;
|
||||
close.title = "Close help";
|
||||
|
||||
@@ -3,9 +3,15 @@
|
||||
const svg = (body: string) =>
|
||||
`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
|
||||
|
||||
/** An icon that is a short text (units: mm, in...). */
|
||||
const glyph = (t: string, size = 10) =>
|
||||
svg(`<text x="12" y="${12 + size * 0.36}" font-size="${size}" font-family="system-ui, sans-serif" font-weight="600" text-anchor="middle" fill="currentColor" stroke="none">${t}</text>`);
|
||||
|
||||
/** A plane (lower right) with a small symbol above its corner. */
|
||||
const planeWith = (mark: string) =>
|
||||
svg(`<path d="M6 19l5-5h11l-5 5z"/><text x="7" y="11" font-size="11" font-family="system-ui, sans-serif" text-anchor="middle" fill="currentColor" stroke="none">${mark}</text>`);
|
||||
/** A kind of plane: what makes it drawn big, a small plane in the corner below. */
|
||||
const planeWith = (mark: string) => svg(`${mark}<path d="M1.8 22l2.6-2.6h6.4L8.2 22z" stroke-width="1.4"/>`);
|
||||
/** A kind of axis: what makes it drawn big, a small dashed axis in the corner below. */
|
||||
const axisWith = (mark: string) => svg(`${mark}<path d="M2 22.2l4.8-4.8" stroke-width="1.4" stroke-dasharray="2 1.5"/>`);
|
||||
|
||||
export const icons = {
|
||||
// The usual share mark: a box with an arrow leaving it.
|
||||
@@ -51,20 +57,27 @@ export const icons = {
|
||||
shell: svg('<path d="M4 8v12h16V8"/><path d="M7 8v9h10V8"/>'),
|
||||
split: svg('<rect x="4" y="5" width="16" height="14"/><path d="M12 2v20" stroke-dasharray="2 2"/>'),
|
||||
fill: svg('<path d="M4 18L12 4l8 14z" fill="currentColor" fill-opacity=".3"/>'),
|
||||
// Fill Pattern: a closed shape with lines across it, edge to edge.
|
||||
hatch: svg('<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 12l8-8M4 20L20 4M12 20l8-8"/>'),
|
||||
wrap: svg('<path d="M4 7c5-3 11-3 16 0v10c-5-3-11-3-16 0z"/><path d="M9 11h6"/>'),
|
||||
replaceFace: svg('<rect x="4" y="9" width="12" height="11"/><path d="M8 9l4-5h8l-4 5M20 4v11l-4 5"/>'),
|
||||
projectEdge: svg('<rect x="4" y="12" width="16" height="8"/><path d="M8 4h8l-2 8h-4z" stroke-dasharray="2 2"/>'),
|
||||
plane: svg('<path d="M3 15l6-6h12l-6 6z"/>'),
|
||||
// Each kind of plane: the plane with its mark in the corner (the same mark it
|
||||
// has in the view).
|
||||
planeOffset: planeWith("⇡"),
|
||||
planeMid: planeWith("⇹"),
|
||||
plane3pt: planeWith("∴"),
|
||||
planeCurve: planeWith("∿"),
|
||||
planePerp: planeWith("⊥"),
|
||||
planeAngle: planeWith("∠"),
|
||||
planeParallel: planeWith("∥"),
|
||||
// Each kind of plane: what makes it big (the mark it has in the view), the plane small.
|
||||
planeOffset: planeWith('<path d="M15 18V3M10 8l5-5 5 5"/>'),
|
||||
planeMid: planeWith('<path d="M8 3v14M22 3v14"/><path d="M15 3v14" stroke-dasharray="2.2 2"/>'),
|
||||
plane3pt: planeWith('<circle cx="9" cy="15" r="2.3" fill="currentColor" stroke="none"/><circle cx="21" cy="15" r="2.3" fill="currentColor" stroke="none"/><circle cx="15" cy="4.5" r="2.3" fill="currentColor" stroke="none"/>'),
|
||||
planeCurve: planeWith('<path d="M6.5 17C9.5 3 13 19 16.5 8.5S20 3 22.5 3"/><circle cx="12.2" cy="10.6" r="2" fill="currentColor" stroke="none"/>'),
|
||||
planePerp: planeWith('<path d="M15 3v14M7 17h15"/><path d="M15 13h3.6v4" stroke-width="1.3"/>'),
|
||||
planeAngle: planeWith('<path d="M22 17H7L18 3.5"/><path d="M13.6 17a6.6 6.6 0 0 0-2.4-5.1"/>'),
|
||||
planeParallel: planeWith('<path d="M11.5 17.5L16.5 3M17.5 17.5L22.5 3"/>'),
|
||||
axis: svg('<path d="M4 20L20 4" stroke-dasharray="3 2"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/>'),
|
||||
// Each kind of axis: what makes it big, the axis small.
|
||||
axisFace: axisWith('<path d="M8 17.5l3.4-3.2H22l-3.4 3.2z"/><path d="M15.3 15.8V3M12.6 5.7L15.3 3l2.7 2.7"/>'),
|
||||
axisEdge: axisWith('<path d="M9 9.5h8.5v8.5H9z" stroke-width="1.3"/><path d="M9 9.5l4-4h8.5V14l-4 4" stroke-width="1.3"/><path d="M17.5 9.5l4-4" stroke-width="2.8"/>'),
|
||||
axisRound: axisWith('<ellipse cx="16" cy="5" rx="5.6" ry="2.2"/><path d="M10.4 5v10.4a5.6 2.2 0 0 0 11.2 0V5"/>'),
|
||||
axis2pt: axisWith('<path d="M11 15L20.5 5" stroke-dasharray="2.2 2"/><circle cx="11" cy="15" r="2.4" fill="currentColor" stroke="none"/><circle cx="20.5" cy="5" r="2.4" fill="currentColor" stroke="none"/>'),
|
||||
axisPlanes: axisWith('<path d="M8.5 4.5l13.5 11M8.5 15.5l13.5-11"/><circle cx="15.25" cy="10" r="1.7" fill="currentColor" stroke="none"/>'),
|
||||
align: svg('<path d="M4 3v18"/><rect x="7" y="6" width="9" height="4"/><rect x="7" y="14" width="13" height="4"/>'),
|
||||
translate: svg('<path d="M4 12h16M16 8l4 4-4 4"/>'),
|
||||
fillet: svg('<path d="M4 20V10a6 6 0 0 1 6-6h10"/><path d="M4 20h16V4" stroke-dasharray="2 2.5"/>'),
|
||||
@@ -75,6 +88,7 @@ export const icons = {
|
||||
subtract: svg('<circle cx="9" cy="12" r="5.5"/><circle cx="15" cy="12" r="5.5" stroke-dasharray="2 2"/>'),
|
||||
intersect: svg('<circle cx="9" cy="12" r="5.5" stroke-dasharray="2 2"/><circle cx="15" cy="12" r="5.5" stroke-dasharray="2 2"/><path d="M12 7.4a5.5 5.5 0 0 1 0 9.2a5.5 5.5 0 0 1 0-9.2z" fill="currentColor" fill-opacity=".35"/>'),
|
||||
trash: svg('<path d="M5 7h14"/><path d="M9 7V4h6v3"/><path d="M7 7l1 13h8l1-13"/>'),
|
||||
back: svg('<path d="M14.5 5l-7 7 7 7"/>'),
|
||||
undo: svg('<path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/>'),
|
||||
redo: svg('<path d="M15 14l5-5-5-5"/><path d="M20 9H10a6 6 0 0 0 0 12h3"/>'),
|
||||
history: svg('<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 2"/>'),
|
||||
@@ -87,6 +101,13 @@ export const icons = {
|
||||
image: svg('<rect x="3" y="5" width="18" height="14" rx="1"/><circle cx="8.5" cy="10" r="1.6"/><path d="M21 16l-5-5-8 8"/>'),
|
||||
construct: svg('<path d="M3 15l6-6h12l-6 6z"/><path d="M12 3v18" stroke-dasharray="2 2"/>'),
|
||||
transform: svg('<path d="M12 3l3 3h-2v4h4V8l3 3-3 3v-2h-4v4h2l-3 3-3-3h2v-4H7v2l-3-3 3-3v2h4V6H9z"/>'),
|
||||
browser: svg('<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3c2.6 2.6 3.8 5.6 3.8 9s-1.2 6.4-3.8 9c-2.6-2.6-3.8-5.6-3.8-9s1.2-6.4 3.8-9z"/>'),
|
||||
reload: svg('<path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/>'),
|
||||
minimize: svg('<path d="M6 13h12"/>'),
|
||||
restore: svg('<rect x="5" y="6" width="14" height="12" rx="1.5"/><path d="M5 9.5h14"/>'),
|
||||
refImage: svg('<rect x="3" y="5" width="18" height="15" rx="1.5"/><path d="M3 8.5h18"/><circle cx="8.5" cy="12.5" r="1.4"/><path d="M21 18l-5-4.5-7 6.5"/>'),
|
||||
newBody: svg('<rect x="3.5" y="9" width="11" height="11" rx="1"/><path d="M18 3v6M15 6h6"/>'),
|
||||
wrench: svg('<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.8-3.8a6 6 0 0 1-7.9 7.9l-6.9 6.9a2.1 2.1 0 0 1-3-3l6.9-6.9a6 6 0 0 1 7.9-7.9z"/>'),
|
||||
tools: svg('<path d="M14 7l3-3 3 3-3 3M4 20l9-9"/><path d="M5 4l4 4-2 2-4-4z"/>'),
|
||||
section: svg('<path d="M4 8l8-4 8 4v8l-8 4-8-4z"/><path d="M4 12h16" stroke-dasharray="2 2"/>'),
|
||||
bim: svg('<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5l8 4.5 8-4.5M12 12v9"/><path d="M8 5.3l8 4.5"/>'),
|
||||
@@ -115,6 +136,15 @@ export const icons = {
|
||||
more: svg('<circle cx="6" cy="12" r="1.3" fill="currentColor"/><circle cx="12" cy="12" r="1.3" fill="currentColor"/><circle cx="18" cy="12" r="1.3" fill="currentColor"/>'),
|
||||
splitLine: svg('<path d="M3 15L10 9.5M14 8L21 3"/><path d="M12 4v16" stroke-dasharray="2 2"/><circle cx="12" cy="9" r="1.6" fill="currentColor"/>'),
|
||||
freeform: svg('<path d="M4 15c2-7 6-9 9-6s5 1 7-3"/><path d="M4 15c3 3 8 4 12 1s4-6 4-10" stroke-dasharray="2 2"/><circle cx="4" cy="15" r="1.4" fill="currentColor"/><circle cx="13" cy="9" r="1.4" fill="currentColor"/><circle cx="20" cy="6" r="1.4" fill="currentColor"/>'),
|
||||
// Freeform's tools: each shape smooth inside its cage (dashed, its control points dotted).
|
||||
ffBox: svg('<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z" stroke-dasharray="2 2" stroke-width="1.2"/><path d="M13.6 6.9L15.9 8.1Q17.5 9.0 17.5 10.8L17.5 13.2Q17.5 15.0 15.9 15.9L13.6 17.1Q12.0 18.0 10.4 17.1L8.1 15.9Q6.5 15.0 6.5 13.2L6.5 10.8Q6.5 9.0 8.1 8.1L10.4 6.9Q12.0 6.0 13.6 6.9z"/><path d="M7.2 9.4L12 12l4.8-2.6M12 12v5.4" stroke-width="1.3"/><circle cx="12" cy="3" r="1.5" fill="currentColor" stroke="none"/><circle cx="20" cy="7.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="4" cy="7.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="12" cy="21" r="1.5" fill="currentColor" stroke="none"/><circle cx="20" cy="16.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="4" cy="16.5" r="1.5" fill="currentColor" stroke="none"/>'),
|
||||
ffCylinder: svg('<path d="M5 6h14v12H5z" stroke-dasharray="2 2" stroke-width="1.2"/><ellipse cx="12" cy="7.5" rx="5.5" ry="2"/><path d="M6.5 7.5v8.5c0 1.1 2.5 2 5.5 2s5.5-.9 5.5-2V7.5"/><circle cx="5" cy="6" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="6" r="1.5" fill="currentColor" stroke="none"/><circle cx="5" cy="18" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="18" r="1.5" fill="currentColor" stroke="none"/>'),
|
||||
ffSphere: svg('<path d="M5 5h14v14H5z" stroke-dasharray="2 2" stroke-width="1.2"/><circle cx="12" cy="12" r="5.6"/><path d="M6.4 12c0 1.3 2.5 2.3 5.6 2.3s5.6-1 5.6-2.3" stroke-width="1.2"/><circle cx="5" cy="5" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="5" r="1.5" fill="currentColor" stroke="none"/><circle cx="5" cy="19" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="19" r="1.5" fill="currentColor" stroke="none"/>'),
|
||||
ffTorus: svg('<path d="M3 7.5h18v10H3z" stroke-dasharray="2 2" stroke-width="1.2"/><ellipse cx="12" cy="12.5" rx="7.5" ry="3.8"/><ellipse cx="12" cy="12.2" rx="3" ry="1.2"/><circle cx="3" cy="7.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="21" cy="7.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="3" cy="17.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="21" cy="17.5" r="1.5" fill="currentColor" stroke="none"/>'),
|
||||
ffSurface: svg('<path d="M3 15.5c3-1.5 5-4 9-4s6 2.5 9 4" stroke-dasharray="2 2" stroke-width="1.2"/><path d="M4 17c3-3 5-6.5 8-6.5s5 3.5 8 6.5M4 17h16"/><circle cx="3" cy="15.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="12" cy="11.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="21" cy="15.5" r="1.5" fill="currentColor" stroke="none"/><path d="M12 9V4M10 6l2-2 2 2" stroke-width="1.4"/>'),
|
||||
faceFreeform: svg('<path d="M3 18l4-5h14l-4 5z"/><path d="M8.5 15.5C9.5 9 14.5 9 15.5 15.5"/><path d="M12 10V4M10 6l2-2 2 2" stroke-width="1.4"/><circle cx="12" cy="10.3" r="1.5" fill="currentColor" stroke="none"/>'),
|
||||
connect: svg('<path d="M3 6c2 1 3 3 3 6s-1 5-3 6"/><path d="M21 6c-2 1-3 3-3 6s1 5 3 6"/><path d="M6 8.5c4 1.5 8 1.5 12 0M6 15.5c4-1.5 8-1.5 12 0" stroke-dasharray="2 2" stroke-width="1.2"/><circle cx="6" cy="8.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="18" cy="8.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="6" cy="15.5" r="1.5" fill="currentColor" stroke="none"/><circle cx="18" cy="15.5" r="1.5" fill="currentColor" stroke="none"/>'),
|
||||
editFreeform: svg('<path d="M3 16c2.5-6 6-8 9-5.5s5 1 7-3" stroke-dasharray="2 2" stroke-width="1.2"/><path d="M3 16c3 2.5 7 3 10 .5s4-5 6-8.5"/><circle cx="3" cy="16" r="1.5" fill="currentColor" stroke="none"/><circle cx="19" cy="7.5" r="1.5" fill="currentColor" stroke="none"/><path d="M13.5 4.5l5 5L11 17H6v-5z" stroke-width="1.4" fill="var(--chrome, #1e2026)"/>'),
|
||||
copy: svg('<rect x="8" y="8" width="12" height="12" rx="1.5"/><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"/>'),
|
||||
color: svg('<circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor"/>'),
|
||||
/** A folder with an arrow out of it (steps out of their group). */
|
||||
@@ -123,6 +153,104 @@ export const icons = {
|
||||
constraints: svg('<path d="M5 5v14M9 5v14"/><path d="M13 19L19 5"/><circle cx="16" cy="12" r="1.2" fill="currentColor"/>'),
|
||||
isolate: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>'),
|
||||
body: svg('<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z" fill="currentColor" fill-opacity=".2"/>'),
|
||||
// A cog: the settings (on the tool wheel).
|
||||
/** A tool's options (on the wheel): three sliders. */
|
||||
options: svg('<path d="M4 6h9M17 6h3M4 12h3M11 12h9M4 18h11M19 18h1"/><circle cx="15" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="17" cy="18" r="2"/>'),
|
||||
// For the wheels' switches and choices: what each one is (on or off shows by its highlight).
|
||||
grid: svg('<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M4 9.3h16M4 14.6h16M9.3 4v16M14.6 4v16"/>'),
|
||||
axes: svg('<path d="M5 19V5"/><path d="M5 19h14"/><path d="M5 19l8-6"/><path d="M3 7l2-2 2 2M17 17l2 2-2 2"/>'),
|
||||
point: svg('<circle cx="12" cy="12" r="2.4" fill="currentColor"/><path d="M12 3.5v4M12 16.5v4M3.5 12h4M16.5 12h4"/>'),
|
||||
hiddenEdges: svg('<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z"/><path d="M12 12l8-4.5M12 12v9M12 12L4 7.5" stroke-dasharray="2 2"/>'),
|
||||
zebra: svg('<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 10l6-6M4 16L16 4M8 20L20 8M14 20l6-6"/>'),
|
||||
curvature: svg('<path d="M3 18c4-10 14-10 18 0"/><path d="M7 12.5L5.5 10M12 10V7M17 12.5l1.5-2.5"/>'),
|
||||
ortho: svg('<rect x="4" y="8" width="12" height="12"/><path d="M4 8l4-4h12l-4 4M16 20l4-4V4"/>'),
|
||||
throughAll: svg('<path d="M3 12h18"/><path d="M17 8l4 4-4 4"/><path d="M8 5v14M12 5v14" stroke-dasharray="2 2"/>'),
|
||||
upTo: svg('<path d="M3 12h12"/><path d="M11 8l4 4-4 4"/><path d="M19 4v16"/>'),
|
||||
oneSide: svg('<path d="M7 4v16"/><path d="M7 12h12"/><path d="M15 8l4 4-4 4"/>'),
|
||||
symmetric: svg('<path d="M12 4v16" stroke-dasharray="2 2"/><path d="M4 12h16"/><path d="M7 9l-3 3 3 3M17 9l3 3-3 3"/>'),
|
||||
auto: svg('<path d="M6 19l6-14 6 14"/><path d="M8.6 13h6.8"/>'),
|
||||
link: svg('<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>'),
|
||||
selectAll: svg('<rect x="3" y="3" width="18" height="18" rx="2" stroke-dasharray="3 2.5"/><path d="M9 8l7 5-3 .6 1.4 3.4-1.4.7-1.4-3.4L9 16z"/>'),
|
||||
unitMm: glyph("mm"),
|
||||
unitCm: glyph("cm"),
|
||||
unitM: glyph("m", 12),
|
||||
unitIn: glyph("in"),
|
||||
unitFt: glyph("ft"),
|
||||
degDecimal: glyph("0.5"),
|
||||
degFraction: glyph("° ′", 11),
|
||||
hint: svg('<path d="M4 5h16v11H9l-5 4z"/><path d="M8 9h8M8 12.5h5"/>'),
|
||||
settings: svg('<circle cx="12" cy="12" r="3.2"/><path d="M19.4 13.5a7.6 7.6 0 0 0 0-3l2-1.5-2-3.4-2.3 1a7.6 7.6 0 0 0-2.6-1.5l-.3-2.6h-4l-.3 2.6a7.6 7.6 0 0 0-2.6 1.5l-2.3-1-2 3.4 2 1.5a7.6 7.6 0 0 0 0 3l-2 1.5 2 3.4 2.3-1a7.6 7.6 0 0 0 2.6 1.5l.3 2.6h4l.3-2.6a7.6 7.6 0 0 0 2.6-1.5l2.3 1 2-3.4z"/>'),
|
||||
};
|
||||
|
||||
export type IconName = keyof typeof icons;
|
||||
|
||||
/** A wheel switch's or choice's own picture, by its label (on or off shows by its highlight). */
|
||||
export function iconNameFor(label: string): IconName | undefined {
|
||||
return ICON_BY_LABEL.find(([re]) => re.test(label))?.[1];
|
||||
}
|
||||
|
||||
const ICON_BY_LABEL: [RegExp, IconName][] = [
|
||||
// Settings: snapping, units, appearance, shaders.
|
||||
[/^(Grid|Show grid|Lock grid size)/, "grid"],
|
||||
[/guide lines/i, "lineDashed"],
|
||||
[/guide points|^Guide points/i, "point"],
|
||||
[/^Distant edges/, "offsetEdge"],
|
||||
[/^Snapping hints/, "hint"],
|
||||
[/^Millimet/, "unitMm"],
|
||||
[/^Centimet/, "unitCm"],
|
||||
[/^Meter|^Metre/, "unitM"],
|
||||
[/^Inch/, "unitIn"],
|
||||
[/^Foot|^Feet/, "unitFt"],
|
||||
[/^Decimal/, "degDecimal"],
|
||||
[/^Fractional/, "degFraction"],
|
||||
[/^Animate camera/, "camera"],
|
||||
[/^Orthographic/, "ortho"],
|
||||
[/world axes/i, "axes"],
|
||||
[/^Wireframe/, "views"],
|
||||
[/^X-Ray/, "eye"],
|
||||
[/^Shaded/, "display"],
|
||||
[/^Show hidden edges/, "hiddenEdges"],
|
||||
[/^Show edges/, "views"],
|
||||
[/^Off$/, "eyeOff"],
|
||||
[/^Zebra/, "zebra"],
|
||||
[/^Curvature/, "curvature"],
|
||||
// A tool's choices and switches.
|
||||
[/^Distance$/, "ruler"],
|
||||
[/^Through all/, "throughAll"],
|
||||
[/^Up to/, "upTo"],
|
||||
[/^One side/, "oneSide"],
|
||||
[/^Symmetric/, "symmetric"],
|
||||
[/^Auto$/, "auto"],
|
||||
[/^New body/, "body"],
|
||||
[/^Add$/, "union"],
|
||||
[/^Cut$/, "subtract"],
|
||||
[/^Intersect$/, "intersect"],
|
||||
[/^Open faces/, "shell"],
|
||||
[/^Clear/, "deselect"],
|
||||
[/^Replace with/, "replaceFace"],
|
||||
[/^(XY|XZ|YZ)\b/, "plane"],
|
||||
[/^Constant$/, "fillet"],
|
||||
[/^Variable$/, "spline"],
|
||||
[/^Round$/, "fillet"],
|
||||
[/^Smooth/, "spline"],
|
||||
[/^Radius$/, "circle"],
|
||||
[/^Chord/, "line"],
|
||||
[/^Equal distance/, "chamfer"],
|
||||
[/^Two distances/, "ruler"],
|
||||
[/^Edge$/, "offsetEdge"],
|
||||
[/^On face/, "offsetFace"],
|
||||
[/^Mirror (plane|line|across)/, "mirror"],
|
||||
[/^Copy$/, "copy"],
|
||||
[/^(Link|Chain)$/, "link"],
|
||||
[/^(From|To) point/, "point"],
|
||||
[/^Move$/, "move"],
|
||||
[/^Turn$/, "rotateAxis"],
|
||||
[/^Scale$/, "scale"],
|
||||
[/^Select all/, "selectAll"],
|
||||
[/^Apply/, "check"],
|
||||
[/^Boundary/, "fill"],
|
||||
[/^Guides/, "spline"],
|
||||
[/^Symmetry/, "mirror"],
|
||||
[/^(Up|Down)$/, "extrude"],
|
||||
];
|
||||
|
||||
|
||||
@@ -71,7 +71,7 @@ export class Install {
|
||||
|
||||
/** The notice: Install / Not now (or, on iOS, how to do it). */
|
||||
offer(fromMenu = false): void {
|
||||
if (isInstalled()) return void (fromMenu && this.toast("supergeometry.app is already installed on this device"));
|
||||
if (isInstalled()) return void (fromMenu && this.toast("superGeometry.app is already installed on this device"));
|
||||
this.banner.innerHTML = "";
|
||||
const ios = isIOS() && !this.deferred;
|
||||
if (!ios && !this.deferred) {
|
||||
@@ -83,8 +83,8 @@ export class Install {
|
||||
"span",
|
||||
"",
|
||||
ios
|
||||
? "Add supergeometry.app to your Home Screen: tap Share (the square with the arrow), then “Add to Home Screen”."
|
||||
: "Install supergeometry.app on this device? It opens like an app, full screen.",
|
||||
? "Add superGeometry.app to your Home Screen: tap Share (the square with the arrow), then “Add to Home Screen”."
|
||||
: "Install superGeometry.app on this device? It opens like an app, full screen.",
|
||||
);
|
||||
const yes = el("button", "text-btn primary", ios ? "Got it" : "Install");
|
||||
yes.addEventListener("click", () => void this.accept(ios));
|
||||
|
||||
@@ -110,7 +110,7 @@ export class ItemsPanel {
|
||||
Bodies: bodies.map((b) => ({ id: b.id, name: names[b.id] ?? b.name, icon: "body" as IconName, open: () => this.h.selectBody(b.id), remove: () => this.h.deleteBody(b.id), extra: iso && !iso.includes(b.id) ? " isolated-out" : "", isBody: true })),
|
||||
// Greyed while something else is isolated (they're hidden until Isolate is off).
|
||||
Sketches: of("sketch").map((s) => ({ id: s.id, name: s.name, icon: "sketch" as IconName, open: () => this.h.editSketch(s.id), remove: () => this.h.deleteFeature(s.id), extra: iso && !iso.includes(s.id) ? " isolated-out" : "" })),
|
||||
"Planes & axes": [...of("plane"), ...of("axis")].map((c) => ({ id: c.id, name: c.name, icon: (c.type === "plane" ? PLANE_ICON[(c as { kind?: string }).kind ?? "offset"] ?? "plane" : "axis") as IconName, open: () => this.h.selectPlane(c.id), remove: () => this.h.deleteFeature(c.id), extra: iso && !iso.includes(c.id) ? " isolated-out" : "" })),
|
||||
"Planes & axes": [...of("plane"), ...of("axis")].map((c) => ({ id: c.id, name: c.name, icon: (c.type === "plane" ? PLANE_ICON[(c as { kind?: string }).kind ?? "offset"] ?? "plane" : AXIS_ICON[(c as { kind?: string }).kind ?? ""] ?? "axis") as IconName, open: () => this.h.selectPlane(c.id), remove: () => this.h.deleteFeature(c.id), extra: iso && !iso.includes(c.id) ? " isolated-out" : "" })),
|
||||
Images: of("image").map((i) => ({ id: i.id, name: i.name, icon: "image" as IconName, open: () => this.h.selectImage(i.id), remove: () => this.h.deleteFeature(i.id) })),
|
||||
};
|
||||
const byId = new Map(Object.values(rows).flat().map((r) => [r.id, r]));
|
||||
@@ -241,16 +241,36 @@ export class ItemsPanel {
|
||||
li.append(eye, label, ren, del);
|
||||
li.dataset.id = r.id;
|
||||
li.classList.toggle("selected", this.selectedIds.has(r.id));
|
||||
li.classList.toggle("flash", this.revealed.has(r.id));
|
||||
this.list.append(li);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reveal in Items: the panel opens, the folders and headings holding the
|
||||
* rows unfold, and the first is scrolled to and flashes.
|
||||
* rows unfold, and the first is scrolled to. The rows pulse until the
|
||||
* next thing done (a tap anywhere, a key).
|
||||
*/
|
||||
private revealed = new Set<string>();
|
||||
private unreveal: (() => void) | null = null;
|
||||
reveal(ids: string[]): void {
|
||||
this.toggle(true);
|
||||
const want = new Set(ids);
|
||||
this.unreveal?.();
|
||||
this.revealed = want;
|
||||
const stop = () => {
|
||||
this.unreveal = null;
|
||||
this.revealed = new Set();
|
||||
removeEventListener("pointerdown", stop, true);
|
||||
removeEventListener("keydown", stop, true);
|
||||
for (const li of this.list.querySelectorAll<HTMLElement>("li.flash")) li.classList.remove("flash");
|
||||
};
|
||||
this.unreveal = stop;
|
||||
// (After the tap that asked for it has ended.)
|
||||
setTimeout(() => {
|
||||
if (this.unreveal !== stop) return;
|
||||
addEventListener("pointerdown", stop, true);
|
||||
addEventListener("keydown", stop, true);
|
||||
});
|
||||
const byId = new Map(this.folders.map((f) => [f.id, f]));
|
||||
for (const f of this.folders)
|
||||
if (f.items.some((i) => want.has(i))) for (let g: ItemFolder | undefined = f; g; g = g.parent ? byId.get(g.parent) : undefined) this.collapsed.delete(g.id);
|
||||
@@ -263,11 +283,8 @@ export class ItemsPanel {
|
||||
this.render(this.last);
|
||||
li = find();
|
||||
}
|
||||
if (!li) return;
|
||||
li.scrollIntoView({ block: "center" });
|
||||
li.classList.remove("flash");
|
||||
void li.offsetWidth;
|
||||
li.classList.add("flash");
|
||||
for (const r of this.list.querySelectorAll<HTMLElement>("li[data-id]")) r.classList.toggle("flash", want.has(r.dataset.id!));
|
||||
li?.scrollIntoView({ block: "center" });
|
||||
}
|
||||
|
||||
/** What's selected in the view (a body double-clicked, a plane…): its row lights up. */
|
||||
@@ -372,5 +389,8 @@ export class ItemsPanel {
|
||||
}
|
||||
}
|
||||
|
||||
/** Each kind of construction plane's icon (its mark in the corner). */
|
||||
/** Each kind of construction plane's icon (its mark big, the plane small). */
|
||||
/** Each kind of axis's icon (an axis from before they were told apart: the plain one). */
|
||||
const AXIS_ICON: Record<string, IconName> = { face: "axisFace", edge: "axisEdge", round: "axisRound", "2pt": "axis2pt", planes: "axisPlanes" };
|
||||
|
||||
const PLANE_ICON: Record<string, IconName> = { offset: "planeOffset", mid: "planeMid", "3pt": "plane3pt", curve: "planeCurve", perp: "planePerp", angle: "planeAngle", parallel: "planeParallel" };
|
||||
|
||||
@@ -10,6 +10,8 @@ import { el, twoTap } from "./ui";
|
||||
|
||||
export interface LibraryActions {
|
||||
open(id: string): void;
|
||||
/** The tutorial: a first part, built one tap at a time (offered in the window's head). */
|
||||
tutorial?(): void;
|
||||
newProject(): void;
|
||||
openFile(): void;
|
||||
download(id: string): void;
|
||||
@@ -40,11 +42,12 @@ function supportBox(): HTMLElement {
|
||||
el(
|
||||
"div",
|
||||
"library-support-text",
|
||||
"This app is free, with no ads and no account, and one person makes it. If it's useful to you, your support will help keep it this way. Thank you!",
|
||||
"This app is free, with no ads and no account, and one person makes it. If it's useful to you, a free MakerWorld Boost or a follow is very useful to me. Thank you!",
|
||||
),
|
||||
);
|
||||
const row = el("div", "library-support-row");
|
||||
for (const w of SUPPORT) {
|
||||
// (Only the ways with a link.)
|
||||
for (const w of SUPPORT.filter((s) => s.url)) {
|
||||
const b = el("button", "library-support-btn");
|
||||
b.type = "button";
|
||||
const logo = el("span", "library-support-logo");
|
||||
@@ -86,6 +89,8 @@ export interface LibraryOptions {
|
||||
welcome?: boolean;
|
||||
/** A Full screen button (null: not offered). */
|
||||
fullscreen?: { isFull(): boolean; toggle(): void } | null;
|
||||
/** Told when the window is closed, however it was (its close button, a project picked, Esc). */
|
||||
onClose?(): void;
|
||||
}
|
||||
|
||||
/** The page already fills the screen (the browser's own full screen, or an app window that has it all). */
|
||||
@@ -98,7 +103,7 @@ export function showLibrary(entries: LibraryEntry[], currentId: string | null, a
|
||||
const box = el("div", "dialog library");
|
||||
if (opts.welcome) box.classList.add("welcome");
|
||||
const head = el("div", "library-head");
|
||||
head.append(el("div", "panel-title", opts.welcome ? "Welcome to supergeometry.app" : "Projects"));
|
||||
head.append(el("div", "panel-title", opts.welcome ? "Welcome to superGeometry.app" : "Projects"));
|
||||
// No projects yet: New project is the way in.
|
||||
const newBtn = el("button", entries.length ? "text-btn" : "text-btn primary", "New project");
|
||||
newBtn.type = "button";
|
||||
@@ -131,6 +136,15 @@ export function showLibrary(entries: LibraryEntry[], currentId: string | null, a
|
||||
paintFull();
|
||||
head.append(fsBtn);
|
||||
}
|
||||
// The tutorial: where someone new starts - the button that stands out while there are no projects yet.
|
||||
if (act.tutorial) {
|
||||
const tutBtn = el("button", entries.length ? "text-btn" : "text-btn primary", "Tutorial");
|
||||
tutBtn.type = "button";
|
||||
tutBtn.title = "Build a bolt and its nut, one tap at a time";
|
||||
tutBtn.addEventListener("click", () => (close(), act.tutorial!()));
|
||||
if (!entries.length) newBtn.className = "text-btn";
|
||||
head.append(tutBtn);
|
||||
}
|
||||
head.append(newBtn, fileBtn, closeBtn);
|
||||
box.append(head);
|
||||
if (opts.welcome) {
|
||||
@@ -146,6 +160,7 @@ export function showLibrary(entries: LibraryEntry[], currentId: string | null, a
|
||||
|
||||
const grid = el("div", "library-grid");
|
||||
const close = () => {
|
||||
if (back.isConnected) opts.onClose?.();
|
||||
back.remove();
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
document.removeEventListener("fullscreenchange", paintFull);
|
||||
|
||||
@@ -44,6 +44,10 @@ export function numpadVariables(hooks: typeof varHooks): void {
|
||||
class Numpad {
|
||||
private el = document.createElement("div");
|
||||
private target: HTMLInputElement | null = null;
|
||||
/** Open on this box. */
|
||||
typingInto(input: HTMLInputElement): boolean {
|
||||
return this.target === input && !this.el.hidden;
|
||||
}
|
||||
|
||||
/** Put away if it's open on this box. */
|
||||
closeIf(input: HTMLInputElement): void {
|
||||
@@ -54,6 +58,12 @@ class Numpad {
|
||||
private selEnd = 0;
|
||||
/** Just opened on a box: the first key typed replaces what's in it. */
|
||||
private fresh = false;
|
||||
/** The keys, to grey the ones a box can't take (no point for whole numbers, no minus where it can't go below 0). */
|
||||
private keys = new Map<string, HTMLButtonElement>();
|
||||
private off = (k: string, t: HTMLInputElement | null) =>
|
||||
!!t && ((k === "." && t.dataset.kind === "int") || (k === "−" && t.dataset.min !== undefined && Number(t.dataset.min) >= 0));
|
||||
/** The first key was − (the sign flipped): digits next type a new negative number. */
|
||||
private minusFirst = false;
|
||||
/** ƒx on: operators and the variables' names to type formulas with. */
|
||||
private fx = false;
|
||||
private fxRow = document.createElement("div");
|
||||
@@ -127,7 +137,7 @@ class Numpad {
|
||||
host.append(b);
|
||||
return b;
|
||||
};
|
||||
for (const k of KEYS) key(k, this.el);
|
||||
for (const k of KEYS) this.keys.set(k, key(k, this.el));
|
||||
this.fxRow.className = "np-fx-row";
|
||||
for (const k of FX_KEYS) key(k, this.fxRow, k === "abc" ? "np-abc" : "np-op");
|
||||
this.chips.className = "np-chips";
|
||||
@@ -193,13 +203,17 @@ class Numpad {
|
||||
open(input: HTMLInputElement, stay = false): void {
|
||||
// Moving on to another box: it stays right where it is (setFx re-places it).
|
||||
const at = stay ? { left: this.el.style.left, top: this.el.style.top } : null;
|
||||
this.target?.classList.remove("np-all");
|
||||
this.target = input;
|
||||
for (const [k, b] of this.keys) b.disabled = this.off(k, input);
|
||||
this.fresh = true;
|
||||
this.minusFirst = false;
|
||||
// A formula in the box already: ƒx is on.
|
||||
this.setFx(/[a-z_]/i.test(input.value.replace(/(\d)\s*(mm|cm|m|in|ft)\b/gi, "$1")));
|
||||
// All of it selected, so typing overrides it - but a minus stays: the
|
||||
// number after it is what's selected (⌫ first clears it all, sign too).
|
||||
this.selStart = input.value.startsWith("-") ? 1 : 0;
|
||||
// (Not a box that only shows where the finger is: digits type it over whole.)
|
||||
this.selStart = input.value.startsWith("-") && input.dataset.follows !== "1" ? 1 : 0;
|
||||
this.selEnd = input.value.length;
|
||||
this.showSelection();
|
||||
this.el.hidden = false;
|
||||
@@ -243,6 +257,7 @@ class Numpad {
|
||||
|
||||
private close(): void {
|
||||
this.el.hidden = true;
|
||||
this.target?.classList.remove("np-all");
|
||||
this.target = null;
|
||||
}
|
||||
|
||||
@@ -256,6 +271,18 @@ class Numpad {
|
||||
}
|
||||
|
||||
private showSelection(): void {
|
||||
const t = this.target;
|
||||
// A finger: the value shows picked (lit), the box's own selection stays a
|
||||
// caret - selected for real, it brought up the phone's Cut / Copy bar.
|
||||
if (t && !matchMedia("(pointer: fine)").matches) {
|
||||
t.classList.toggle("np-all", this.selStart !== this.selEnd);
|
||||
try {
|
||||
t.setSelectionRange(this.selEnd, this.selEnd);
|
||||
} catch {
|
||||
// not a text box
|
||||
}
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.target?.setSelectionRange(this.selStart, this.selEnd);
|
||||
} catch {
|
||||
@@ -288,6 +315,7 @@ class Numpad {
|
||||
|
||||
private press(k: string): void {
|
||||
const t = this.target;
|
||||
if (this.off(k, t)) return;
|
||||
// The box went away (its tool finished): nothing to type into.
|
||||
if (!t || !t.isConnected) return this.close();
|
||||
let v = t.value;
|
||||
@@ -295,10 +323,17 @@ class Numpad {
|
||||
let e = Math.min(this.selEnd, v.length);
|
||||
// First key after opening: a digit or point types over the number (a
|
||||
// minus in front stays); ⌫ clears it all, sign too - then type it positive.
|
||||
if (this.fresh && (k === "." || /^\d$/.test(k))) [s, e] = [v.startsWith("-") ? 1 : 0, v.length];
|
||||
// (A line's Up showing -2.7, only where the finger last was: 34 typed
|
||||
// went down, -34 - the outline drawn upside down.)
|
||||
if (this.fresh && (k === "." || /^\d$/.test(k))) [s, e] = [v.startsWith("-") && t.dataset.follows !== "1" ? 1 : 0, v.length];
|
||||
// A variable tapped first: the box becomes it.
|
||||
if (this.fresh && varHooks?.names().includes(k)) [s, e] = [0, v.length];
|
||||
if (this.fresh && k === "⌫") [s, e] = [0, v.length];
|
||||
// − first, then digits: that number, negative. (−24 in a box showing
|
||||
// -24.6224 flipped it, then put the 24 on the end: 24.622424. − then ↵
|
||||
// still flips the sign.)
|
||||
if (this.minusFirst && (k === "." || /^\d$/.test(k))) [v, s, e] = ["-", 1, 1];
|
||||
this.minusFirst = this.fresh && k === "−" && !this.fx;
|
||||
if (k !== "↵") this.fresh = false;
|
||||
const put = (text: string) => {
|
||||
v = v.slice(0, s) + text + v.slice(e);
|
||||
@@ -330,7 +365,7 @@ class Numpad {
|
||||
// Anything else (a name not made yet): the system keyboard.
|
||||
this.close();
|
||||
t.inputMode = "text";
|
||||
t.focus();
|
||||
t.focus({ preventScroll: true });
|
||||
return;
|
||||
} else if (k === "+ New") {
|
||||
// A variable from this value: it's made, and the box uses it.
|
||||
@@ -357,6 +392,15 @@ class Numpad {
|
||||
|
||||
let pad: Numpad | null = null;
|
||||
|
||||
/**
|
||||
* Is this box being typed into - focused, or the numpad's (which works without
|
||||
* focus)? Then its text is left as it is: "1." is on its way to 1.5, and a
|
||||
* box that rewrote itself from the value on each key made it 1, then 15.
|
||||
*/
|
||||
export function typingInto(input: HTMLInputElement): boolean {
|
||||
return document.activeElement === input || pad?.typingInto(input) === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Let a numeric input use the on-screen numpad (when it's on): the system
|
||||
* keyboard stays away and the numpad opens under the box when it's tapped.
|
||||
@@ -461,6 +505,9 @@ function scrubbable(input: HTMLInputElement): void {
|
||||
const n = Math.round(dx / 4);
|
||||
let nv = start.v + n * start.step;
|
||||
if (start.kind === "int") nv = Math.round(nv);
|
||||
// (A box with a least or a most: the drag stops there.)
|
||||
if (input.dataset.min !== undefined) nv = Math.max(Number(input.dataset.min), nv);
|
||||
if (input.dataset.max !== undefined) nv = Math.min(Number(input.dataset.max), nv);
|
||||
const dec = Math.max(0, -Math.floor(Math.log10(start.step) + 1e-9));
|
||||
const text = String(Number(nv.toFixed(dec)));
|
||||
if (text !== input.value) {
|
||||
@@ -482,7 +529,7 @@ function scrubbable(input: HTMLInputElement): void {
|
||||
// A first click: the whole value, ready to be typed over. In use
|
||||
// already: the caret where it was clicked (to add to it).
|
||||
if (!s.focused || document.activeElement !== input) {
|
||||
input.focus();
|
||||
input.focus({ preventScroll: true });
|
||||
input.select();
|
||||
} else {
|
||||
const i = caretAt(input, e.clientX);
|
||||
|
||||
@@ -1,16 +1,26 @@
|
||||
// Right column popovers: snapping, units & grid, views, display modes, screenshot, history.
|
||||
// The right column: what is used while modelling - Fit, Display - and one
|
||||
// Settings button for what is set now and then (units & grid, snapping, the
|
||||
// number pad, appearance), each row there showing how it is set now. Views
|
||||
// are on the view cube; Screenshot is in Print / Share; History has its own
|
||||
// button at the top. (Their lists are still kept by id: other parts of the
|
||||
// app open them.)
|
||||
|
||||
import type { SavedView, Units, Vec3 } from "../doc/types";
|
||||
import type { DocStore } from "../doc/store";
|
||||
import { settings, type Settings } from "../settings";
|
||||
import { UNIT_LABEL, units } from "../units";
|
||||
import { MOUSE_PRESETS, mousePreset, settings, type Settings } from "../settings";
|
||||
import { fmtLen as lenText, UNIT_LABEL, units } from "../units";
|
||||
import type { Viewport } from "../view/viewport";
|
||||
import type { UI } from "./ui";
|
||||
import { el } from "./ui";
|
||||
import { textField } from "./textField";
|
||||
|
||||
export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnits: (u: Units) => void, isolatedNames: () => string[] = () => []): void {
|
||||
ui.addRight("fit", "fit", "Zoom to fit (F)", () => view.fitAll(), () => "Fit");
|
||||
ui.addRight("snap", "magnet", "Snapping", (host) => {
|
||||
// (Kept by id, with no button in the column: opened from Settings.)
|
||||
const stash = { host: el("div", ""), className: "right-btn" };
|
||||
const lists: Record<string, (host: HTMLElement) => void> = {};
|
||||
const kept = (id: string, open: (host: HTMLElement) => void) => (lists[id] = open);
|
||||
ui.addRight("snap", "magnet", "Snapping", kept("snap", (host) => {
|
||||
const s = settings.value;
|
||||
host.append(heading("Snap to"));
|
||||
const snapRow = (key: keyof Settings["snap"], label: string) =>
|
||||
@@ -19,13 +29,13 @@ export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnit
|
||||
host.append(heading("Show"));
|
||||
host.append(toggleRow("Guide points", s.showGuidePoints, (v) => settings.set("showGuidePoints", v)), toggleRow("Snapping hints", s.showSnapHints, (v) => settings.set("showSnapHints", v)));
|
||||
host.append(el("div", "pop-note", "Hold Shift while drawing to place a point without snapping."));
|
||||
});
|
||||
}), undefined, stash);
|
||||
|
||||
ui.addRight(
|
||||
"units",
|
||||
"ruler",
|
||||
"Units & grid",
|
||||
(host) => {
|
||||
kept("units", (host) => {
|
||||
host.append(heading("Units"));
|
||||
const list: [Units, string][] = [
|
||||
["mm", "Millimeter"],
|
||||
@@ -37,27 +47,54 @@ export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnit
|
||||
for (const [u, label] of list) host.append(choiceRow(label, units() === u, () => (onUnits(u), ui.refreshPopover())));
|
||||
host.append(heading("Grid"));
|
||||
const s = settings.value;
|
||||
host.append(toggleRow(`Lock grid size (${s.gridStep} mm)`, s.gridLocked, (v) => settings.set("gridLocked", v)));
|
||||
// Switched on, it keeps the squares as they are right now, at this zoom (asked for: "I want the lock grid size
|
||||
// toggle to adjust to whatever the zoom level is so I can just click toggle on").
|
||||
const lockRow = toggleRow(s.gridLocked ? `Lock grid size (${fmtStep(s.gridStep)})` : `Lock grid size (now ${fmtStep(view.grid.step)})`, s.gridLocked, (v) => {
|
||||
if (v) settings.set("gridStep", +view.grid.step.toPrecision(6));
|
||||
settings.set("gridLocked", v);
|
||||
ui.refreshPopover();
|
||||
});
|
||||
host.append(lockRow);
|
||||
const stepRow = el("label", "pop-row");
|
||||
stepRow.append(el("span", "", "Locked size (mm)"));
|
||||
const input = document.createElement("input");
|
||||
input.className = "pop-input";
|
||||
input.value = String(s.gridStep);
|
||||
const input = textField("pop-input");
|
||||
input.inputMode = "decimal";
|
||||
// (Not locked: the squares' size right now - what locking would keep.)
|
||||
input.value = String(s.gridLocked ? s.gridStep : +view.grid.step.toPrecision(6));
|
||||
input.addEventListener("change", () => {
|
||||
const v = Number(input.value);
|
||||
if (v > 0) settings.set("gridStep", v);
|
||||
});
|
||||
stepRow.append(input);
|
||||
host.append(stepRow);
|
||||
host.append(el("div", "pop-note", `Tip: the grid adapts to zoom (now ${fmtStep(view.grid.step)} per square).`));
|
||||
const gridNote = el("div", "pop-note", s.gridLocked ? "The squares stay this size at any zoom, and a sketch snaps to them. Switch the lock off for a grid that follows the zoom." : `The grid follows the zoom (now ${fmtStep(view.grid.step)} a square), and a sketch snaps to the squares shown. Lock it to keep them as they are now.`);
|
||||
host.append(gridNote);
|
||||
// Not locked, the size follows the zoom while this is open: the row, the box and the note say the squares'
|
||||
// size as it is now (asked for: "the lock grid size should change on the fly when I zoom so I can see what
|
||||
// size grid it is in that moment"). They said the size it was when the window opened.
|
||||
if (!s.gridLocked) {
|
||||
let shown = view.grid.step;
|
||||
const follow = () => {
|
||||
// (Closed, or drawn again: this one is done.)
|
||||
if (!lockRow.isConnected || lockRow.closest("[hidden]")) return void view.frameHooks.delete(follow);
|
||||
const now = view.grid.step;
|
||||
if (now === shown) return;
|
||||
shown = now;
|
||||
(lockRow.firstElementChild as HTMLElement).textContent = `Lock grid size (now ${fmtStep(now)})`;
|
||||
if (document.activeElement !== input) input.value = String(+now.toPrecision(6));
|
||||
gridNote.textContent = `The grid follows the zoom (now ${fmtStep(now)} a square), and a sketch snaps to the squares shown. Lock it to keep them as they are now.`;
|
||||
};
|
||||
view.frameHooks.add(follow);
|
||||
}
|
||||
host.append(heading("Degree format"));
|
||||
host.append(choiceRow("Decimal (27.15°)", s.degrees === "decimal", () => settings.set("degrees", "decimal")), choiceRow("Fractional (27° 15′)", s.degrees === "fractional", () => settings.set("degrees", "fractional")));
|
||||
},
|
||||
host.append(choiceRow("Decimal (27.15°)", s.degrees === "decimal", () => (settings.set("degrees", "decimal"), ui.refreshPopover())), choiceRow("Fractional (27° 15′)", s.degrees === "fractional", () => (settings.set("degrees", "fractional"), ui.refreshPopover())));
|
||||
}),
|
||||
() => UNIT_LABEL[units()],
|
||||
stash,
|
||||
);
|
||||
|
||||
// Appearance (camera, projection, grid, axes): back in the right-hand column.
|
||||
ui.addRight("appearance", "eye", "Appearance", (host) => {
|
||||
ui.addRight("appearance", "eye", "Appearance", kept("appearance", (host) => {
|
||||
const s = settings.value;
|
||||
host.append(
|
||||
heading("Appearance"),
|
||||
@@ -66,7 +103,25 @@ export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnit
|
||||
toggleRow("Show grid", s.showGrid, (v) => settings.set("showGrid", v)),
|
||||
toggleRow("Show world axes", s.showAxes, (v) => settings.set("showAxes", v)),
|
||||
);
|
||||
});
|
||||
}), undefined, stash);
|
||||
|
||||
// Mouse: which drags turn, move and zoom the view - the app's own way or another CAD program's, for hands used
|
||||
// to it (asked for by many: "a setting menu with a list: default, Autodesk, onshape, etc", then "it should have
|
||||
// controls presets from all major CAD apps"). Only where there is a mouse.
|
||||
lists.mouse = (host) => {
|
||||
const s = settings.value;
|
||||
const now = mousePreset(s.mouse);
|
||||
host.append(heading("Mouse like in"));
|
||||
for (const m of MOUSE_PRESETS) {
|
||||
const row = choiceRow(m.apps, now.id === m.id, () => (settings.set("mouse", m.id), ui.refreshPopover()));
|
||||
row.title = m.text;
|
||||
host.append(row);
|
||||
}
|
||||
host.append(el("div", "pop-note", now.text));
|
||||
host.append(heading("Wheel"));
|
||||
host.append(toggleRow("Forward zooms out", s.wheelReverse, (v) => settings.set("wheelReverse", v)));
|
||||
host.append(el("div", "pop-note", "Always: the wheel zooms where the pointer is, a plain right drag turns the view, Alt + left drag turns it too (a trackpad), and a left drag on empty space draws a box to select with."));
|
||||
};
|
||||
|
||||
// Views (standard and saved): the button at the view cube's bottom right.
|
||||
const cube = document.getElementById("viewcube")!;
|
||||
@@ -76,7 +131,7 @@ export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnit
|
||||
const showViews = () => {
|
||||
body.innerHTML = "";
|
||||
// Picking a view closes the list (it would only cover the view picked).
|
||||
const go = (label: string, n: Vec3, x?: Vec3) => choiceRow(label, false, () => (view.cam.lookAlong(n, x), ui.closePopover()));
|
||||
const go = (label: string, n: Vec3, x?: Vec3) => choiceRow(label, false, () => (view.cam.flatUntilTurned(), view.cam.lookAlong(n, x), ui.closePopover()));
|
||||
body.append(choiceRow("⌂ Default view", false, () => (view.cam.iso(), view.fitAll(), ui.closePopover())));
|
||||
body.append(go("Top", [0, 0, 1]), go("Bottom", [0, 0, -1]), go("Front", [0, -1, 0]), go("Back", [0, 1, 0], [-1, 0, 0]), go("Right", [1, 0, 0], [0, 1, 0]), go("Left", [-1, 0, 0], [0, -1, 0]));
|
||||
body.append(heading("Saved views"));
|
||||
@@ -142,17 +197,53 @@ export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnit
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
|
||||
ui.toast("Screenshot saved");
|
||||
});
|
||||
});
|
||||
}, undefined, stash);
|
||||
|
||||
// On-screen numpad: one tap on, one tap off (lit while on).
|
||||
const pad = ui.addRight("numpad", "numpad", "On-screen numpad for typing values (tap to switch on / off)", () => {
|
||||
settings.set("numpad", !settings.value.numpad);
|
||||
ui.toast(settings.value.numpad ? "On-screen numpad on" : "On-screen numpad off");
|
||||
}, () => "NumPad");
|
||||
}, () => "NumPad", stash);
|
||||
const markPad = () => pad.classList.toggle("on", settings.value.numpad);
|
||||
settings.onChange(() => (markPad(), ui.refreshRight()));
|
||||
markPad();
|
||||
ui.addRight("history", "history", "History", () => ui.toggleHistory());
|
||||
ui.addRight("history", "history", "History", () => ui.toggleHistory(), undefined, stash);
|
||||
|
||||
// Settings: one row for each thing set now and then, saying how it is set; a tap opens its list (and back).
|
||||
let page: "units" | "snap" | "appearance" | "mouse" | null = null;
|
||||
const gear = ui.addRight(
|
||||
"settings",
|
||||
"settings",
|
||||
"Settings",
|
||||
(host) => {
|
||||
const s = settings.value;
|
||||
if (page) {
|
||||
const back = el("button", "pop-row pop-back", "‹ Settings");
|
||||
back.addEventListener("click", () => ((page = null), ui.refreshPopover()));
|
||||
host.append(back);
|
||||
lists[page](host);
|
||||
return;
|
||||
}
|
||||
const nav = (label: string, now: string, to: NonNullable<typeof page>) => {
|
||||
const row = el("button", "pop-row pop-nav");
|
||||
row.append(el("span", "", label), el("span", "pop-value", now), el("span", "pop-chev", "›"));
|
||||
row.addEventListener("click", () => ((page = to), ui.refreshPopover()));
|
||||
return row;
|
||||
};
|
||||
const snaps = Object.values(s.snap).filter(Boolean).length;
|
||||
host.append(
|
||||
heading("Settings"),
|
||||
nav("Units & grid", `${UNIT_LABEL[units()]}${s.gridLocked ? ` · grid ${s.gridStep} mm` : ""}`, "units"),
|
||||
nav("Snapping", snaps ? `${snaps} of ${Object.keys(s.snap).length} on` : "Off", "snap"),
|
||||
toggleRow("Number pad on screen", s.numpad, (v) => settings.set("numpad", v)),
|
||||
nav("Appearance", `${s.ortho ? "Orthographic" : "Perspective"}${s.showGrid ? "" : " · no grid"}`, "appearance"),
|
||||
);
|
||||
if (matchMedia("(any-pointer: fine)").matches) host.append(nav("Mouse", mousePreset(s.mouse).apps.split(",")[0], "mouse"));
|
||||
},
|
||||
() => UNIT_LABEL[units()],
|
||||
);
|
||||
// (Opened afresh: its first page.)
|
||||
gear.addEventListener("pointerdown", () => (page = null));
|
||||
// Sketch mode only (CSS shows it under body.sketching): show/hide the constraint column.
|
||||
const cons = ui.addRight("constraints", "constraints", "Constraints (sketch)", () => settings.set("showConstraints", !settings.value.showConstraints));
|
||||
cons.classList.add("sketch-only");
|
||||
@@ -207,5 +298,6 @@ function choiceRow(label: string, active: boolean, run: () => void): HTMLElement
|
||||
}
|
||||
|
||||
function fmtStep(mm: number): string {
|
||||
return mm >= 1000 ? `${mm / 1000} m` : mm >= 10 ? `${mm / 10} cm` : `${mm} mm`;
|
||||
// (In the unit in use: 10 mm was said as "1 cm" in a project of millimetres.)
|
||||
return lenText(mm, 4);
|
||||
}
|
||||
|
||||