Compare commits
328 Commits
| 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 | |||
| a448d87ea5 | |||
| 5088a5c9fd | |||
| 777720540b | |||
| 3e00e60b37 | |||
| 337c802689 | |||
| 835816fef1 | |||
| f692ac9e92 | |||
| 3bc4c143ba | |||
| 23e7932c7d | |||
| 0646991d21 | |||
| 52bbe0acb1 | |||
| 3f2f8811c3 | |||
| 5090030843 | |||
| 495e1cef79 | |||
| 7368d01b62 | |||
| 2c9fc953fd | |||
| 66acab2163 | |||
| f2fdb5acc7 | |||
| 2d36f9f20d | |||
| f6eb68c07e | |||
| 3d9cb2533b | |||
| e0a8f6a982 | |||
| c675482277 | |||
| 93e355ced8 | |||
| 272aee1888 | |||
| 8468f8409d | |||
| 9160a0669d | |||
| c0a1fe72cf | |||
| 7d14d5f525 | |||
| 7620d398f6 | |||
| 21e4e28850 | |||
| 90822d82c9 | |||
| bdcb66b4a6 | |||
| 997156bb88 | |||
| 3363a7f140 | |||
| 4bbf53e7a8 | |||
| a58fa408e7 | |||
| 2b7b29ab41 | |||
| 60c66fd731 | |||
| c9562582d9 | |||
| 31ed4ad14b | |||
| a728e74d91 | |||
| 0bd3f44977 | |||
| a791ffad5e | |||
| 76d597bdab | |||
| 70f17540f8 | |||
| 7d580425d3 | |||
| a8b031ea7f | |||
| ae49d30f8f | |||
| 4465a430fe | |||
| c74770930a | |||
| 2036d7b8eb | |||
| 03b340a733 | |||
| 1d40bd0daf | |||
| 9963abe841 | |||
| 80e348744a | |||
| 6106f7f4c3 | |||
| 300b507c4d | |||
| 41984d3092 | |||
| 79a69ca9a5 | |||
| da321a17f4 | |||
| bd64c83a82 | |||
| d1e6813928 | |||
| 225bd7e021 | |||
| 7d7d0960df | |||
| 9217cc937e | |||
| b63833b611 | |||
| 52d03e4dde | |||
| 725e07b0fd | |||
| 7442b13910 | |||
| a9919395b3 | |||
| b20d93a32f | |||
| 623dfb7a8e | |||
| 63a8236bde | |||
| 86835f6588 | |||
| e13a0d6a5e | |||
| 03ed32c740 | |||
| 9cd59bfc28 | |||
| c30abdf92f | |||
| 14dd3898f6 | |||
| 24e516c812 | |||
| 0d57e2a642 | |||
| bb4a1faaa0 | |||
| db270bb2f4 | |||
| a8102dfc14 | |||
| 4e976b4cd2 | |||
| e8292106c0 | |||
| ae88149180 | |||
| 1e5453fd0f | |||
| f9867107fb | |||
| 07dad071d3 | |||
| 6fc54e4871 | |||
| de38479e43 | |||
| a2dc0cc860 | |||
| 1043a38051 | |||
| f905c20008 | |||
| ef9fa8ddf5 | |||
| 98254380a6 | |||
| bb816bf60c | |||
| 4a6bee6a37 | |||
| 95e4fdfd69 | |||
| 522bef980b | |||
| cfaafde27d |
@@ -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.
|
||||
|
||||
```
|
||||
|
||||
@@ -4,22 +4,31 @@
|
||||
<meta charset="UTF-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>
|
||||
html, body { margin: 0; height: 100%; background: #2b2d31; color: #e8e9ec; }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; }
|
||||
</style>
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||
<meta name="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." />
|
||||
<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. -->
|
||||
@@ -27,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",
|
||||
@@ -46,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>
|
||||
@@ -79,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>
|
||||
@@ -91,25 +100,34 @@
|
||||
<button id="m-stl">Export STL</button>
|
||||
<button id="m-step">Export STEP</button>
|
||||
<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-tutorial">Tutorial <span class="menu-soon">soon</span></button>
|
||||
<button id="m-update">Update</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>
|
||||
<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</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>
|
||||
@@ -129,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",
|
||||
@@ -9,7 +9,10 @@
|
||||
"dev": "vite --host",
|
||||
"build": "tsc --noEmit && vite build",
|
||||
"preview": "vite preview --host",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"check": "tsx scripts/check.ts",
|
||||
"render": "tsx scripts/render.ts",
|
||||
"live": "tsx scripts/live.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource/bebas-neue": "^5.3.0",
|
||||
|
||||
@@ -16,3 +16,23 @@
|
||||
|
||||
/assets/*
|
||||
Cache-Control: public, max-age=31536000, immutable
|
||||
|
||||
/sw.js
|
||||
Cache-Control: no-cache
|
||||
|
||||
/offline-files.json
|
||||
Cache-Control: no-cache
|
||||
|
||||
/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 |
@@ -0,0 +1,105 @@
|
||||
// Offline mode (More → Offline mode). Registered only while it's on.
|
||||
//
|
||||
// The page asks it to download the app's files (the list the build writes,
|
||||
// offline-files.json) into one store per version. Files are then served from
|
||||
// that store, so the app opens and works with no connection. The page itself
|
||||
// is fetched from the site first while online (so a new version shows up),
|
||||
// and from the store when there's no connection.
|
||||
|
||||
const PREFIX = "sg-offline-";
|
||||
const scope = self.registration.scope;
|
||||
|
||||
self.addEventListener("install", () => self.skipWaiting());
|
||||
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
|
||||
|
||||
async function tell(msg) {
|
||||
for (const c of await self.clients.matchAll({ includeUncontrolled: true })) c.postMessage(msg);
|
||||
}
|
||||
|
||||
let running = null;
|
||||
|
||||
/** Store every file of the site's current version. `keep`: the version the open page runs (not removed). */
|
||||
async function download(fresh, keep) {
|
||||
let list;
|
||||
try {
|
||||
list = await (await fetch(new URL("offline-files.json", scope).href, { cache: "no-store" })).json();
|
||||
} catch {
|
||||
await tell({ type: "offline-failed", reason: "offline" });
|
||||
return;
|
||||
}
|
||||
const name = PREFIX + list.build;
|
||||
if (fresh) await caches.delete(name);
|
||||
const store = await caches.open(name);
|
||||
let done = 0;
|
||||
try {
|
||||
for (const f of list.files) {
|
||||
const url = new URL(f, scope).href;
|
||||
if (!(await store.match(url))) {
|
||||
// A file an older version already has (the same name means the same contents) is copied over.
|
||||
const same = f !== "./" && f !== "index.html" && !fresh ? await caches.match(url, { ignoreVary: true }) : null;
|
||||
const res = same ?? (await fetch(url, { cache: "no-cache" }));
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
await store.put(url, res);
|
||||
}
|
||||
done++;
|
||||
await tell({ type: "offline-progress", done, total: list.files.length });
|
||||
}
|
||||
} catch {
|
||||
await tell({ type: "offline-failed", reason: "network" });
|
||||
return;
|
||||
}
|
||||
for (const k of await caches.keys()) if (k.startsWith(PREFIX) && k !== name && k !== PREFIX + keep) await caches.delete(k);
|
||||
await tell({ type: "offline-ready", build: list.build });
|
||||
}
|
||||
|
||||
self.addEventListener("message", (e) => {
|
||||
if (e.data?.type !== "download") return;
|
||||
running ??= download(!!e.data.fresh, e.data.keep).finally(() => (running = null));
|
||||
e.waitUntil(running);
|
||||
});
|
||||
|
||||
/** The page from the store (the newest version stored). */
|
||||
async function storedPage() {
|
||||
const names = (await caches.keys()).filter((k) => k.startsWith(PREFIX));
|
||||
for (const n of names.reverse()) {
|
||||
const hit = (await (await caches.open(n)).match(scope)) ?? (await (await caches.open(n)).match(new URL("index.html", scope).href));
|
||||
if (hit) return hit;
|
||||
}
|
||||
return Response.error();
|
||||
}
|
||||
|
||||
self.addEventListener("fetch", (e) => {
|
||||
const req = e.request;
|
||||
if (req.method !== "GET") return;
|
||||
const url = new URL(req.url);
|
||||
if (url.origin !== location.origin) return;
|
||||
// The update check always asks the site.
|
||||
if (url.searchParams.has("check") || url.pathname.endsWith("offline-files.json")) return;
|
||||
if (req.mode === "navigate") {
|
||||
// Online: the site's page (a new version shows up). Offline or very slow: the stored one.
|
||||
e.respondWith(
|
||||
new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const fallback = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
storedPage().then(resolve);
|
||||
};
|
||||
const timer = setTimeout(fallback, 6000);
|
||||
fetch(req)
|
||||
.then((res) => {
|
||||
clearTimeout(timer);
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
resolve(res);
|
||||
})
|
||||
.catch(() => {
|
||||
clearTimeout(timer);
|
||||
fallback();
|
||||
});
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
e.respondWith(caches.match(req, { ignoreSearch: true, ignoreVary: true }).then((hit) => hit ?? fetch(req)));
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
// Check a project from the command line: rebuild it step by step and say what
|
||||
// each step did (its error, the bodies it made, changed or took away) and how
|
||||
// sound each body is at the end.
|
||||
//
|
||||
// npx tsx scripts/check.ts project.super step by step, then the bodies
|
||||
// npx tsx scripts/check.ts project.super --end only the bodies at the end
|
||||
// npx tsx scripts/check.ts project.super --json the same, as JSON
|
||||
// npx tsx scripts/check.ts project.super --png a.png and a picture of it (see render.ts)
|
||||
//
|
||||
// Exit code 1 when a step fails or a body isn't sound.
|
||||
import { readFileSync } from "node:fs";
|
||||
import opencascade from "replicad-opencascadejs";
|
||||
import { setOC } from "replicad";
|
||||
import { parseProject } from "../src/doc/store";
|
||||
import { debugBodies, healthReport, regenerate } from "../src/kernel/engine";
|
||||
import type { BodyHealth } from "../src/kernel/protocol";
|
||||
import type { Feature } from "../src/doc/types";
|
||||
import { renderPNG, type RenderOptions } from "./render";
|
||||
|
||||
export interface StepReport {
|
||||
index: number;
|
||||
id: string;
|
||||
name: string;
|
||||
type: string;
|
||||
off?: boolean;
|
||||
error?: string;
|
||||
note?: string;
|
||||
/** Bodies it made, took away, or changed (volume before → after, mm³). */
|
||||
made: string[];
|
||||
gone: string[];
|
||||
changed: { body: string; from: number; to: number }[];
|
||||
/** Bodies that were sound before it and aren't after. */
|
||||
broke: string[];
|
||||
ms: number;
|
||||
}
|
||||
|
||||
export interface CheckReport {
|
||||
name: string;
|
||||
steps?: StepReport[];
|
||||
bodies: BodyHealth[];
|
||||
errors: { step: string; message: string }[];
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
/** Every body's health after the steps (name from the rebuild). */
|
||||
function bodiesNow(names: Map<string, string>): BodyHealth[] {
|
||||
return [...debugBodies()].map(([id, s]) => healthReport(id, names.get(id) ?? id, s));
|
||||
}
|
||||
|
||||
export async function checkProject(features: Feature[], name: string, stepwise = true): Promise<CheckReport> {
|
||||
const steps: StepReport[] = [];
|
||||
if (stepwise) {
|
||||
let before = new Map<string, BodyHealth>();
|
||||
for (let i = 0; i < features.length; i++) {
|
||||
const f = features[i];
|
||||
const t0 = performance.now();
|
||||
const r = await regenerate(features.slice(0, i + 1));
|
||||
const names = new Map(r.bodies.map((b) => [b.id, b.name]));
|
||||
const now = new Map(bodiesNow(names).map((h) => [h.id, h]));
|
||||
const step: StepReport = { index: i + 1, id: f.id, name: f.name, type: f.type, made: [], gone: [], changed: [], broke: [], ms: Math.round(performance.now() - t0) };
|
||||
if (f.suppressed) step.off = true;
|
||||
const err = r.errors.find((e) => e.featureId === f.id);
|
||||
if (err) step.error = err.message;
|
||||
const note = r.notes?.find((e) => e.featureId === f.id);
|
||||
if (note) step.note = note.message;
|
||||
for (const [id, h] of now) {
|
||||
const was = before.get(id);
|
||||
if (!was) step.made.push(h.name);
|
||||
else if (Math.abs(was.volume - h.volume) > 1e-6 * Math.max(1, was.volume) || was.faces !== h.faces) step.changed.push({ body: h.name, from: was.volume, to: h.volume });
|
||||
if (was?.healthy && !h.healthy) step.broke.push(h.name);
|
||||
if (!was && !h.healthy) step.broke.push(h.name);
|
||||
}
|
||||
for (const [id, h] of before) if (!now.has(id)) step.gone.push(h.name);
|
||||
steps.push(step);
|
||||
before = now;
|
||||
}
|
||||
}
|
||||
const r = await regenerate(features);
|
||||
const names = new Map(r.bodies.map((b) => [b.id, b.name]));
|
||||
const bodies = bodiesNow(names);
|
||||
const byId = new Map(features.map((f) => [f.id, f]));
|
||||
const errors = r.errors.map((e) => ({ step: byId.get(e.featureId)?.name ?? e.featureId, message: e.message }));
|
||||
return { name, ...(stepwise ? { steps } : {}), bodies, errors, ok: !errors.length && bodies.every((b) => b.healthy) };
|
||||
}
|
||||
|
||||
const n = (v: number) => (Math.abs(v) >= 100 ? v.toFixed(0) : Math.abs(v) >= 1 ? v.toFixed(2) : v.toPrecision(3));
|
||||
|
||||
/** The report as lines to read. */
|
||||
export function reportText(rep: CheckReport): string {
|
||||
const out: string[] = [`Project: ${rep.name}`];
|
||||
if (rep.steps) {
|
||||
out.push("", "Steps:");
|
||||
for (const s of rep.steps) {
|
||||
const what: string[] = [];
|
||||
if (s.off) what.push("switched off");
|
||||
if (s.made.length) what.push(`made ${s.made.join(", ")}`);
|
||||
for (const c of s.changed) what.push(`${c.body} ${c.to >= c.from ? "+" : ""}${n(c.to - c.from)} mm³`);
|
||||
if (s.gone.length) what.push(`took away ${s.gone.join(", ")}`);
|
||||
if (s.broke.length) what.push(`!! not sound after it: ${s.broke.join(", ")}`);
|
||||
if (s.note) what.push(`note: ${s.note}`);
|
||||
if (s.error) what.push(`ERROR: ${s.error}`);
|
||||
out.push(`${String(s.index).padStart(3)}. ${s.name} [${s.type}]${what.length ? " - " + what.join("; ") : ""} (${s.ms} ms)`);
|
||||
}
|
||||
}
|
||||
out.push("", "Bodies:");
|
||||
if (!rep.bodies.length) out.push(" (none)");
|
||||
for (const b of rep.bodies) {
|
||||
const size = b.box[1].map((v, k) => n(v - b.box[0][k])).join(" x ");
|
||||
const bad: string[] = [];
|
||||
if (!b.valid) bad.push("invalid");
|
||||
if (b.solids !== 1) bad.push(`${b.solids} solids`);
|
||||
if (b.openEdges) bad.push(`${b.openEdges} open edges`);
|
||||
if (b.thin) bad.push(`${b.thin} hair-thin faces`);
|
||||
if (!(b.volume > 0)) bad.push("no volume");
|
||||
out.push(` ${b.healthy ? "ok " : "BAD "} ${b.name}: ${n(b.volume)} mm³, ${b.faces} faces, ${b.edges} edges, ${size} mm${bad.length ? " - " + bad.join(", ") : ""}`);
|
||||
}
|
||||
if (rep.errors.length) {
|
||||
out.push("", "Errors:");
|
||||
for (const e of rep.errors) out.push(` ${e.step}: ${e.message}`);
|
||||
}
|
||||
out.push("", rep.ok ? "All sound." : "Not all sound.");
|
||||
return out.join("\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ command line
|
||||
|
||||
if (process.argv[1]?.replace(/\\/g, "/").endsWith("scripts/check.ts")) {
|
||||
const args = process.argv.slice(2);
|
||||
const file = args.find((a) => !a.startsWith("--") && !/\.png$/i.test(a));
|
||||
if (!file) {
|
||||
console.log("Usage: npx tsx scripts/check.ts <project.super> [--end] [--json] [--png out.png] [--view iso|front|top|right|...]");
|
||||
process.exit(2);
|
||||
}
|
||||
const doc = parseProject(readFileSync(file, "utf8"));
|
||||
setOC(await (opencascade as unknown as () => Promise<any>)());
|
||||
const rep = await checkProject(doc.features, doc.name, !args.includes("--end"));
|
||||
console.log(args.includes("--json") ? JSON.stringify(rep, null, 2) : reportText(rep));
|
||||
const png = args[args.indexOf("--png") + 1];
|
||||
if (args.includes("--png") && png) {
|
||||
const view = args.includes("--view") ? (args[args.indexOf("--view") + 1] as RenderOptions["view"]) : "iso";
|
||||
const hidden = new Set(doc.hidden ?? []);
|
||||
renderPNG([...debugBodies()].filter(([id]) => !hidden.has(id)).map(([id, shape]) => ({ shape, color: doc.colors?.[id] })), png, { view });
|
||||
console.log(`Picture: ${png}`);
|
||||
}
|
||||
process.exit(rep.ok ? 0 : 1);
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Is the push live? Compares the commit superGeometry.app was built from
|
||||
// (its /version.json) with main here.
|
||||
//
|
||||
// npx tsx scripts/live.ts once
|
||||
// npx tsx scripts/live.ts --wait until it is (up to 20 minutes)
|
||||
// npx tsx scripts/live.ts --site http://localhost:4173
|
||||
import { execSync } from "node:child_process";
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const site = (args.includes("--site") ? args[args.indexOf("--site") + 1] : "https://supergeometry.app").replace(/\/$/, "");
|
||||
const git = (cmd: string) => {
|
||||
try {
|
||||
return execSync(`git ${cmd}`, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
const want = git("rev-parse origin/main");
|
||||
const short = (c: string) => c.slice(0, 7);
|
||||
|
||||
interface Version {
|
||||
version: string;
|
||||
commit: string;
|
||||
subject: string;
|
||||
script: string;
|
||||
built: string;
|
||||
}
|
||||
|
||||
async function live(): Promise<Version | null> {
|
||||
try {
|
||||
const r = await fetch(`${site}/version.json?t=${Date.now()}`, { cache: "no-store" });
|
||||
if (!r.ok) return null;
|
||||
return (await r.json()) as Version;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const until = Date.now() + 20 * 60_000;
|
||||
for (;;) {
|
||||
const v = await live();
|
||||
if (v?.commit && v.commit === want) {
|
||||
console.log(`Live: ${short(v.commit)} ${v.subject} (built ${v.built}, ${v.script})`);
|
||||
process.exit(0);
|
||||
}
|
||||
if (!args.includes("--wait") || Date.now() > until) {
|
||||
if (!v) console.log(`${site} has no version.json yet (built before it was added), main is ${short(want)}`);
|
||||
else console.log(`Not live yet: the site is ${short(v.commit)} ${v.subject} (built ${v.built}), main is ${short(want)} ${git(`log -1 --format=%s ${want}`)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 20_000));
|
||||
}
|
||||
@@ -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,269 @@
|
||||
// A picture of solids without a browser: the bodies meshed, drawn shaded with
|
||||
// their edges by a small software renderer, and written as a PNG.
|
||||
//
|
||||
// npx tsx scripts/render.ts project.super out.png [--view iso|front|back|top|bottom|left|right] [--size 800]
|
||||
// import { renderPNG } from "./render"; renderPNG([{ shape }], "out.png", { view: "front" });
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { deflateSync } from "node:zlib";
|
||||
import type { Shape3D } from "replicad";
|
||||
|
||||
type V3 = [number, number, number];
|
||||
|
||||
export interface RenderOptions {
|
||||
view?: "iso" | "front" | "back" | "top" | "bottom" | "left" | "right";
|
||||
/** Width and height in pixels (default 800). */
|
||||
size?: number;
|
||||
/** Background, "#rrggbb" (default light grey). */
|
||||
background?: string;
|
||||
/** Edges drawn over the faces (default on). */
|
||||
edges?: boolean;
|
||||
}
|
||||
|
||||
export interface RenderBody {
|
||||
shape: Shape3D;
|
||||
/** "#rrggbb" (default a blue-grey). */
|
||||
color?: string;
|
||||
}
|
||||
|
||||
// The views: the direction looked from (towards the viewer) and which way is up on the picture.
|
||||
const VIEWS: Record<NonNullable<RenderOptions["view"]>, { dir: V3; up: V3 }> = {
|
||||
iso: { dir: [1, -1, 1], up: [0, 0, 1] },
|
||||
front: { dir: [0, -1, 0], up: [0, 0, 1] },
|
||||
back: { dir: [0, 1, 0], up: [0, 0, 1] },
|
||||
top: { dir: [0, 0, 1], up: [0, 1, 0] },
|
||||
bottom: { dir: [0, 0, -1], up: [0, -1, 0] },
|
||||
left: { dir: [-1, 0, 0], up: [0, 0, 1] },
|
||||
right: { dir: [1, 0, 0], up: [0, 0, 1] },
|
||||
};
|
||||
|
||||
const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
||||
const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
||||
const norm = (a: V3): V3 => {
|
||||
const l = Math.hypot(...a) || 1;
|
||||
return [a[0] / l, a[1] / l, a[2] / l];
|
||||
};
|
||||
const rgb = (hex: string): V3 => {
|
||||
const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim());
|
||||
const v = m ? parseInt(m[1], 16) : 0x8fa3b8;
|
||||
return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
|
||||
};
|
||||
|
||||
/** The picture as RGBA pixels (size x size). */
|
||||
export function renderRGBA(bodies: RenderBody[], o: RenderOptions = {}): { width: number; height: number; data: Uint8Array } {
|
||||
const size = o.size ?? 800;
|
||||
const SS = 2; // drawn twice as big, then averaged down (smooth edges)
|
||||
const W = size * SS;
|
||||
const view = VIEWS[o.view ?? "iso"];
|
||||
const fwd = norm(view.dir);
|
||||
const right = norm(cross(view.up, fwd));
|
||||
const up = cross(fwd, right);
|
||||
const bg = rgb(o.background ?? "#eef0f3");
|
||||
|
||||
// Meshes in view space: x right, y up, z towards the viewer.
|
||||
const meshes = bodies.flatMap((b) => {
|
||||
try {
|
||||
const m = b.shape.mesh({ tolerance: 0.05, angularTolerance: 0.15 });
|
||||
let lines: number[] = [];
|
||||
if (o.edges !== false) {
|
||||
try {
|
||||
lines = (b.shape as any).meshEdges({ tolerance: 0.05, angularTolerance: 0.15 }).lines as number[];
|
||||
} catch {
|
||||
lines = [];
|
||||
}
|
||||
}
|
||||
return [{ v: m.vertices as number[], t: m.triangles as number[], lines, color: rgb(b.color ?? "#8fa3b8") }];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
const toView = (a: number[], i: number): V3 => {
|
||||
const p: V3 = [a[i], a[i + 1], a[i + 2]];
|
||||
return [dot(p, right), dot(p, up), dot(p, fwd)];
|
||||
};
|
||||
let lo: V3 = [Infinity, Infinity, Infinity];
|
||||
let hi: V3 = [-Infinity, -Infinity, -Infinity];
|
||||
for (const m of meshes)
|
||||
for (let i = 0; i < m.v.length; i += 3) {
|
||||
const p = toView(m.v, i);
|
||||
lo = [Math.min(lo[0], p[0]), Math.min(lo[1], p[1]), Math.min(lo[2], p[2])];
|
||||
hi = [Math.max(hi[0], p[0]), Math.max(hi[1], p[1]), Math.max(hi[2], p[2])];
|
||||
}
|
||||
const color = new Float32Array(W * W * 3);
|
||||
for (let i = 0; i < W * W; i++) color.set(bg, i * 3);
|
||||
const depth = new Float32Array(W * W).fill(-Infinity);
|
||||
if (Number.isFinite(lo[0])) {
|
||||
// Fit with a margin, centred.
|
||||
const span = Math.max(hi[0] - lo[0], hi[1] - lo[1]) || 1;
|
||||
const k = (W * 0.86) / span;
|
||||
const cx = (lo[0] + hi[0]) / 2;
|
||||
const cy = (lo[1] + hi[1]) / 2;
|
||||
const px = (p: V3): V3 => [W / 2 + (p[0] - cx) * k, W / 2 - (p[1] - cy) * k, p[2]];
|
||||
const light = norm([0.35, 0.55, 1]);
|
||||
for (const m of meshes) {
|
||||
const P: V3[] = [];
|
||||
for (let i = 0; i < m.v.length; i += 3) P.push(px(toView(m.v, i)));
|
||||
for (let t = 0; t < m.t.length; t += 3) {
|
||||
const a = P[m.t[t]];
|
||||
const b = P[m.t[t + 1]];
|
||||
const c = P[m.t[t + 2]];
|
||||
// The face's normal in view space (screen y is down: flip it back).
|
||||
const n = norm(cross(sub([b[0], -b[1], b[2]], [a[0], -a[1], a[2]]), sub([c[0], -c[1], c[2]], [a[0], -a[1], a[2]])));
|
||||
const facing = n[2] < 0 ? ([-n[0], -n[1], -n[2]] as V3) : n;
|
||||
const shade = 0.38 + 0.62 * Math.max(0, dot(facing, light));
|
||||
const col: V3 = [m.color[0] * shade, m.color[1] * shade, m.color[2] * shade];
|
||||
fillTri(a, b, c, col, color, depth, W);
|
||||
}
|
||||
// Edges: dark, drawn where they are not behind a face.
|
||||
const bias = (hi[2] - lo[2] || 1) * 2e-3;
|
||||
for (let i = 0; i + 5 < m.lines.length; i += 6) {
|
||||
const a = px(toView(m.lines, i));
|
||||
const b = px(toView(m.lines, i + 3));
|
||||
drawLine(a, b, [40, 44, 52], color, depth, W, bias, SS);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Average each SS x SS block.
|
||||
const data = new Uint8Array(size * size * 4);
|
||||
for (let y = 0; y < size; y++)
|
||||
for (let x = 0; x < size; x++) {
|
||||
let r = 0,
|
||||
g = 0,
|
||||
b = 0;
|
||||
for (let j = 0; j < SS; j++)
|
||||
for (let i = 0; i < SS; i++) {
|
||||
const q = ((y * SS + j) * W + x * SS + i) * 3;
|
||||
r += color[q];
|
||||
g += color[q + 1];
|
||||
b += color[q + 2];
|
||||
}
|
||||
const o4 = (y * size + x) * 4;
|
||||
data[o4] = r / (SS * SS);
|
||||
data[o4 + 1] = g / (SS * SS);
|
||||
data[o4 + 2] = b / (SS * SS);
|
||||
data[o4 + 3] = 255;
|
||||
}
|
||||
return { width: size, height: size, data };
|
||||
}
|
||||
|
||||
function fillTri(a: V3, b: V3, c: V3, col: V3, color: Float32Array, depth: Float32Array, W: number): void {
|
||||
const x0 = Math.max(0, Math.floor(Math.min(a[0], b[0], c[0])));
|
||||
const x1 = Math.min(W - 1, Math.ceil(Math.max(a[0], b[0], c[0])));
|
||||
const y0 = Math.max(0, Math.floor(Math.min(a[1], b[1], c[1])));
|
||||
const y1 = Math.min(W - 1, Math.ceil(Math.max(a[1], b[1], c[1])));
|
||||
const area = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
|
||||
if (Math.abs(area) < 1e-12) return;
|
||||
for (let y = y0; y <= y1; y++)
|
||||
for (let x = x0; x <= x1; x++) {
|
||||
const px = x + 0.5;
|
||||
const py = y + 0.5;
|
||||
const w0 = ((b[0] - px) * (c[1] - py) - (b[1] - py) * (c[0] - px)) / area;
|
||||
const w1 = ((c[0] - px) * (a[1] - py) - (c[1] - py) * (a[0] - px)) / area;
|
||||
const w2 = 1 - w0 - w1;
|
||||
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
|
||||
const z = w0 * a[2] + w1 * b[2] + w2 * c[2];
|
||||
const i = y * W + x;
|
||||
if (z <= depth[i]) continue;
|
||||
depth[i] = z;
|
||||
color[i * 3] = col[0];
|
||||
color[i * 3 + 1] = col[1];
|
||||
color[i * 3 + 2] = col[2];
|
||||
}
|
||||
}
|
||||
|
||||
function drawLine(a: V3, b: V3, col: V3, color: Float32Array, depth: Float32Array, W: number, bias: number, thick: number): void {
|
||||
const steps = Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]))) + 1;
|
||||
for (let s = 0; s <= steps; s++) {
|
||||
const t = s / steps;
|
||||
const x = a[0] + (b[0] - a[0]) * t;
|
||||
const y = a[1] + (b[1] - a[1]) * t;
|
||||
const z = a[2] + (b[2] - a[2]) * t;
|
||||
for (let j = 0; j < thick; j++)
|
||||
for (let i = 0; i < thick; i++) {
|
||||
const X = Math.floor(x - thick / 2 + i + 0.5);
|
||||
const Y = Math.floor(y - thick / 2 + j + 0.5);
|
||||
if (X < 0 || Y < 0 || X >= W || Y >= W) continue;
|
||||
const k = Y * W + X;
|
||||
if (z + bias < depth[k]) continue;
|
||||
color[k * 3] = col[0];
|
||||
color[k * 3 + 1] = col[1];
|
||||
color[k * 3 + 2] = col[2];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ PNG
|
||||
|
||||
const CRC = (() => {
|
||||
const t = new Uint32Array(256);
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
t[n] = c >>> 0;
|
||||
}
|
||||
return t;
|
||||
})();
|
||||
function crc32(buf: Uint8Array): number {
|
||||
let c = 0xffffffff;
|
||||
for (const b of buf) c = CRC[(c ^ b) & 255] ^ (c >>> 8);
|
||||
return (c ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
function chunk(type: string, data: Uint8Array): Uint8Array {
|
||||
const out = new Uint8Array(12 + data.length);
|
||||
const dv = new DataView(out.buffer);
|
||||
dv.setUint32(0, data.length);
|
||||
out.set(Buffer.from(type, "ascii"), 4);
|
||||
out.set(data, 8);
|
||||
dv.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** RGBA pixels as a PNG file. */
|
||||
export function encodePNG(width: number, height: number, rgba: Uint8Array): Uint8Array {
|
||||
const raw = new Uint8Array(height * (width * 4 + 1));
|
||||
for (let y = 0; y < height; y++) raw.set(rgba.subarray(y * width * 4, (y + 1) * width * 4), y * (width * 4 + 1) + 1);
|
||||
const ihdr = new Uint8Array(13);
|
||||
const dv = new DataView(ihdr.buffer);
|
||||
dv.setUint32(0, width);
|
||||
dv.setUint32(4, height);
|
||||
ihdr.set([8, 6, 0, 0, 0], 8);
|
||||
const parts = [new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]), chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", new Uint8Array())];
|
||||
const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0));
|
||||
let at = 0;
|
||||
for (const p of parts) out.set(p, at), (at += p.length);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Draw the bodies and write the picture to `file`. */
|
||||
export function renderPNG(bodies: RenderBody[], file: string, o: RenderOptions = {}): void {
|
||||
const { width, height, data } = renderRGBA(bodies, o);
|
||||
writeFileSync(file, encodePNG(width, height, data));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ command line
|
||||
|
||||
if (process.argv[1]?.replace(/\\/g, "/").endsWith("scripts/render.ts")) {
|
||||
const args = process.argv.slice(2);
|
||||
const [file, out] = args.filter((a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"));
|
||||
if (!file || !out) {
|
||||
console.log("Usage: npx tsx scripts/render.ts <project.super> <out.png> [--view iso|front|back|top|bottom|left|right] [--size 800]");
|
||||
process.exit(2);
|
||||
}
|
||||
const { readFileSync } = await import("node:fs");
|
||||
const opencascade = (await import("replicad-opencascadejs")).default;
|
||||
const { setOC } = await import("replicad");
|
||||
const { parseProject } = await import("../src/doc/store");
|
||||
const { debugBodies, regenerate } = await import("../src/kernel/engine");
|
||||
const doc = parseProject(readFileSync(file, "utf8"));
|
||||
setOC(await (opencascade as unknown as () => Promise<any>)());
|
||||
const r = await regenerate(doc.features);
|
||||
for (const e of r.errors) console.log(`error in ${e.featureId}: ${e.message}`);
|
||||
const hidden = new Set(doc.hidden ?? []);
|
||||
const opt = (k: string) => (args.includes(k) ? args[args.indexOf(k) + 1] : undefined);
|
||||
renderPNG(
|
||||
[...debugBodies()].filter(([id]) => !hidden.has(id)).map(([id, shape]) => ({ shape, color: doc.colors?.[id] })),
|
||||
out,
|
||||
{ view: (opt("--view") as RenderOptions["view"]) ?? "iso", size: Number(opt("--size") ?? 800) },
|
||||
);
|
||||
console.log(`Picture: ${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" };
|
||||
@@ -0,0 +1,317 @@
|
||||
// BIM: each body given a real material (with its technical data), and from
|
||||
// those the technical sheet (parts list, masses, the materials' data) that
|
||||
// the drawings are made with. Entered from BIM in the left column.
|
||||
//
|
||||
// Tap a body (or its row in the card), then a material: it is that material
|
||||
// from then on - its colour on the model, its mass in the sheet.
|
||||
|
||||
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";
|
||||
import { allMaterials, assignMaterial, fmtMass, fmtVolume, massOf, MATERIAL_CLASSES, materialOf, materialRows } from "./materials";
|
||||
|
||||
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>> {
|
||||
const props = await app.kernel.properties(app.store.doc.features as never);
|
||||
// Opened right as a project loads, the model on screen may not be this one
|
||||
// yet: the parts are listed from it, so wait for it (a while at most).
|
||||
const t0 = performance.now();
|
||||
const shown = () => new Set(app.view.bodyList.map((b) => b.id));
|
||||
while (props.some((p) => !shown().has(p.id)) && performance.now() - t0 < 20000) await new Promise((r) => setTimeout(r, 100));
|
||||
return new Map(props.map((p) => [p.id, p]));
|
||||
}
|
||||
|
||||
|
||||
export class BimTool implements Tool {
|
||||
readonly id = "bim";
|
||||
private card: HTMLElement | null = null;
|
||||
/** What the card shows (below its grip, name and X). */
|
||||
private body: HTMLElement | null = null;
|
||||
private props = new Map<string, BodyProps>();
|
||||
/** The project the properties were measured for. */
|
||||
private measured: unknown = null;
|
||||
private search = "";
|
||||
/** The material whose technical data is shown open. */
|
||||
private details: string | null = null;
|
||||
|
||||
constructor(private app: AppContext) {}
|
||||
|
||||
private get picked(): string[] {
|
||||
return [...new Set(this.app.selection.flatMap((s) => ("body" in s ? [s.body] : [])))];
|
||||
}
|
||||
|
||||
enter(): void {
|
||||
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", 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-inner");
|
||||
this.card.append(this.header(), this.body);
|
||||
document.body.append(this.card);
|
||||
this.putCard(BimTool.spot());
|
||||
document.body.classList.add("bim-open");
|
||||
// Bodies picked before: what the materials go to.
|
||||
const bodies = this.picked;
|
||||
this.app.setSelection(bodies.map((body) => ({ kind: "body", body })));
|
||||
this.render();
|
||||
void this.measure();
|
||||
}
|
||||
|
||||
exit(): void {
|
||||
this.card?.remove();
|
||||
this.card = null;
|
||||
this.body = null;
|
||||
document.body.classList.remove("bim-open");
|
||||
this.app.ui.setHint(null);
|
||||
this.app.setSelection([]);
|
||||
this.app.setHover(null);
|
||||
}
|
||||
|
||||
key(e: KeyboardEvent): boolean {
|
||||
if (e.key === "Escape") {
|
||||
if (this.app.selection.length) this.app.setSelection([]);
|
||||
else this.app.setTool(null);
|
||||
this.render();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** After a rebuild: bodies may have changed size (their mass with them). */
|
||||
refresh(): void {
|
||||
this.render();
|
||||
void this.measure();
|
||||
}
|
||||
|
||||
private async measure(): Promise<void> {
|
||||
const doc = this.app.store.doc.features;
|
||||
if (this.measured === doc) return;
|
||||
this.measured = doc;
|
||||
try {
|
||||
const props = await measureBodies(this.app);
|
||||
if (this.measured !== doc) return;
|
||||
this.props = props;
|
||||
this.render();
|
||||
} catch {
|
||||
// Measured again after the next change.
|
||||
this.measured = null;
|
||||
}
|
||||
}
|
||||
|
||||
private bodyAt(p: ToolPointer): string | null {
|
||||
const s = hitToSel(this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false, axes: false, images: false }));
|
||||
return s && "body" in s ? s.body : null;
|
||||
}
|
||||
|
||||
hover(p: ToolPointer | null): void {
|
||||
const b = p ? this.bodyAt(p) : null;
|
||||
this.app.setHover(b ? { kind: "body", body: b } : null);
|
||||
}
|
||||
|
||||
tap(p: ToolPointer): void {
|
||||
const b = this.bodyAt(p);
|
||||
if (!b) {
|
||||
this.app.setSelection([]);
|
||||
return this.render();
|
||||
}
|
||||
// Tap: that body (or another one added to it, with the first still picked: one tap each).
|
||||
const now = this.picked;
|
||||
const next: Sel[] = now.includes(b) ? now.filter((x) => x !== b).map((body) => ({ kind: "body", body })) : [...now, b].map((body) => ({ kind: "body", body }));
|
||||
this.app.setSelection(next);
|
||||
this.render();
|
||||
}
|
||||
|
||||
private give(m: MaterialDef | null): void {
|
||||
const bodies = this.picked;
|
||||
if (!bodies.length) return this.app.ui.toast("Tap a body first (or its row above)");
|
||||
this.app.store.commit((d) => assignMaterial(d, bodies, m));
|
||||
this.app.ui.toast(m ? `${bodies.length === 1 ? "It is" : `${bodies.length} bodies are`} ${m.name} now` : "Material taken off");
|
||||
this.render();
|
||||
}
|
||||
|
||||
// ---- The card's top: a grip to drag it anywhere (it opens there again), its name, X to leave BIM.
|
||||
|
||||
private static POS = "sg-bim-card";
|
||||
private static spot(): { x: number; y: number } | null {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(BimTool.POS) ?? "{}")?.[document.documentElement.dataset.screen ?? "desktop"] ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private header(): HTMLElement {
|
||||
const head = el("div", "bim-head");
|
||||
const grip = el("div", "bim-grip");
|
||||
grip.append(el("span", ""));
|
||||
const title = el("span", "panel-title", "Materials");
|
||||
const x = el("button", "bim-close");
|
||||
x.innerHTML = icons.close;
|
||||
x.title = "Exit BIM";
|
||||
x.setAttribute("aria-label", "Exit BIM");
|
||||
x.addEventListener("click", () => this.app.setTool(null));
|
||||
head.append(grip, title, x);
|
||||
let drag: { id: number; dx: number; dy: number } | null = null;
|
||||
head.addEventListener("pointerdown", (e) => {
|
||||
if (!this.card || (e.target as HTMLElement).closest(".bim-close")) return;
|
||||
e.preventDefault();
|
||||
const r = this.card.getBoundingClientRect();
|
||||
drag = { id: e.pointerId, dx: e.clientX - r.left, dy: e.clientY - r.top };
|
||||
head.setPointerCapture(e.pointerId);
|
||||
});
|
||||
head.addEventListener("pointermove", (e) => {
|
||||
if (drag?.id === e.pointerId) this.putCard({ x: e.clientX - drag.dx, y: e.clientY - drag.dy });
|
||||
});
|
||||
const end = (e: PointerEvent) => {
|
||||
if (drag?.id !== e.pointerId || !this.card) return;
|
||||
drag = null;
|
||||
try {
|
||||
const all = JSON.parse(localStorage.getItem(BimTool.POS) ?? "{}") ?? {};
|
||||
all[document.documentElement.dataset.screen ?? "desktop"] = { x: this.card.offsetLeft, y: this.card.offsetTop };
|
||||
localStorage.setItem(BimTool.POS, JSON.stringify(all));
|
||||
} catch {
|
||||
// private window: not remembered
|
||||
}
|
||||
};
|
||||
head.addEventListener("pointerup", end);
|
||||
head.addEventListener("pointercancel", end);
|
||||
return head;
|
||||
}
|
||||
|
||||
/** The card at a spot, kept whole on screen (null: where it opens by default). */
|
||||
private putCard(at: { x: number; y: number } | null): void {
|
||||
const c = this.card;
|
||||
if (!c || !at) return;
|
||||
c.style.width = `${c.offsetWidth}px`;
|
||||
c.style.right = "auto";
|
||||
c.style.bottom = "auto";
|
||||
c.style.left = `${Math.round(Math.max(4, Math.min(window.innerWidth - c.offsetWidth - 4, at.x)))}px`;
|
||||
c.style.top = `${Math.round(Math.max(4, Math.min(window.innerHeight - c.offsetHeight - 4, at.y)))}px`;
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
const card = this.body;
|
||||
if (!card) return;
|
||||
const doc = this.app.store.doc;
|
||||
const keep = card.querySelector<HTMLElement>(".bim-materials")?.scrollTop ?? 0;
|
||||
card.innerHTML = "";
|
||||
|
||||
// ---- The bodies, each with its material and mass.
|
||||
const bodies = this.app.view.bodyList.filter((b) => !doc.hidden.includes(b.id));
|
||||
const picked = new Set(this.picked);
|
||||
const list = el("div", "bim-bodies");
|
||||
bodies.forEach((b, i) => {
|
||||
const m = materialOf(doc, b.id);
|
||||
const p = this.props.get(b.id);
|
||||
const row = el("button", `bim-body${picked.has(b.id) ? " on" : ""}`);
|
||||
const dot = el("span", "bim-swatch");
|
||||
dot.style.background = doc.colors?.[b.id] ?? "#b9bec7";
|
||||
const text = el("span", "bim-body-text");
|
||||
text.append(el("span", "bim-body-name", `${i + 1}. ${doc.names?.[b.id] ?? b.name}`), el("span", "bim-sub", m ? m.name : "No material yet"));
|
||||
const mass = el("span", "bim-mass", m && p ? fmtMass(massOf(m, p.volume)) : p ? fmtVolume(p.volume) : "");
|
||||
row.append(dot, text, mass);
|
||||
row.addEventListener("click", () => {
|
||||
this.app.setSelection([{ kind: "body", body: b.id }]);
|
||||
this.render();
|
||||
});
|
||||
list.append(row);
|
||||
});
|
||||
if (!bodies.length) list.append(el("div", "bim-sub", "No bodies yet: make one, then give it a material."));
|
||||
card.append(list);
|
||||
|
||||
// ---- What's picked, and what it weighs.
|
||||
const sel = this.picked;
|
||||
const now = sel.map((id) => materialOf(doc, id));
|
||||
const same = now.every((m) => m?.id === now[0]?.id) ? now[0] : undefined;
|
||||
const info = el("div", "bim-picked");
|
||||
if (!sel.length) info.append(el("span", "bim-sub", "Tap a body, or its row, to give it a material."));
|
||||
else {
|
||||
const kg = sel.reduce((s, id) => {
|
||||
const m = materialOf(doc, id);
|
||||
const p = this.props.get(id);
|
||||
return m && p ? s + massOf(m, p.volume) : s;
|
||||
}, 0);
|
||||
const known = sel.every((id) => materialOf(doc, id) && this.props.get(id));
|
||||
info.append(el("span", "", `${sel.length === 1 ? "1 body" : `${sel.length} bodies`} picked${known ? ` · ${fmtMass(kg)}` : ""}`));
|
||||
if (now.some(Boolean)) {
|
||||
const off = el("button", "text-btn", "Take off material");
|
||||
off.addEventListener("click", () => this.give(null));
|
||||
info.append(off);
|
||||
}
|
||||
}
|
||||
card.append(info);
|
||||
|
||||
// ---- The library, by class; search to narrow it.
|
||||
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<HTMLElement>(".bim-search");
|
||||
again?.focus();
|
||||
if (again) caretToEnd(again);
|
||||
});
|
||||
card.append(find);
|
||||
const box = el("div", "bim-materials");
|
||||
const q = this.search.trim().toLowerCase();
|
||||
const all = allMaterials(doc).filter((m) => !q || `${m.name} ${m.category} ${m.standard ?? ""}`.toLowerCase().includes(q));
|
||||
const classes = [...MATERIAL_CLASSES, ...new Set(all.map((m) => m.category).filter((c) => !(MATERIAL_CLASSES as readonly string[]).includes(c)))];
|
||||
for (const c of classes) {
|
||||
const ms = all.filter((m) => m.category === c);
|
||||
if (!ms.length) continue;
|
||||
box.append(el("div", "bim-class", c));
|
||||
for (const m of ms) {
|
||||
const row = el("div", `bim-material${same?.id === m.id ? " on" : ""}`);
|
||||
const pick = el("button", "bim-material-pick");
|
||||
const sw = el("span", "bim-swatch");
|
||||
sw.style.background = m.color;
|
||||
const text = el("span", "bim-body-text");
|
||||
text.append(el("span", "bim-body-name", m.name), el("span", "bim-sub", `${m.density} kg/m³${m.standard ? ` · ${m.standard}` : ""}`));
|
||||
pick.append(sw, text);
|
||||
pick.addEventListener("click", () => this.give(m));
|
||||
const more = el("button", `bim-info${this.details === m.id ? " on" : ""}`, "i");
|
||||
more.title = "Technical data";
|
||||
more.addEventListener("click", () => {
|
||||
this.details = this.details === m.id ? null : m.id;
|
||||
this.render();
|
||||
});
|
||||
row.append(pick, more);
|
||||
box.append(row);
|
||||
if (this.details === m.id) box.append(dataTable(m));
|
||||
}
|
||||
}
|
||||
if (!all.length) box.append(el("div", "bim-sub", "No material by that name."));
|
||||
card.append(box);
|
||||
box.scrollTop = keep;
|
||||
}
|
||||
}
|
||||
|
||||
/** A material's technical data, by group (identity, physical, thermal). */
|
||||
export function dataTable(m: MaterialDef): HTMLElement {
|
||||
const t = el("div", "bim-data");
|
||||
for (const g of materialRows(m)) {
|
||||
t.append(el("div", "bim-data-group", g.group));
|
||||
for (const [k, v] of g.rows) {
|
||||
const r = el("div", "bim-data-row");
|
||||
r.append(el("span", "", k), el("span", "", v));
|
||||
t.append(r);
|
||||
}
|
||||
}
|
||||
return t;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
// Real materials for bodies (BIM). Like a material in the big BIM tools,
|
||||
// each one carries more than a look: who it is (identity: name, class, the
|
||||
// standard its grade comes from), how it shows (a colour, see-through for
|
||||
// glass), and its technical data - physical (density, stiffness, strength)
|
||||
// and thermal (conductivity, specific heat, expansion). A body's mass, the
|
||||
// technical sheet and the drawings' parts list are worked out from them.
|
||||
//
|
||||
// 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. 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", "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, 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, 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, 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, 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, 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, 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. */
|
||||
export function allMaterials(doc: ProjectDoc): MaterialDef[] {
|
||||
return [...MATERIALS, ...(doc.customMaterials ?? [])];
|
||||
}
|
||||
|
||||
/** The material given to a body (undefined: none yet). */
|
||||
export function materialOf(doc: ProjectDoc, body: string): MaterialDef | undefined {
|
||||
const id = doc.materials?.[body];
|
||||
return id ? allMaterials(doc).find((m) => m.id === id) : undefined;
|
||||
}
|
||||
|
||||
/** The technical data of a material, as rows to show: [label, value with its unit]. Only what it has. */
|
||||
export function materialRows(m: MaterialDef): { group: string; rows: [string, string][] }[] {
|
||||
const n = (v: number) => String(Math.round(v * 1000) / 1000);
|
||||
const row = (label: string, v: number | undefined, unit: string): [string, string][] => (v === undefined ? [] : [[label, `${n(v)} ${unit}`.trim()]]);
|
||||
const groups = [
|
||||
{ group: "Identity", rows: [["Class", m.category], ...(m.standard ? [["Standard", m.standard]] : []), ...(m.note ? [["Note", m.note]] : [])] as [string, string][] },
|
||||
{
|
||||
group: "Physical",
|
||||
rows: [
|
||||
...row("Density", m.density, "kg/m³"),
|
||||
...row("Young's modulus", m.youngs, "GPa"),
|
||||
...row("Poisson's ratio", m.poisson, ""),
|
||||
...row("Yield strength", m.yield, "MPa"),
|
||||
...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)"),
|
||||
...row("Melting point", m.melting, "°C"),
|
||||
...row("Max service temperature", m.maxTemp, "°C"),
|
||||
],
|
||||
},
|
||||
];
|
||||
return groups.filter((g) => g.rows.length);
|
||||
}
|
||||
|
||||
/** Mass in kg of `volumeMM3` cubic millimetres of it. */
|
||||
export function massOf(m: MaterialDef, volumeMM3: number): number {
|
||||
return volumeMM3 * 1e-9 * m.density;
|
||||
}
|
||||
|
||||
/** A mass for people: g under a kilo, kg up to a tonne, t above. */
|
||||
export function fmtMass(kg: number): string {
|
||||
if (kg < 1) return `${trim(kg * 1000, 1)} g`;
|
||||
if (kg < 1000) return `${trim(kg, 3)} kg`;
|
||||
return `${trim(kg / 1000, 3)} t`;
|
||||
}
|
||||
|
||||
export function fmtVolume(mm3: number): string {
|
||||
const k = UNIT_MM[units()];
|
||||
return `${trim(mm3 / (k * k * k), 3)} ${UNIT_LABEL[units()]}³`;
|
||||
}
|
||||
|
||||
export function fmtArea(mm2: number): string {
|
||||
const k = UNIT_MM[units()];
|
||||
return `${trim(mm2 / (k * k), 3)} ${UNIT_LABEL[units()]}²`;
|
||||
}
|
||||
|
||||
/** Give bodies a material (its colour, and see-through for glass, come with it); null takes it away. */
|
||||
export function assignMaterial(d: ProjectDoc, bodies: string[], m: MaterialDef | null): void {
|
||||
const materials = { ...(d.materials ?? {}) };
|
||||
const colors = { ...(d.colors ?? {}) };
|
||||
const opacity = { ...(d.opacity ?? {}) };
|
||||
for (const b of bodies) {
|
||||
if (!m) {
|
||||
delete materials[b];
|
||||
continue;
|
||||
}
|
||||
materials[b] = m.id;
|
||||
colors[b] = m.color;
|
||||
if (m.opacity !== undefined) opacity[b] = m.opacity;
|
||||
else delete opacity[b];
|
||||
}
|
||||
d.materials = materials;
|
||||
d.colors = colors;
|
||||
d.opacity = opacity;
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// The technical sheet: the project as a document. A title block (who, what,
|
||||
// which revision), the parts list - each body with its item number, material,
|
||||
// volume, area, mass, centre of mass and size - and the technical data of
|
||||
// every material used. The item numbers are the ones the drawings' balloons
|
||||
// point to: the drawings show the shapes, this sheet says what they are made of.
|
||||
//
|
||||
// It prints (or saves as a PDF from the print window) and its parts list
|
||||
// downloads as a spreadsheet (CSV).
|
||||
|
||||
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";
|
||||
import { massOf, materialOf } from "./materials";
|
||||
|
||||
/** One row of the parts list. */
|
||||
export interface PartRow {
|
||||
item: number;
|
||||
id: string;
|
||||
name: string;
|
||||
material: string;
|
||||
volume: number;
|
||||
area: number;
|
||||
/** kg; undefined without a material. */
|
||||
mass?: number;
|
||||
center: [number, number, number];
|
||||
size: [number, number, number];
|
||||
}
|
||||
|
||||
/** The parts list: every body shown, numbered as in the drawings. */
|
||||
export function partsList(app: AppContext, props: Map<string, BodyProps>): PartRow[] {
|
||||
const doc = app.store.doc;
|
||||
return app.view.bodyList
|
||||
.filter((b) => !doc.hidden.includes(b.id) && props.has(b.id))
|
||||
.map((b, i) => {
|
||||
const p = props.get(b.id)!;
|
||||
const m = materialOf(doc, b.id);
|
||||
return {
|
||||
item: i + 1,
|
||||
id: b.id,
|
||||
name: doc.names?.[b.id] ?? b.name,
|
||||
material: m?.name ?? "",
|
||||
volume: p.volume,
|
||||
area: p.area,
|
||||
mass: m ? massOf(m, p.volume) : undefined,
|
||||
center: p.center,
|
||||
size: [p.box[1][0] - p.box[0][0], p.box[1][1] - p.box[0][1], p.box[1][2] - p.box[0][2]],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
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");
|
||||
const bar = el("div", "bim-sheet-bar");
|
||||
const close = el("button", "text-btn", "Close");
|
||||
const print = el("button", "text-btn", "Print / PDF");
|
||||
const csv = el("button", "text-btn", "Parts list (CSV)");
|
||||
bar.append(el("span", "bim-sheet-name", "Technical Sheet"), print, csv, close);
|
||||
const paper = el("div", "bim-paper");
|
||||
paper.append(el("div", "bim-sub", "Measuring the bodies…"));
|
||||
back.append(bar, paper);
|
||||
document.body.append(back);
|
||||
const shut = () => {
|
||||
back.remove();
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
};
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") (e.preventDefault(), e.stopPropagation(), shut());
|
||||
};
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
close.addEventListener("click", shut);
|
||||
print.addEventListener("click", () => printPage("printing-sheet"));
|
||||
|
||||
let rows: PartRow[] = [];
|
||||
try {
|
||||
rows = partsList(app, await measureBodies(app));
|
||||
} catch (err) {
|
||||
paper.innerHTML = "";
|
||||
paper.append(el("div", "bim-sub", `The bodies could not be measured: ${err instanceof Error ? err.message : String(err)}`));
|
||||
return;
|
||||
}
|
||||
csv.addEventListener("click", () => {
|
||||
const u = UNIT_LABEL[units()];
|
||||
const q = (s: string) => `"${s.replace(/"/g, '""')}"`;
|
||||
const k = UNIT_MM[units()];
|
||||
const lines = [
|
||||
["Item", "Name", "Material", `Volume (${u}3)`, `Area (${u}2)`, "Mass (kg)", `Centre of mass X (${u})`, `Y (${u})`, `Z (${u})`, `Size X (${u})`, `Size Y (${u})`, `Size Z (${u})`].join(","),
|
||||
...rows.map((r) =>
|
||||
[r.item, q(r.name), q(r.material), trim(r.volume / k ** 3, 4), trim(r.area / k ** 2, 4), r.mass === undefined ? "" : trim(r.mass, 4), ...r.center.map(len), ...r.size.map(len)].join(","),
|
||||
),
|
||||
];
|
||||
const a = document.createElement("a");
|
||||
a.href = URL.createObjectURL(new Blob([lines.join("\r\n")], { type: "text/csv" }));
|
||||
a.download = `${app.store.doc.name || "project"} - parts list.csv`;
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
|
||||
});
|
||||
paper.innerHTML = "";
|
||||
render(app, paper, rows);
|
||||
}
|
||||
|
||||
function render(app: AppContext, paper: HTMLElement, rows: PartRow[]): void {
|
||||
const doc = app.store.doc;
|
||||
const info: ProjectInfo = doc.info ?? {};
|
||||
|
||||
// ---- Title block
|
||||
const head = el("div", "bim-title-block");
|
||||
const field = (label: string, value: string, key?: keyof ProjectInfo) => {
|
||||
const f = el("label", "bim-tb-field");
|
||||
f.append(el("span", "bim-tb-label", label));
|
||||
if (!key) f.append(el("span", "bim-tb-value", value));
|
||||
else {
|
||||
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 })));
|
||||
f.append(input);
|
||||
}
|
||||
head.append(f);
|
||||
};
|
||||
field("Project", doc.name || "Untitled");
|
||||
field("Document", "Technical sheet");
|
||||
field("Number", info.number ?? "", "number");
|
||||
field("Revision", info.revision ?? "", "revision");
|
||||
field("Author", info.author ?? "", "author");
|
||||
field("Company", info.company ?? "", "company");
|
||||
field("Date", new Date().toISOString().slice(0, 10));
|
||||
field("Units", `${UNIT_LABEL[units()]}, kg`);
|
||||
paper.append(head);
|
||||
|
||||
// ---- Parts list
|
||||
paper.append(el("h2", "bim-h", "1. Parts list"));
|
||||
const missing = rows.filter((r) => r.mass === undefined).length;
|
||||
if (missing) paper.append(el("div", "bim-warn", `${missing === 1 ? "1 body has" : `${missing} bodies have`} no material yet: no mass for ${missing === 1 ? "it" : "them"}. Give each body a material in BIM - Materials.`));
|
||||
const u = UNIT_LABEL[units()];
|
||||
const t = el("table", "bim-table");
|
||||
const hr = el("tr", "");
|
||||
for (const h of ["Item", "Name", "Material", "Volume", "Surface area", "Mass", `Centre of mass (${u})`, `Size X × Y × Z (${u})`]) hr.append(el("th", "", h));
|
||||
t.append(hr);
|
||||
for (const r of rows) {
|
||||
const tr = el("tr", "");
|
||||
for (const v of [String(r.item), r.name, r.material || "-", fmtVolume(r.volume), fmtArea(r.area), r.mass === undefined ? "-" : fmtMass(r.mass), r.center.map(len).join(", "), r.size.map(len).join(" × ")]) tr.append(el("td", "", v));
|
||||
t.append(tr);
|
||||
}
|
||||
const total = rows.reduce((s, r) => s + (r.mass ?? 0), 0);
|
||||
const tf = el("tr", "bim-total");
|
||||
for (const v of ["", `${rows.length} ${rows.length === 1 ? "part" : "parts"}`, "", fmtVolume(rows.reduce((s, r) => s + r.volume, 0)), "", `${fmtMass(total)}${missing ? " +" : ""}`, "", ""]) tf.append(el("td", "", v));
|
||||
t.append(tf);
|
||||
const wrap = el("div", "bim-table-wrap");
|
||||
wrap.append(t);
|
||||
paper.append(wrap);
|
||||
|
||||
// ---- Materials used, with their data
|
||||
paper.append(el("h2", "bim-h", "2. Materials"));
|
||||
const used = new Map<string, number[]>();
|
||||
for (const r of rows) {
|
||||
const m = materialOf(doc, r.id);
|
||||
if (m) used.set(m.id, [...(used.get(m.id) ?? []), r.item]);
|
||||
}
|
||||
if (!used.size) paper.append(el("div", "bim-sub", "No materials given yet."));
|
||||
const grid = el("div", "bim-material-grid");
|
||||
for (const [, items] of used) {
|
||||
const m = materialOf(doc, rows.find((r) => r.item === items[0])!.id)!;
|
||||
const c = el("div", "bim-material-card");
|
||||
const h = el("div", "bim-material-head");
|
||||
const sw = el("span", "bim-swatch");
|
||||
sw.style.background = m.color;
|
||||
h.append(sw, el("b", "", m.name));
|
||||
c.append(h, el("div", "bim-sub", `Items ${items.join(", ")}`), dataTable(m));
|
||||
grid.append(c);
|
||||
}
|
||||
paper.append(grid);
|
||||
paper.append(
|
||||
el(
|
||||
"div",
|
||||
"bim-foot",
|
||||
"Strengths are the minimums of the standard named, where the grade has one; other values are typical (thermal values of building materials: ISO 10456 design values). A supplier's data sheet comes first where it differs. Masses are worked out from each body's measured volume and its material's density.",
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// Where the drawing sheet is seen from: how close (screen pixels per mm of
|
||||
// paper) and which point of the paper is in the middle of the screen. The
|
||||
// sheet is shown through its SVG viewBox, so lines stay sharp at any zoom and
|
||||
// moving round never redraws the sheet.
|
||||
|
||||
export class SheetCamera {
|
||||
/** Pixels per mm. */
|
||||
z = 1;
|
||||
/** The paper point (mm) in the middle of the screen. */
|
||||
cx = 0;
|
||||
cy = 0;
|
||||
/** Showing all of the sheet (and kept so when the window or sheet changes size). */
|
||||
fitted = true;
|
||||
/** The screen area (px) and the sheet (mm). */
|
||||
vw = 1;
|
||||
vh = 1;
|
||||
W = 420;
|
||||
H = 297;
|
||||
|
||||
/** Room round the sheet when it is all in view (px). */
|
||||
static MARGIN = 16;
|
||||
|
||||
/** Pixels per mm with all of the sheet in view. */
|
||||
fitZoom(): number {
|
||||
const m = SheetCamera.MARGIN;
|
||||
return Math.max(1e-3, Math.min((this.vw - 2 * m) / this.W, (this.vh - 2 * m) / this.H));
|
||||
}
|
||||
/** How far it may go: a quarter of the whole sheet out, 60 times in (and at least 40 px a mm). */
|
||||
minZoom(): number {
|
||||
return this.fitZoom() / 4;
|
||||
}
|
||||
maxZoom(): number {
|
||||
return Math.max(this.fitZoom() * 60, 40);
|
||||
}
|
||||
|
||||
/** All of the sheet, in the middle. */
|
||||
fit(): void {
|
||||
this.z = this.fitZoom();
|
||||
this.cx = this.W / 2;
|
||||
this.cy = this.H / 2;
|
||||
this.fitted = true;
|
||||
}
|
||||
|
||||
/** The screen area changed size: still all of the sheet if it was, else the same middle and zoom. */
|
||||
resize(vw: number, vh: number): void {
|
||||
this.vw = Math.max(1, vw);
|
||||
this.vh = Math.max(1, vh);
|
||||
if (this.fitted) this.fit();
|
||||
else this.clamp();
|
||||
}
|
||||
|
||||
/** Another sheet size (A3 to A4…): all of it. */
|
||||
setSheet(W: number, H: number): void {
|
||||
if (W === this.W && H === this.H) return;
|
||||
this.W = W;
|
||||
this.H = H;
|
||||
this.fit();
|
||||
}
|
||||
|
||||
/** A screen point (px from the area's top left) on the paper (mm). */
|
||||
toPaper(px: number, py: number): [number, number] {
|
||||
return [this.cx + (px - this.vw / 2) / this.z, this.cy + (py - this.vh / 2) / this.z];
|
||||
}
|
||||
/** A paper point on the screen. */
|
||||
toScreen(x: number, y: number): [number, number] {
|
||||
return [this.vw / 2 + (x - this.cx) * this.z, this.vh / 2 + (y - this.cy) * this.z];
|
||||
}
|
||||
|
||||
/** Closer (k > 1) or further, keeping the paper under the screen point where it is. */
|
||||
zoomAt(px: number, py: number, k: number): void {
|
||||
const [x, y] = this.toPaper(px, py);
|
||||
this.z = Math.min(this.maxZoom(), Math.max(this.minZoom(), this.z * k));
|
||||
this.cx = x - (px - this.vw / 2) / this.z;
|
||||
this.cy = y - (py - this.vh / 2) / this.z;
|
||||
this.fitted = false;
|
||||
this.clamp();
|
||||
}
|
||||
|
||||
/** The paper moved with the finger by (dx, dy) screen pixels. */
|
||||
panBy(dx: number, dy: number): void {
|
||||
this.cx -= dx / this.z;
|
||||
this.cy -= dy / this.z;
|
||||
this.fitted = false;
|
||||
this.clamp();
|
||||
}
|
||||
|
||||
/** The sheet never goes out of sight: the middle of the screen stays over it. */
|
||||
clamp(): void {
|
||||
this.cx = Math.min(this.W, Math.max(0, this.cx));
|
||||
this.cy = Math.min(this.H, Math.max(0, this.cy));
|
||||
}
|
||||
|
||||
/** How close, against all of the sheet in view (1: fitted). */
|
||||
ratio(): number {
|
||||
return this.z / this.fitZoom();
|
||||
}
|
||||
|
||||
/** The SVG viewBox for what's in view. */
|
||||
viewBox(): string {
|
||||
const w = this.vw / this.z;
|
||||
const h = this.vh / this.z;
|
||||
const r = (v: number) => Math.round(v * 1e4) / 1e4;
|
||||
return `${r(this.cx - w / 2)} ${r(this.cy - h / 2)} ${r(w)} ${r(h)}`;
|
||||
}
|
||||
|
||||
/** The state, to go smoothly from one to another. */
|
||||
get state(): { z: number; cx: number; cy: number } {
|
||||
return { z: this.z, cx: this.cx, cy: this.cy };
|
||||
}
|
||||
/** Part way (t: 0 to 1) from one state to another: zoom evenly in scale, the middle so the view glides. */
|
||||
blend(a: { z: number; cx: number; cy: number }, b: { z: number; cx: number; cy: number }, t: number): void {
|
||||
this.z = a.z * Math.pow(b.z / a.z, t);
|
||||
this.cx = a.cx + (b.cx - a.cx) * t;
|
||||
this.cy = a.cy + (b.cy - a.cy) * t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
// The console's handle on the app: `sg` - read what's there and work the tools
|
||||
// without tapping at pixels. For checking the app by hand or by script (the
|
||||
// browser's console, or a test driving the page). Type sg.help() to list it.
|
||||
//
|
||||
// sg.state() the project, tool, hint, panel, selection, errors, bodies
|
||||
// sg.select(sg.sel.body("Box")) pick something (as a tap would)
|
||||
// sg.actions() what the picked thing offers (left column, bottom bar)
|
||||
// sg.run("Project as Sketch") run one (by id or label, also in sub-menus)
|
||||
// sg.panel() the open tool's window: slots, values, choices
|
||||
// sg.set("XY") sg.set("Height", 2) sg.set("Sink in", true)
|
||||
// sg.pick(sg.sel.face("Box", 3)) give the waiting slot a face / edge / plane…
|
||||
// sg.done() sg.cancel() await sg.idle() await sg.health()
|
||||
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";
|
||||
import { newProjectId } from "./doc/library";
|
||||
|
||||
// (The app's insides it reads: kept out of the classes' public faces on purpose.)
|
||||
interface Insides {
|
||||
tool: { id: string; editingId?: string; activeSketch?: string; slots?: { label: string; accept(h: PickHit): boolean; multi?: boolean }[]; active?: number; advance?(): void; render?(): void; update?(): void };
|
||||
regenerate(): Promise<void>;
|
||||
undo(): void;
|
||||
redo(): void;
|
||||
switchProject(doc: ProjectDoc, id: string): Promise<void>;
|
||||
}
|
||||
interface UIInsides {
|
||||
toolItems: ToolItem[];
|
||||
bottomItems: ToolItem[];
|
||||
panelSpec: { title: string; items?: PanelItem[]; fields?: { label: string; value: number; onInput(v: number): void }[]; actions?: ToolItem[]; onDone?(): void; onCancel?(): void } | null;
|
||||
hintText: string | null;
|
||||
recentToasts?: string[];
|
||||
}
|
||||
|
||||
interface Listed {
|
||||
id: string;
|
||||
label: string;
|
||||
/** Where it sits: "Sketch › Rectangle". */
|
||||
path: string;
|
||||
disabled?: boolean;
|
||||
why?: string;
|
||||
item: ToolItem;
|
||||
}
|
||||
|
||||
function flatten(items: ToolItem[], path: string[] = []): Listed[] {
|
||||
// (Separators have no label.)
|
||||
return items.filter((it) => it.label).flatMap((it) => [
|
||||
{ id: it.id, label: it.label, path: [...path, it.label].join(" › "), ...(it.disabled ? { disabled: true, why: it.why } : {}), item: it },
|
||||
...flatten(it.children ?? [], [...path, it.label]),
|
||||
]);
|
||||
}
|
||||
const plain = (l: Listed[]) => l.map(({ item: _, ...rest }) => rest);
|
||||
const same = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase();
|
||||
|
||||
export function installDebug(app: App): void {
|
||||
const inside = app as unknown as Insides;
|
||||
const ui = app.ui as unknown as UIInsides;
|
||||
const features = () => app.store.doc.features;
|
||||
/** A step or body by id or name. */
|
||||
const featureOf = (key: string): Feature | undefined => features().find((f) => f.id === key) ?? features().find((f) => same(f.name, key));
|
||||
const bodyId = (key: string): string => {
|
||||
const list = app.view.bodyList;
|
||||
const names = app.store.doc.names ?? {};
|
||||
return list.find((b) => b.id === key)?.id ?? list.find((b) => same(names[b.id] ?? b.name, key))?.id ?? key;
|
||||
};
|
||||
|
||||
const panelItems = (): PanelItem[] => {
|
||||
const spec = ui.panelSpec;
|
||||
if (!spec) return [];
|
||||
const fields: PanelItem[] = (spec.fields ?? []).map((f) => ({ type: "number", label: f.label, value: f.value, onInput: f.onInput }));
|
||||
return [...fields, ...(spec.items ?? [])];
|
||||
};
|
||||
|
||||
const shown = (): ToolItem[] => [...ui.toolItems, ...ui.bottomItems, ...(ui.panelSpec?.actions ?? [])];
|
||||
|
||||
const sg = {
|
||||
app,
|
||||
|
||||
/** What's there now, in one look. */
|
||||
state() {
|
||||
const r = app.result;
|
||||
const byId = new Map(features().map((f) => [f.id, f.name]));
|
||||
return {
|
||||
project: app.store.doc.name,
|
||||
tool: inside.tool.id,
|
||||
editing: inside.tool.editingId ?? inside.tool.activeSketch ?? null,
|
||||
hint: ui.hintText,
|
||||
panel: ui.panelSpec?.title ?? null,
|
||||
selection: app.selection,
|
||||
steps: features().length,
|
||||
errors: (r?.errors ?? []).map((e) => `${byId.get(e.featureId) ?? e.featureId}: ${e.message}`),
|
||||
notes: (r?.notes ?? []).map((e) => `${byId.get(e.featureId) ?? e.featureId}: ${e.message}`),
|
||||
toasts: ui.recentToasts?.slice(-5) ?? [],
|
||||
bodies: sg.bodies(),
|
||||
};
|
||||
},
|
||||
|
||||
/** The steps in History: id, name, type, switched off, its error. */
|
||||
steps() {
|
||||
const errs = new Map((app.result?.errors ?? []).map((e) => [e.featureId, e.message]));
|
||||
return features().map((f, i) => ({ i: i + 1, id: f.id, name: f.name, type: f.type, ...(f.suppressed ? { off: true } : {}), ...(errs.has(f.id) ? { error: errs.get(f.id) } : {}) }));
|
||||
},
|
||||
|
||||
/** A step as stored (by id or name). */
|
||||
step: (key: string) => featureOf(key),
|
||||
|
||||
/** The bodies shown: id, name, how many faces and edges, hidden. */
|
||||
bodies() {
|
||||
const names = app.store.doc.names ?? {};
|
||||
const hidden = new Set(app.store.doc.hidden);
|
||||
return app.view.bodyList.map((b) => ({ id: b.id, name: names[b.id] ?? b.name, faces: b.faces.length, edges: b.edges.length, ...(hidden.has(b.id) ? { hidden: true } : {}) }));
|
||||
},
|
||||
|
||||
/** Each body measured on the solid: valid, closed, solids, faces, volume, box. */
|
||||
health: () => app.kernel.health(features()),
|
||||
|
||||
/** The main tools (the left column with nothing picked, with their sub-menus). */
|
||||
tools: () => plain(flatten(app.mainTools())),
|
||||
|
||||
/** What's offered now: the left column (what the picked thing offers), the bottom bar, the open window's buttons. */
|
||||
actions: () => plain(flatten(shown())),
|
||||
|
||||
/** Run a tool or action by id or label (what's offered now first, then the main tools). */
|
||||
run(key: string): string {
|
||||
const all = [...flatten(shown()), ...flatten(app.mainTools())];
|
||||
const hit = all.find((x) => x.id === key) ?? all.find((x) => same(x.label, key)) ?? all.find((x) => same(x.path, key));
|
||||
if (!hit) return `No "${key}" here. sg.actions() / sg.tools() list what there is.`;
|
||||
if (hit.disabled) return `"${hit.label}" is off: ${hit.why ?? "(no reason given)"}`;
|
||||
if (!hit.item.run) return `"${hit.label}" opens a menu: ${(hit.item.children ?? []).map((c) => c.label).join(", ")}`;
|
||||
hit.item.run();
|
||||
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);
|
||||
return app.selection;
|
||||
},
|
||||
|
||||
/** Things to pick, by name or id. */
|
||||
sel: {
|
||||
body: (body: string): Sel => ({ kind: "body", body: bodyId(body) }),
|
||||
face: (body: string, face: number): Sel => ({ kind: "face", body: bodyId(body), face }),
|
||||
edge: (body: string, edge: number): Sel => ({ kind: "edge", body: bodyId(body), edge }),
|
||||
vertex: (body: string, vertex: number): Sel => ({ kind: "vertex", body: bodyId(body), vertex }),
|
||||
/** A sketch's closed shape (regions counted as the sketch finds them). */
|
||||
profile: (sketch: string, region = 0): Sel => ({ kind: "profile", sketch: featureOf(sketch)?.id ?? sketch, region }),
|
||||
curve: (sketch: string, entity: string): Sel => ({ kind: "curve", sketch: featureOf(sketch)?.id ?? sketch, entity }),
|
||||
plane: (id: string): Sel => ({ kind: "plane", id: featureOf(id)?.id ?? id }),
|
||||
axis: (id: string): Sel => ({ kind: "axis", id: featureOf(id)?.id ?? id }),
|
||||
origin: (): Sel => ({ kind: "origin" }),
|
||||
},
|
||||
|
||||
/** A body's faces: index, type, centre, normal, area (to find the one to pick). */
|
||||
faces(body: string) {
|
||||
return (app.view.body(bodyId(body))?.faces ?? []).map((f, i) => ({ i, type: f.type, center: f.center, normal: f.normal, area: +f.area.toFixed(3), ...(f.round ? { round: f.round } : {}) }));
|
||||
},
|
||||
|
||||
/** A body's edges: index, type, ends. */
|
||||
edges(body: string) {
|
||||
return (app.view.body(bodyId(body))?.edges ?? []).map((e, i) => ({ i, type: e.type, start: e.start, mid: e.mid, end: e.end, length: +e.length.toFixed(3) }));
|
||||
},
|
||||
|
||||
/** The open tool's window: title, rows (slots, numbers, choices, toggles), buttons. */
|
||||
panel() {
|
||||
const spec = ui.panelSpec;
|
||||
if (!spec) return null;
|
||||
return {
|
||||
title: spec.title,
|
||||
rows: panelItems().map((it) => {
|
||||
switch (it.type) {
|
||||
case "number":
|
||||
case "slider":
|
||||
case "toggle":
|
||||
return { type: it.type, label: it.label, value: it.value };
|
||||
case "slot":
|
||||
return { type: it.type, label: it.label, value: it.value, ...(it.active ? { waiting: true } : {}), filled: it.filled };
|
||||
case "choice":
|
||||
return { type: it.type, label: it.label ?? "", value: it.value, options: it.options.map((o) => o.label) };
|
||||
case "button":
|
||||
return { type: it.type, label: it.label };
|
||||
case "chips":
|
||||
return { type: it.type, label: it.label ?? "", chips: it.chips.map((c) => c.label + (c.on ? " (on)" : "")) };
|
||||
default:
|
||||
return { type: (it as { type: string }).type };
|
||||
}
|
||||
}),
|
||||
buttons: (spec.actions ?? []).map((a) => a.label),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Set a row of the open window by its label: a number, a toggle, a choice
|
||||
* (or just a choice's option: sg.set("XY")), a slot to fill next, a button.
|
||||
*/
|
||||
set(label: string, value?: number | boolean | string): string {
|
||||
const items = panelItems();
|
||||
const row = items.find((it) => "label" in it && it.label && same(it.label, label));
|
||||
if (row) {
|
||||
switch (row.type) {
|
||||
case "number":
|
||||
case "slider":
|
||||
row.onInput(Number(value));
|
||||
return `${row.label} = ${value}`;
|
||||
case "toggle":
|
||||
row.onChange(value === undefined ? !row.value : !!value);
|
||||
return `${row.label} ${value === undefined ? !row.value : !!value ? "on" : "off"}`;
|
||||
case "choice": {
|
||||
const o = row.options.find((x) => x.id === value || same(x.label, String(value)));
|
||||
if (!o) return `${row.label}: no "${value}" (${row.options.map((x) => x.label).join(", ")})`;
|
||||
row.onChange(o.id);
|
||||
return `${row.label} = ${o.label}`;
|
||||
}
|
||||
case "slot":
|
||||
row.onClick();
|
||||
return `${row.label}: waiting for a pick`;
|
||||
case "button":
|
||||
row.onClick();
|
||||
return `pressed ${row.label}`;
|
||||
}
|
||||
}
|
||||
// An option of a choice with no label (the X / Y / Z, XY / XZ / YZ by a slot), or a chip.
|
||||
for (const it of items) {
|
||||
if (it.type === "choice") {
|
||||
const o = it.options.find((x) => same(x.label, label));
|
||||
if (o) {
|
||||
it.onChange(o.id);
|
||||
return `chose ${o.label}`;
|
||||
}
|
||||
}
|
||||
if (it.type === "chips") {
|
||||
const c = it.chips.find((x) => same(x.label, label));
|
||||
if (c) {
|
||||
c.onClick();
|
||||
return `tapped ${c.label}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
const btn = ui.panelSpec?.actions?.find((a) => same(a.label, label) || a.id === label);
|
||||
if (btn?.run) {
|
||||
btn.run();
|
||||
return `pressed ${btn.label}`;
|
||||
}
|
||||
return `No "${label}" in the window. sg.panel() lists its rows.`;
|
||||
},
|
||||
|
||||
/** Give the open tool's waiting slot a pick (a face, edge, profile, plane…), as a tap on it would. */
|
||||
pick(sel: Sel, point?: [number, number, number]): string {
|
||||
const t = inside.tool;
|
||||
const slot = t.slots?.[t.active ?? -1];
|
||||
if (!slot) return "No slot waiting (sg.set(<slot label>) makes one wait).";
|
||||
let at = point;
|
||||
if (!at && (sel.kind === "face" || sel.kind === "edge")) {
|
||||
const b = app.view.body(sel.body);
|
||||
at = sel.kind === "face" ? b?.faces[sel.face]?.center : b?.edges[sel.edge]?.mid;
|
||||
}
|
||||
const hit = { ...sel, point: at ?? [0, 0, 0] } as PickHit;
|
||||
if (!slot.accept(hit)) return `${slot.label} doesn't take that.`;
|
||||
t.advance?.();
|
||||
t.render?.();
|
||||
t.update?.();
|
||||
return `${slot.label}: picked`;
|
||||
},
|
||||
|
||||
/** Done / Cancel in the open tool's window. */
|
||||
done(): string {
|
||||
const spec = ui.panelSpec;
|
||||
if (!spec?.onDone) return "No window with Done open.";
|
||||
spec.onDone();
|
||||
return `done: ${spec.title}`;
|
||||
},
|
||||
cancel(): string {
|
||||
const spec = ui.panelSpec;
|
||||
if (spec?.onCancel) spec.onCancel();
|
||||
else app.setTool(null);
|
||||
return "cancelled";
|
||||
},
|
||||
|
||||
undo: () => inside.undo(),
|
||||
redo: () => inside.redo(),
|
||||
|
||||
/** Wait until the geometry engine has nothing left to do (and the page has drawn it). */
|
||||
async idle(timeoutMs = 30000): Promise<boolean> {
|
||||
const k = app.kernel as unknown as { pending: Map<number, unknown>; regenRunning: boolean };
|
||||
const t0 = performance.now();
|
||||
let quiet = 0;
|
||||
while (performance.now() - t0 < timeoutMs) {
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
quiet = k.pending.size || k.regenRunning ? 0 : quiet + 1;
|
||||
if (quiet >= 3) return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/** The project as saved (JSON). */
|
||||
save: () => JSON.stringify(app.store.doc),
|
||||
|
||||
/**
|
||||
* Open a project (its JSON, as text or object) as a new one in the
|
||||
* library, as File → Open does; the one open now is kept. Resolves once
|
||||
* it is built.
|
||||
*/
|
||||
async load(project: string | object, name?: string): Promise<string> {
|
||||
const doc = parseProject(typeof project === "string" ? project : JSON.stringify(project));
|
||||
if (name) doc.name = name;
|
||||
await inside.switchProject(doc, newProjectId());
|
||||
await sg.idle();
|
||||
return doc.name;
|
||||
},
|
||||
|
||||
/** What there is, with one line each. */
|
||||
help(): number {
|
||||
const lines: string[] = Object.entries(sg as Record<string, unknown>)
|
||||
.filter(([k]) => k !== "app")
|
||||
.map(([k, v]) => (typeof v === "function" ? `sg.${k}(${((v as () => void).toString().match(/^[^(]*\(([^)]*)\)/)?.[1] ?? "").replace(/\s+/g, " ")})` : `sg.${k}`));
|
||||
console.log(lines.join("\n"));
|
||||
return lines.length;
|
||||
},
|
||||
};
|
||||
|
||||
(window as unknown as { sg: typeof sg }).sg = sg;
|
||||
}
|
||||
@@ -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];
|
||||
@@ -145,6 +151,7 @@ export function detachFreeformCopy(doc: ProjectDoc, bodyId: string, newId: strin
|
||||
names: Object.fromEntries(Object.entries(doc.names ?? {}).map(([k, v]) => [renameIn(`"${k}"`, bodyId, newId).slice(1, -1), v])),
|
||||
};
|
||||
if (doc.colors) out.colors = Object.fromEntries(Object.entries(doc.colors).map(([k, v]) => [renameIn(`"${k}"`, bodyId, newId).slice(1, -1), v]));
|
||||
if (doc.materials) out.materials = Object.fromEntries(Object.entries(doc.materials).map(([k, v]) => [renameIn(`"${k}"`, bodyId, newId).slice(1, -1), v]));
|
||||
// The copy's name in Items stays what it was.
|
||||
if (!out.names?.[newId] && doc.names?.[bodyId]) out.names = { ...out.names, [newId]: doc.names[bodyId] };
|
||||
return { doc: out, id: newId };
|
||||
|
||||
@@ -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,14 +48,42 @@ 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.
|
||||
if (c.type === "fix" && c.at && c.atExpr)
|
||||
c.at = c.at.map((x, i) => {
|
||||
const e = c.atExpr![i];
|
||||
if (!e) return x;
|
||||
const v = evaluate(e, "length");
|
||||
if (v === null) problems.push(`${f.name}: "${e}" can't be evaluated`);
|
||||
return v ?? x;
|
||||
}) as typeof c.at;
|
||||
if (!c.expr) continue;
|
||||
const v = evaluate(c.expr, c.prop === "angle" ? "angle" : "length");
|
||||
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,
|
||||
@@ -57,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;
|
||||
}
|
||||
@@ -54,9 +54,18 @@ const LABELS: Record<FeatureType, string> = {
|
||||
replaceFace: "Replace Face",
|
||||
repair: "Repair",
|
||||
fillToPlane: "Fill to Plane",
|
||||
fill: "Fill",
|
||||
connect: "Connect",
|
||||
faceFreeform: "Freeform Face",
|
||||
freeformEdit: "Edit Freeform",
|
||||
thread: "Thread",
|
||||
imprint: "Project as Edge",
|
||||
wrap: "Wrap & Emboss",
|
||||
};
|
||||
|
||||
/** Steps still being tried out: shown with a BETA tag wherever they appear. */
|
||||
export const BETA_TYPES: ReadonlySet<string> = new Set(["connect", "faceFreeform", "imprint", "wrap"]);
|
||||
|
||||
/**
|
||||
* Holds the document and its undo/redo history. Every change goes through
|
||||
* `commit`, which snapshots the previous state, so undo is exact.
|
||||
@@ -167,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")}` };
|
||||
}
|
||||
|
||||
@@ -181,6 +191,8 @@ export class DocStore {
|
||||
const before = this.transientBase ?? pack(this.doc);
|
||||
const next = unpack(pack(this.doc));
|
||||
mutate(next);
|
||||
// With a breakpoint: what's after it stays last, so a new step goes in at the breakpoint.
|
||||
if (next.features.some((f) => f.rolledBack)) next.features = [...next.features.filter((f) => !f.rolledBack), ...next.features.filter((f) => f.rolledBack)];
|
||||
this.problems = resolveDoc(next);
|
||||
const wasLive = this.transientBase !== null;
|
||||
this.transientBase = null;
|
||||
@@ -218,6 +230,18 @@ export class DocStore {
|
||||
this.listeners.forEach((fn) => fn());
|
||||
}
|
||||
|
||||
/**
|
||||
* What the engine worked out for the project as it is (a sketch's curves
|
||||
* where the edges they follow are now): taken in as it stands - not a step
|
||||
* to undo, and nothing for the engine to do again.
|
||||
*/
|
||||
adopt(mutate: (doc: ProjectDoc) => void): void {
|
||||
const next = unpack(pack(this.doc));
|
||||
mutate(next);
|
||||
this.doc = next;
|
||||
this.changed(false);
|
||||
}
|
||||
|
||||
add(feature: Feature): void {
|
||||
this.commit((d) => d.features.push(feature));
|
||||
}
|
||||
@@ -323,15 +347,21 @@ export class DocStore {
|
||||
if (v === this.edits) this.setSaved(true);
|
||||
}
|
||||
|
||||
private changed(): void {
|
||||
private changed(tell = true): void {
|
||||
this.edits++;
|
||||
this.setSaved(false);
|
||||
this.listeners.forEach((fn) => fn());
|
||||
if (tell) this.listeners.forEach((fn) => fn());
|
||||
clearTimeout(this.saveTimer);
|
||||
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);
|
||||
@@ -367,17 +397,44 @@ export function newId(prefix: string): string {
|
||||
}
|
||||
|
||||
export function parseProject(text: string): ProjectDoc {
|
||||
return migrate(JSON.parse(text));
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = JSON.parse(text);
|
||||
} catch {
|
||||
// (Not the parser's "Expected ',' or '}' at position 47".)
|
||||
throw new Error("The file is damaged - cut short, or not a project file");
|
||||
}
|
||||
return migrate(raw);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ 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");
|
||||
|
||||
// v1: rect {a, b}; extrude profiles referenced entity ids.
|
||||
const sketches = new Map<string, SketchEntity[]>();
|
||||
|
||||
@@ -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;
|
||||
@@ -58,6 +66,14 @@ export interface FaceRef {
|
||||
center: Vec3;
|
||||
normal: Vec3;
|
||||
area: number;
|
||||
/** The step that made the face (only faces made by it are matched; none left: it's gone). */
|
||||
step?: string;
|
||||
/**
|
||||
* Which of that step's faces it is: the sketch curve it was made from (a
|
||||
* side of an extrusion), or the end of it. Where the face is can change
|
||||
* (the sketch redrawn, the holes moved past each other); this doesn't.
|
||||
*/
|
||||
curve?: string;
|
||||
}
|
||||
|
||||
export interface EdgeRef {
|
||||
@@ -65,8 +81,13 @@ export interface EdgeRef {
|
||||
mid: Vec3;
|
||||
dir: Vec3;
|
||||
length: number;
|
||||
/** The steps that made the faces either side of it (sorted). */
|
||||
steps?: string[];
|
||||
/** Which faces of those steps it lies between (their curves, see FaceRef; sorted). */
|
||||
curves?: string[];
|
||||
}
|
||||
|
||||
|
||||
export type ExtrudeSource =
|
||||
| { kind: "profile"; sketch: string; regions: RegionRef[] }
|
||||
| { kind: "face"; face: FaceRef };
|
||||
@@ -76,6 +97,11 @@ interface FeatureBase {
|
||||
name: string;
|
||||
/** Suppressed features are skipped during regeneration. */
|
||||
suppressed?: boolean;
|
||||
/**
|
||||
* After the History's breakpoint: off until the breakpoint is removed (the
|
||||
* model as it was there). These steps are kept last; new ones go before them.
|
||||
*/
|
||||
rolledBack?: boolean;
|
||||
/**
|
||||
* Parametric values: field path → expression (e.g. "distance": "depth*2").
|
||||
* The number at that path is recomputed from the expression on every change.
|
||||
@@ -102,7 +128,9 @@ export type ConstraintType =
|
||||
| "symmetric"
|
||||
| "fix"
|
||||
| "distance"
|
||||
| "dim";
|
||||
| "dim"
|
||||
| "pattern"
|
||||
| "follow";
|
||||
|
||||
/**
|
||||
* Sketch constraint. Geometry refs: `pts` (points) and `curves` (entity ids).
|
||||
@@ -117,8 +145,20 @@ export interface SketchConstraint {
|
||||
prop?: string;
|
||||
value?: number;
|
||||
expr?: string;
|
||||
/** fix: where the point is held. */
|
||||
/** fix: where the point is held. pattern: the copy's offset (move), or the centre it turns round (turn). */
|
||||
at?: Vec2;
|
||||
/** fix: X / Y of `at` typed with a variable ("Ws/2 - S/2"): the point follows it. */
|
||||
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 {
|
||||
@@ -126,10 +166,83 @@ export interface SketchFeature extends FeatureBase {
|
||||
plane: PlaneDef;
|
||||
/** When drawn on a body face, the sketch follows that face when it moves. */
|
||||
attachedTo?: FaceRef;
|
||||
/**
|
||||
* Drawn on a construction plane (its id): the sketch follows the plane when
|
||||
* it moves - its offset typed again, or driven by a variable.
|
||||
*/
|
||||
onPlane?: string;
|
||||
entities: SketchEntity[];
|
||||
constraints?: SketchConstraint[];
|
||||
/**
|
||||
* Offsets of the outline of the face it's drawn on (a lid's lip 2 mm in
|
||||
* from the rim): made again from the face as it is on every rebuild, so
|
||||
* they follow it when it changes size. Their curves are "lnk-<id>-<n>".
|
||||
*/
|
||||
outlineOffsets?: OutlineOffset[];
|
||||
/**
|
||||
* Curves of the sketch that follow an edge of a body (projected from it):
|
||||
* put where that edge is on every rebuild, the sketch's dimensions to them
|
||||
* kept - a hole 10 mm from the wall of another part stays 10 mm from it.
|
||||
* Their ids begin "ref-".
|
||||
*/
|
||||
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 {
|
||||
@@ -137,19 +250,53 @@ export interface ExtrudeFeature extends FeatureBase {
|
||||
source: ExtrudeSource;
|
||||
distance: number;
|
||||
/** auto: join `target` when distance > 0, cut it when < 0; new body without a target. */
|
||||
mode: "auto" | "new" | "join" | "cut";
|
||||
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).
|
||||
*/
|
||||
taper?: number;
|
||||
/** Both ways from the shape: `distance` each side (a boss through its middle plane). */
|
||||
symmetric?: boolean;
|
||||
/**
|
||||
* Where it ends: `distance` (missing too), through everything there is
|
||||
* (`distance` only gives the way: its sign), or up to `to` - a face (flat or
|
||||
* round, followed as its body changes) or a plane.
|
||||
*/
|
||||
extent?: "distance" | "through" | "to";
|
||||
to?: { face?: FaceRef; plane?: PlaneDef };
|
||||
/** It starts this far from the shape, along its normal (missing: at the shape). */
|
||||
start?: number;
|
||||
/** Degrees the sides lean in (negative: out) towards the far end - a draft, as for a mould. */
|
||||
draft?: number;
|
||||
}
|
||||
|
||||
export interface EdgeFeature extends FeatureBase {
|
||||
type: "fillet" | "chamfer";
|
||||
edges: EdgeRef[];
|
||||
radius: number;
|
||||
/** Chamfer, Two-Distance: the second distance (along the other face); missing: equal distances. */
|
||||
distance2?: number;
|
||||
/** Chamfer, Two-Distance: the first distance goes along the other face of each edge.
|
||||
* Fillet, Variable: the start and end radii swap ends. */
|
||||
flip?: boolean;
|
||||
/** Fillet, Variable: the radius at each edge's other end (it runs evenly from radius to this); missing: one radius. */
|
||||
radius2?: number;
|
||||
/** Fillet: the sizes are chord widths (straight across the round, face to face), not radii. */
|
||||
chord?: boolean;
|
||||
/** Fillet: a smooth (G2) blend, its bend easing in from flat at both faces, not a circular round. */
|
||||
g2?: boolean;
|
||||
/** Fillet: where three or more rounded edges meet, they stop this far from the corner and a smooth patch joins them (0 or missing: the usual corner). */
|
||||
setback?: number;
|
||||
}
|
||||
|
||||
export interface BooleanFeature extends FeatureBase {
|
||||
@@ -161,11 +308,31 @@ 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
|
||||
* count changes. Worked out by the engine the first time it runs (see bodyList).
|
||||
*/
|
||||
whole?: string[];
|
||||
}
|
||||
|
||||
export interface DeleteFeature extends FeatureBase {
|
||||
type: "delete";
|
||||
bodies: string[];
|
||||
/**
|
||||
* 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
|
||||
* count changes. Worked out by the engine the first time it runs (see bodyList).
|
||||
*/
|
||||
whole?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -180,7 +347,7 @@ export interface AxisRef {
|
||||
|
||||
export type PathRef = { kind: "sketch"; sketch: string; entities: string[] } | { kind: "edges"; edges: EdgeRef[] };
|
||||
|
||||
type BodyMode = "auto" | "new" | "join" | "cut";
|
||||
type BodyMode = "auto" | "new" | "join" | "cut" | "intersect";
|
||||
|
||||
export interface RevolveFeature extends FeatureBase {
|
||||
type: "revolve";
|
||||
@@ -200,6 +367,16 @@ export interface SweepFeature extends FeatureBase {
|
||||
path: PathRef;
|
||||
mode: BodyMode;
|
||||
target?: string;
|
||||
/** The profile's size at the path's end, as a multiple of its size at the start (1 = same size). */
|
||||
scale?: number;
|
||||
/** Degrees the profile turns round the path from start to end, evenly along it (0 or missing: none). */
|
||||
twist?: number;
|
||||
/** Where the profile starts: where it is (auto), or moved onto the path's nearer end, square to it (start). */
|
||||
position?: "auto" | "start";
|
||||
/** The profile turns with the path (normal, the default) or keeps facing the same way (parallel). */
|
||||
orientation?: "normal" | "parallel";
|
||||
/** At a sharp corner of the path: rounded (the default) or mitred. */
|
||||
corner?: "round" | "mitre";
|
||||
}
|
||||
|
||||
export interface LoftFeature extends FeatureBase {
|
||||
@@ -208,6 +385,20 @@ export interface LoftFeature extends FeatureBase {
|
||||
ruled: boolean;
|
||||
mode: BodyMode;
|
||||
target?: string;
|
||||
/** Goes on from the last profile back round to the first (a ring, no ends). */
|
||||
closed?: boolean;
|
||||
/** A curve the body follows from profile to profile (its centre line). */
|
||||
guide?: PathRef;
|
||||
/** Guide curves along its sides: each runs through every profile, and the sides follow them. */
|
||||
rails?: PathRef[];
|
||||
/** Connection points: which point of each profile joins which (one point per profile, in `sections` order). */
|
||||
connections?: Vec3[][];
|
||||
/** How the body leaves the first profile and meets the last: straight out of it (G1, tangent) or smoother still (G2); missing: free. */
|
||||
startContinuity?: "g1" | "g2";
|
||||
endContinuity?: "g1" | "g2";
|
||||
/** How far that pull reaches (1: a quarter of the way to the next profile). */
|
||||
startWeight?: number;
|
||||
endWeight?: number;
|
||||
}
|
||||
|
||||
export interface ShellFeature extends FeatureBase {
|
||||
@@ -229,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. */
|
||||
@@ -244,6 +440,12 @@ export interface SplitFeature extends FeatureBase {
|
||||
type: "split";
|
||||
body: string;
|
||||
plane: PlaneDef;
|
||||
/** More planes to cut along at once. */
|
||||
planes?: PlaneDef[];
|
||||
/** Bodies it's cut with, along their surfaces (they stay as they are). */
|
||||
tools?: string[];
|
||||
/** Cut only with the tools: `plane` isn't one. */
|
||||
noPlane?: boolean;
|
||||
}
|
||||
|
||||
/** Construction plane. Optionally follows a face (offset along its normal). */
|
||||
@@ -262,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";
|
||||
@@ -271,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). */
|
||||
@@ -316,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). */
|
||||
@@ -327,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.
|
||||
@@ -371,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 };
|
||||
}
|
||||
@@ -380,18 +609,108 @@ export interface ThreadFeature extends FeatureBase {
|
||||
* removed, faces fixed and merged, inside-out solids turned - the shape
|
||||
* itself stays. Turns loose faces (an imported mesh or STEP surface) into a solid.
|
||||
*/
|
||||
/**
|
||||
* Connect: a smooth freeform bridge from one face to another (of two bodies,
|
||||
* or of one), made again from the faces on every rebuild. Like an extrude it
|
||||
* joins the bodies (Add / Auto), cuts its way through them (Cut), or is a
|
||||
* body of its own (New body).
|
||||
*/
|
||||
/**
|
||||
* A face of a body made freeform: its edges stay where they are, and the face
|
||||
* becomes a smooth surface through a grid of points over it - some of them
|
||||
* pulled out of it or pushed in.
|
||||
*/
|
||||
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
|
||||
* runs round the face's edge and stays there; the inside points are moved.
|
||||
*/
|
||||
cage: { verts: Vec3[]; faces: [number, number, number, number][] };
|
||||
/** How many cells across the cage was laid (3, 5, 7, 9). */
|
||||
grid?: number;
|
||||
}
|
||||
|
||||
export interface ConnectFeature extends FeatureBase {
|
||||
type: "connect";
|
||||
faces: [FaceRef, FaceRef];
|
||||
mode: "auto" | "new" | "join" | "cut";
|
||||
/** How far the bridge bows out of each face (1: plain; 0: straight across). */
|
||||
bulge?: number;
|
||||
/** Its outline, as a fraction of the faces' (1: their own edges). */
|
||||
size?: number;
|
||||
/** A curve the bridge follows from one face to the other (a sketch spline, say). */
|
||||
guide?: PathRef;
|
||||
}
|
||||
|
||||
export interface RepairFeature extends FeatureBase {
|
||||
type: "repair";
|
||||
bodies: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Project as Edge: curves drawn onto a body's faces, the faces split along
|
||||
* them - a sketch's shapes along its normal (onto the faces seen from it), or
|
||||
* edges along a face's normal (onto that face).
|
||||
*/
|
||||
export interface ImprintFeature extends FeatureBase {
|
||||
type: "imprint";
|
||||
body: string;
|
||||
source?: ExtrudeSource;
|
||||
edges?: EdgeRef[];
|
||||
/** With edges: the face they are projected onto. */
|
||||
face?: FaceRef;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap & Emboss: a sketch's shapes wrapped round a round face (lengths kept),
|
||||
* raised from it (height > 0) or sunk into it (height < 0).
|
||||
*/
|
||||
export interface WrapFeature extends FeatureBase {
|
||||
type: "wrap";
|
||||
source: ExtrudeSource;
|
||||
face: FaceRef;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fill: a surface stretched over a network of curves - the boundary (sketch
|
||||
* curves and body edges that close a loop) and guide curves inside it that
|
||||
* it passes through.
|
||||
*/
|
||||
export interface FillFeature extends FeatureBase {
|
||||
type: "fill";
|
||||
boundary: PathRef[];
|
||||
guides?: PathRef[];
|
||||
/** Along body edges: just touching (G0), tangent to the face there (G1) or curving on with it (G2). Sketch curves are always G0. */
|
||||
continuity?: "g0" | "g1" | "g2";
|
||||
/** One edge's own continuity, by fillEdgeKey (missing: `continuity`). */
|
||||
edgeContinuity?: Record<string, "g0" | "g1" | "g2">;
|
||||
}
|
||||
|
||||
/** Which boundary edge of a Fill an edge continuity is for. */
|
||||
export const fillEdgeKey = (r: EdgeRef): string => `${r.body}@${r.mid.map((x) => x.toFixed(3)).join(",")}`;
|
||||
|
||||
export type Feature =
|
||||
| FillFeature
|
||||
| ImprintFeature
|
||||
| WrapFeature
|
||||
| ConnectFeature
|
||||
| FaceFreeformFeature
|
||||
| FillToPlaneFeature
|
||||
| ThreadFeature
|
||||
| RepairFeature
|
||||
| ScaleFaceFeature
|
||||
| ReplaceFaceFeature
|
||||
| FreeformFeature
|
||||
| FreeformEditFeature
|
||||
| DeleteGeomFeature
|
||||
| MoveFaceFeature
|
||||
| SketchFeature
|
||||
@@ -457,12 +776,262 @@ export interface ProjectDoc {
|
||||
colors?: Record<string, string>;
|
||||
/** See-through bodies: opacity 0–1 by body id (missing: solid). */
|
||||
opacity?: Record<string, number>;
|
||||
/** BIM: the material of each body (a material id, by body id). */
|
||||
materials?: Record<string, string>;
|
||||
/** BIM: the project's own materials (beside the library's). */
|
||||
customMaterials?: MaterialDef[];
|
||||
/** BIM: what the title block of the technical sheet and the drawings says. */
|
||||
info?: ProjectInfo;
|
||||
/** BIM: the project's one drawing, as projects saved before there could be several had it (read as the first of `drawings`). */
|
||||
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 body colours offered by the Color tool (first = default). */
|
||||
/** The drawing sheet: paper size, projection method, scale (missing: the largest that fits), what it shows. */
|
||||
export interface DrawingOptions {
|
||||
/** Which drawing of the project it is. */
|
||||
id?: string;
|
||||
/** The sheet's title (missing: the project's name). */
|
||||
title?: string;
|
||||
size?: "A4" | "A3" | "A2" | "A1" | "A0" | "ANSI A" | "ANSI B" | "ANSI C" | "ANSI D" | "ANSI E";
|
||||
portrait?: boolean;
|
||||
angle?: "first" | "third";
|
||||
scale?: number;
|
||||
hidden?: boolean;
|
||||
/** Old projects: the isometric view on or off (now in `views`). */
|
||||
iso?: boolean;
|
||||
/** Which views are drawn (missing: all four). */
|
||||
views?: { front?: boolean; top?: boolean; side?: boolean; iso?: boolean };
|
||||
/** The bodies drawn (missing: every body shown). */
|
||||
bodies?: string[];
|
||||
/** simple / table (with the parts list) / block (with a revision table): a block in the corner; horizontal: a strip along the bottom; vertical: a column down the right, with a revision table. */
|
||||
titleBlock?: "none" | "border" | "simple" | "table" | "block" | "horizontal" | "vertical";
|
||||
/** The revision table (Block and Vertical title blocks). */
|
||||
revisions?: DrawingRevision[];
|
||||
dateFormat?: "iso" | "dmy" | "mdy";
|
||||
units?: "mm" | "cm" | "m" | "in";
|
||||
/** Decimals shown in dimensions. */
|
||||
precision?: number;
|
||||
/** Decimals shown in angles. */
|
||||
anglePrecision?: number;
|
||||
comma?: boolean;
|
||||
/** 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. */
|
||||
overallDims?: Record<string, OverallEdit>;
|
||||
/** Views moved by hand: mm on the paper, by view. */
|
||||
moved?: Record<string, [number, number]>;
|
||||
dims?: DrawingDim[];
|
||||
notes?: DrawingNote[];
|
||||
/** Views added by hand: base views and projections. */
|
||||
extra?: DrawingView[];
|
||||
/** The isometric view's own scale (missing: picked to fit). */
|
||||
isoScale?: number;
|
||||
/** Pictures put on the sheet (a logo, a photo). */
|
||||
images?: DrawingImage[];
|
||||
sections?: DrawingSection[];
|
||||
details?: DrawingDetail[];
|
||||
/** Centre marks and centrelines. */
|
||||
marks?: DrawingMark[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A section view (A-A): the model cut along a line drawn on another view,
|
||||
* seen square to the cut, lined up with that view.
|
||||
*/
|
||||
export interface DrawingSection {
|
||||
id: string;
|
||||
letter: string;
|
||||
/** The view the cut line is on, and the line (that view's coordinates: model mm, y down). */
|
||||
view: string;
|
||||
a: [number, number];
|
||||
b: [number, number];
|
||||
/** The way the eye looks, on that view (a unit vector square to the line): where its arrows point. */
|
||||
look: [number, number];
|
||||
/** How far its middle is from its view's edge (mm on the paper). */
|
||||
gap: number;
|
||||
}
|
||||
|
||||
/** Which way a base view looks at the model: a side, or an isometric corner (front/back, right/left). */
|
||||
export type ViewOrient = "front" | "back" | "top" | "bottom" | "left" | "right" | "iso-fr" | "iso-fl" | "iso-br" | "iso-bl";
|
||||
|
||||
/**
|
||||
* A view added by hand: a base view (seen from any side or corner, put
|
||||
* anywhere), or one projected from another view - square on, lined up with
|
||||
* it, or from a corner (an isometric one).
|
||||
*/
|
||||
export interface DrawingView {
|
||||
id: string;
|
||||
/** A base view: the way it looks. */
|
||||
orient?: ViewOrient;
|
||||
/** A projection: the view it is projected from, and the way it goes from it on the paper (one of eight). */
|
||||
view?: string;
|
||||
dir?: [number, number];
|
||||
/** Projected square on: how far its middle is from its view's edge (mm on the paper). */
|
||||
gap?: number;
|
||||
/** A base view or an isometric projection: where its middle is on the paper. */
|
||||
at?: [number, number];
|
||||
/** Its own scale (missing: the sheet's; a lined-up projection always has its view's). */
|
||||
scale?: number;
|
||||
}
|
||||
|
||||
/** A picture on the sheet (mm on the paper), kept as a data URL. */
|
||||
export interface DrawingImage {
|
||||
id: string;
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
src: string;
|
||||
}
|
||||
|
||||
/** A detail view (B): a circle of another view drawn bigger. */
|
||||
export interface DrawingDetail {
|
||||
id: string;
|
||||
letter: string;
|
||||
view: string;
|
||||
/** The circle (the view's coordinates). */
|
||||
c: [number, number];
|
||||
r: number;
|
||||
/** Its scale (missing: twice its view's). */
|
||||
scale?: number;
|
||||
/** Where its middle is on the paper. */
|
||||
at: [number, number];
|
||||
}
|
||||
|
||||
/** A centre mark on a circle, or a centreline from a to b (a view's coordinates). */
|
||||
export interface DrawingMark {
|
||||
id: string;
|
||||
view: string;
|
||||
/** cross: an intersection mark - where two edges would meet (a corner rounded off), `c`, from the near ends `a` and `b`. */
|
||||
kind: "center" | "line" | "cross";
|
||||
c?: [number, number];
|
||||
r?: number;
|
||||
a?: [number, number];
|
||||
b?: [number, number];
|
||||
}
|
||||
|
||||
/** An overall size moved or given text by hand (the rest follows the model). */
|
||||
export interface OverallEdit extends DimText {
|
||||
offset?: number;
|
||||
slide?: number;
|
||||
/** Taken off (Overall sizes, switched off and on, brings it back). */
|
||||
hidden?: boolean;
|
||||
}
|
||||
|
||||
/** What a dimension adds to its value: text before and after, a tolerance. */
|
||||
export interface DimText {
|
||||
prefix?: string;
|
||||
suffix?: string;
|
||||
/** Symmetrical (± up), deviation (+up / -down), limits (the largest and smallest sizes), basic (boxed). */
|
||||
tol?: { kind: "sym" | "dev" | "limits" | "basic"; up?: number; down?: number };
|
||||
}
|
||||
|
||||
/**
|
||||
* A dimension put on a drawing: its points in its view's own coordinates
|
||||
* (model mm, y down), so it stays on its edge at any scale or place of the view.
|
||||
*/
|
||||
export interface DrawingDim extends DimText {
|
||||
id: string;
|
||||
view: string;
|
||||
/** Angle: from ray c→a to ray c→b, its arc `offset` mm (on the paper) from c. */
|
||||
kind: "length" | "distance" | "radius" | "diameter" | "angle";
|
||||
a: [number, number];
|
||||
b?: [number, number];
|
||||
/** Circle (radius, diameter): its centre and radius. */
|
||||
c?: [number, number];
|
||||
r?: number;
|
||||
/** How far out from what it measures (mm on the paper); for a circle, past it. */
|
||||
offset: number;
|
||||
/** Circle: the leader's direction (radians). */
|
||||
angle?: number;
|
||||
/** A length or distance: its value moved along its line from the middle (mm on the paper, towards b); past an end, the line runs out to it. */
|
||||
slide?: number;
|
||||
/** An arc's angle: a point on the arc, so the angle goes round the way the arc does (past 180° too). */
|
||||
through?: [number, number];
|
||||
/** A min-max distance: the nearest and the farthest points of the two things it was measured between (a and b are one pair). */
|
||||
minmax?: { min: [[number, number], [number, number]]; max: [[number, number], [number, number]] };
|
||||
/** A min-max distance showing the farthest. */
|
||||
max?: boolean;
|
||||
}
|
||||
|
||||
/** A note on the sheet (mm on the paper). */
|
||||
export interface DrawingNote {
|
||||
id: string;
|
||||
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] };
|
||||
}
|
||||
|
||||
/** A row of a drawing's revision table. */
|
||||
export interface DrawingRevision {
|
||||
rev: string;
|
||||
note?: string;
|
||||
date?: string;
|
||||
by?: string;
|
||||
}
|
||||
|
||||
/** The title block: who made it, for whom, which revision. */
|
||||
export interface ProjectInfo {
|
||||
author?: string;
|
||||
company?: string;
|
||||
number?: string;
|
||||
revision?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A real material (see src/bim/materials.ts). Strengths in MPa, stiffness in
|
||||
* GPa, density in kg/m³, conductivity in W/(m·K), specific heat in J/(kg·K),
|
||||
* expansion in µm/(m·K). What isn't known is left out.
|
||||
*/
|
||||
export interface MaterialDef {
|
||||
id: string;
|
||||
name: string;
|
||||
category: string;
|
||||
/** The standard the grade is defined in (or the data comes from). */
|
||||
standard?: string;
|
||||
note?: string;
|
||||
/** How a body of it shows: "#rrggbb", and how see-through (glass). */
|
||||
color: string;
|
||||
opacity?: number;
|
||||
density: number;
|
||||
youngs?: number;
|
||||
poisson?: number;
|
||||
yield?: number;
|
||||
tensile?: number;
|
||||
compressive?: number;
|
||||
bending?: number;
|
||||
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: 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" },
|
||||
@@ -470,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). */
|
||||
@@ -494,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 {
|
||||
@@ -519,3 +1087,21 @@ export interface ItemFolder {
|
||||
export function emptyDoc(): ProjectDoc {
|
||||
return { format: "super", version: 2, name: "Untitled", features: [], variables: [], views: [], units: "mm", hidden: [], pins: [], names: {} };
|
||||
}
|
||||
|
||||
/** A sketch curve that follows a body's edge (see SketchFeature.links). */
|
||||
export interface EdgeLink {
|
||||
/** The curve. */
|
||||
id: string;
|
||||
edge: EdgeRef;
|
||||
}
|
||||
|
||||
/** An offset of a face outline in a sketch on that face (see SketchFeature.outlineOffsets). */
|
||||
export interface OutlineOffset {
|
||||
id: string;
|
||||
/** Positive grows a closed outline outward, negative goes inside it. */
|
||||
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);
|
||||
}
|
||||
@@ -63,7 +63,10 @@ export function usesOf(features: readonly Feature[]): Map<string, VarUse[]> {
|
||||
if (f.suppressed) continue;
|
||||
for (const [path, expr] of Object.entries(f.exprs ?? {})) for (const n of namesIn(expr)) add1(n, { feature: f.id, where: path, kind: kindOfPath(path), expr });
|
||||
if (f.type === "sketch")
|
||||
for (const c of f.constraints ?? []) if (c.expr) for (const n of namesIn(c.expr)) add1(n, { feature: f.id, where: c.id, kind: c.prop === "angle" ? "angle" : "length", expr: c.expr! });
|
||||
for (const c of f.constraints ?? []) {
|
||||
if (c.expr) for (const n of namesIn(c.expr)) add1(n, { feature: f.id, where: c.id, kind: c.prop === "angle" ? "angle" : "length", expr: c.expr! });
|
||||
for (const x of c.atExpr ?? []) if (x) for (const n of namesIn(x)) add1(n, { feature: f.id, where: c.id, kind: "length", expr: x });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -273,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
|
||||
@@ -305,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 {
|
||||
@@ -326,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.
|
||||
@@ -349,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,13 +189,21 @@ 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]];
|
||||
const mul3 = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];
|
||||
|
||||
/** Catmull–Clark, `levels` times. Boundary edges (open sheets) stay sharp B-spline curves. */
|
||||
export function subdivide(cage: Cage, levels = 3): Subdivided {
|
||||
/**
|
||||
* Catmull–Clark, `levels` times. Boundary edges (open sheets) stay sharp
|
||||
* B-spline curves. `sharp`: border points the border passes through as a
|
||||
* 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]],
|
||||
@@ -189,7 +234,7 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
|
||||
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[]>();
|
||||
@@ -200,10 +245,15 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
|
||||
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.
|
||||
if (fs.length === 1) return p;
|
||||
// (Told which points are corners: only those - a sheet's own corner on a round edge isn't one.)
|
||||
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];
|
||||
@@ -232,10 +282,20 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
|
||||
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 } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -247,7 +307,7 @@ export function subdivide(cage: Cage, levels = 3): Subdivided {
|
||||
* Inside: (n²·p + 4·Σ edge neighbours + Σ diagonal neighbours) / (n(n+5)).
|
||||
* Along an open border: (prev + 4·p + next) / 6. Corners of a sheet stay.
|
||||
*/
|
||||
export function limitPoints(s: Subdivided): Vec3[] {
|
||||
export function limitPoints(s: Subdivided, sharp?: Set<number>): Vec3[] {
|
||||
const P = s.points;
|
||||
const quads: number[][] = [];
|
||||
for (const g of s.grids) for (let i = 0; i < s.n; i++) for (let j = 0; j < s.n; j++) quads.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]);
|
||||
@@ -269,12 +329,28 @@ export function limitPoints(s: Subdivided): 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 (faces[v] === 1 || bd.length !== 2) return p;
|
||||
if ((sharp ? sharp.has(v) : faces[v] === 1) || bd.length !== 2) return p;
|
||||
return [0, 1, 2].map((k) => (P[bd[0]][k] + 4 * p[k] + P[bd[1]][k]) / 6) as Vec3;
|
||||
}
|
||||
const n = nbE[v].size;
|
||||
@@ -287,6 +363,62 @@ export function limitPoints(s: Subdivided): Vec3[] {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A sheet whose smooth border runs THROUGH the cage's border points (as
|
||||
* drawn, a smooth surface's border only comes near them) and turns a corner
|
||||
* where they do: the cage with its border points moved to where they pull the
|
||||
* border onto the old ones, and the corners. For a sheet laid over a face,
|
||||
* whose border points lie on the face's edge - so does the surface's then.
|
||||
*/
|
||||
export function borderThrough(cage: Cage): { cage: Cage; sharp: Set<number> } {
|
||||
const next = new Map<number, number>();
|
||||
for (const [a, b] of boundaryEdges(cage)) next.set(a, b);
|
||||
const prev = new Map<number, number>();
|
||||
for (const [a, b] of next) prev.set(b, a);
|
||||
const P = cage.verts;
|
||||
const sharp = new Set<number>();
|
||||
for (const [v, n] of next) {
|
||||
const p = prev.get(v);
|
||||
if (p === undefined) continue;
|
||||
const d1 = [0, 1, 2].map((k) => P[v][k] - P[p][k]);
|
||||
const d2 = [0, 1, 2].map((k) => P[n][k] - P[v][k]);
|
||||
const l = Math.hypot(...d1) * Math.hypot(...d2);
|
||||
const cos = l > 0 ? (d1[0] * d2[0] + d1[1] * d2[1] + d1[2] * d2[2]) / l : 1;
|
||||
if (cos < Math.cos((25 * Math.PI) / 180)) sharp.add(v);
|
||||
}
|
||||
// The border's point at a control point is (before + 4·it + after) / 6:
|
||||
// solved for the control points that put it on the old point (it settles in
|
||||
// a few rounds: each point depends mostly on itself).
|
||||
const C = P.map((p) => [...p] as Vec3);
|
||||
const free = [...next.keys()].filter((v) => !sharp.has(v) && prev.has(v));
|
||||
for (let round = 0; round < 60; round++)
|
||||
for (const v of free) {
|
||||
const a = C[prev.get(v)!];
|
||||
const b = C[next.get(v)!];
|
||||
C[v] = [0, 1, 2].map((k) => (6 * P[v][k] - a[k] - b[k]) / 4) as Vec3;
|
||||
}
|
||||
return { cage: { verts: C, faces: cage.faces }, sharp };
|
||||
}
|
||||
|
||||
/** The points along a subdivided sheet's open border, as pieces [from, to]. */
|
||||
export function borderPieces(s: Subdivided): [Vec3, Vec3][] {
|
||||
const count = new Map<string, [number, number]>();
|
||||
const seen = new Map<string, number>();
|
||||
for (const g of s.grids)
|
||||
for (let i = 0; i < s.n; i++)
|
||||
for (let j = 0; j < s.n; j++) {
|
||||
const q = [g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]];
|
||||
for (let k = 0; k < 4; k++) {
|
||||
const a = q[k];
|
||||
const b = q[(k + 1) % 4];
|
||||
const key = a < b ? `${a},${b}` : `${b},${a}`;
|
||||
seen.set(key, (seen.get(key) ?? 0) + 1);
|
||||
count.set(key, [a, b]);
|
||||
}
|
||||
}
|
||||
return [...count].filter(([k]) => seen.get(k) === 1).map(([, [a, b]]) => [s.points[a], s.points[b]]);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- subdivision plan
|
||||
//
|
||||
// Catmull–Clark and the limit points are fixed weighted sums of the cage
|
||||
@@ -344,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(";")}` : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -362,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) => {
|
||||
@@ -396,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)) {
|
||||
@@ -424,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);
|
||||
@@ -445,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;
|
||||
@@ -480,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);
|
||||
@@ -558,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>();
|
||||
@@ -647,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}`);
|
||||
@@ -717,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]) });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1162,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. */
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
// Connect: a smooth bridge from one face to another. The faces' own outlines
|
||||
// are swept along a curve (the guide the user drew, or one that leaves each
|
||||
// face straight out of it): the bridge starts and ends exactly on the faces,
|
||||
// so joined to them it leaves no step.
|
||||
|
||||
import type { Vec3 } from "../doc/types";
|
||||
|
||||
const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
|
||||
const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
|
||||
const mul = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k];
|
||||
const len = (a: Vec3) => Math.hypot(a[0], a[1], a[2]);
|
||||
const unit = (a: Vec3): Vec3 => mul(a, 1 / (len(a) || 1));
|
||||
const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
const cross = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
||||
|
||||
/**
|
||||
* A guide curve as a function of 0..1 (by length): run from the end nearer
|
||||
* A's middle, and moved (gradually, end to end) so it starts at A's middle and
|
||||
* ends at B's. With `da0`/`db0`: for `ease` along it from each end, eased
|
||||
* from the way it leaves A (arrives at B) onto the curve.
|
||||
*/
|
||||
export function guideCurve(pts: Vec3[], ca: Vec3, cb: Vec3, da0?: Vec3, db0?: Vec3, ease = 0): (t: number) => Vec3 {
|
||||
const p = oriented(pts, ca, cb);
|
||||
const acc = [0];
|
||||
for (let i = 1; i < p.length; i++) acc.push(acc[i - 1] + len(sub(p[i], p[i - 1])));
|
||||
const total = acc[acc.length - 1] || 1;
|
||||
const da = sub(ca, p[0]);
|
||||
const db = sub(cb, p[p.length - 1]);
|
||||
const on = (t: number) => {
|
||||
const want = Math.max(0, Math.min(1, t)) * total;
|
||||
let i = 1;
|
||||
while (i < p.length - 1 && acc[i] < want) i++;
|
||||
const f = Math.max(0, Math.min(1, acc[i] > acc[i - 1] ? (want - acc[i - 1]) / (acc[i] - acc[i - 1]) : 0));
|
||||
// Smoothly through the points (Catmull-Rom), not straight from one to the
|
||||
// next: the corners between straight pieces read as turns far too tight.
|
||||
const P0 = p[Math.max(0, i - 2)];
|
||||
const P1 = p[i - 1];
|
||||
const P2 = p[i];
|
||||
const P3 = p[Math.min(p.length - 1, i + 1)];
|
||||
const f2 = f * f;
|
||||
const f3 = f2 * f;
|
||||
const q = mul(add(add(mul(P1, 2), mul(sub(P2, P0), f)), add(mul(add(sub(mul(P0, 2), mul(P1, 5)), sub(mul(P2, 4), P3)), f2), mul(add(sub(mul(P1, 3), P0), sub(P3, mul(P2, 3))), f3))), 0.5);
|
||||
const s = want / total;
|
||||
return add(q, add(mul(da, 1 - s), mul(db, s)));
|
||||
};
|
||||
if (!da0 || !db0 || !(ease > 0)) return on;
|
||||
// Near each end, a smooth curve from straight out of the face onto the
|
||||
// guide (meeting it going its way): the bridge leaves the face square, with no kink.
|
||||
const w = Math.min(0.45, ease / total);
|
||||
const slope = (t: number) => mul(sub(on(t + 1e-4), on(t - 1e-4)), w / 2e-4);
|
||||
const hermite = (p0: Vec3, t0: Vec3, p1: Vec3, t1: Vec3) => (s: number) =>
|
||||
add(add(mul(p0, 2 * s ** 3 - 3 * s ** 2 + 1), mul(t0, s ** 3 - 2 * s ** 2 + s)), add(mul(p1, -2 * s ** 3 + 3 * s ** 2), mul(t1, s ** 3 - s ** 2)));
|
||||
const ta = slope(w);
|
||||
const tb = slope(1 - w);
|
||||
const startA = hermite(ca, mul(unit(da0), len(ta)), on(w), ta);
|
||||
const intoB = hermite(on(1 - w), tb, cb, mul(unit(db0), -len(tb)));
|
||||
return (t: number) => (t < w ? startA(t / w) : t > 1 - w ? intoB((t - (1 - w)) / w) : on(t));
|
||||
}
|
||||
|
||||
/** The bridge's two outlines: points round each, from its middle, as they lie at that end. */
|
||||
export interface Rings {
|
||||
a: Vec3[];
|
||||
b: Vec3[];
|
||||
}
|
||||
|
||||
interface Frame {
|
||||
r: Vec3;
|
||||
s: Vec3;
|
||||
t: Vec3;
|
||||
}
|
||||
|
||||
/**
|
||||
* `n` + 1 points along a curve, and at each the directions across it carried
|
||||
* along from the start without twisting about the curve (double reflection) -
|
||||
* the way the sweep carries the bridge's outline.
|
||||
*/
|
||||
function carried(c: (t: number) => Vec3, n: number): { P: Vec3[]; F: Frame[] } {
|
||||
const P = Array.from({ length: n + 1 }, (_, i) => c(i / n));
|
||||
const T = P.map((_, i) => unit(sub(P[Math.min(n, i + 1)], P[Math.max(0, i - 1)])));
|
||||
const seed: Vec3 = Math.abs(T[0][0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
|
||||
let r = unit(sub(seed, mul(T[0], dot(seed, T[0]))));
|
||||
const F: Frame[] = [{ r, s: cross(T[0], r), t: T[0] }];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const v1 = sub(P[i + 1], P[i]);
|
||||
const c1 = dot(v1, v1);
|
||||
let next = r;
|
||||
if (c1 > 1e-24) {
|
||||
const rL = sub(r, mul(v1, (2 / c1) * dot(v1, r)));
|
||||
const tL = sub(T[i], mul(v1, (2 / c1) * dot(v1, T[i])));
|
||||
const v2 = sub(T[i + 1], tL);
|
||||
const c2 = dot(v2, v2);
|
||||
next = c2 > 1e-24 ? sub(rL, mul(v2, (2 / c2) * dot(v2, rL))) : rL;
|
||||
}
|
||||
const t = T[i + 1];
|
||||
r = unit(sub(next, mul(t, dot(next, t))));
|
||||
F.push({ r, s: cross(t, r), t });
|
||||
}
|
||||
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
|
||||
* of the turn (with a little to spare). Tighter, the outline's inner side
|
||||
* runs backwards and the bridge folds through itself. The outline is taken
|
||||
* where the sweep has carried it by then - turned with the curve (measured as
|
||||
* it lay at the faces, an arch's top went unchecked) - and as far between the
|
||||
* two ends' outlines as the point is along the curve (A's at A, B's at B).
|
||||
*/
|
||||
export function gentle(c: (t: number) => Vec3, rings: Rings, spare = 1.1): boolean {
|
||||
const N = 200;
|
||||
const { P, F } = carried(c, N);
|
||||
const across = (ring: Vec3[], f: Frame) => ring.map((p): Vec3 => [dot(p, f.r), dot(p, f.s), dot(p, f.t)]);
|
||||
const ends = [across(rings.a, F[0]), across(rings.b, F[N])];
|
||||
const h = 1 / N;
|
||||
for (let i = 1; i < N; i++) {
|
||||
const v = mul(sub(P[i + 1], P[i - 1]), 1 / (2 * h));
|
||||
const a = mul(add(sub(P[i + 1], mul(P[i], 2)), P[i - 1]), 1 / (h * h));
|
||||
const k = len(cross(v, a));
|
||||
if (k < 1e-12) continue;
|
||||
// Towards the middle of the turn: the part of `a` across the curve.
|
||||
const n = unit(sub(a, mul(v, dot(v, a) / dot(v, v))));
|
||||
const f = F[i];
|
||||
const nl: Vec3 = [dot(n, f.r), dot(n, f.s), dot(n, f.t)];
|
||||
const [ra, rb] = ends.map((ring) => ring.reduce((m, p) => Math.max(m, dot(p, nl)), 0));
|
||||
if (len(v) ** 3 / k < spare * (ra + (rb - ra) * (i / N))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A curve from `ca` to `cb` that leaves along `na` and arrives against `nb`, each held for `lead`. */
|
||||
function hermite(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3, lead: number): (t: number) => Vec3 {
|
||||
const T0 = mul(unit(na), lead);
|
||||
const T1 = mul(unit(nb), -lead);
|
||||
return (t: number) => {
|
||||
const h00 = 2 * t ** 3 - 3 * t ** 2 + 1;
|
||||
const h10 = t ** 3 - 2 * t ** 2 + t;
|
||||
const h01 = -2 * t ** 3 + 3 * t ** 2;
|
||||
const h11 = t ** 3 - t ** 2;
|
||||
return add(add(mul(ca, h00), mul(T0, h10)), add(mul(cb, h01), mul(T1, h11)));
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* With no guide: a curve from A's middle to B's that leaves A along `na` and
|
||||
* arrives at B against `nb`, bowing out by `bulge` (1: plain) - but never
|
||||
* turning tighter than the bridge is wide (see gentle): a tighter turn folds
|
||||
* the bridge's inside, however little the bulge. `gentle` false: none of
|
||||
* these curves is (the faces too close, or too far to the side of each other,
|
||||
* for their width) - the plain one, for the caller to do better by.
|
||||
*/
|
||||
export function plainSpine(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3, bulge: number, rings: Rings): { along: (t: number) => Vec3; gentle: boolean } {
|
||||
const gap = len(sub(cb, ca)) || 1;
|
||||
// The bulge asked for, else the nearest to it (more, or less) that turns gently enough.
|
||||
const want = gap * Math.max(0.05, bulge);
|
||||
for (let k = 0; k < 40; k++)
|
||||
for (const lead of k ? [want * 1.06 ** k, want / 1.06 ** k] : [want]) {
|
||||
const c = hermite(ca, na, cb, nb, lead);
|
||||
if (gentle(c, rings)) return { along: c, gentle: true };
|
||||
}
|
||||
return { along: hermite(ca, na, cb, nb, want), gentle: false };
|
||||
}
|
||||
|
||||
/**
|
||||
* Two arcs of circles, one out of A along `na` and one into B against `nb`,
|
||||
* meeting smoothly half way: of the ways from one face to the other this
|
||||
* turns the least tightly (well less than the plain curve at its tightest),
|
||||
* so it fits where that one would fold. Null where there is none (B straight
|
||||
* behind A).
|
||||
*/
|
||||
export function arcSpine(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3): ((t: number) => Vec3) | null {
|
||||
const T0 = unit(na);
|
||||
const T1 = unit(mul(nb, -1));
|
||||
const v = sub(cb, ca);
|
||||
const vv = dot(v, v);
|
||||
if (vv < 1e-18) return null;
|
||||
// (Equal chords: the corner points ca + d T0 and cb - d T1 are d from the ends and 2d apart.)
|
||||
const q = 1 - dot(T0, T1);
|
||||
const vt = dot(v, add(T0, T1));
|
||||
let d: number;
|
||||
if (q < 1e-9) {
|
||||
const ahead = dot(v, T0);
|
||||
if (ahead <= 1e-9) return null;
|
||||
d = vv / (4 * ahead);
|
||||
} else d = (-vt + Math.sqrt(vt * vt + 2 * q * vv)) / (2 * q);
|
||||
if (!(d > 1e-9) || !Number.isFinite(d)) return null;
|
||||
const J = mul(add(add(ca, mul(T0, d)), sub(cb, mul(T1, d))), 0.5);
|
||||
// The arc from A, leaving along T, to B: its length, and the point `s` along it.
|
||||
const arc = (A: Vec3, T: Vec3, B: Vec3) => {
|
||||
const w = sub(B, A);
|
||||
const ahead = dot(w, T);
|
||||
const side = sub(w, mul(T, ahead));
|
||||
const off = len(side);
|
||||
if (off < 1e-9 * (len(w) || 1)) return { length: Math.abs(ahead), at: (s: number) => add(A, mul(T, s * Math.sign(ahead || 1))) };
|
||||
const n = mul(side, 1 / off);
|
||||
const r = dot(w, w) / (2 * off);
|
||||
return { length: r * 2 * Math.atan2(off, ahead), at: (s: number) => add(A, mul(add(mul(T, Math.sin(s / r)), mul(n, 1 - Math.cos(s / r))), r)) };
|
||||
};
|
||||
const out = arc(ca, T0, J);
|
||||
const back = arc(cb, mul(T1, -1), J);
|
||||
const total = out.length + back.length;
|
||||
if (!(total > 0)) return null;
|
||||
return (t: number) => {
|
||||
const s = Math.max(0, Math.min(1, t)) * total;
|
||||
return s <= out.length ? out.at(s) : back.at(total - s);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* For a bridge too wide to turn with its curve (it would fold): the direction
|
||||
* its outline can keep facing instead, all the way, sliding along the curve
|
||||
* without turning - a sheared bridge, thinner where the curve leans. Only
|
||||
* where both ends face nearly the same way (`ta`, `tb`: the way the curve
|
||||
* leaves A and arrives at B), the curve never runs across that direction (the
|
||||
* bridge would thin to nothing), and it gets further along it than the two
|
||||
* outlines lean apart (`reach`: how far they reach from their middles).
|
||||
*/
|
||||
export function slideAxis(c: (t: number) => Vec3, ta: Vec3, tb: Vec3, reach: number, least = 0.2): Vec3 | null {
|
||||
const a = unit(ta);
|
||||
const b = unit(tb);
|
||||
const cos = dot(a, b);
|
||||
if (cos < 0.94) return null;
|
||||
const d = unit(add(a, b));
|
||||
if (dot(sub(c(1), c(0)), d) < 2 * reach * Math.sqrt(Math.max(0, 1 - cos * cos))) return null;
|
||||
const N = 200;
|
||||
let prev = c(0);
|
||||
for (let i = 1; i <= N; i++) {
|
||||
const p = c(i / N);
|
||||
const step = sub(p, prev);
|
||||
const L = len(step);
|
||||
if (L > 1e-12 && dot(step, d) / L < least) return null;
|
||||
prev = p;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
/** The plain curve (its bulge as asked, else the nearest less of it) that a bridge can slide along (see slideAxis). */
|
||||
export function slidingSpine(ca: Vec3, na: Vec3, cb: Vec3, nb: Vec3, bulge: number, reach: number): { along: (t: number) => Vec3; axis: Vec3 } | null {
|
||||
const gap = len(sub(cb, ca)) || 1;
|
||||
const want = gap * Math.max(0.05, bulge);
|
||||
for (let k = 0; k < 40; k++) {
|
||||
const c = hermite(ca, na, cb, nb, want / 1.06 ** k);
|
||||
const axis = slideAxis(c, na, mul(nb, -1), reach);
|
||||
if (axis) return { along: c, axis };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** `n` points evenly along a polyline (by length), its ends kept. */
|
||||
export function evenly(pts: Vec3[], n: number): Vec3[] {
|
||||
const acc = [0];
|
||||
for (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + len(sub(pts[i], pts[i - 1])));
|
||||
const total = acc[acc.length - 1];
|
||||
if (!(total > 0)) return pts;
|
||||
const out: Vec3[] = [];
|
||||
let i = 1;
|
||||
for (let k = 0; k < n; k++) {
|
||||
const want = (total * k) / (n - 1);
|
||||
while (i < pts.length - 1 && acc[i] < want) i++;
|
||||
const f = acc[i] > acc[i - 1] ? Math.max(0, Math.min(1, (want - acc[i - 1]) / (acc[i] - acc[i - 1]))) : 0;
|
||||
out.push(add(pts[i - 1], mul(sub(pts[i], pts[i - 1]), f)));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A guide's points run from the end nearer A to the end nearer B. */
|
||||
export function oriented(pts: Vec3[], ca: Vec3, cb: Vec3): Vec3[] {
|
||||
return len(sub(pts[0], ca)) + len(sub(pts[pts.length - 1], cb)) <= len(sub(pts[pts.length - 1], ca)) + len(sub(pts[0], cb)) ? pts : [...pts].reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* A polyline (run from A to B) rounded off `passes` times - each point
|
||||
* towards its neighbours' middle - its ends kept, and still leaving the first
|
||||
* along `da` and arriving at the last against `db` (held by points out past
|
||||
* each end that don't move): its tight turns open out, its ends stay square.
|
||||
*/
|
||||
export function smoothed(pts: Vec3[], passes: number, da: Vec3, db: Vec3): Vec3[] {
|
||||
const step = len(sub(pts[1], pts[0])) || 1;
|
||||
const n = pts.length;
|
||||
const before = Array.from({ length: n }, (_, k) => sub(pts[0], mul(unit(da), step * (n - k))));
|
||||
const after = Array.from({ length: n }, (_, k) => add(pts[n - 1], mul(unit(db), step * (k + 1))));
|
||||
let p = [...before, ...pts, ...after];
|
||||
const fixed = (i: number) => i <= n || i >= 2 * n - 1;
|
||||
for (let k = 0; k < passes; k++) p = p.map((q, i) => (fixed(i) ? q : mul(add(add(p[i - 1], p[i + 1]), mul(q, 2)), 0.25)));
|
||||
return p.slice(n, 2 * n);
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
// The cage Freeform Face shapes a flat face with: a grid of quads over the
|
||||
// face whose border runs round the face's edge (on a rectangle, a plain grid;
|
||||
// on a round or odd-shaped face, a grid stretched to fit it). The border
|
||||
// points stay where they are - the face's edges don't move - and the inside
|
||||
// points are moved like any freeform cage's.
|
||||
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { cross, dot, norm, sub, xDirFor } from "../geom";
|
||||
import type { Cage } from "./cage";
|
||||
|
||||
type P2 = [number, number];
|
||||
|
||||
/** The outer outline of a set of triangles, in order (anticlockwise about `normal`), in the plane's 2D. */
|
||||
function outline(tris: [Vec3, Vec3, Vec3][], uv: (p: Vec3) => P2): P2[] {
|
||||
const key = (p: P2) => `${Math.round(p[0] * 1e5)},${Math.round(p[1] * 1e5)}`;
|
||||
const at = new Map<string, P2>();
|
||||
const uses = new Map<string, number>();
|
||||
const dir = new Map<string, string>();
|
||||
for (const t of tris) {
|
||||
const q = t.map(uv);
|
||||
// Each triangle anticlockwise in the plane.
|
||||
const area = (q[1][0] - q[0][0]) * (q[2][1] - q[0][1]) - (q[2][0] - q[0][0]) * (q[1][1] - q[0][1]);
|
||||
if (Math.abs(area) < 1e-14) continue;
|
||||
const r = area > 0 ? q : [q[0], q[2], q[1]];
|
||||
for (let k = 0; k < 3; k++) {
|
||||
const a = key(r[k]);
|
||||
const b = key(r[(k + 1) % 3]);
|
||||
if (a === b) continue;
|
||||
at.set(a, r[k]);
|
||||
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
|
||||
uses.set(e, (uses.get(e) ?? 0) + 1);
|
||||
dir.set(`${a}>${b}`, b);
|
||||
}
|
||||
}
|
||||
// Border edges (used once), followed head to tail.
|
||||
const next = new Map<string, string>();
|
||||
for (const [k, b] of dir) {
|
||||
const a = k.slice(0, k.indexOf(">"));
|
||||
const e = a < b ? `${a}|${b}` : `${b}|${a}`;
|
||||
if (uses.get(e) === 1) next.set(a, b);
|
||||
}
|
||||
const loops: P2[][] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const start of next.keys()) {
|
||||
if (seen.has(start)) continue;
|
||||
const loop: P2[] = [];
|
||||
let k: string | undefined = start;
|
||||
while (k && !seen.has(k)) {
|
||||
seen.add(k);
|
||||
loop.push(at.get(k)!);
|
||||
k = next.get(k);
|
||||
}
|
||||
if (loop.length >= 3) loops.push(loop);
|
||||
}
|
||||
const signed = (l: P2[]) => l.reduce((s, p, i) => s + p[0] * l[(i + 1) % l.length][1] - l[(i + 1) % l.length][0] * p[1], 0) / 2;
|
||||
// The outer one: the biggest (anticlockwise).
|
||||
loops.sort((a, b) => Math.abs(signed(b)) - Math.abs(signed(a)));
|
||||
const outer = loops[0] ?? [];
|
||||
return signed(outer) < 0 ? outer.reverse() : outer;
|
||||
}
|
||||
|
||||
/**
|
||||
* `n` + 1 points along a polyline, both ends included: evenly by length, then
|
||||
* the one nearest each corner on the way moved onto it - the grid's border
|
||||
* goes through the face's corners (an L's inward one too), so the smooth
|
||||
* surface laid on the grid can have its border on the face's edges.
|
||||
*/
|
||||
function resample(pts: P2[], n: number): P2[] {
|
||||
const out = evenly(pts, n);
|
||||
const acc = [0];
|
||||
for (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
|
||||
const total = acc[acc.length - 1];
|
||||
const used = new Set<number>();
|
||||
for (let i = 1; i < pts.length - 1 && total > 0; i++) {
|
||||
const d1 = [pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]];
|
||||
const d2 = [pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]];
|
||||
const turn = Math.abs(Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]));
|
||||
if (turn < (25 * Math.PI) / 180) continue;
|
||||
// (The sample whose place along the side is nearest: the order of the points stays.)
|
||||
const k = Math.round((acc[i] / total) * n);
|
||||
if (k < 1 || k > n - 1 || used.has(k)) continue;
|
||||
used.add(k);
|
||||
out[k] = [pts[i][0], pts[i][1]];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** `n` + 1 points evenly along a polyline (by length), both ends included. */
|
||||
function evenly(pts: P2[], n: number): P2[] {
|
||||
const acc = [0];
|
||||
for (let i = 1; i < pts.length; i++) acc.push(acc[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]));
|
||||
const total = acc[acc.length - 1];
|
||||
const out: P2[] = [];
|
||||
let i = 1;
|
||||
for (let k = 0; k <= n; k++) {
|
||||
const want = (total * k) / n;
|
||||
while (i < pts.length - 1 && acc[i] < want) i++;
|
||||
const f = acc[i] > acc[i - 1] ? (want - acc[i - 1]) / (acc[i] - acc[i - 1]) : 0;
|
||||
const t = Math.max(0, Math.min(1, f));
|
||||
out.push([pts[i - 1][0] + (pts[i][0] - pts[i - 1][0]) * t, pts[i - 1][1] + (pts[i][1] - pts[i - 1][1]) * t]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ways to choose the four points of the outline where the grid's sides meet
|
||||
* (best first): the face's own
|
||||
* outward corners when it has four or more (the four best spread), else
|
||||
* spread evenly (a round face).
|
||||
*/
|
||||
function fourCorners(loop: P2[], acc: number[], total: number): number[][] {
|
||||
const N = loop.length;
|
||||
const turn = loop.map((p, i) => {
|
||||
const a = loop[(i + N - 1) % N];
|
||||
const b = loop[(i + 1) % N];
|
||||
const d1 = [p[0] - a[0], p[1] - a[1]];
|
||||
const d2 = [b[0] - p[0], b[1] - p[1]];
|
||||
// (Signed: turning in, at a corner going into the face like an L's, is negative.)
|
||||
return Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]);
|
||||
});
|
||||
// Only outward corners: an inward one (an L's) stays along a side.
|
||||
let corners = loop.map((_, i) => i).filter((i) => turn[i] > (25 * Math.PI) / 180);
|
||||
if (corners.length > 16) corners = corners.sort((a, b) => turn[b] - turn[a]).slice(0, 16).sort((a, b) => a - b);
|
||||
const cand = [...corners];
|
||||
// Too few corners: points evenly round it to choose from too.
|
||||
if (corners.length < 4)
|
||||
for (let k = 0; k < 32; k++) {
|
||||
const want = (total * k) / 32;
|
||||
let i = 0;
|
||||
while (i < N - 1 && acc[i + 1] <= want) i++;
|
||||
if (!cand.includes(i)) cand.push(i);
|
||||
}
|
||||
cand.sort((a, b) => a - b);
|
||||
const isCorner = new Set(corners);
|
||||
const gap = (i: number, j: number) => (acc[j] - acc[i] + total) % total;
|
||||
const all: { q: number[]; score: number }[] = [];
|
||||
const C = cand.length;
|
||||
for (let a = 0; a < C; a++)
|
||||
for (let b = a + 1; b < C; b++)
|
||||
for (let c = b + 1; c < C; c++)
|
||||
for (let d = c + 1; d < C; d++) {
|
||||
const q = [cand[a], cand[b], cand[c], cand[d]];
|
||||
const m = Math.min(gap(q[0], q[1]), gap(q[1], q[2]), gap(q[2], q[3]), gap(q[3], q[0]));
|
||||
const score = m / total + 0.2 * q.filter((i) => isCorner.has(i)).length;
|
||||
all.push({ q, score });
|
||||
}
|
||||
// Best first (the next ones are tried when a grid on the best won't fit the face).
|
||||
return all.sort((a, b) => b.score - a.score).slice(0, 12).map((x) => x.q);
|
||||
}
|
||||
|
||||
/**
|
||||
* A cage over the flat face made of `tris` (points relative to `center`):
|
||||
* `n` cells across its longer way.
|
||||
*/
|
||||
export function faceCage(tris: [Vec3, Vec3, Vec3][], center: Vec3, normal: Vec3, n = 5): Cage | null {
|
||||
const nn = norm(normal);
|
||||
const u = xDirFor(nn);
|
||||
const v = norm(cross(nn, u));
|
||||
const uv = (p: Vec3): P2 => [dot(sub(p, center), u), dot(sub(p, center), v)];
|
||||
const drawn = outline(tris, uv);
|
||||
if (drawn.length < 3) return null;
|
||||
// Points along its straight edges too (a triangle's outline is three points:
|
||||
// nowhere for a fourth corner of the grid to go but a point along an edge).
|
||||
const around = drawn.reduce((t, p, i) => t + Math.hypot(drawn[(i + 1) % drawn.length][0] - p[0], drawn[(i + 1) % drawn.length][1] - p[1]), 0);
|
||||
const loop: P2[] = [];
|
||||
drawn.forEach((p, i) => {
|
||||
const q = drawn[(i + 1) % drawn.length];
|
||||
const pieces = Math.max(1, Math.ceil((Math.hypot(q[0] - p[0], q[1] - p[1]) / around) * 32));
|
||||
for (let k = 0; k < pieces; k++) loop.push([p[0] + ((q[0] - p[0]) * k) / pieces, p[1] + ((q[1] - p[1]) * k) / pieces]);
|
||||
});
|
||||
const N = loop.length;
|
||||
const acc = [0];
|
||||
for (let i = 1; i <= N; i++) acc.push(acc[i - 1] + Math.hypot(loop[i % N][0] - loop[i - 1][0], loop[i % N][1] - loop[i - 1][1]));
|
||||
const total = acc[N];
|
||||
for (const cs of fourCorners(loop, acc, total)) {
|
||||
// The four sides, each from one corner to the next.
|
||||
const side = (a: number, b: number): P2[] => {
|
||||
const out: P2[] = [];
|
||||
for (let i = a; ; i = (i + 1) % N) {
|
||||
out.push(loop[i]);
|
||||
if (i === b) break;
|
||||
}
|
||||
return out;
|
||||
};
|
||||
const sides = [0, 1, 2, 3].map((k) => side(cs[k], cs[(k + 1) % 4]));
|
||||
const length = (s: P2[]) => s.reduce((t, p, i) => (i ? t + Math.hypot(p[0] - s[i - 1][0], p[1] - s[i - 1][1]) : 0), 0);
|
||||
const Lu = (length(sides[0]) + length(sides[2])) / 2;
|
||||
const Lv = (length(sides[1]) + length(sides[3])) / 2;
|
||||
const big = Math.max(Lu, Lv);
|
||||
const nu = Math.max(2, Math.round((n * Lu) / big));
|
||||
const nv = Math.max(2, Math.round((n * Lv) / big));
|
||||
const bottom = resample(sides[0], nu);
|
||||
const right = resample(sides[1], nv);
|
||||
const top = resample(sides[2], nu).reverse();
|
||||
const left = resample(sides[3], nv).reverse();
|
||||
// Coons: the inside blended from the four sides.
|
||||
const id = (i: number, j: number) => j * (nu + 1) + i;
|
||||
const at: P2[] = [];
|
||||
for (let j = 0; j <= nv; j++)
|
||||
for (let i = 0; i <= nu; i++) {
|
||||
const s = i / nu;
|
||||
const t = j / nv;
|
||||
if (j === 0) at.push(bottom[i]);
|
||||
else if (j === nv) at.push(top[i]);
|
||||
else if (i === 0) at.push(left[j]);
|
||||
else if (i === nu) at.push(right[j]);
|
||||
else {
|
||||
const c = (k: 0 | 1) =>
|
||||
(1 - t) * bottom[i][k] + t * top[i][k] + (1 - s) * left[j][k] + s * right[j][k] -
|
||||
((1 - s) * (1 - t) * bottom[0][k] + s * (1 - t) * bottom[nu][k] + (1 - s) * t * top[0][k] + s * t * top[nu][k]);
|
||||
at.push([c(0), c(1)]);
|
||||
}
|
||||
}
|
||||
// A face that isn't convex (an L): the blend can put points outside it.
|
||||
// Evened out (each inside point to the middle of its four neighbours) a
|
||||
// step at a time, till they're all on the face (evened out all the way they
|
||||
// can end up outside again); never: null (a coarser grid may do).
|
||||
const inside = (p: P2) => {
|
||||
let w = false;
|
||||
for (let a = 0, b = N - 1; a < N; b = a++) {
|
||||
const [pa, pb] = [loop[a], loop[b]];
|
||||
if (pa[1] > p[1] !== pb[1] > p[1] && p[0] < ((pb[0] - pa[0]) * (p[1] - pa[1])) / (pb[1] - pa[1]) + pa[0]) w = !w;
|
||||
}
|
||||
return w;
|
||||
};
|
||||
const allIn = () => at.every((p, k) => k % (nu + 1) === 0 || k % (nu + 1) === nu || k <= nu || k >= nv * (nu + 1) || inside(p));
|
||||
for (let round = 0; round < 400 && !allIn(); round++)
|
||||
for (let j = 1; j < nv; j++)
|
||||
for (let i = 1; i < nu; i++) {
|
||||
const q = [at[id(i - 1, j)], at[id(i + 1, j)], at[id(i, j - 1)], at[id(i, j + 1)]];
|
||||
at[id(i, j)] = [(q[0][0] + q[1][0] + q[2][0] + q[3][0]) / 4, (q[0][1] + q[1][1] + q[2][1] + q[3][1]) / 4];
|
||||
}
|
||||
if (!allIn()) continue;
|
||||
const verts: Vec3[] = at.map((p) => [u[0] * p[0] + v[0] * p[1], u[1] * p[0] + v[1] * p[1], u[2] * p[0] + v[2] * p[1]]);
|
||||
const faces: [number, number, number, number][] = [];
|
||||
for (let j = 0; j < nv; j++) for (let i = 0; i < nu; i++) faces.push([id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)]);
|
||||
return { verts, faces };
|
||||
}
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// More file formats: GLB out (glTF's one-file form, for the web, AR and
|
||||
// renderers) and 3MF in (slicer files: the exact model packed in one of ours,
|
||||
// else its meshes).
|
||||
|
||||
// ------------------------------------------------------------------ unzip
|
||||
|
||||
/** The files of a ZIP archive (what 3MF is), by name. */
|
||||
export async function unzip(bytes: Uint8Array): Promise<Map<string, Uint8Array>> {
|
||||
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
let end = -1;
|
||||
for (let i = bytes.length - 22; i >= Math.max(0, bytes.length - 65557); i--)
|
||||
if (dv.getUint32(i, true) === 0x06054b50) {
|
||||
end = i;
|
||||
break;
|
||||
}
|
||||
if (end < 0) throw new Error("it isn't a ZIP-based file, or it is damaged");
|
||||
const count = dv.getUint16(end + 10, true);
|
||||
let at = dv.getUint32(end + 16, true);
|
||||
const out = new Map<string, Uint8Array>();
|
||||
const dec = new TextDecoder();
|
||||
for (let k = 0; k < count; k++) {
|
||||
if (dv.getUint32(at, true) !== 0x02014b50) throw new Error("the file is damaged");
|
||||
const method = dv.getUint16(at + 10, true);
|
||||
const packed = dv.getUint32(at + 20, true);
|
||||
const n = dv.getUint16(at + 28, true);
|
||||
const extra = dv.getUint16(at + 30, true);
|
||||
const comment = dv.getUint16(at + 32, true);
|
||||
const local = dv.getUint32(at + 42, true);
|
||||
const name = dec.decode(bytes.subarray(at + 46, at + 46 + n));
|
||||
const start = local + 30 + dv.getUint16(local + 26, true) + dv.getUint16(local + 28, true);
|
||||
const data = bytes.subarray(start, start + packed);
|
||||
if (!name.endsWith("/")) out.set(name, method === 8 ? await inflate(data) : data);
|
||||
at += 46 + n + extra + comment;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function inflate(d: Uint8Array): Promise<Uint8Array> {
|
||||
const s = new Blob([d as BlobPart]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
|
||||
return new Uint8Array(await new Response(s).arrayBuffer());
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- 3MF
|
||||
|
||||
const UNIT_MM: Record<string, number> = { micron: 0.001, millimeter: 1, centimeter: 10, inch: 25.4, foot: 304.8, meter: 1000 };
|
||||
const attrs = (s: string) => Object.fromEntries([...s.matchAll(/([\w:]+)\s*=\s*"([^"]*)"/g)].map((m) => [m[1].replace(/^\w+:/, ""), m[2]]));
|
||||
type M = number[];
|
||||
/** 3MF's 3×4 matrix ("m00 m01 m02 m10 … m32"), points as rows: p·M. */
|
||||
const matrix = (t?: string): M => (t ? t.trim().split(/\s+/).map(Number) : [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
|
||||
const apply = (m: M, p: number[]) => [p[0] * m[0] + p[1] * m[3] + p[2] * m[6] + m[9], p[0] * m[1] + p[1] * m[4] + p[2] * m[7] + m[10], p[0] * m[2] + p[1] * m[5] + p[2] * m[8] + m[11]];
|
||||
/** a then b. */
|
||||
const compose = (a: M, b: M): M => {
|
||||
const r: M = [];
|
||||
for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) r[3 * i + j] = a[3 * i] * b[j] + a[3 * i + 1] * b[3 + j] + a[3 * i + 2] * b[6 + j];
|
||||
const t = apply(b, [a[9], a[10], a[11]]);
|
||||
return [...r, ...t];
|
||||
};
|
||||
|
||||
/**
|
||||
* A 3MF file as something to import: the exact STEP model when it carries one
|
||||
* (ours do), else its meshes - each build item, its components placed - as a
|
||||
* binary STL, in millimetres.
|
||||
*/
|
||||
export async function read3mf(bytes: Uint8Array): Promise<{ format: "step" | "stl"; bytes: Uint8Array }> {
|
||||
const files = await unzip(bytes);
|
||||
for (const [name, data] of files) if (/\.(step|stp)$/i.test(name)) return { format: "step", bytes: data };
|
||||
const modelName = [...files.keys()].find((n) => /^\/?3D\/.*\.model$/i.test(n));
|
||||
if (!modelName) throw new Error("it has no 3D model in it");
|
||||
const xml = new TextDecoder().decode(files.get(modelName));
|
||||
const unit = UNIT_MM[attrs(xml.match(/<(?:\w+:)?model\b([^>]*)>/)?.[1] ?? "").unit ?? "millimeter"] ?? 1;
|
||||
type Obj = { v: number[][]; t: number[][]; parts: { id: string; m: M }[] };
|
||||
const objects = new Map<string, Obj>();
|
||||
for (const o of xml.matchAll(/<(?:\w+:)?object\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:\w+:)?object>)/g)) {
|
||||
const body = o[2] ?? "";
|
||||
const v = [...body.matchAll(/<(?:\w+:)?vertex\b([^>]*)>/g)].map((m) => {
|
||||
const a = attrs(m[1]);
|
||||
return [Number(a.x), Number(a.y), Number(a.z)];
|
||||
});
|
||||
const t = [...body.matchAll(/<(?:\w+:)?triangle\b([^>]*)>/g)].map((m) => {
|
||||
const a = attrs(m[1]);
|
||||
return [Number(a.v1), Number(a.v2), Number(a.v3)];
|
||||
});
|
||||
const parts = [...body.matchAll(/<(?:\w+:)?component\b([^>]*)>/g)].map((m) => {
|
||||
const a = attrs(m[1]);
|
||||
return { id: a.objectid, m: matrix(a.transform) };
|
||||
});
|
||||
objects.set(attrs(o[1]).id, { v, t, parts });
|
||||
}
|
||||
const tris: number[][][] = [];
|
||||
const add = (id: string, m: M, depth: number) => {
|
||||
const o = objects.get(id);
|
||||
if (!o || depth > 16) return;
|
||||
for (const [a, b, c] of o.t) {
|
||||
if (![a, b, c].every((k) => Number.isInteger(k) && k >= 0 && k < o.v.length)) continue;
|
||||
tris.push([a, b, c].map((k) => apply(m, o.v[k]).map((x) => x * unit)));
|
||||
}
|
||||
for (const p of o.parts) add(p.id, compose(p.m, m), depth + 1);
|
||||
};
|
||||
const items = [...xml.matchAll(/<(?:\w+:)?item\b([^>]*)>/g)].map((m) => attrs(m[1]));
|
||||
if (items.length) for (const it of items) add(it.objectid, matrix(it.transform), 0);
|
||||
else for (const id of objects.keys()) add(id, matrix(), 0);
|
||||
if (!tris.length) throw new Error("it has no triangles in it");
|
||||
return { format: "stl", bytes: stlOf(tris) };
|
||||
}
|
||||
|
||||
/** Triangles as a binary STL (normals left zero: readers work them out). */
|
||||
function stlOf(tris: number[][][]): Uint8Array {
|
||||
const buf = new ArrayBuffer(84 + tris.length * 50);
|
||||
const dv = new DataView(buf);
|
||||
dv.setUint32(80, tris.length, true);
|
||||
let o = 84;
|
||||
for (const t of tris) {
|
||||
o += 12;
|
||||
for (const p of t) for (const x of p) (dv.setFloat32(o, x, true), (o += 4));
|
||||
o += 2;
|
||||
}
|
||||
return new Uint8Array(buf);
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------- GLB
|
||||
|
||||
export interface GlbBody {
|
||||
name: string;
|
||||
positions: Float32Array;
|
||||
indices: Uint32Array;
|
||||
/** "#rrggbb" */
|
||||
color?: string;
|
||||
opacity?: number;
|
||||
}
|
||||
|
||||
/** sRGB "#rrggbb" to glTF's linear colour. */
|
||||
const linear = (hex: string) =>
|
||||
[1, 3, 5].map((i) => {
|
||||
const c = parseInt(hex.slice(i, i + 2), 16) / 255;
|
||||
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
|
||||
});
|
||||
|
||||
/**
|
||||
* The bodies as one GLB: a mesh each (smooth normals, its colour), named,
|
||||
* under a root that turns Z up into glTF's Y up and millimetres into metres.
|
||||
*/
|
||||
export function glb(bodies: GlbBody[], title: string): Uint8Array {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let length = 0;
|
||||
const views: object[] = [];
|
||||
const accessors: object[] = [];
|
||||
const push = (data: ArrayBufferView, target: number) => {
|
||||
const bytes = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
||||
views.push({ buffer: 0, byteOffset: length, byteLength: bytes.length, target });
|
||||
chunks.push(bytes);
|
||||
length += bytes.length;
|
||||
const pad = (4 - (length % 4)) % 4;
|
||||
if (pad) (chunks.push(new Uint8Array(pad)), (length += pad));
|
||||
return views.length - 1;
|
||||
};
|
||||
const meshes: object[] = [];
|
||||
const materials: object[] = [];
|
||||
const nodes: object[] = [{ name: title, rotation: [-Math.SQRT1_2, 0, 0, Math.SQRT1_2], scale: [0.001, 0.001, 0.001], children: bodies.map((_, i) => i + 1) }];
|
||||
bodies.forEach((b, i) => {
|
||||
const p = b.positions;
|
||||
const n = new Float32Array(p.length);
|
||||
// Smooth normals: each corner's, from the triangles round it (weighted by their size).
|
||||
for (let t = 0; t < b.indices.length; t += 3) {
|
||||
const [a, c, d] = [b.indices[t], b.indices[t + 1], b.indices[t + 2]];
|
||||
const u = [p[3 * c] - p[3 * a], p[3 * c + 1] - p[3 * a + 1], p[3 * c + 2] - p[3 * a + 2]];
|
||||
const v = [p[3 * d] - p[3 * a], p[3 * d + 1] - p[3 * a + 1], p[3 * d + 2] - p[3 * a + 2]];
|
||||
const x = [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 [a, c, d]) for (let j = 0; j < 3; j++) n[3 * k + j] += x[j];
|
||||
}
|
||||
for (let k = 0; k < n.length; k += 3) {
|
||||
const l = Math.hypot(n[k], n[k + 1], n[k + 2]) || 1;
|
||||
n[k] /= l;
|
||||
n[k + 1] /= l;
|
||||
n[k + 2] /= l;
|
||||
}
|
||||
const min = [Infinity, Infinity, Infinity];
|
||||
const max = [-Infinity, -Infinity, -Infinity];
|
||||
for (let k = 0; k < p.length; k += 3)
|
||||
for (let j = 0; j < 3; j++) {
|
||||
min[j] = Math.min(min[j], p[k + j]);
|
||||
max[j] = Math.max(max[j], p[k + j]);
|
||||
}
|
||||
const count = p.length / 3;
|
||||
accessors.push({ bufferView: push(new Float32Array(p), 34962), componentType: 5126, count, type: "VEC3", min, max });
|
||||
accessors.push({ bufferView: push(n, 34962), componentType: 5126, count, type: "VEC3" });
|
||||
accessors.push({ bufferView: push(new Uint32Array(b.indices), 34963), componentType: 5125, count: b.indices.length, type: "SCALAR" });
|
||||
const alpha = b.opacity ?? 1;
|
||||
materials.push({
|
||||
name: b.name,
|
||||
pbrMetallicRoughness: { baseColorFactor: [...linear(b.color ?? "#b8bcc6"), alpha], metallicFactor: 0, roughnessFactor: 0.6 },
|
||||
...(alpha < 1 ? { alphaMode: "BLEND" } : {}),
|
||||
});
|
||||
meshes.push({ name: b.name, primitives: [{ attributes: { POSITION: 3 * i, NORMAL: 3 * i + 1 }, indices: 3 * i + 2, material: i }] });
|
||||
nodes.push({ name: b.name, mesh: i });
|
||||
});
|
||||
const json = {
|
||||
asset: { version: "2.0", generator: "superGeometry.app" },
|
||||
scene: 0,
|
||||
scenes: [{ name: title, nodes: [0] }],
|
||||
nodes,
|
||||
meshes,
|
||||
materials,
|
||||
accessors,
|
||||
bufferViews: views,
|
||||
buffers: [{ byteLength: length }],
|
||||
};
|
||||
let jsonBytes = new TextEncoder().encode(JSON.stringify(json));
|
||||
const jpad = (4 - (jsonBytes.length % 4)) % 4;
|
||||
if (jpad) {
|
||||
const padded = new Uint8Array(jsonBytes.length + jpad).fill(0x20);
|
||||
padded.set(jsonBytes);
|
||||
jsonBytes = padded;
|
||||
}
|
||||
const total = 12 + 8 + jsonBytes.length + 8 + length;
|
||||
const out = new Uint8Array(total);
|
||||
const dv = new DataView(out.buffer);
|
||||
dv.setUint32(0, 0x46546c67, true); // "glTF"
|
||||
dv.setUint32(4, 2, true);
|
||||
dv.setUint32(8, total, true);
|
||||
dv.setUint32(12, jsonBytes.length, true);
|
||||
dv.setUint32(16, 0x4e4f534a, true); // "JSON"
|
||||
out.set(jsonBytes, 20);
|
||||
let o = 20 + jsonBytes.length;
|
||||
dv.setUint32(o, length, true);
|
||||
dv.setUint32(o + 4, 0x004e4942, true); // "BIN"
|
||||
o += 8;
|
||||
for (const c of chunks) (out.set(c, o), (o += c.length));
|
||||
return out;
|
||||
}
|
||||
@@ -1,26 +1,58 @@
|
||||
// Insert menu: files (STEP/STL/OBJ/DXF/projects), images, variables.
|
||||
|
||||
import { migrate, newId } from "../doc/store";
|
||||
import { newId, parseProject } from "../doc/store";
|
||||
import type { Feature, ImageFeature, PlaneDef, SketchEntity, SketchFeature } from "../doc/types";
|
||||
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();
|
||||
});
|
||||
}
|
||||
|
||||
/** Why a mesh / STEP file can't be what it says (null: it looks right). */
|
||||
function unreadable(bytes: Uint8Array, format: "step" | "stl"): string | null {
|
||||
if (format === "step") {
|
||||
const head = new TextDecoder().decode(bytes.subarray(0, 4096));
|
||||
if (!/ISO-10303-21/.test(head)) return "it isn't a STEP file";
|
||||
if (!new TextDecoder().decode(bytes).includes("DATA;")) return "the file is damaged (it has no shapes in it)";
|
||||
return null;
|
||||
}
|
||||
// Binary STL: 80 bytes, a triangle count, 50 bytes per triangle.
|
||||
if (bytes.length >= 84) {
|
||||
const n = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(80, true);
|
||||
if (n > 0 && 84 + n * 50 === bytes.length) return null;
|
||||
}
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
if (/\bfacet\b/i.test(text) && /\bvertex\b/i.test(text)) return null;
|
||||
return bytes.length ? "it isn't an STL file, or it is damaged" : "the file is empty";
|
||||
}
|
||||
|
||||
export async function insertFile(app: AppContext): Promise<void> {
|
||||
const file = await pickFile(".step,.stp,.stl,.obj,.dxf,.svg,.dwg,.super,.tessel");
|
||||
const file = await pickFile(".step,.stp,.stl,.obj,.3mf,.dxf,.svg,.dwg,.super,.tessel");
|
||||
if (!file) return;
|
||||
const ext = file.name.split(".").pop()!.toLowerCase();
|
||||
try {
|
||||
@@ -45,17 +77,25 @@ export async function insertFile(app: AppContext): Promise<void> {
|
||||
return;
|
||||
}
|
||||
if (ext === "super" || ext === "tessel") {
|
||||
insertProject(app, migrate(JSON.parse(await file.text())).features, file.name);
|
||||
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") {
|
||||
bytes = objToStl(new TextDecoder().decode(bytes));
|
||||
format = "stl";
|
||||
}
|
||||
// 3MF: the exact model packed in it (ours), else its meshes.
|
||||
if (ext === "3mf") ({ format, bytes } = await read3mf(bytes));
|
||||
// A damaged or wrong file stops here, not as a failed step in History
|
||||
// (that kept the broken file in the project).
|
||||
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);
|
||||
@@ -76,14 +116,32 @@ function insertProject(app: AppContext, features: Feature[], name: string): void
|
||||
export async function insertImage(app: AppContext, plane: PlaneDef = GROUND): Promise<ImageFeature | null> {
|
||||
const file = await pickFile("image/*");
|
||||
if (!file) return null;
|
||||
const src = await new Promise<string>((resolve) => {
|
||||
let src = await new Promise<string>((resolve) => {
|
||||
const r = new FileReader();
|
||||
r.onload = () => resolve(r.result as string);
|
||||
r.readAsDataURL(file);
|
||||
});
|
||||
const img = new Image();
|
||||
img.src = src;
|
||||
await img.decode();
|
||||
try {
|
||||
await img.decode();
|
||||
} catch {
|
||||
app.ui.toast(`${file.name} can't be shown here - save it as JPG or PNG first (an iPhone's HEIC photos too)`, "error");
|
||||
return null;
|
||||
}
|
||||
// A phone photo (4000 px, 12 MB) kept whole went into the project and was
|
||||
// saved again on every change, and wider than a phone can draw (4096 px):
|
||||
// 2048 px across is plenty to trace over.
|
||||
const MAX = 2048;
|
||||
const k = Math.min(1, MAX / Math.max(img.width, img.height));
|
||||
if (k < 1 || file.size > 2e6) {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = Math.round(img.width * k);
|
||||
c.height = Math.round(img.height * k);
|
||||
c.getContext("2d")!.drawImage(img, 0, 0, c.width, c.height);
|
||||
// PNG keeps see-through parts (a logo); a photo is smaller as JPEG.
|
||||
src = file.type === "image/png" ? c.toDataURL("image/png") : c.toDataURL("image/jpeg", 0.85);
|
||||
}
|
||||
const width = 100;
|
||||
const f: ImageFeature = { ...app.store.newIdentity("image"), type: "image", plane, src, width, height: (width * img.height) / img.width, opacity: 0.8 };
|
||||
app.store.add(f);
|
||||
@@ -91,29 +149,70 @@ export async function insertImage(app: AppContext, plane: PlaneDef = GROUND): Pr
|
||||
return f;
|
||||
}
|
||||
|
||||
/** Create a named variable (optionally from a field's current value); returns its name. */
|
||||
/**
|
||||
* Create a named variable (optionally from a field's current value); returns
|
||||
* its name. "Add Another" at the top makes it and opens a fresh one (a window
|
||||
* needs twenty: the dialog had to be reopened from the card each time) - the
|
||||
* name returned is still the first one's, the one made from the field's value.
|
||||
*/
|
||||
export async function createVariable(app: AppContext, value = ""): Promise<string | null> {
|
||||
let first: string | null = null;
|
||||
let name = "";
|
||||
for (;;) {
|
||||
const r = await createOne(app, name, value);
|
||||
first ??= r.made;
|
||||
// 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];
|
||||
}
|
||||
}
|
||||
|
||||
async function createOne(app: AppContext, name: string, value: string): Promise<{ made: string | null; another: boolean; typed: { name: string; expr: string } }> {
|
||||
const list = app.store.doc.variables;
|
||||
const note = list.length ? `Existing: ${list.map((v) => `${v.name} = ${v.expr}`).join(", ")}` : "Use variables in any field, e.g. width*2 or wall + 1mm.";
|
||||
const v = await app.ui.dialog("Create Variable", [
|
||||
{ key: "name", label: "Name", value: "", placeholder: "width" },
|
||||
{ key: "name", label: "Name", value: name, placeholder: "width" },
|
||||
{ key: "expr", label: "Value", value, placeholder: "40 or 1.5in or depth/2" },
|
||||
], note);
|
||||
if (!v) return null;
|
||||
], note, { label: "Add Another", icon: "variableNew" });
|
||||
if (!v) return { made: null, another: false, typed: { name: "", expr: "" } };
|
||||
return { made: makeVariable(app, list, v), another: !!v[DIALOG_ACTION], typed: { name: v.name, expr: v.expr } };
|
||||
}
|
||||
|
||||
function makeVariable(app: AppContext, list: AppContext["store"]["doc"]["variables"], v: Record<string, string>): string | null {
|
||||
const name = v.name.trim();
|
||||
if (!/^[a-z_][a-z0-9_]*$/i.test(name) || /^(mm|cm|m|in|ft)$/i.test(name)) {
|
||||
app.ui.toast("Names use letters, digits and _ (not starting with a digit, not a unit)", "error");
|
||||
// (A variable called sin or pi hid the function: sin(30) stopped working.)
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -138,26 +237,80 @@ export async function editVariables(app: AppContext): Promise<void> {
|
||||
// Shown without the unit in use ("220"): a plain number keeps the unit it had.
|
||||
const next = list.filter((x) => v[x.name]?.trim()).map((x) => ({ name: x.name, expr: withUnitOf(v[x.name], x.expr) }));
|
||||
setVariables(next);
|
||||
const bad = next.find((x) => evaluate(x.expr) === null);
|
||||
// (An angle - "30 deg" - is a value too: it was refused as a length.)
|
||||
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");
|
||||
}
|
||||
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));
|
||||
// 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);
|
||||
// (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++);
|
||||
// (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"}`);
|
||||
}
|
||||
if (!v[DIALOG_ACTION]) return;
|
||||
await createVariable(app);
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
// DXF of a drawing sheet (for CAD programs): the sheet's SVG read back and
|
||||
// written as AutoCAD R12 DXF, millimetres, y up. Lines, arcs and circles stay
|
||||
// exact; text stays text; arrowheads are solids; the hatching of a section is
|
||||
// written out as lines; a detail view is cut to its circle. Layers by kind of
|
||||
// line: VISIBLE, THIN (dimensions, the frame, hatching), HIDDEN (dashed),
|
||||
// CENTER (centrelines), TEXT.
|
||||
|
||||
type M = [number, number, number, number, number, number];
|
||||
type P = [number, number];
|
||||
|
||||
const n = (v: number) => (Math.abs(v) < 1e-9 ? "0" : String(Math.round(v * 1e5) / 1e5));
|
||||
const deg = (r: number) => ((((r * 180) / Math.PI) % 360) + 360) % 360;
|
||||
const mul = (a: M, b: M): M => [a[0] * b[0] + a[2] * b[1], a[1] * b[0] + a[3] * b[1], a[0] * b[2] + a[2] * b[3], a[1] * b[2] + a[3] * b[3], a[0] * b[4] + a[2] * b[5] + a[4], a[1] * b[4] + a[3] * b[5] + a[5]];
|
||||
const apply = (m: M, p: P): P => [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]];
|
||||
const ID: M = [1, 0, 0, 1, 0, 0];
|
||||
|
||||
/** A transform="…" (rotate and translate, as the sheet writes them). */
|
||||
function transformOf(t: string | undefined): M {
|
||||
let m = ID;
|
||||
if (!t) return m;
|
||||
for (const [, k, args] of t.matchAll(/(rotate|translate|matrix|scale)\(([^)]*)\)/g)) {
|
||||
const a = args.split(/[\s,]+/).filter(Boolean).map(Number);
|
||||
if (k === "translate") m = mul(m, [1, 0, 0, 1, a[0] ?? 0, a[1] ?? 0]);
|
||||
else if (k === "scale") m = mul(m, [a[0], 0, 0, a[1] ?? a[0], 0, 0]);
|
||||
else if (k === "matrix") m = mul(m, a as M);
|
||||
else {
|
||||
const r = ((a[0] ?? 0) * Math.PI) / 180;
|
||||
const [cx, cy] = [a[1] ?? 0, a[2] ?? 0];
|
||||
m = mul(m, mul([1, 0, 0, 1, cx, cy], mul([Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0], [1, 0, 0, 1, -cx, -cy])));
|
||||
}
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
const unescape = (s: string) =>
|
||||
s
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'|'/g, "'")
|
||||
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
|
||||
.replace(/&/g, "&");
|
||||
|
||||
/** Text as R12 writes it: Ø ± ° as its codes, other letters past ASCII as \U+XXXX. */
|
||||
const dxfText = (s: string) =>
|
||||
s.replace(/[^\x20-\x7e]/gu, (c) => (c === "Ø" || c === "ø" || c === "⌀" ? "%%c" : c === "±" ? "%%p" : c === "°" ? "%%d" : `\\U+${c.codePointAt(0)!.toString(16).toUpperCase().padStart(4, "0")}`));
|
||||
|
||||
interface Style {
|
||||
stroke: string;
|
||||
width: number;
|
||||
dash: string;
|
||||
fill: string;
|
||||
m: M;
|
||||
/** Cut to this circle (a detail view). */
|
||||
clip?: { c: P; r: number };
|
||||
/** Filled with this hatch (its angle, degrees). */
|
||||
hatch?: number;
|
||||
}
|
||||
|
||||
/** A segment a→b cut to a circle: the parts inside. */
|
||||
function clipToCircle(a: P, b: P, c: P, r: number): [P, P][] {
|
||||
const d: P = [b[0] - a[0], b[1] - a[1]];
|
||||
const f: P = [a[0] - c[0], a[1] - c[1]];
|
||||
const A = d[0] * d[0] + d[1] * d[1];
|
||||
if (A < 1e-18) return [];
|
||||
const B = 2 * (f[0] * d[0] + f[1] * d[1]);
|
||||
const C = f[0] * f[0] + f[1] * f[1] - r * r;
|
||||
const disc = B * B - 4 * A * C;
|
||||
if (disc <= 0) return [];
|
||||
const s = Math.sqrt(disc);
|
||||
const t0 = Math.max(0, (-B - s) / (2 * A));
|
||||
const t1 = Math.min(1, (-B + s) / (2 * A));
|
||||
if (t1 <= t0) return [];
|
||||
return [
|
||||
[
|
||||
[a[0] + d[0] * t0, a[1] + d[1] * t0],
|
||||
[a[0] + d[0] * t1, a[1] + d[1] * t1],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** The sheet (its SVG, mm, y down, `H` tall) as a DXF file's text. */
|
||||
export function sheetToDXF(svg: string): string {
|
||||
const vb = /viewBox="([^"]+)"/.exec(svg)?.[1].split(/\s+/).map(Number) ?? [0, 0, 420, 297];
|
||||
const H = vb[3];
|
||||
const flip = (p: P): P => [p[0], H - p[1]];
|
||||
const out: string[] = [];
|
||||
const head = (type: string, layer: string) => out.push("0", type, "8", layer);
|
||||
const layerOf = (s: Style): string | null => {
|
||||
if (s.dash === "3 1") return "HIDDEN";
|
||||
if (s.dash && s.dash !== "none") return /^(8 |1\.5 1 6)/.test(s.dash) ? "CENTER" : null;
|
||||
return s.width >= 0.4 ? "VISIBLE" : "THIN";
|
||||
};
|
||||
const line = (a: P, b: P, s: Style, layer: string) => {
|
||||
const segs: [P, P][] = s.clip ? clipToCircle(a, b, s.clip.c, s.clip.r) : [[a, b]];
|
||||
for (const [p, q] of segs) {
|
||||
const [P1, P2] = [flip(apply(s.m, p)), flip(apply(s.m, q))];
|
||||
if (Math.hypot(P2[0] - P1[0], P2[1] - P1[1]) < 1e-6) continue;
|
||||
head("LINE", layer);
|
||||
out.push("10", n(P1[0]), "20", n(P1[1]), "30", "0", "11", n(P2[0]), "21", n(P2[1]), "31", "0");
|
||||
}
|
||||
};
|
||||
/** A circle's arc from angle a0 sweeping by `sweep` (SVG's angles, y down), or the whole circle. */
|
||||
const arc = (c: P, r: number, a0: number, sweep: number, s: Style, layer: string) => {
|
||||
if (s.clip) {
|
||||
// Cut to a detail's circle: as short lines.
|
||||
const k = Math.max(8, Math.ceil((Math.abs(sweep) / (Math.PI * 2)) * 96));
|
||||
let prev: P = [c[0] + r * Math.cos(a0), c[1] + r * Math.sin(a0)];
|
||||
for (let i = 1; i <= k; i++) {
|
||||
const t = a0 + (sweep * i) / k;
|
||||
const q: P = [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)];
|
||||
line(prev, q, s, layer);
|
||||
prev = q;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const C = flip(apply(s.m, c));
|
||||
const rot = Math.atan2(s.m[1], s.m[0]);
|
||||
if (Math.abs(Math.abs(sweep) - Math.PI * 2) < 1e-9) {
|
||||
head("CIRCLE", layer);
|
||||
out.push("10", n(C[0]), "20", n(C[1]), "30", "0", "40", n(r));
|
||||
return;
|
||||
}
|
||||
// y flipped: SVG's angle t is -t; the DXF arc runs counter-clockwise.
|
||||
const s0 = -(a0 + rot);
|
||||
const s1 = -(a0 + sweep + rot);
|
||||
const [from, to] = sweep >= 0 ? [s1, s0] : [s0, s1];
|
||||
head("ARC", layer);
|
||||
out.push("10", n(C[0]), "20", n(C[1]), "30", "0", "40", n(r), "50", n(deg(from)), "51", n(deg(to)));
|
||||
};
|
||||
const solid = (pts: P[], s: Style, layer: string) => {
|
||||
const q = pts.map((p) => flip(apply(s.m, p)));
|
||||
const c = [q[0], q[1], q[q.length - 1], q.length > 3 ? q[2] : q[q.length - 1]];
|
||||
head("SOLID", layer);
|
||||
out.push("10", n(c[0][0]), "20", n(c[0][1]), "30", "0", "11", n(c[1][0]), "21", n(c[1][1]), "31", "0", "12", n(c[2][0]), "22", n(c[2][1]), "32", "0", "13", n(c[3][0]), "23", n(c[3][1]), "33", "0");
|
||||
};
|
||||
/** Hatch lines inside the loops (even-odd), every 2.5 mm at `angle` degrees from the vertical, as the sheet's pattern. */
|
||||
const hatchLines = (loops: P[][], angle: number, s: Style) => {
|
||||
const r = (angle * Math.PI) / 180;
|
||||
// In the pattern's own frame the lines are x = 2.5k.
|
||||
const toPat = (p: P): P => [p[0] * Math.cos(r) + p[1] * Math.sin(r), -p[0] * Math.sin(r) + p[1] * Math.cos(r)];
|
||||
const fromPat = (p: P): P => [p[0] * Math.cos(r) - p[1] * Math.sin(r), p[0] * Math.sin(r) + p[1] * Math.cos(r)];
|
||||
const edges: [P, P][] = [];
|
||||
for (const l of loops) for (let i = 0; i < l.length; i++) edges.push([toPat(l[i]), toPat(l[(i + 1) % l.length])]);
|
||||
if (!edges.length) return;
|
||||
const xs = edges.flatMap(([a, b]) => [a[0], b[0]]);
|
||||
for (let k = Math.ceil(Math.min(...xs) / 2.5); k * 2.5 <= Math.max(...xs); k++) {
|
||||
const x = k * 2.5;
|
||||
const ys: number[] = [];
|
||||
for (const [a, b] of edges) if (a[0] <= x !== b[0] <= x) ys.push(a[1] + ((x - a[0]) / (b[0] - a[0])) * (b[1] - a[1]));
|
||||
ys.sort((p, q) => p - q);
|
||||
for (let i = 0; i + 1 < ys.length; i += 2) line(fromPat([x, ys[i]]), fromPat([x, ys[i + 1]]), s, "THIN");
|
||||
}
|
||||
};
|
||||
const pathOf = (d: string, s: Style) => {
|
||||
const layer = s.hatch === undefined ? layerOf(s) : "THIN";
|
||||
const filled = s.fill !== "none" && s.fill !== "transparent" && !s.fill.startsWith("url(");
|
||||
const stroked = s.stroke !== "none";
|
||||
if (!layer || (!stroked && !filled && s.hatch === undefined)) return;
|
||||
const loops: P[][] = [];
|
||||
let cur: P = [0, 0];
|
||||
let start: P = [0, 0];
|
||||
let loop: P[] = [];
|
||||
const toks = d.match(/[MLHVAZmlhvaz]|-?(?:\d+\.?\d*|\.\d+)(?:e-?\d+)?/g) ?? [];
|
||||
let i = 0;
|
||||
let cmd = "";
|
||||
const num = () => Number(toks[i++]);
|
||||
const close = () => {
|
||||
if (loop.length > 1) loops.push(loop);
|
||||
loop = [];
|
||||
};
|
||||
while (i < toks.length) {
|
||||
if (/[A-Za-z]/.test(toks[i])) cmd = toks[i++];
|
||||
const C = cmd.toUpperCase();
|
||||
if (C === "Z") {
|
||||
if (stroked && s.hatch === undefined) line(cur, start, s, layer);
|
||||
cur = start;
|
||||
close();
|
||||
continue;
|
||||
}
|
||||
if (C === "M") {
|
||||
close();
|
||||
cur = start = [num(), num()];
|
||||
loop = [cur];
|
||||
cmd = cmd === "m" ? "l" : "L";
|
||||
continue;
|
||||
}
|
||||
let next: P;
|
||||
if (C === "L") next = [num(), num()];
|
||||
else if (C === "H") next = [num(), cur[1]];
|
||||
else if (C === "V") next = [cur[0], num()];
|
||||
else if (C === "A") {
|
||||
const rx = num();
|
||||
num();
|
||||
num();
|
||||
const large = num();
|
||||
const sweepF = num();
|
||||
next = [num(), num()];
|
||||
// The circle through cur and next (SVG's endpoint form, rx = ry).
|
||||
const dx = (cur[0] - next[0]) / 2;
|
||||
const dy = (cur[1] - next[1]) / 2;
|
||||
const r = Math.max(rx, Math.hypot(dx, dy));
|
||||
const h = Math.sqrt(Math.max(0, r * r - dx * dx - dy * dy)) / Math.hypot(dx, dy || 1e-30);
|
||||
const sg = large === sweepF ? 1 : -1;
|
||||
const c: P = [(cur[0] + next[0]) / 2 + sg * h * -dy, (cur[1] + next[1]) / 2 + sg * h * dx];
|
||||
const a0 = Math.atan2(cur[1] - c[1], cur[0] - c[0]);
|
||||
let sw = Math.atan2(next[1] - c[1], next[0] - c[0]) - a0;
|
||||
if (sweepF && sw < 0) sw += Math.PI * 2;
|
||||
if (!sweepF && sw > 0) sw -= Math.PI * 2;
|
||||
if (stroked && s.hatch === undefined) arc(c, r, a0, sw, s, layer);
|
||||
for (let k = 1; k <= 12; k++) loop.push([c[0] + r * Math.cos(a0 + (sw * k) / 12), c[1] + r * Math.sin(a0 + (sw * k) / 12)]);
|
||||
cur = next;
|
||||
continue;
|
||||
} else {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (stroked && s.hatch === undefined) line(cur, next, s, layer);
|
||||
loop.push(next);
|
||||
cur = next;
|
||||
}
|
||||
close();
|
||||
if (s.hatch !== undefined) return hatchLines(loops, s.hatch, s);
|
||||
// A small filled shape, no outline (an arrowhead): a solid.
|
||||
if (filled && !stroked) for (const l of loops) if (l.length >= 3 && l.length <= 4) solid(l, s, "THIN");
|
||||
};
|
||||
|
||||
// ---- Walk the elements, styles and transforms handed down through groups.
|
||||
const clips = new Map<string, { c: P; r: number }>();
|
||||
for (const [, id, body] of svg.matchAll(/<clipPath id="([^"]+)">(.*?)<\/clipPath>/gs)) {
|
||||
const c = /<circle cx="([-\d.]+)" cy="([-\d.]+)" r="([-\d.]+)"/.exec(body);
|
||||
if (c) clips.set(id, { c: [Number(c[1]), Number(c[2])], r: Number(c[3]) });
|
||||
}
|
||||
const hatches = new Map<string, number>();
|
||||
for (const [, id, a] of svg.matchAll(/<pattern id="([^"]+)"[^>]*patternTransform="rotate\(([-\d.]+)\)"/g)) hatches.set(id, Number(a));
|
||||
const body = svg.replace(/<defs>.*?<\/defs>/gs, "").replace(/<clipPath[^>]*>.*?<\/clipPath>/gs, "").replace(/<pattern[^>]*>.*?<\/pattern>/gs, "");
|
||||
const stack: Style[] = [{ stroke: "none", width: 0.25, dash: "", fill: "#000", m: ID }];
|
||||
const attrs = (s: string) => Object.fromEntries([...s.matchAll(/([\w:-]+)="([^"]*)"/g)].map(([, k, v]) => [k, v]));
|
||||
const styled = (a: Record<string, string>, up: Style): Style => {
|
||||
const s: Style = {
|
||||
stroke: a.stroke ?? up.stroke,
|
||||
width: a["stroke-width"] !== undefined ? Number(a["stroke-width"]) : up.width,
|
||||
dash: a["stroke-dasharray"] ?? up.dash,
|
||||
fill: a.fill ?? up.fill,
|
||||
m: a.transform ? mul(up.m, transformOf(a.transform)) : up.m,
|
||||
clip: up.clip,
|
||||
hatch: up.hatch,
|
||||
};
|
||||
const cp = /url\(#([^)]+)\)/.exec(a["clip-path"] ?? "")?.[1];
|
||||
if (cp && clips.has(cp)) s.clip = clips.get(cp);
|
||||
const hp = /url\(#([^)]+)\)/.exec(a.fill ?? "")?.[1];
|
||||
s.hatch = hp && hatches.has(hp) ? hatches.get(hp) : undefined;
|
||||
return s;
|
||||
};
|
||||
const tagRe = /<(\/?)([a-zA-Z]+)([^>]*?)(\/?)>|([^<]+)/g;
|
||||
let textOf: { a: Record<string, string>; s: Style; t: string } | null = null;
|
||||
for (const m of body.matchAll(tagRe)) {
|
||||
const [, closing, tag, rest, self, txt] = m;
|
||||
if (txt !== undefined) {
|
||||
if (textOf) textOf.t += txt;
|
||||
continue;
|
||||
}
|
||||
if (closing) {
|
||||
if (tag === "g") stack.length > 1 && stack.pop();
|
||||
if (tag === "text" && textOf) {
|
||||
const { a, s, t } = textOf;
|
||||
textOf = null;
|
||||
const str = unescape(t).trim();
|
||||
if (!str) continue;
|
||||
const p = flip(apply(s.m, [Number(a.x ?? 0), Number(a.y ?? 0)]));
|
||||
const size = Number(a["font-size"] ?? 3.5);
|
||||
const rot = -deg(Math.atan2(s.m[1], s.m[0]));
|
||||
const just = a["text-anchor"] === "middle" ? 1 : a["text-anchor"] === "end" ? 2 : 0;
|
||||
head("TEXT", "TEXT");
|
||||
out.push("10", n(p[0]), "20", n(p[1]), "30", "0", "40", n(size * 0.7), "1", dxfText(str), "50", n(((rot % 360) + 360) % 360));
|
||||
if (just) out.push("72", String(just), "11", n(p[0]), "21", n(p[1]), "31", "0");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const a = attrs(rest);
|
||||
const up = stack[stack.length - 1];
|
||||
if (tag === "g") {
|
||||
const s = styled(a, up);
|
||||
if (!self) stack.push(s);
|
||||
continue;
|
||||
}
|
||||
if (tag === "text") {
|
||||
textOf = { a, s: styled(a, up), t: "" };
|
||||
continue;
|
||||
}
|
||||
const s = styled(a, up);
|
||||
if (tag === "path" && a.d) pathOf(a.d, s);
|
||||
else if (tag === "line") pathOf(`M${a.x1} ${a.y1}L${a.x2} ${a.y2}`, s);
|
||||
else if (tag === "rect" && s.stroke !== "none") {
|
||||
const [x, y, w, h] = [Number(a.x ?? 0), Number(a.y ?? 0), Number(a.width), Number(a.height)];
|
||||
pathOf(`M${x} ${y}L${x + w} ${y}L${x + w} ${y + h}L${x} ${y + h}Z`, { ...s, fill: "none" });
|
||||
} else if (tag === "circle") {
|
||||
const layer = layerOf(s);
|
||||
const filled = s.fill !== "none" && s.fill !== "transparent" && s.fill !== "#fff";
|
||||
if (layer && (s.stroke !== "none" || filled)) arc([Number(a.cx), Number(a.cy)], Number(a.r), 0, Math.PI * 2, s, s.stroke !== "none" ? layer : "THIN");
|
||||
}
|
||||
}
|
||||
|
||||
const ltype = (name: string, desc: string, parts: number[]) => ["0", "LTYPE", "2", name, "70", "0", "3", desc, "72", "65", "73", String(parts.length), "40", n(parts.reduce((x, y) => x + Math.abs(y), 0)), ...parts.flatMap((v) => ["49", n(v)])];
|
||||
const layer = (name: string, color: number, lt: string) => ["0", "LAYER", "2", name, "70", "0", "62", String(color), "6", lt];
|
||||
return [
|
||||
"0", "SECTION", "2", "HEADER",
|
||||
"9", "$ACADVER", "1", "AC1009",
|
||||
"9", "$INSUNITS", "70", "4",
|
||||
"9", "$MEASUREMENT", "70", "1",
|
||||
"9", "$EXTMIN", "10", n(vb[0]), "20", "0", "30", "0",
|
||||
"9", "$EXTMAX", "10", n(vb[0] + vb[2]), "20", n(H), "30", "0",
|
||||
"0", "ENDSEC",
|
||||
"0", "SECTION", "2", "TABLES",
|
||||
"0", "TABLE", "2", "LTYPE", "70", "3",
|
||||
...ltype("CONTINUOUS", "Solid line", []),
|
||||
...ltype("DASHED", "Dashed __ __ __", [3, -1]),
|
||||
...ltype("CENTER", "Center ____ _ ____", [8, -1.5, 1.5, -1.5]),
|
||||
"0", "ENDTAB",
|
||||
"0", "TABLE", "2", "LAYER", "70", "6",
|
||||
...layer("0", 7, "CONTINUOUS"),
|
||||
...layer("VISIBLE", 7, "CONTINUOUS"),
|
||||
...layer("THIN", 8, "CONTINUOUS"),
|
||||
...layer("HIDDEN", 8, "DASHED"),
|
||||
...layer("CENTER", 1, "CENTER"),
|
||||
...layer("TEXT", 7, "CONTINUOUS"),
|
||||
"0", "ENDTAB",
|
||||
"0", "ENDSEC",
|
||||
"0", "SECTION", "2", "ENTITIES",
|
||||
...out,
|
||||
"0", "ENDSEC",
|
||||
"0", "EOF",
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
@@ -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">');
|
||||
|
||||
@@ -1,5 +1,15 @@
|
||||
import type { Feature } from "../doc/types";
|
||||
import type { Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
|
||||
import type { BodyHealth, BodyMesh, BodyProps, ProjectedView, ViewSpec, Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
|
||||
|
||||
/**
|
||||
* The steps as the engine needs them: a reference image without its picture
|
||||
* (megabytes the engine never reads, copied across and hashed on every rebuild
|
||||
* - every step of a drag). The same for every kind of call, so the engine sees
|
||||
* the same steps each time.
|
||||
*/
|
||||
function lean(features: Feature[]): Feature[] {
|
||||
return features.some((f) => f.type === "image" && f.src) ? features.map((f) => (f.type === "image" ? { ...f, src: "" } : f)) : features;
|
||||
}
|
||||
|
||||
/** Promise-based wrapper around the kernel worker. */
|
||||
export class KernelClient {
|
||||
@@ -12,29 +22,120 @@ export class KernelClient {
|
||||
|
||||
// Coalesce regenerations: while one runs, only the most recent request waits.
|
||||
private regenRunning = false;
|
||||
private regenQueued: { features: Feature[]; resolve: (r: RegenResult | null) => void } | null = null;
|
||||
private regenQueued: { features: Feature[]; saved: boolean; resolve: (r: RegenResult | null) => void } | null = null;
|
||||
/** The last answer's meshes by key: the worker sends a mesh once, then just its key. */
|
||||
private meshes = new Map<number, BodyMesh>();
|
||||
|
||||
/**
|
||||
* The engine (OpenCascade) never hands memory back, and some of its
|
||||
* operations leak (a union with a freeform body: ~10 MB each time). Past
|
||||
* this much a spare engine is started, brought up to date in the
|
||||
* background, and swapped in while nothing is running - a phone would
|
||||
* otherwise run out after a while of editing.
|
||||
*/
|
||||
static RECYCLE_MB = 500;
|
||||
private last: { features: Feature[]; saved: Feature[] | null } = { features: [], saved: null };
|
||||
/**
|
||||
* Some steps cost the engine tens of MB each time they are rebuilt (memory
|
||||
* it never gets back): dragging one of their sizes, a rebuild per move,
|
||||
* would fill it in seconds. After a rebuild seen to cost a lot, the next
|
||||
* previews wait a moment - fewer of them, the drag's last one always shown.
|
||||
*/
|
||||
private memoryMB = 0;
|
||||
/** What the last few rebuilds cost, each (MB; the engine's memory grows in jumps, so one rebuild's own cost says little). */
|
||||
private costMB = 0;
|
||||
private restUntil = 0;
|
||||
/** How long previews rest after a rebuild that cost `mb` of the engine's memory (ms). */
|
||||
static restFor(mb: number): number {
|
||||
return mb < 4 ? 0 : Math.min(400, mb * 8);
|
||||
}
|
||||
private spare: { worker: Worker; bodies: BodyMesh[] | null } | null = null;
|
||||
|
||||
constructor() {
|
||||
this.start();
|
||||
}
|
||||
|
||||
private handler = (e: MessageEvent<Envelope<Response>>) => {
|
||||
const cb = this.pending.get(e.data.id);
|
||||
this.pending.delete(e.data.id);
|
||||
cb?.(e.data.msg);
|
||||
};
|
||||
|
||||
private start(): void {
|
||||
// A fresh worker sends every mesh again.
|
||||
this.meshes = new Map();
|
||||
this.worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
|
||||
this.worker.onmessage = (e: MessageEvent<Envelope<Response>>) => {
|
||||
const cb = this.pending.get(e.data.id);
|
||||
this.pending.delete(e.data.id);
|
||||
cb?.(e.data.msg);
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/** A spare engine, given the last saved project (and the last preview): it's ready to take over. */
|
||||
private warmSpare(): void {
|
||||
if (this.spare) return;
|
||||
const worker = new Worker(new URL("./worker.ts", import.meta.url), { type: "module" });
|
||||
const spare: { worker: Worker; bodies: BodyMesh[] | null } = { worker, bodies: null };
|
||||
this.spare = spare;
|
||||
let n = 0;
|
||||
const waiting = new Map<number, (r: Response) => void>();
|
||||
worker.onmessage = (e: MessageEvent<Envelope<Response>>) => waiting.get(e.data.id)?.(e.data.msg);
|
||||
const ask = (msg: Request) =>
|
||||
new Promise<Response>((resolve) => {
|
||||
waiting.set(++n, resolve);
|
||||
worker.postMessage({ id: n, msg } satisfies Envelope<Request>);
|
||||
});
|
||||
const { features, saved } = this.last;
|
||||
(async () => {
|
||||
if ((await ask({ type: "init" })).type !== "ready") throw new Error("init");
|
||||
const got = new Map<number, BodyMesh>();
|
||||
const regen = async (fs: Feature[], asSaved: boolean) => {
|
||||
const r = await ask({ type: "regenerate", features: lean(fs), saved: asSaved });
|
||||
if (r.type !== "regenerated") throw new Error("regenerate");
|
||||
const bodies = r.result.bodies.map((b) => ((b as { same?: boolean }).same ? got.get(b.key)! : b));
|
||||
for (const b of bodies) got.set(b.key, b);
|
||||
return bodies;
|
||||
};
|
||||
let bodies = saved ? await regen(saved, true) : [];
|
||||
if (!saved || features !== saved) bodies = await regen(features, false);
|
||||
if (this.spare !== spare) throw new Error("stopped");
|
||||
spare.bodies = bodies;
|
||||
this.swapIfIdle();
|
||||
})().catch(() => {
|
||||
worker.terminate();
|
||||
if (this.spare === spare) this.spare = null;
|
||||
});
|
||||
}
|
||||
|
||||
/** The spare engine takes over, if it's ready and nothing is running. */
|
||||
private swapIfIdle(): void {
|
||||
const s = this.spare;
|
||||
if (!s?.bodies || this.regenRunning || this.pending.size) return;
|
||||
this.spare = null;
|
||||
this.worker.terminate();
|
||||
this.worker = s.worker;
|
||||
this.worker.onmessage = this.handler;
|
||||
this.ready = Promise.resolve();
|
||||
// It sends meshes it already sent (to us, while warming) as keys only.
|
||||
this.meshes = new Map(s.bodies.map((b) => [b.key, b]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop whatever the engine is working on (it can't be interrupted mid-way:
|
||||
* the worker is thrown away and a fresh one started). Waiting calls end empty.
|
||||
*/
|
||||
stop(): void {
|
||||
this.spare?.worker.terminate();
|
||||
this.spare = null;
|
||||
this.worker.terminate();
|
||||
const waiting = [...this.pending.values()];
|
||||
this.pending.clear();
|
||||
@@ -49,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++;
|
||||
@@ -66,37 +173,93 @@ export class KernelClient {
|
||||
* Rebuild geometry. If calls arrive faster than the kernel can answer, the
|
||||
* intermediate ones resolve with null (they were superseded).
|
||||
*/
|
||||
regenerate(features: Feature[]): Promise<RegenResult | null> {
|
||||
regenerate(features: Feature[], saved = false): Promise<RegenResult | null> {
|
||||
return new Promise((resolve) => {
|
||||
if (this.regenRunning) {
|
||||
this.regenQueued?.resolve(null);
|
||||
this.regenQueued = { features, resolve };
|
||||
this.regenQueued = { features, saved, resolve };
|
||||
return;
|
||||
}
|
||||
this.runRegen(features, resolve);
|
||||
this.runRegen(features, saved, resolve);
|
||||
});
|
||||
}
|
||||
|
||||
private async runRegen(features: Feature[], resolve: (r: RegenResult | null) => void) {
|
||||
/** `saved`: the project as saved (not a tool's preview) - the engine keeps its steps for Cancel. */
|
||||
private async runRegen(features: Feature[], saved: boolean, resolve: (r: RegenResult | null) => void) {
|
||||
this.regenRunning = true;
|
||||
await this.ready;
|
||||
this.running = features;
|
||||
this.last = { features, saved: saved ? features : this.last.saved };
|
||||
const worker = this.worker;
|
||||
const r = await this.call({ type: "regenerate", features });
|
||||
const r = await this.call({ type: "regenerate", features: lean(features), saved });
|
||||
// Stopped meanwhile: the fresh worker has its own queue.
|
||||
if (worker !== this.worker) return resolve(null);
|
||||
this.running = null;
|
||||
resolve(r.type === "regenerated" ? r.result : null);
|
||||
resolve(r.type === "regenerated" ? this.withMeshes(r.result) : null);
|
||||
if (r.type === "error") console.error(r.message);
|
||||
if (r.type === "regenerated" && r.result.memoryMB !== undefined) {
|
||||
// (A fresh engine starts small again: that isn't a rebuild giving memory back.)
|
||||
const cost = this.memoryMB ? Math.max(0, r.result.memoryMB - this.memoryMB) : 0;
|
||||
if (r.result.memoryMB < this.memoryMB) this.costMB = 0;
|
||||
this.memoryMB = r.result.memoryMB;
|
||||
this.costMB = this.costMB * 0.7 + cost * 0.3;
|
||||
this.restUntil = performance.now() + KernelClient.restFor(this.costMB);
|
||||
}
|
||||
// A preview waiting its turn rests first (whatever is asked meanwhile takes its place).
|
||||
const rest = this.restUntil - performance.now();
|
||||
if (this.regenQueued && !this.regenQueued.saved && rest > 0) {
|
||||
await new Promise((done) => setTimeout(done, rest));
|
||||
if (worker !== this.worker) return;
|
||||
}
|
||||
this.regenRunning = false;
|
||||
// A big engine: a spare is got ready (also in the middle of a drag, where
|
||||
// it used to wait for the drag to end), and takes over between two rebuilds.
|
||||
if (r.type === "regenerated" && (r.result.memoryMB ?? 0) > KernelClient.RECYCLE_MB) this.warmSpare();
|
||||
this.swapIfIdle();
|
||||
const q = this.regenQueued;
|
||||
this.regenQueued = null;
|
||||
if (q) this.runRegen(q.features, q.resolve);
|
||||
if (q) this.runRegen(q.features, q.saved, q.resolve);
|
||||
}
|
||||
|
||||
/** Meshes sent as their key only (unchanged bodies): the ones the page has. */
|
||||
private withMeshes(result: RegenResult): RegenResult {
|
||||
const bodies = result.bodies.map((b) => {
|
||||
if (!(b as { same?: boolean }).same) return b;
|
||||
const had = this.meshes.get(b.key)!;
|
||||
// (The same object when nothing about it changed: the view keeps what it drew.)
|
||||
return had.id === b.id && had.name === b.name ? had : { ...had, id: b.id, name: b.name };
|
||||
});
|
||||
this.meshes = new Map(bodies.map((b) => [b.key, b]));
|
||||
return { ...result, bodies };
|
||||
}
|
||||
|
||||
/** The bodies drawn in views, hidden lines found (for BIM drawings). */
|
||||
async drawing(features: Feature[], views: ViewSpec[], bodies?: string[]): Promise<ProjectedView[]> {
|
||||
await this.ready;
|
||||
const r = await this.call({ type: "drawing", features: lean(features), views, bodies });
|
||||
if (r.type === "drawing") return r.views;
|
||||
throw new Error(r.type === "error" ? r.message : "Could not draw the views");
|
||||
}
|
||||
|
||||
/** Each body's volume, area, centre of mass and box (for BIM). */
|
||||
async properties(features: Feature[]): Promise<BodyProps[]> {
|
||||
await this.ready;
|
||||
const r = await this.call({ type: "properties", features: lean(features) });
|
||||
if (r.type === "properties") return r.bodies;
|
||||
throw new Error(r.type === "error" ? r.message : "Could not measure the bodies");
|
||||
}
|
||||
|
||||
/** Each body's health: valid, closed, solids, faces, volume (the console's sg.health()). */
|
||||
async health(features: Feature[]): Promise<BodyHealth[]> {
|
||||
await this.ready;
|
||||
const r = await this.call({ type: "health", features: lean(features) });
|
||||
if (r.type === "health") return r.bodies;
|
||||
throw new Error(r.type === "error" ? r.message : "Could not check the bodies");
|
||||
}
|
||||
|
||||
async export(features: Feature[], format: ExportFormat, bodies?: string[]): Promise<Blob> {
|
||||
await this.ready;
|
||||
const r = await this.call({ type: "export", features, format, bodies });
|
||||
const r = await this.call({ type: "export", features: lean(features), format, bodies });
|
||||
if (r.type === "exported") return r.blob;
|
||||
throw new Error(r.type === "error" ? r.message : "Export failed");
|
||||
}
|
||||
|
||||
@@ -6,10 +6,14 @@
|
||||
// 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, measureVolume, cast, Vector, type Face, type Shape3D } from "replicad";
|
||||
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 } 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";
|
||||
|
||||
interface Cyl {
|
||||
c: Vec3;
|
||||
@@ -31,16 +35,67 @@ 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;
|
||||
/** Each step starts the sizes over: what a step builds mustn't depend on which steps were rebuilt before it. */
|
||||
export function sameSizesAgain(): void {
|
||||
jitter = 0;
|
||||
}
|
||||
const vary = (L: number) => L * (1 + 0.0137 * (jitter = (jitter + 1) % 37));
|
||||
|
||||
/** Solid on the positive side of a plane, big enough for `L`. */
|
||||
@@ -91,12 +146,8 @@ export function onFace(body: Shape3D, F: Face): { p: Vec3; n: Vec3 } {
|
||||
const p = tup(F.pointOnSurface(0.5, 0.5));
|
||||
return { p, n: norm(tup(F.normalAt(p))) };
|
||||
}
|
||||
let t = F.triangulation();
|
||||
if (!t || !t.trianglesIndexes.length) {
|
||||
body.mesh({ tolerance: sizeOf(body) * 1e-3, angularTolerance: 0.3 });
|
||||
t = F.triangulation();
|
||||
}
|
||||
if (t && t.trianglesIndexes.length) {
|
||||
const t = faceTriangles(F, sizeOf(body));
|
||||
if (t) {
|
||||
// Centroid of the biggest triangle: well inside the face.
|
||||
const v = (i: number): Vec3 => [t!.vertices[3 * i], t!.vertices[3 * i + 1], t!.vertices[3 * i + 2]];
|
||||
let best: Vec3 = v(0);
|
||||
@@ -109,7 +160,10 @@ export function onFace(body: Shape3D, F: Face): { p: Vec3; n: Vec3 } {
|
||||
best = scale(add(add(a, b), c), 1 / 3);
|
||||
}
|
||||
}
|
||||
return { p: best, n: norm(tup(F.normalAt(best))) };
|
||||
const n = norm(tup(F.normalAt(best)));
|
||||
// (The mesh's corners are kept to seven digits: the point is put back on the face's own plane.)
|
||||
const on = tup(F.pointOnSurface(0.5, 0.5));
|
||||
return { p: sub(best, scale(n, dot(sub(best, on), n))), n };
|
||||
}
|
||||
const p = tup(F.pointOnSurface(0.5, 0.5));
|
||||
return { p, n: norm(tup(F.normalAt(p))) };
|
||||
@@ -127,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
|
||||
@@ -143,6 +242,41 @@ function filletEnding(body: Shape3D, F: Face, g: Face, cy: Cyl): [PlaneDef, Plan
|
||||
return pls;
|
||||
}
|
||||
|
||||
/**
|
||||
* The plane a curved face g touches all along its one straight edge with F
|
||||
* (its normal the same the whole way: a curve pulled straight), else null.
|
||||
*/
|
||||
function tangentPlaneAlong(F: Face, g: Face): PlaneDef | null {
|
||||
const shared = g.edges.filter((e) => F.edges.some((fe) => fe.isSame(e)));
|
||||
if (shared.length !== 1 || shared[0].geomType !== "LINE") return null;
|
||||
const e = shared[0];
|
||||
try {
|
||||
const ns = [0, 0.5, 1].map((t) => norm(tup(g.normalAt(e.pointAt(t)))));
|
||||
if (ns.some((n) => dot(n, ns[0]) < 1 - 1e-9)) return null;
|
||||
const dir = norm(tup(e.tangentAt(0.5)));
|
||||
if (Math.abs(dot(dir, ns[0])) > 1e-6) return null;
|
||||
return { origin: tup(e.pointAt(0.5)), normal: ns[1], xDir: dir };
|
||||
} catch {
|
||||
return 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;
|
||||
@@ -153,12 +287,12 @@ function neighbours(body: Shape3D, F: Face): Face[] {
|
||||
* E: the region bounded by F's neighbours' extended surfaces, each on the side
|
||||
* that contains `q` (a point just inside the body under F). Bounded by a box.
|
||||
*/
|
||||
export function extendedRegion(body: Shape3D, F: Face, q: Vec3, L: number): Shape3D {
|
||||
return regionAround(body, F, neighbours(body, F), q, L);
|
||||
export function extendedRegion(body: Shape3D, F: Face, q: Vec3, L: number, part?: Vec3[]): Shape3D {
|
||||
return regionAround(body, F, neighbours(body, F), q, L, part);
|
||||
}
|
||||
|
||||
/** As extendedRegion, bounded by the given faces round F (those along one of its outlines). */
|
||||
function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number): Shape3D {
|
||||
function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number, part?: Vec3[]): Shape3D {
|
||||
const c = body.boundingBox.center as Vec3;
|
||||
// Bounding box, bigger than the other tools so no faces coincide with theirs.
|
||||
const big = () => halfSpace({ origin: sub(c, [0, 0, 1.5 * L]), xDir: [1, 0, 0], normal: [0, 0, 1] }, 3 * L);
|
||||
@@ -189,7 +323,43 @@ function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number): S
|
||||
const rel = sub(q, cy.c);
|
||||
const radial = len(sub(rel, scale(cy.a, dot(rel, cy.a))));
|
||||
(radial < cy.r ? keep : remove).push(infiniteCylinder(cy, cy.r, L));
|
||||
// A flat face ending on a round boss from one side (a lever's arm on its
|
||||
// hub): taking the boss out isn't enough, the arm's side faces carry on
|
||||
// past it and out the far side. The face lies all on one side of the
|
||||
// boss's axis: the region does too. (`part`: the piece of F it's for, one of F's cells.)
|
||||
if (radial >= cy.r && F.geomType === "PLANE") {
|
||||
const off = (p: Vec3) => {
|
||||
const r = sub(p, cy.c);
|
||||
return sub(r, scale(cy.a, dot(r, cy.a)));
|
||||
};
|
||||
const pts = part ?? F.edges.flatMap((e) => [0, 0.25, 0.5, 0.75].map((t) => tup(e.pointAt(t))));
|
||||
const d = off(scale(pts.reduce((a, b) => add(a, b), [0, 0, 0] as Vec3), 1 / pts.length));
|
||||
if (len(d) > cy.r * 1e-3) {
|
||||
const dn = norm(d);
|
||||
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
|
||||
// the flat faces round it, a heel's foot moved down ran off along the heel.
|
||||
const tangent = tangentPlaneAlong(F, g);
|
||||
if (tangent) {
|
||||
const side = dot(sub(q, tangent.origin), tangent.normal) < 0 ? scale(tangent.normal, -1) : tangent.normal;
|
||||
keep.push(halfSpace({ origin: tangent.origin, normal: side, xDir: xDirFor(side) }, L));
|
||||
continue;
|
||||
}
|
||||
// Any other surface (a twisted corner patch where a chamfer meets a
|
||||
// fillet, a lofted side) has no one way to carry on: the flat faces
|
||||
// round it do, and bound the region there. Left open, it would run off
|
||||
@@ -214,6 +384,245 @@ function regionAround(body: Shape3D, F: Face, nb: Face[], q: Vec3, L: number): S
|
||||
* radius afterwards - extending a fillet's cylinder through the body would
|
||||
* carve a tunnel into it.
|
||||
*/
|
||||
/**
|
||||
* The face made a smooth surface through `points` (absolute), its own edges
|
||||
* kept: the rest of the body is untouched and closes round it again.
|
||||
*/
|
||||
export function freeformFace(body: Shape3D, F: Face, points: 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");
|
||||
// Degree 2 overshoots least between points pulled out together; it can't
|
||||
// always follow an outline with inward corners (an L): then 3.
|
||||
for (const degree of [2, 3]) {
|
||||
try {
|
||||
const solid = filledFace(body, F, points, degree);
|
||||
if (validNow(solid.wrapped)) return solid;
|
||||
} catch {
|
||||
// the next degree
|
||||
}
|
||||
}
|
||||
throw new Error("This face can't be shaped like that (it would fold over itself) - move the points less, or not past each other");
|
||||
}
|
||||
|
||||
/**
|
||||
* The face made the cage's own smooth surface (the same patches a freeform
|
||||
* body is made of), its border on the face's edges: no fitting through
|
||||
* points, so it comes out the same every time and on any outline the cage
|
||||
* follows. Throws when the cage's border isn't on the face's edge (a cage
|
||||
* from before its border followed the face's corners) or the body doesn't
|
||||
* 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();
|
||||
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]);
|
||||
});
|
||||
const onPiece = (p: Vec3, [a, b]: [Vec3, Vec3]): Vec3 => {
|
||||
const d = sub(b, a);
|
||||
const l = dot(d, d);
|
||||
return add(a, scale(d, l > 0 ? Math.max(0, Math.min(1, dot(sub(p, a), d) / l)) : 0));
|
||||
};
|
||||
const nearest = (p: Vec3, pieces: [Vec3, Vec3][]) => {
|
||||
let best: Vec3 = p;
|
||||
let d = Infinity;
|
||||
for (const q of pieces) {
|
||||
const at = onPiece(p, q);
|
||||
const e = dist(p, at);
|
||||
if (e < d) ((d = e), (best = at));
|
||||
}
|
||||
return { at: best, d };
|
||||
};
|
||||
// The cage's border points onto the edge itself (they were laid on the
|
||||
// face as drawn on screen: a round edge's are a hair inside it).
|
||||
const borderVerts = new Set(boundaryEdges(cage).flat());
|
||||
const verts = cage.verts.map((v, i) => {
|
||||
if (!borderVerts.has(i)) return v;
|
||||
const hit = nearest(v, edge);
|
||||
if (hit.d > Math.max(0.2, size * 0.02)) throw new Error("border off the edge");
|
||||
return hit.at;
|
||||
});
|
||||
const through = borderThrough({ verts, faces: cage.faces });
|
||||
const s = subdivide(through.cage, 3, through.sharp);
|
||||
s.points = limitPoints(s, through.sharp);
|
||||
// Its border against the face's edge, both ways round.
|
||||
const pieces = borderPieces(s);
|
||||
for (const [a, b] of edge) if (nearest(a, pieces).d > tol || nearest(b, pieces).d > tol) throw new Error("border off the edge");
|
||||
for (const [a] of pieces) if (nearest(a, edge).d > tol) throw new Error("border off the edge");
|
||||
// Seen along the face's normal, all of it over the face. By an inward
|
||||
// corner of the outline a smooth surface swells a little past the edge (a
|
||||
// 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 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)]);
|
||||
const onBorder = new Set<Vec3>(pieces.flat());
|
||||
for (const [k, q] of s.points.entries()) {
|
||||
// (The border is on the edge already.)
|
||||
if (onBorder.has(q)) continue;
|
||||
const x = dot(q, u);
|
||||
const y = dot(q, v);
|
||||
let inside = false;
|
||||
for (const [ax, ay, bx, by] of flat) if (ay > y !== by > y && x < ((bx - ax) * (y - ay)) / (by - ay) + ax) inside = !inside;
|
||||
if (inside) continue;
|
||||
// (Counted along the other axis too: a ray through a corner of the outline, or along a piece of it, can miscount.)
|
||||
let also = false;
|
||||
for (const [ax, ay, bx, by] of flat) if (ax > x !== bx > x && y < ((by - ay) * (x - ax)) / (bx - ax) + ay) also = !also;
|
||||
if (also) continue;
|
||||
const h = dot(sub(q, edge[0][0]), n);
|
||||
const hit = nearest(sub(q, scale(n, h)), edge);
|
||||
if (hit.d > Math.max(0.5, size * 0.04)) throw new Error("spills over the edge");
|
||||
// (A little inside the edge, not on it: the surface between the points mustn't touch the wall below.)
|
||||
if (hit.d > tol / 4) s.points[k] = add(add(hit.at, scale(norm(sub(hit.at, sub(q, scale(n, h)))), Math.max(0.05, size * 0.004))), scale(n, h));
|
||||
}
|
||||
const rim = edge;
|
||||
const sheet = cageToShape(through.cage, 3, undefined, s);
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
const sew = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
|
||||
try {
|
||||
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);
|
||||
sew.Perform(progress);
|
||||
const shells = subShapes(cast(sew.SewedShape()) as Shape3D, "SHELL");
|
||||
if (shells.length !== 1) throw new Error("sew");
|
||||
const fix = new oc.ShapeFix_Solid();
|
||||
const made = fix.SolidFromShell(shells[0]);
|
||||
fix.delete();
|
||||
oc.BRepLib.OrientClosedSolid(oc.TopoDS.Solid(made));
|
||||
const solid = cast(made) as Shape3D;
|
||||
if (!(quickVolume(solid) > 0)) throw new Error("volume");
|
||||
if (!validNow(solid.wrapped)) throw new Error("invalid");
|
||||
return solid;
|
||||
} finally {
|
||||
sew.delete();
|
||||
progress.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A new surface may meet the rest of the body only along the old face's
|
||||
* edges (`rim`): a point pushed through the far side passes the body's
|
||||
* checks, but crosses itself. Throws when it meets it anywhere else.
|
||||
*/
|
||||
function meetsOnlyAt(surface: unknown, others: Face[], rim: [Vec3, Vec3][], size: number): void {
|
||||
const away = (p: Vec3) => {
|
||||
let d = Infinity;
|
||||
for (const [a, b] of rim) {
|
||||
const v = sub(b, a);
|
||||
const l = dot(v, v);
|
||||
d = Math.min(d, dist(p, add(a, scale(v, l > 0 ? Math.max(0, Math.min(1, dot(sub(p, a), v) / l)) : 0))));
|
||||
}
|
||||
return d;
|
||||
};
|
||||
const oc = getOC();
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
try {
|
||||
for (const other of others) {
|
||||
const sec = new oc.BRepAlgoAPI_Section();
|
||||
try {
|
||||
sec.Init1(surface as never);
|
||||
sec.Init2(other.wrapped);
|
||||
sec.Build(progress);
|
||||
const cut = cast(sec.Shape());
|
||||
for (const e of "edges" in cut ? cut.edges : [])
|
||||
for (const t of [0.25, 0.5, 0.75]) {
|
||||
const p = e.pointAt(t).toTuple() as Vec3;
|
||||
if (away(p) > Math.max(0.05, size * 0.01)) throw new Error("crosses");
|
||||
}
|
||||
} finally {
|
||||
sec.delete();
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
progress.delete();
|
||||
}
|
||||
}
|
||||
|
||||
function filledFace(body: Shape3D, F: Face, points: Vec3[], degree: number): Shape3D {
|
||||
const oc = getOC();
|
||||
const fill = new oc.BRepOffsetAPI_MakeFilling(degree, 15, 2, false, 1e-5, 1e-4, 0.01, 0.1, 8, 9);
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
const sew = new oc.BRepBuilderAPI_Sewing(1e-4, true, true, true, false);
|
||||
try {
|
||||
for (const e of F.edges) fill.Add(e.wrapped, oc.GeomAbs_Shape.GeomAbs_C0, true);
|
||||
for (const p of points) {
|
||||
const g = new oc.gp_Pnt(p[0], p[1], p[2]);
|
||||
fill.Add(g);
|
||||
g.delete();
|
||||
}
|
||||
fill.Build(progress);
|
||||
if (!fill.IsDone()) throw new Error("fill");
|
||||
const filled = fill.Shape();
|
||||
const others = body.faces.filter((f) => !f.isSame(F));
|
||||
// The new surface may meet the rest of the body only along its own edges
|
||||
// (a point pushed through the far side passes the body's checks, but
|
||||
// crosses itself).
|
||||
const rim = F.edges.flatMap((e) => Array.from({ length: 41 }, (_, i) => e.pointAt(i / 40).toTuple() as Vec3));
|
||||
const size = Math.sqrt(measureArea(F));
|
||||
for (const other of others) {
|
||||
const sec = new oc.BRepAlgoAPI_Section();
|
||||
try {
|
||||
sec.Init1(filled);
|
||||
sec.Init2(other.wrapped);
|
||||
sec.Build(progress);
|
||||
const cut = cast(sec.Shape());
|
||||
for (const e of "edges" in cut ? cut.edges : [])
|
||||
for (const t of [0.25, 0.5, 0.75]) {
|
||||
const p = e.pointAt(t).toTuple() as Vec3;
|
||||
if (Math.min(...rim.map((q) => dist(p, q))) > Math.max(0.05, size * 0.01)) throw new Error("crosses");
|
||||
}
|
||||
} finally {
|
||||
sec.delete();
|
||||
}
|
||||
}
|
||||
for (const f of others) sew.Add(f.wrapped);
|
||||
sew.Add(filled);
|
||||
sew.Perform(progress);
|
||||
const shells = subShapes(cast(sew.SewedShape()) as Shape3D, "SHELL");
|
||||
if (shells.length !== 1) throw new Error("sew");
|
||||
const fix = new oc.ShapeFix_Solid();
|
||||
const made = fix.SolidFromShell(shells[0]);
|
||||
fix.delete();
|
||||
oc.BRepLib.OrientClosedSolid(oc.TopoDS.Solid(made));
|
||||
const solid = cast(made) as Shape3D;
|
||||
if (!(quickVolume(solid) > 0)) throw new Error("volume");
|
||||
return solid;
|
||||
} finally {
|
||||
fill.delete();
|
||||
sew.delete();
|
||||
progress.delete();
|
||||
}
|
||||
}
|
||||
|
||||
export function replaceFacePlane(body: Shape3D, F: Face, to: PlaneDef): Shape3D {
|
||||
if (F.geomType !== "PLANE") throw new Error("Only flat faces can be moved or tilted");
|
||||
const blends = blendsOf(body, F);
|
||||
@@ -231,7 +640,7 @@ export function replaceFacePlane(body: Shape3D, F: Face, to: PlaneDef): Shape3D
|
||||
// (the half-space trick would clip it to its convex part).
|
||||
const old = planeOf(F);
|
||||
const nn = norm(to.normal);
|
||||
if (Math.abs(dot(nn, old.normal)) > 1 - 1e-9 && !convexFace(F)) {
|
||||
if (Math.abs(dot(nn, old.normal)) > 1 - 1e-9 && !convexFace(F) && !F.clone().innerWires().length) {
|
||||
const d = dot(sub(to.origin, old.origin), old.normal);
|
||||
if (Math.abs(d) < 1e-12) return body;
|
||||
try {
|
||||
@@ -389,14 +798,11 @@ function faceColumn(body: Shape3D, F: Face, L: number): Shape3D {
|
||||
}
|
||||
return null;
|
||||
});
|
||||
let t = F.triangulation();
|
||||
if (!t || !t.trianglesIndexes.length) {
|
||||
body.mesh({ tolerance: sizeOf(body) * 1e-3, angularTolerance: 0.3 });
|
||||
t = F.triangulation();
|
||||
}
|
||||
if (!t || !t.trianglesIndexes.length) return extendedRegion(body, F, q0, L);
|
||||
const t = faceTriangles(F, sizeOf(body));
|
||||
if (!t) return extendedRegion(body, F, q0, L);
|
||||
const v = (i: number): Vec3 => [t!.vertices[3 * i], t!.vertices[3 * i + 1], t!.vertices[3 * i + 2]];
|
||||
const cells = new Map<string, Vec3>();
|
||||
const parts = new Map<string, Vec3[]>();
|
||||
for (let k = 0; k < t.trianglesIndexes.length; k += 3) {
|
||||
const [a, b, c] = [0, 1, 2].map((j) => v(t!.trianglesIndexes[k + j]));
|
||||
// The middle and near each corner: a triangle may straddle a line where a neighbour's surface crosses the face.
|
||||
@@ -415,12 +821,13 @@ function faceColumn(body: Shape3D, F: Face, L: number): Shape3D {
|
||||
if (ds.some((d, i) => sides[i] && Math.abs(d) < tol)) continue;
|
||||
const key = ds.map((d, i) => (!sides[i] ? "" : d < 0 ? "-" : "+")).join("");
|
||||
if (!cells.has(key)) cells.set(key, q);
|
||||
(parts.get(key) ?? parts.set(key, []).get(key)!).push(on);
|
||||
}
|
||||
}
|
||||
if (cells.size <= 1) return extendedRegion(body, F, q0, L);
|
||||
let E: Shape3D | null = null;
|
||||
for (const q of cells.values()) {
|
||||
const c = extendedRegion(body, F, q, L);
|
||||
for (const [key, q] of cells) {
|
||||
const c = extendedRegion(body, F, q, L, parts.get(key));
|
||||
E = E ? fuseCells(E, c) : c;
|
||||
}
|
||||
return E!;
|
||||
@@ -551,112 +958,161 @@ 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;
|
||||
const size = sizeOf(body);
|
||||
const tol = size * 1e-6;
|
||||
const nbrs = neighbours(body, F);
|
||||
// F's outline as a loop of edges, end to end.
|
||||
const edges = F.clone().outerWire().edges;
|
||||
const ends = (e: { startPoint: { toTuple(): number[] }; endPoint: { toTuple(): number[] } }): [Vec3, Vec3] => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3];
|
||||
const order: { k: number; rev: boolean }[] = [{ k: 0, rev: false }];
|
||||
const used = new Set([0]);
|
||||
let at = ends(edges[0])[1];
|
||||
while (used.size < edges.length) {
|
||||
const k = edges.findIndex((e, i) => !used.has(i) && ends(e).some((q) => dist(q, at) < tol * 10));
|
||||
if (k < 0) throw new Error("outline not closed");
|
||||
used.add(k);
|
||||
const [a, b] = ends(edges[k]);
|
||||
const rev = dist(b, at) < dist(a, at);
|
||||
order.push({ k, rev });
|
||||
at = rev ? a : b;
|
||||
}
|
||||
// Where a point on edge k goes: along its neighbour, across the edge, out of F's plane.
|
||||
// Cutting: the cutter reaches a hair past the walls and above F, so no sliver stays on the coincident surfaces.
|
||||
const eps = d < 0 ? size * 1e-4 : 0;
|
||||
const outward = (k: number, t: number): Vec3 => {
|
||||
const e = edges[k];
|
||||
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)))!;
|
||||
const ng = norm(tup(g.normalAt(tup(e.pointAt(t)))));
|
||||
const flat = sub(ng, scale(n, dot(ng, n)));
|
||||
return len(flat) < 1e-9 ? [0, 0, 0] : scale(norm(flat), eps);
|
||||
};
|
||||
const movedAt = (k: number, t: number): Vec3 => {
|
||||
const e = edges[k];
|
||||
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)));
|
||||
if (!g) throw new Error("no neighbour");
|
||||
const p = tup(e.pointAt(t));
|
||||
const dt = 1e-3;
|
||||
const tangent = norm(sub(tup(e.pointAt(Math.min(1, t + dt))), tup(e.pointAt(Math.max(0, t - dt)))));
|
||||
// Just inside the edge on g: its normal there (exactly on the edge it can be the other face's).
|
||||
const ng = norm(tup(g.normalAt(p)));
|
||||
let dir = norm(cross(ng, tangent));
|
||||
if (dot(dir, n) < 0) dir = scale(dir, -1);
|
||||
const rise = dot(dir, n);
|
||||
if (rise < 0.15) throw new Error("neighbour runs along the face");
|
||||
return add(add(p, scale(dir, d / rise)), outward(k, t));
|
||||
};
|
||||
const liftedAt = (k: number, t: number): Vec3 => add(add(tup(edges[k].pointAt(t)), scale(n, eps)), outward(k, t));
|
||||
// Corners: shared by two edges. Where the two neighbours meet along an edge
|
||||
// of the body (a box's corner edge), the corner slides along that edge to
|
||||
// the new plane - it stays on both neighbours. Each neighbour on its own
|
||||
// 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.
|
||||
const m = order.length;
|
||||
const fEdges = F.edges;
|
||||
const bodyEdges = body.edges.filter((e) => !fEdges.some((fe) => fe.isSame(e)));
|
||||
const alongEdge = (v: Vec3): Vec3 | null => {
|
||||
for (const e of bodyEdges) {
|
||||
const [a, b] = ends(e);
|
||||
const atStart = dist(a, v) < tol * 10;
|
||||
if (!atStart && dist(b, v) >= tol * 10) continue;
|
||||
const dt = 1e-3;
|
||||
const q = tup(e.pointAt(atStart ? dt : 1 - dt));
|
||||
const dir = norm(sub(q, v));
|
||||
const rise = dot(dir, n);
|
||||
if (Math.abs(rise) < 0.15) continue;
|
||||
return add(v, scale(dir, d / rise));
|
||||
// The slab between one of F's outlines (its outer one, or a hole's) and
|
||||
// where that outline goes: the outline as a loop of edges, end to end.
|
||||
const column = (edges: Edge[]): Shape3D => {
|
||||
const ends = (e: { startPoint: { toTuple(): number[] }; endPoint: { toTuple(): number[] } }): [Vec3, Vec3] => [e.startPoint.toTuple() as Vec3, e.endPoint.toTuple() as Vec3];
|
||||
const order: { k: number; rev: boolean }[] = [{ k: 0, rev: false }];
|
||||
const used = new Set([0]);
|
||||
let at = ends(edges[0])[1];
|
||||
while (used.size < edges.length) {
|
||||
const k = edges.findIndex((e, i) => !used.has(i) && ends(e).some((q) => dist(q, at) < tol * 10));
|
||||
if (k < 0) throw new Error("outline not closed");
|
||||
used.add(k);
|
||||
const [a, b] = ends(edges[k]);
|
||||
const rev = dist(b, at) < dist(a, at);
|
||||
order.push({ k, rev });
|
||||
at = rev ? a : b;
|
||||
}
|
||||
return null;
|
||||
// Where a point on edge k goes: along its neighbour, across the edge, out of F's plane.
|
||||
// Cutting: the cutter reaches a hair past the walls and above F, so no sliver stays on the coincident surfaces.
|
||||
const eps = d < 0 ? size * 1e-4 : 0;
|
||||
const outward = (k: number, t: number): Vec3 => {
|
||||
const e = edges[k];
|
||||
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)))!;
|
||||
const ng = norm(tup(g.normalAt(tup(e.pointAt(t)))));
|
||||
const flat = sub(ng, scale(n, dot(ng, n)));
|
||||
return len(flat) < 1e-9 ? [0, 0, 0] : scale(norm(flat), eps);
|
||||
};
|
||||
const movedAt = (k: number, t: number): Vec3 => {
|
||||
const e = edges[k];
|
||||
const g = nbrs.find((h) => h.edges.some((he) => he.isSame(e)));
|
||||
if (!g) throw new Error("no neighbour");
|
||||
const p = tup(e.pointAt(t));
|
||||
const dt = 1e-3;
|
||||
const tangent = norm(sub(tup(e.pointAt(Math.min(1, t + dt))), tup(e.pointAt(Math.max(0, t - dt)))));
|
||||
// Just inside the edge on g: its normal there (exactly on the edge it can be the other face's).
|
||||
const ng = norm(tup(g.normalAt(p)));
|
||||
let dir = norm(cross(ng, tangent));
|
||||
if (dot(dir, n) < 0) dir = scale(dir, -1);
|
||||
const rise = dot(dir, n);
|
||||
if (rise < 0.15) throw new Error("neighbour runs along the face");
|
||||
return add(add(p, scale(dir, d / rise)), outward(k, t));
|
||||
};
|
||||
const liftedAt = (k: number, t: number): Vec3 => add(add(tup(edges[k].pointAt(t)), scale(n, eps)), outward(k, t));
|
||||
// Corners: shared by two edges. Where the two neighbours meet along an edge
|
||||
// of the body (a box's corner edge), the corner slides along that edge to
|
||||
// the new plane - it stays on both neighbours. Each neighbour on its own
|
||||
// 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)));
|
||||
const alongEdge = (v: Vec3): Vec3 | null => {
|
||||
for (const e of bodyEdges) {
|
||||
const [a, b] = ends(e);
|
||||
const atStart = dist(a, v) < tol * 10;
|
||||
if (!atStart && dist(b, v) >= tol * 10) continue;
|
||||
const dt = 1e-3;
|
||||
const q = tup(e.pointAt(atStart ? dt : 1 - dt));
|
||||
const dir = norm(sub(q, v));
|
||||
const rise = dot(dir, n);
|
||||
if (Math.abs(rise) < 0.15) continue;
|
||||
return add(v, scale(dir, d / rise));
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const corner: Vec3[] = order.map(({ k, rev }, i) => {
|
||||
const prev = order[(i - 1 + m) % m];
|
||||
const a = movedAt(k, rev ? 1 : 0);
|
||||
const b = movedAt(prev.k, prev.rev ? 0 : 1);
|
||||
const v = ends(edges[k])[rev ? 1 : 0];
|
||||
return alongEdge(v) ?? scale(add(a, b), 0.5);
|
||||
});
|
||||
const lowerCorner: Vec3[] = order.map(({ k, rev }) => liftedAt(k, rev ? 1 : 0));
|
||||
const lowerEdges = eps
|
||||
? order.map(({ k, rev }, i) => {
|
||||
// Cutting: F's outline nudged up and out (see eps).
|
||||
const c0 = lowerCorner[i];
|
||||
const c1 = lowerCorner[(i + 1) % m];
|
||||
if (edges[k].geomType === "LINE") return makeLine(c0, c1);
|
||||
const pts: Vec3[] = [];
|
||||
for (let j = 0; j <= 24; j++) pts.push(liftedAt(k, rev ? 1 - j / 24 : j / 24));
|
||||
pts[0] = c0;
|
||||
pts[24] = c1;
|
||||
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
|
||||
})
|
||||
: order.map(({ k }) => edges[k].clone());
|
||||
const upperEdges = order.map(({ k, rev }, i) => {
|
||||
const e = edges[k];
|
||||
const c0 = corner[i];
|
||||
const c1 = corner[(i + 1) % m];
|
||||
if (e.geomType === "LINE") return makeLine(c0, c1);
|
||||
// A curved edge: a smooth curve through its moved points.
|
||||
const pts: Vec3[] = [];
|
||||
for (let j = 0; j <= 24; j++) pts.push(movedAt(k, rev ? 1 - j / 24 : j / 24));
|
||||
pts[0] = c0;
|
||||
pts[24] = c1;
|
||||
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
|
||||
});
|
||||
const a = assembleWire(lowerEdges);
|
||||
const b = assembleWire(upperEdges);
|
||||
return loft(d > 0 ? [a, b] : [b, a], { ruled: true }) as Shape3D;
|
||||
};
|
||||
const corner: Vec3[] = order.map(({ k, rev }, i) => {
|
||||
const prev = order[(i - 1 + m) % m];
|
||||
const a = movedAt(k, rev ? 1 : 0);
|
||||
const b = movedAt(prev.k, prev.rev ? 0 : 1);
|
||||
const v = ends(edges[k])[rev ? 1 : 0];
|
||||
return alongEdge(v) ?? scale(add(a, b), 0.5);
|
||||
});
|
||||
const lowerCorner: Vec3[] = order.map(({ k, rev }) => liftedAt(k, rev ? 1 : 0));
|
||||
const lowerEdges = eps
|
||||
? order.map(({ k, rev }, i) => {
|
||||
// Cutting: F's outline nudged up and out (see eps).
|
||||
const c0 = lowerCorner[i];
|
||||
const c1 = lowerCorner[(i + 1) % m];
|
||||
if (edges[k].geomType === "LINE") return makeLine(c0, c1);
|
||||
const pts: Vec3[] = [];
|
||||
for (let j = 0; j <= 24; j++) pts.push(liftedAt(k, rev ? 1 - j / 24 : j / 24));
|
||||
pts[0] = c0;
|
||||
pts[24] = c1;
|
||||
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
|
||||
})
|
||||
: order.map(({ k }) => edges[k].clone());
|
||||
const upperEdges = order.map(({ k, rev }, i) => {
|
||||
const e = edges[k];
|
||||
const c0 = corner[i];
|
||||
const c1 = corner[(i + 1) % m];
|
||||
if (e.geomType === "LINE") return makeLine(c0, c1);
|
||||
// A curved edge: a smooth curve through its moved points.
|
||||
const pts: Vec3[] = [];
|
||||
for (let j = 0; j <= 24; j++) pts.push(movedAt(k, rev ? 1 - j / 24 : j / 24));
|
||||
pts[0] = c0;
|
||||
pts[24] = c1;
|
||||
return makeBSplineApproximation(pts, { tolerance: size * 1e-6, degMax: 5, degMin: 2 });
|
||||
});
|
||||
const a = assembleWire(lowerEdges);
|
||||
const b = assembleWire(upperEdges);
|
||||
const slab = loft(d > 0 ? [a, b] : [b, a], { ruled: true });
|
||||
let slab = column(F.clone().outerWire().edges);
|
||||
// A hole in F (or something standing on it): the slab stops at its walls,
|
||||
// carried on the same way. (Over the whole outline, a top pulled up closed
|
||||
// the hole through it with a lid; pushed down, it cut a boss off at its foot.)
|
||||
for (const hole of F.clone().innerWires()) slab = slab.cut(column(hole.edges)) as Shape3D;
|
||||
const out = d > 0 ? body.fuse(slab) : body.cut(slab);
|
||||
return sanity(body, out);
|
||||
}
|
||||
@@ -666,13 +1122,32 @@ export function offsetFace(body: Shape3D, F: Face, d: number): Shape3D {
|
||||
// Curved neighbours, or a face with inward corners (a zigzag, an L): the
|
||||
// half-space trick would clip it to its convex part, so each edge carries on
|
||||
// along its own neighbour instead.
|
||||
if (F.geomType === "PLANE" && (needsContinuation(body, F) || !convexFace(F))) {
|
||||
// (A face with holes whose neighbours are flat or stand upright: the plane
|
||||
// trick first - it takes each hole's own walls on as they are, a round one
|
||||
// staying one true cylinder. Edge by edge is the way for it only if that fails.)
|
||||
const holed = F.geomType === "PLANE" && F.clone().innerWires().length > 0;
|
||||
const curved = F.geomType === "PLANE" && needsContinuation(body, F);
|
||||
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
|
||||
}
|
||||
}
|
||||
if (holed && !curved) {
|
||||
const { origin, normal } = planeOf(F);
|
||||
try {
|
||||
return replaceFacePlane(body, F, { origin: add(origin, scale(normal, d)), normal, xDir: xDirFor(normal) });
|
||||
} catch (err) {
|
||||
try {
|
||||
return offsetByContinuation(body, F, d);
|
||||
} catch {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (F.geomType === "PLANE") {
|
||||
const { origin, normal } = planeOf(F);
|
||||
return replaceFacePlane(body, F, { origin: add(origin, scale(normal, d)), normal, xDir: xDirFor(normal) });
|
||||
@@ -1141,7 +1616,19 @@ export function unify(body: Shape3D, size?: number): Shape3D {
|
||||
u.SetLinearTolerance((size ?? sizeOf(body)) * 1e-6);
|
||||
u.SetAngularTolerance(1e-6);
|
||||
u.Build();
|
||||
return cast(u.Shape()) as Shape3D;
|
||||
// (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 {
|
||||
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;
|
||||
|
||||
@@ -2,21 +2,24 @@
|
||||
// bicubic B-spline face interpolating its grid of points; faces are sewn and,
|
||||
// when the cage is closed, made into a solid.
|
||||
|
||||
import { cast, getOC, measureVolume, type Shape3D } from "replicad";
|
||||
import { cast, getOC, type Shape3D } from "replicad";
|
||||
import { quickVolume } from "./ocFree";
|
||||
import { subShapes } from "./health";
|
||||
import { cubicKnots, interpolateGrid } from "../freeform/bspline";
|
||||
import { isClosed, limitPoints, subdivide, type Cage } from "../freeform/cage";
|
||||
import { isClosed, limitPoints, subdivide, type Cage, type Subdivided } from "../freeform/cage";
|
||||
|
||||
export interface Thicken {
|
||||
thickness: number;
|
||||
side: "up" | "down" | "both";
|
||||
}
|
||||
|
||||
export function cageToShape(cage: Cage, levels = 3, thicken?: Thicken): Shape3D {
|
||||
/** `ready`: the cage already subdivided, its points on the smooth surface (else done here). */
|
||||
export function cageToShape(cage: Cage, levels = 3, thicken?: Thicken, ready?: Subdivided): Shape3D {
|
||||
if (!cage.faces.length) throw new Error("The freeform has no faces");
|
||||
const oc = getOC();
|
||||
const s = subdivide(cage, levels);
|
||||
const s = ready ?? subdivide(cage, levels);
|
||||
// Fitted through points on the smooth surface itself (see limitPoints).
|
||||
s.points = limitPoints(s);
|
||||
if (!ready) s.points = limitPoints(s);
|
||||
const N = s.n + 1;
|
||||
const tol = Math.max(1e-4, sizeOf(s.points) * 1e-5);
|
||||
const sewing = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
|
||||
@@ -71,15 +74,39 @@ 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();
|
||||
}
|
||||
};
|
||||
if (side === "up") return thick(t);
|
||||
if (side === "down") return thick(-t);
|
||||
return thick(t / 2).fuse(thick(-t / 2));
|
||||
// Both ways: the sheet moved half the thickness back, then thickened the
|
||||
// whole way forward - one solid. (Two halves fused leaked ~50 MB of the
|
||||
// engine's memory on every rebuild: a phone ran out after a few dozen.)
|
||||
const mk = new oc.BRepOffsetAPI_MakeOffsetShape();
|
||||
try {
|
||||
mk.PerformBySimple(sheet as never, -t / 2);
|
||||
if (!mk.IsDone()) throw new Error("offset");
|
||||
return thickenSheet(mk.Shape(), { thickness: t, side: "up" });
|
||||
} finally {
|
||||
mk.delete();
|
||||
}
|
||||
}
|
||||
|
||||
function sizeOf(pts: number[][]): number {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Health checks for solids, shared by the engine's edit guard and the repair tool.
|
||||
|
||||
import { cast, getOC, measureArea, type Edge, type Shape3D } from "replicad";
|
||||
import { meshFaces, meshOff } from "./meshing";
|
||||
|
||||
/** OpenCascade's own check (self-crossing faces, bad edges…). */
|
||||
const validCache = new WeakMap<Shape3D, boolean>();
|
||||
@@ -14,43 +15,122 @@ export function shapeValid(shape: Shape3D): boolean {
|
||||
|
||||
function checkValid(shape: Shape3D): boolean {
|
||||
try {
|
||||
const oc = getOC();
|
||||
const check = new oc.BRepCheck_Analyzer(shape.wrapped, true, false, false);
|
||||
const ok = (check as unknown as { IsValid(): boolean }).IsValid();
|
||||
check.delete();
|
||||
return ok;
|
||||
return validNow(shape.wrapped);
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* OpenCascade's check of a shape, made now (nothing remembered). Its checker
|
||||
* keeps what it found on every face, edge and corner, and deleting it doesn't
|
||||
* give that back: each check of an everyday body left over half a megabyte
|
||||
* behind for good. A plate of 35 faces checked 3 000 times took the engine
|
||||
* from 100 MB to 1.9 GB - and every edit checks its result, so a long session
|
||||
* ran the engine out of memory. Pointed at nothing before it goes, the checker
|
||||
* lets go of it all.
|
||||
*/
|
||||
export function validNow(wrapped: unknown): boolean {
|
||||
const oc = getOC();
|
||||
const check = new oc.BRepCheck_Analyzer(wrapped as never, true, false, false);
|
||||
try {
|
||||
return (check as unknown as { IsValid(): boolean }).IsValid();
|
||||
} finally {
|
||||
const builder = new oc.TopoDS_Builder();
|
||||
const nothing = new oc.TopoDS_Compound();
|
||||
try {
|
||||
builder.MakeCompound(nothing);
|
||||
check.Init(nothing, false);
|
||||
} catch {
|
||||
// As it is: the check itself is done.
|
||||
}
|
||||
builder.delete();
|
||||
nothing.delete();
|
||||
check.delete();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Edges with a face on one side only (gaps), by index. Worked out once per
|
||||
* 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, { 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 = findEdgeUse(shape)));
|
||||
return known;
|
||||
}
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
/**
|
||||
* A real copy: its own topology and its own curves and surfaces (replicad's
|
||||
* clone() only wraps the same shape again). Made by "moving" it nowhere with
|
||||
* copying on.
|
||||
* clone() only wraps the same shape again), its faces and edges in the same
|
||||
* order. Written out and read back. The kernel's own copier ("moving" it
|
||||
* nowhere with copying on) keeps every piece of the shape and of the copy,
|
||||
* and can't be made to let go of them (release.ts): each edit of a step that
|
||||
* works on a copy - a fillet's size dragged - lost a whole body for good.
|
||||
* What is read from a file is held by its handle alone. (The mesh goes out
|
||||
* and in with it, and is taken off: a copy has none.)
|
||||
*/
|
||||
let copies = 0;
|
||||
export function deepCopy(s: Shape3D): Shape3D {
|
||||
const oc = getOC();
|
||||
const name = `/copy-${copies++}.bin`;
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
const read = new oc.TopoDS_Shape();
|
||||
try {
|
||||
if (oc.BinTools.Write(s.wrapped, name, progress) && oc.BinTools.Read(read, name, progress) && !read.IsNull()) {
|
||||
oc.BRepTools.Clean(read, true);
|
||||
return cast(read) as Shape3D;
|
||||
}
|
||||
} catch (err) {
|
||||
// (The engine itself breaking down is not a copy that couldn't be made.)
|
||||
if (typeof WebAssembly !== "undefined" && err instanceof WebAssembly.RuntimeError) throw err;
|
||||
} finally {
|
||||
try {
|
||||
oc.FS.unlink(name);
|
||||
} catch {
|
||||
// never written
|
||||
}
|
||||
progress.delete();
|
||||
read.delete();
|
||||
}
|
||||
// The old way, if it can't be written.
|
||||
const t = new oc.gp_Trsf();
|
||||
const mk = new oc.BRepBuilderAPI_Transform(s.wrapped, t, true, false);
|
||||
try {
|
||||
@@ -65,13 +145,39 @@ export function subShapes(s: Shape3D, kind: "SOLID" | "SHELL"): any[] {
|
||||
const oc = getOC();
|
||||
const ex = new oc.TopExp_Explorer(s.wrapped, kind === "SOLID" ? oc.TopAbs_ShapeEnum.TopAbs_SOLID : oc.TopAbs_ShapeEnum.TopAbs_SHELL, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
|
||||
const out: any[] = [];
|
||||
for (; ex.More(); ex.Next()) out.push(kind === "SOLID" ? oc.TopoDS.Solid(ex.Current()) : oc.TopoDS.Shell(ex.Current()));
|
||||
for (; ex.More(); ex.Next()) {
|
||||
const item = ex.Current();
|
||||
out.push(kind === "SOLID" ? oc.TopoDS.Solid(item) : oc.TopoDS.Shell(item));
|
||||
item.delete();
|
||||
}
|
||||
ex.delete();
|
||||
return out;
|
||||
}
|
||||
|
||||
/** How many faces are next to nothing in area (once per shape: every face's area is slow on curved faces). */
|
||||
const thinCache = new WeakMap<Shape3D, number>();
|
||||
export function hairThin(s: Shape3D): number {
|
||||
let known = thinCache.get(s);
|
||||
if (known === undefined) thinCache.set(s, (known = countHairThin(s)));
|
||||
return known;
|
||||
}
|
||||
|
||||
function countHairThin(s: Shape3D): number {
|
||||
const areas = s.faces.map((f) => measureArea(f));
|
||||
const total = areas.reduce((a, b) => a + b, 0);
|
||||
return areas.filter((a) => a < total * 1e-7).length;
|
||||
}
|
||||
|
||||
/** A solid's volume counted from a mesh of it (coarse, so the view's own finer mesh still gets made). */
|
||||
export function meshVolume(s: Shape3D, size: number): number {
|
||||
const m = meshFaces(s, size * 1e-3, 0.3);
|
||||
meshOff(s);
|
||||
const p = m.vertices;
|
||||
const t = m.triangles;
|
||||
let v = 0;
|
||||
for (let k = 0; k < t.length; k += 3) {
|
||||
const [i, j, l] = [3 * t[k], 3 * t[k + 1], 3 * t[k + 2]];
|
||||
v += p[i] * (p[j + 1] * p[l + 2] - p[j + 2] * p[l + 1]) - p[i + 1] * (p[j] * p[l + 2] - p[j + 2] * p[l]) + p[i + 2] * (p[j] * p[l + 1] - p[j + 1] * p[l]);
|
||||
}
|
||||
return v / 6;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// A loft through sections that are each one closed curve (circles, ellipses,
|
||||
// a closed spline) whose starts already line up, made as one smooth side.
|
||||
//
|
||||
// OpenCascade's loft first makes the sections "compatible": where their start
|
||||
// points aren't exactly in line it projects each one's start onto the others
|
||||
// and splits them all there. Six ellipses turned to a propeller's pitch came
|
||||
// out with six faces down the blade instead of one, the blade's root on the hub
|
||||
// chopped into pieces 1.3 mm long, and its root fillet failed. When the starts
|
||||
// are near enough in line already (and the curves all run the same way round),
|
||||
// the sections are lofted as they are.
|
||||
import { cast, getOC, isShape3D, type Shape3D, type Wire } from "replicad";
|
||||
import { add, cross, dot, len, norm, scale, sub } from "../geom";
|
||||
import type { Vec3 } from "../doc/types";
|
||||
|
||||
const centre = (w: Wire): Vec3 => {
|
||||
const e = w.edges[0];
|
||||
let c: Vec3 = [0, 0, 0];
|
||||
const n = 32;
|
||||
for (let k = 0; k < n; k++) c = add(c, e.pointAt(k / n).toTuple() as Vec3);
|
||||
return scale(c, 1 / n);
|
||||
};
|
||||
|
||||
/** Single closed curves, starts in line, all one way round: lofted without splitting (else null). */
|
||||
export function loftInLine(wires: Wire[], ruled: boolean): Shape3D | null {
|
||||
if (wires.length < 2 || wires.some((w) => w.edges.length !== 1 || !w.isClosed)) return null;
|
||||
const cs = wires.map(centre);
|
||||
const axis = norm(sub(cs[cs.length - 1], cs[0]));
|
||||
if (!(len(sub(cs[cs.length - 1], cs[0])) > 1e-9)) return null;
|
||||
let prev: Vec3 | null = null;
|
||||
let sense = 0;
|
||||
for (const [i, w] of wires.entries()) {
|
||||
const e = w.edges[0];
|
||||
const s = sub(e.startPoint.toTuple() as Vec3, cs[i]);
|
||||
// Seen down the loft's run, its start's direction from its middle...
|
||||
const flat = sub(s, scale(axis, dot(s, axis)));
|
||||
if (len(flat) < 1e-9) return null;
|
||||
const d = norm(flat);
|
||||
// ...within 45° of the one before's.
|
||||
if (prev && dot(d, prev) < Math.SQRT1_2) return null;
|
||||
prev = d;
|
||||
// And the same way round.
|
||||
const turn = Math.sign(dot(cross(s, e.tangentAt(0).toTuple() as Vec3), axis));
|
||||
if (!turn || (sense && turn !== sense)) return null;
|
||||
sense = turn;
|
||||
}
|
||||
const oc = getOC();
|
||||
const b = new oc.BRepOffsetAPI_ThruSections(true, ruled, 1e-6);
|
||||
try {
|
||||
b.CheckCompatibility(false);
|
||||
for (const w of wires) b.AddWire(w.wrapped);
|
||||
b.Build();
|
||||
if (!b.IsDone()) return null;
|
||||
const shape = cast(b.Shape());
|
||||
return isShape3D(shape) ? shape : null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
b.delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
// A loft held by guide curves (rails) along its sides and by connection
|
||||
// points (which point of each profile joins which).
|
||||
//
|
||||
// OpenCascade's loft takes no rails, so the profiles are resampled here on one
|
||||
// shared parametrisation: each guide's or connection's point on a profile is at
|
||||
// the same parameter on every profile, so the loft joins them. Between profiles
|
||||
// that guides run along, extra sections are added: the two profiles blended,
|
||||
// then moved so each guide's point lands on its guide - the sides follow the
|
||||
// guides. Profiles become B-splines (within a ten-thousandth of their size).
|
||||
import { cast, getOC, isShape3D, type Shape3D, type Wire } from "replicad";
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { add, cross, dot, len, norm, scale, sub } from "../geom";
|
||||
|
||||
/** Dense points along a curve, with how far along each is (0…1 of its length). */
|
||||
interface Curve {
|
||||
pts: Vec3[];
|
||||
s: number[];
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
function sample(w: Wire, n = 720): Curve {
|
||||
const oc = getOC();
|
||||
const ad = new oc.BRepAdaptor_CompCurve(w.wrapped, true);
|
||||
const pts: Vec3[] = [];
|
||||
try {
|
||||
const u0 = ad.FirstParameter();
|
||||
const u1 = ad.LastParameter();
|
||||
for (let i = 0; i <= n; i++) {
|
||||
const p = ad.Value(u0 + ((u1 - u0) * i) / n);
|
||||
pts.push([p.X(), p.Y(), p.Z()]);
|
||||
p.delete();
|
||||
}
|
||||
} finally {
|
||||
ad.delete();
|
||||
}
|
||||
const s = [0];
|
||||
for (let i = 1; i < pts.length; i++) s.push(s[i - 1] + len(sub(pts[i], pts[i - 1])));
|
||||
const L = s[s.length - 1] || 1;
|
||||
return { pts, s: s.map((x) => x / L), closed: len(sub(pts[0], pts[pts.length - 1])) < 1e-6 * L + 1e-9 };
|
||||
}
|
||||
|
||||
const reversed = (c: Curve): Curve => ({ pts: [...c.pts].reverse(), s: [...c.s].reverse().map((x) => 1 - x), closed: c.closed });
|
||||
|
||||
/** The point `f` of the way along (round again past the end of a closed one). */
|
||||
function at(c: Curve, f: number): Vec3 {
|
||||
if (c.closed) f = ((f % 1) + 1) % 1;
|
||||
else f = Math.min(1, Math.max(0, f));
|
||||
let lo = 0;
|
||||
let hi = c.s.length - 1;
|
||||
while (hi - lo > 1) {
|
||||
const m = (lo + hi) >> 1;
|
||||
if (c.s[m] <= f) lo = m;
|
||||
else hi = m;
|
||||
}
|
||||
const d = c.s[hi] - c.s[lo];
|
||||
const t = d > 0 ? (f - c.s[lo]) / d : 0;
|
||||
return add(c.pts[lo], scale(sub(c.pts[hi], c.pts[lo]), t));
|
||||
}
|
||||
|
||||
/** Where on the curve is nearest p: how far along, and how far off. */
|
||||
function nearest(c: Curve, p: Vec3): { f: number; d: number } {
|
||||
let best = { f: 0, d: Infinity };
|
||||
for (let i = 0; i + 1 < c.pts.length; i++) {
|
||||
const a = c.pts[i];
|
||||
const ab = sub(c.pts[i + 1], a);
|
||||
const l2 = dot(ab, ab);
|
||||
const t = l2 > 0 ? Math.min(1, Math.max(0, dot(sub(p, a), ab) / l2)) : 0;
|
||||
const d = len(sub(p, add(a, scale(ab, t))));
|
||||
if (d < best.d) best = { f: c.s[i] + (c.s[i + 1] - c.s[i]) * t, d };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/** Where a guide meets a profile: how far along each. */
|
||||
function meet(rail: Curve, sec: Curve): { onRail: number; onSec: number; d: number } {
|
||||
let best = { onRail: 0, onSec: 0, d: Infinity };
|
||||
// Coarse, then the best few of the guide's points refined.
|
||||
const step = Math.max(1, Math.floor(rail.pts.length / 240));
|
||||
const tries: { i: number; d: number }[] = [];
|
||||
for (let i = 0; i < rail.pts.length; i += step) tries.push({ i, d: nearest(sec, rail.pts[i]).d });
|
||||
tries.sort((a, b) => a.d - b.d);
|
||||
for (const { i } of tries.slice(0, 3))
|
||||
for (let k = Math.max(0, i - step); k <= Math.min(rail.pts.length - 1, i + step); k++) {
|
||||
const q = nearest(sec, rail.pts[k]);
|
||||
if (q.d < best.d) best = { onRail: rail.s[k], onSec: q.f, d: q.d };
|
||||
}
|
||||
// And back: the profile's point onto the guide.
|
||||
const back = nearest(rail, at(sec, best.onSec));
|
||||
return { onRail: back.f, onSec: best.onSec, d: Math.min(best.d, back.d) };
|
||||
}
|
||||
|
||||
const centroidOf = (ps: Vec3[]): Vec3 => scale(ps.reduce((a, p) => add(a, p), [0, 0, 0] as Vec3), 1 / Math.max(1, ps.length));
|
||||
const centroid = (c: Curve): Vec3 => scale(c.pts.slice(0, -1).reduce((a, p) => add(a, p), [0, 0, 0] as Vec3), 1 / Math.max(1, c.pts.length - 1));
|
||||
/** Which way round a closed curve runs (Newell's normal, its size the area). */
|
||||
function winding(c: Curve): Vec3 {
|
||||
let n: Vec3 = [0, 0, 0];
|
||||
for (let i = 0; i + 1 < c.pts.length; i++) n = add(n, cross(c.pts[i], c.pts[i + 1]));
|
||||
return n;
|
||||
}
|
||||
|
||||
interface Anchor {
|
||||
/** A guide's index, or -1 for connection points. */
|
||||
rail: number;
|
||||
/** How far along each profile. */
|
||||
a: number[];
|
||||
/** How far along the guide, at each profile. */
|
||||
r: number[];
|
||||
}
|
||||
|
||||
/** Does a section turn sharply anywhere (more than 20° from one point to the next)? */
|
||||
function sharp(rows: Vec3[][]): boolean {
|
||||
const cos20 = Math.cos((20 * Math.PI) / 180);
|
||||
for (const row of rows)
|
||||
for (let j = 0; j < row.length; j++) {
|
||||
const a = sub(row[j], row[(j - 1 + row.length) % row.length]);
|
||||
const b = sub(row[(j + 1) % row.length], row[j]);
|
||||
if (len(a) > 0 && len(b) > 0 && dot(norm(a), norm(b)) < cos20) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The loft from its grid of points (a row per section, the same number round
|
||||
* each): one smooth side through them, the two ends capped flat with the
|
||||
* side's own end curves, sewn into a solid.
|
||||
*/
|
||||
function gridSolid(rows: Vec3[][], size: number): Shape3D {
|
||||
const oc = getOC();
|
||||
const nu = rows.length;
|
||||
const nv = rows[0].length + 1;
|
||||
const gc: { delete(): void }[] = [];
|
||||
const keep = <T extends { delete(): void }>(x: T): T => (gc.push(x), x);
|
||||
try {
|
||||
const grid = keep(new oc.NCollection_Array2_gp_Pnt(1, nu, 1, nv));
|
||||
rows.forEach((row, i) => {
|
||||
for (let j = 0; j < nv; j++) {
|
||||
const p = keep(new oc.gp_Pnt(...row[j % row.length]));
|
||||
grid.SetValue(i + 1, j + 1, p);
|
||||
}
|
||||
});
|
||||
// Through the points exactly (fitted within a tolerance, a square's corners came out rounded).
|
||||
// Smooth profiles: through the points, smooth (C2) all round. Profiles with
|
||||
// sharp corners (a square): fitted allowing a kink, so the corners stay
|
||||
// sharp - interpolated, they rippled 0.3 % of the size out past them.
|
||||
const fit = keep(sharp(rows) ? new oc.GeomAPI_PointsToBSplineSurface(grid, 3, 3, oc.GeomAbs_Shape.GeomAbs_C0, size * 1e-5) : new oc.GeomAPI_PointsToBSplineSurface());
|
||||
if (!sharp(rows)) fit.Interpolate(grid, false);
|
||||
const surf = fit.Surface();
|
||||
const sew = keep(new oc.BRepBuilderAPI_Sewing(size * 1e-6, true, true, true, false));
|
||||
const side = keep(new oc.BRepBuilderAPI_MakeFace(surf, 1e-6));
|
||||
sew.Add(side.Face());
|
||||
for (const [u, row] of [[surf.UKnot(1), rows[0]], [surf.UKnot(surf.NbUKnots()), rows[nu - 1]]] as const) {
|
||||
const edge = keep(new oc.BRepBuilderAPI_MakeEdge(surf.UIso(u)));
|
||||
const wire = keep(new oc.BRepBuilderAPI_MakeWire(edge.Edge()));
|
||||
// On the profile's own plane (from its points).
|
||||
const c = centroidOf(row);
|
||||
const n = norm(row.reduce((a, p, j) => add(a, cross(sub(p, c), sub(row[(j + 1) % row.length], c))), [0, 0, 0] as Vec3));
|
||||
const pln = keep(new oc.gp_Pln(keep(new oc.gp_Pnt(...c)), keep(new oc.gp_Dir(...n))));
|
||||
const cap = keep(new oc.BRepBuilderAPI_MakeFace(pln, wire.Wire(), true));
|
||||
if (!cap.IsDone()) throw new Error("A profile isn't flat: the loft's end can't be closed");
|
||||
sew.Add(cap.Face());
|
||||
}
|
||||
const progress = keep(new oc.Message_ProgressRange());
|
||||
sew.Perform(progress);
|
||||
const sewed = sew.SewedShape();
|
||||
if (sewed.ShapeType() !== oc.TopAbs_ShapeEnum.TopAbs_SHELL) throw new Error("These profiles can't be lofted along those guides");
|
||||
const fix = keep(new oc.ShapeFix_Solid());
|
||||
const solid = cast(fix.SolidFromShell(oc.TopoDS.Shell(sewed)));
|
||||
if (!isShape3D(solid)) throw new Error("These profiles can't be lofted along those guides");
|
||||
return solid;
|
||||
} finally {
|
||||
for (const o of gc.reverse()) o.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loft through closed profiles (in order), held by guide curves along its
|
||||
* sides and by connection points (one point near each profile per connection).
|
||||
* (Its sides are always smooth: Straight sides doesn't apply.)
|
||||
*/
|
||||
export function railLoft(wires: Wire[], rails: Wire[], connections: Vec3[][]): Shape3D {
|
||||
let secs = wires.map((w) => sample(w));
|
||||
if (secs.some((c) => !c.closed)) throw new Error("Guide curves and connection points need closed profiles");
|
||||
const size = Math.max(...secs.map((c) => Math.max(...c.pts.map((p) => len(sub(p, centroid(c)))))), 1e-6);
|
||||
// All one way round, seen down the loft.
|
||||
const axis = norm(sub(centroid(secs[secs.length - 1]), centroid(secs[0])));
|
||||
secs = secs.map((c) => (dot(winding(c), axis) < 0 ? reversed(c) : c));
|
||||
|
||||
const anchors: Anchor[] = [];
|
||||
const railCurves = rails.map((w) => sample(w, 1200));
|
||||
const tol = Math.max(size * 0.03, 0.05);
|
||||
railCurves.forEach((rc, k) => {
|
||||
const m = secs.map((sec) => meet(rc, sec));
|
||||
const off = m.findIndex((x) => x.d > tol);
|
||||
if (off >= 0) throw new Error(`Guide curve ${k + 1} doesn't touch profile ${off + 1}: each guide must run through every profile`);
|
||||
anchors.push({ rail: k, a: m.map((x) => x.onSec), r: m.map((x) => x.onRail) });
|
||||
});
|
||||
for (const [k, pts] of connections.entries()) {
|
||||
if (pts.length !== secs.length) throw new Error(`Connection ${k + 1} needs a point on every profile`);
|
||||
anchors.push({ rail: -1, a: secs.map((sec, i) => nearest(sec, pts[i]).f), r: [] });
|
||||
}
|
||||
if (!anchors.length) throw new Error("Add a guide curve or a connection");
|
||||
|
||||
// Round each profile from the first anchor; the anchors must come in the same order on all.
|
||||
anchors.sort((x, y) => x.a[0] - y.a[0]);
|
||||
const rel = (i: number, k: number) => (((anchors[k].a[i] - anchors[0].a[i]) % 1) + 1) % 1;
|
||||
for (let i = 1; i < secs.length; i++)
|
||||
for (let k = 1; k < anchors.length; k++)
|
||||
if (rel(i, k) <= rel(i, k - 1)) throw new Error("The guides or connections cross over between profiles: they must go round each profile in the same order");
|
||||
|
||||
// The same number of points between each two anchors on every profile.
|
||||
const N = 160;
|
||||
const counts = anchors.map((_, k) => Math.max(3, Math.round(N * ((k + 1 < anchors.length ? rel(0, k + 1) : 1) - rel(0, k)))));
|
||||
const start = counts.map((_, k) => counts.slice(0, k).reduce((a, b) => a + b, 0));
|
||||
const total = counts.reduce((a, b) => a + b, 0);
|
||||
const resampled = secs.map((sec, i) => {
|
||||
const out: Vec3[] = [];
|
||||
anchors.forEach((an, k) => {
|
||||
const from = an.a[i];
|
||||
const to = from + ((k + 1 < anchors.length ? rel(i, k + 1) : 1) - rel(i, k));
|
||||
for (let m = 0; m < counts[k]; m++) out.push(at(sec, from + ((to - from) * m) / counts[k]));
|
||||
});
|
||||
return out;
|
||||
});
|
||||
|
||||
// Between profiles: sections that follow the guides.
|
||||
const railAnchors = anchors.map((an, k) => ({ an, idx: start[k] })).filter((x) => x.an.rail >= 0);
|
||||
const sections: Vec3[][] = [resampled[0]];
|
||||
for (let i = 0; i + 1 < resampled.length; i++) {
|
||||
{
|
||||
const M = railAnchors.length ? 6 : 3;
|
||||
for (let m = 1; m <= M; m++) {
|
||||
const t = m / (M + 1);
|
||||
const P = resampled[i].map((p, j) => add(p, scale(sub(resampled[i + 1][j], p), t)));
|
||||
if (!railAnchors.length) {
|
||||
sections.push(P);
|
||||
continue;
|
||||
}
|
||||
const moves = railAnchors.map(({ an, idx }) => ({ idx, d: sub(at(railCurves[an.rail], an.r[i] + (an.r[i + 1] - an.r[i]) * t), P[idx]) }));
|
||||
// Each point moved as the guides either side of it are, by how near it is to each.
|
||||
sections.push(
|
||||
P.map((p, j) => {
|
||||
if (moves.length === 1) return add(p, moves[0].d);
|
||||
let q = moves.length - 1;
|
||||
for (let k = 0; k < moves.length; k++) if (moves[k].idx <= j) q = k;
|
||||
const a = moves[q];
|
||||
const b = moves[(q + 1) % moves.length];
|
||||
const span = (b.idx - a.idx + total) % total || total;
|
||||
const w = ((j - a.idx + total) % total) / span;
|
||||
return add(p, add(scale(a.d, 1 - w), scale(b.d, w)));
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
sections.push(resampled[i + 1]);
|
||||
}
|
||||
|
||||
return gridSolid(sections, size);
|
||||
}
|
||||
@@ -0,0 +1,623 @@
|
||||
// A body as triangles and lines: for the view, for a printed file, and for the
|
||||
// checks that go by a mesh.
|
||||
|
||||
import { getOC, type Face, type Shape3D } from "replicad";
|
||||
import { Earcut } from "three/src/extras/Earcut.js";
|
||||
|
||||
/** A body's faces as triangles. `faceGroups[i]` is where face i's corners are in `triangles` (the body's faces in their own order). */
|
||||
export interface FaceMesh {
|
||||
vertices: Float32Array;
|
||||
normals: Float32Array;
|
||||
triangles: Uint32Array;
|
||||
faceGroups: { start: number; count: number }[];
|
||||
}
|
||||
|
||||
/** A body's edges as lines. `edgeGroups[i]` is where edge i's points are in `lines` (the body's edges in their own order). */
|
||||
export interface EdgeLines {
|
||||
lines: Float32Array;
|
||||
edgeGroups: { start: number; count: number }[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Faces meshed in one go. OpenCascade's mesher keeps its working notes on every
|
||||
* face and edge of what it is given until all of it is done, tens of kilobytes
|
||||
* each: a body of 4 500 faces took the engine's memory from 100 MB to 1.3 GB
|
||||
* (and memory once taken is never given back), one of 40 000 - a scanned part
|
||||
* sewn into a solid - to the 4 GB a browser allows, where the engine breaks.
|
||||
* The same faces a few hundred at a time are the same triangles in the same
|
||||
* order, a little sooner, and the memory doesn't move.
|
||||
*/
|
||||
const LOT = 300;
|
||||
|
||||
/**
|
||||
* Outlines (the face's own, and one for each hole) from which a flat face is
|
||||
* cut into triangles here instead of by OpenCascade, whose mesher takes time
|
||||
* and memory by the square of a face's holes: a plate's two faces with 100
|
||||
* holes 0.3 s, with 400 holes 5 s and 700 MB - and again for every print file
|
||||
* and every check that wants a point on such a face. Here: a few milliseconds.
|
||||
*/
|
||||
const LOOPS = 30;
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
/** The shapes whose faces are meshed, and how finely (so its edge lines needn't mesh it again). */
|
||||
const meshedAt = new WeakMap<object, string>();
|
||||
/** The edge lines of a body some of whose faces were cut into triangles here: worked out with them. */
|
||||
const linesReady = new WeakMap<object, { key: string; lines: EdgeLines }>();
|
||||
|
||||
/** One explorer for each kernel, pointed at shape after shape (each one made stays in the kernel for good: release.ts). */
|
||||
const explorers = new WeakMap<object, { ex: any; nothing: any }>();
|
||||
function explorer(): { ex: any; nothing: any } {
|
||||
const oc = getOC() as any;
|
||||
let e = explorers.get(oc);
|
||||
if (!e) explorers.set(oc, (e = { ex: new oc.TopExp_Explorer(), nothing: new oc.TopoDS_Shape() }));
|
||||
return e;
|
||||
}
|
||||
|
||||
/** How many closed outlines a face has (its own, and one for each hole). */
|
||||
function loopCount(face: { wrapped: unknown }): number {
|
||||
const oc = getOC() as any;
|
||||
const { ex, nothing } = explorer();
|
||||
const ANY = oc.TopAbs_ShapeEnum.TopAbs_SHAPE;
|
||||
let n = 0;
|
||||
for (ex.Init(face.wrapped, oc.TopAbs_ShapeEnum.TopAbs_WIRE, ANY); ex.More(); ex.Next()) n++;
|
||||
ex.Init(nothing, ANY, ANY);
|
||||
return n;
|
||||
}
|
||||
|
||||
/** Is this a flat face with so many holes that it is cut into triangles here? */
|
||||
const manyHoled = (face: Face): boolean => loopCount(face) >= LOOPS && face.geomType === "PLANE";
|
||||
|
||||
/** A shape's edges, each once, in the order met - the kernel's own handles: `done()` gives them back. */
|
||||
function edgesOf(wrapped: unknown): { edges: any[]; at: (edge: any) => number; done: () => void } {
|
||||
const oc = getOC() as any;
|
||||
const { ex, nothing } = explorer();
|
||||
const ANY = oc.TopAbs_ShapeEnum.TopAbs_SHAPE;
|
||||
const buckets = new Map<number, number[]>();
|
||||
const edges: any[] = [];
|
||||
const hash = (x: any): number => oc.ReplicadShapeHasher.HashCode(x, 2147483647);
|
||||
for (ex.Init(wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE, ANY); ex.More(); ex.Next()) {
|
||||
const item = ex.Current();
|
||||
const h = hash(item);
|
||||
const b = buckets.get(h);
|
||||
if (b?.some((i) => edges[i].IsSame(item))) {
|
||||
item.delete();
|
||||
continue;
|
||||
}
|
||||
if (b) b.push(edges.length);
|
||||
else buckets.set(h, [edges.length]);
|
||||
edges.push(item);
|
||||
}
|
||||
ex.Init(nothing, ANY, ANY);
|
||||
return {
|
||||
edges,
|
||||
at: (edge) => buckets.get(hash(edge))?.find((i) => edges[i].IsSame(edge)) ?? -1,
|
||||
done: () => edges.forEach((e) => e.delete()),
|
||||
};
|
||||
}
|
||||
|
||||
/** The lines of a shape's edges as the kernel has them (in the order of the shape's edges). */
|
||||
function readLines(wrapped: unknown, tolerance: number, angularTolerance: number): EdgeLines {
|
||||
const raw = (getOC() as any).ReplicadEdgeMeshExtractor.extract(wrapped, tolerance, angularTolerance);
|
||||
try {
|
||||
const groups = ints(raw.getEdgeGroupsPtr(), raw.getEdgeGroupsSize());
|
||||
const edgeGroups: EdgeLines["edgeGroups"] = [];
|
||||
for (let i = 0; i < groups.length; i += 3) edgeGroups.push({ start: groups[i], count: groups[i + 1] });
|
||||
return { lines: floats(raw.getLinesPtr(), raw.getLinesSize()), edgeGroups };
|
||||
} finally {
|
||||
raw.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Edge lines joined end to end into closed outlines (each a run of x, y, z;
|
||||
* its last point not its first again). Null: they don't close up.
|
||||
*/
|
||||
function outlines(lines: Float32Array[], grain: number): Float32Array[] | null {
|
||||
const key = (l: Float32Array, k: number) => `${Math.round(l[k] / grain)},${Math.round(l[k + 1] / grain)},${Math.round(l[k + 2] / grain)}`;
|
||||
const out: Float32Array[] = [];
|
||||
// (A point given twice running - the kernel's lines have some, where a round face's seam is - is one point.)
|
||||
const add = (pts: ArrayLike<number>) => {
|
||||
const once: number[] = [];
|
||||
const apart = (k: number, j: number) => Math.hypot(pts[k] - once[j], pts[k + 1] - once[j + 1], pts[k + 2] - once[j + 2]) > grain;
|
||||
for (let k = 0; k < pts.length; k += 3) if (!once.length || apart(k, once.length - 3)) once.push(pts[k], pts[k + 1], pts[k + 2]);
|
||||
const m = once.length;
|
||||
if (m >= 6 && Math.hypot(once[m - 3] - once[0], once[m - 2] - once[1], once[m - 1] - once[2]) <= grain) once.length = m - 3;
|
||||
if (once.length >= 9) out.push(Float32Array.from(once));
|
||||
};
|
||||
const ends = new Map<string, number[]>();
|
||||
const open: number[] = [];
|
||||
lines.forEach((l, i) => {
|
||||
if (l.length < 6) return;
|
||||
const [a, b] = [key(l, 0), key(l, l.length - 3)];
|
||||
if (a === b) {
|
||||
// (An edge that closes on itself - a circle - is an outline; one that only goes there and back is nothing.)
|
||||
add(l);
|
||||
return;
|
||||
}
|
||||
open.push(i);
|
||||
for (const k of [a, b]) ends.set(k, [...(ends.get(k) ?? []), i]);
|
||||
});
|
||||
const used = new Set<number>();
|
||||
for (const first of open) {
|
||||
if (used.has(first)) continue;
|
||||
used.add(first);
|
||||
const pts: number[] = Array.from(lines[first]);
|
||||
const start = key(lines[first], 0);
|
||||
let tip = key(lines[first], lines[first].length - 3);
|
||||
for (let guard = 0; tip !== start; guard++) {
|
||||
const next = ends.get(tip)?.find((i) => !used.has(i));
|
||||
if (next === undefined || guard > open.length) return null;
|
||||
used.add(next);
|
||||
const l = lines[next];
|
||||
if (key(l, 0) === tip) {
|
||||
for (let k = 3; k < l.length; k++) pts.push(l[k]);
|
||||
tip = key(l, l.length - 3);
|
||||
} else {
|
||||
for (let k = l.length - 6; k >= 0; k -= 3) pts.push(l[k], l[k + 1], l[k + 2]);
|
||||
tip = key(l, 0);
|
||||
}
|
||||
}
|
||||
add(pts);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A flat face as triangles between the points of its outlines (no points of
|
||||
* its own: it meets its neighbours along the very points they have). Null
|
||||
* when it doesn't come out as the face's area.
|
||||
*/
|
||||
function flatTriangles(loops: Float32Array[], normal: [number, number, number]): FaceMesh | null {
|
||||
if (!loops.length) return null;
|
||||
const n = normal;
|
||||
const l = Math.hypot(n[0], n[1], n[2]);
|
||||
if (!(l > 0)) return null;
|
||||
// Two directions across the face (x, then y so that x, y, n turn the usual way).
|
||||
const a = Math.abs(n[0]) < 0.9 * l ? [1, 0, 0] : [0, 1, 0];
|
||||
let x = [a[1] * n[2] - a[2] * n[1], a[2] * n[0] - a[0] * n[2], a[0] * n[1] - a[1] * n[0]];
|
||||
const xl = Math.hypot(x[0], x[1], x[2]);
|
||||
x = x.map((v) => v / xl);
|
||||
const y = [(n[1] * x[2] - n[2] * x[1]) / l, (n[2] * x[0] - n[0] * x[2]) / l, (n[0] * x[1] - n[1] * x[0]) / l];
|
||||
const flat = loops.map((p) => {
|
||||
const q = new Float64Array((p.length / 3) * 2);
|
||||
for (let k = 0, j = 0; k < p.length; k += 3, j += 2) {
|
||||
q[j] = p[k] * x[0] + p[k + 1] * x[1] + p[k + 2] * x[2];
|
||||
q[j + 1] = p[k] * y[0] + p[k + 1] * y[1] + p[k + 2] * y[2];
|
||||
}
|
||||
return q;
|
||||
});
|
||||
const area = (q: Float64Array) => {
|
||||
let s = 0;
|
||||
for (let j = 0, m = q.length; j < m; j += 2) s += q[j] * q[(j + 3) % m] - q[(j + 2) % m] * q[j + 1];
|
||||
return s / 2;
|
||||
};
|
||||
const areas = flat.map(area);
|
||||
// The outline itself is the biggest; the others are its holes.
|
||||
let outer = 0;
|
||||
areas.forEach((v, i) => Math.abs(v) > Math.abs(areas[outer]) && (outer = i));
|
||||
const order = [outer, ...loops.map((_, i) => i).filter((i) => i !== outer)];
|
||||
const count = order.reduce((s, i) => s + flat[i].length / 2, 0);
|
||||
const data = new Float64Array(count * 2);
|
||||
const vertices = new Float32Array(count * 3);
|
||||
const holes: number[] = [];
|
||||
let at = 0;
|
||||
for (const i of order) {
|
||||
if (i !== outer) holes.push(at);
|
||||
data.set(flat[i], at * 2);
|
||||
vertices.set(loops[i], at * 3);
|
||||
at += flat[i].length / 2;
|
||||
}
|
||||
// Earcut leaves out a point that lies on the straight line between its
|
||||
// neighbours (and its neighbours include the cuts it makes from hole to
|
||||
// hole): a row of square holes lost corners, and the face no longer met the
|
||||
// holes' walls at them. So no three points are in line for it - each is
|
||||
// moved a hair (for the cutting only) - and what that makes of points truly
|
||||
// in line, a triangle with no area, is taken out again below.
|
||||
let span = 1e-9;
|
||||
for (let j = 0; j < data.length; j++) span = Math.max(span, Math.abs(data[j]));
|
||||
const shaken = new Float64Array(data.length);
|
||||
for (let j = 0; j < data.length; j++) shaken[j] = data[j] + span * 1e-9 * Math.sin(j * 12.9898 + 4.1414) * 0.5;
|
||||
const cut = Earcut.triangulate(shaken as unknown as number[], holes, 2);
|
||||
if (cut.length < 3) return null;
|
||||
const twice = (p: number, q: number, r: number) => (data[2 * q] - data[2 * p]) * (data[2 * r + 1] - data[2 * p + 1]) - (data[2 * r] - data[2 * p]) * (data[2 * q + 1] - data[2 * p + 1]);
|
||||
const far2 = (p: number, q: number) => (data[2 * q] - data[2 * p]) ** 2 + (data[2 * q + 1] - data[2 * p + 1]) ** 2;
|
||||
// All turning the way the face looks (they all turn one way: as a whole, not
|
||||
// one by one - a triangle with next to no area can't say which way it turns).
|
||||
let tris: number[][] = [];
|
||||
let turn = 0;
|
||||
for (let k = 0; k < cut.length; k += 3) {
|
||||
tris.push([cut[k], cut[k + 1], cut[k + 2]]);
|
||||
turn += twice(cut[k], cut[k + 1], cut[k + 2]);
|
||||
}
|
||||
if (turn < 0) tris = tris.map(([p, q, r]) => [p, r, q]);
|
||||
// No area: its third corner on its long side, to what a point's seven digits
|
||||
// can be out by, and well in from both its ends. (Not a long thin needle
|
||||
// between two holes far apart: that one has an area, small as it is.)
|
||||
const middle = (t: number[]): [number, number, number] | null => {
|
||||
let j = 0;
|
||||
for (let m = 1; m < 3; m++) if (far2(t[m], t[(m + 1) % 3]) > far2(t[j], t[(j + 1) % 3])) j = m;
|
||||
const [u, v, mid] = [t[j], t[(j + 1) % 3], t[(j + 2) % 3]];
|
||||
const long2 = far2(u, v);
|
||||
if (Math.abs(twice(u, v, mid)) > Math.sqrt(long2) * span * 4e-7) return null;
|
||||
return Math.min(far2(u, mid), far2(v, mid)) > long2 * 1e-6 ? [u, v, mid] : null;
|
||||
};
|
||||
// Such a triangle is a point lying on the long side of its neighbour: that
|
||||
// neighbour is cut in two at the point, and the flat one goes. (Points in a
|
||||
// row - the tops of a row of round holes - make a fan of flat triangles:
|
||||
// taken from the outside in, each next to a neighbour that has an area. Each
|
||||
// is dealt with once: what can't be put right this way stays as it is.)
|
||||
const dealt = new Set<string>();
|
||||
for (let pass = 0; pass < 4096; pass++) {
|
||||
const flatOnes: [number, [number, number, number]][] = [];
|
||||
tris.forEach((t, i) => {
|
||||
const m = middle(t);
|
||||
if (m && !dealt.has([...t].sort((x, y) => x - y).join())) flatOnes.push([i, m]);
|
||||
});
|
||||
if (!flatOnes.length) break;
|
||||
const side = new Map<number, number>();
|
||||
tris.forEach((t, i) => {
|
||||
for (let j = 0; j < 3; j++) side.set(t[j] * count + t[(j + 1) % 3], i);
|
||||
});
|
||||
const gone = new Set<number>();
|
||||
const more: number[][] = [];
|
||||
for (const [i, [u, v, mid]] of flatOnes) {
|
||||
if (gone.has(i)) continue;
|
||||
const n = side.get(v * count + u);
|
||||
if (n === undefined || n === i || gone.has(n)) continue;
|
||||
const other = tris[n];
|
||||
if (middle(other)) continue;
|
||||
const x = other.find((c) => c !== u && c !== v)!;
|
||||
dealt.add([...tris[i]].sort((p, q) => p - q).join());
|
||||
gone.add(i);
|
||||
gone.add(n);
|
||||
more.push([v, mid, x], [mid, u, x]);
|
||||
}
|
||||
if (!gone.size) break;
|
||||
tris = [...tris.filter((_, i) => !gone.has(i)), ...more];
|
||||
}
|
||||
// Along every piece of its outlines there must be a triangle: that is where it meets its neighbours.
|
||||
const sides = new Set<number>();
|
||||
for (const t of tris) for (let j = 0; j < 3; j++) sides.add(Math.min(t[j], t[(j + 1) % 3]) * count + Math.max(t[j], t[(j + 1) % 3]));
|
||||
at = 0;
|
||||
for (const i of order) {
|
||||
const m = flat[i].length / 2;
|
||||
for (let k = 0; k < m; k++) {
|
||||
const [p, q] = [at + k, at + ((k + 1) % m)];
|
||||
if (!sides.has(Math.min(p, q) * count + Math.max(p, q))) return null;
|
||||
}
|
||||
at += m;
|
||||
}
|
||||
const want = Math.abs(areas[outer]) - areas.reduce((sum, v, i) => (i === outer ? sum : sum + Math.abs(v)), 0);
|
||||
const triangles = new Uint32Array(tris.length * 3);
|
||||
let got = 0;
|
||||
tris.forEach((t, i) => {
|
||||
got += Math.abs(twice(t[0], t[1], t[2])) / 2;
|
||||
triangles.set(t, i * 3);
|
||||
});
|
||||
if (!(want > 0) || Math.abs(got - want) > want * 1e-4) return null;
|
||||
const normals = new Float32Array(count * 3);
|
||||
for (let k = 0; k < normals.length; k += 3) normals.set([n[0] / l, n[1] / l, n[2] / l], k);
|
||||
return { vertices, normals, triangles, faceGroups: [{ start: 0, count: triangles.length }] };
|
||||
}
|
||||
|
||||
/** One edge's points out of a set of edge lines. */
|
||||
const lineOf = (e: EdgeLines, i: number): Float32Array => e.lines.subarray(e.edgeGroups[i].start * 3, (e.edgeGroups[i].start + e.edgeGroups[i].count) * 3);
|
||||
|
||||
function compoundOf(items: { wrapped: unknown }[]): any {
|
||||
const oc = getOC() as any;
|
||||
const builder = new oc.TopoDS_Builder();
|
||||
const compound = new oc.TopoDS_Compound();
|
||||
builder.MakeCompound(compound);
|
||||
for (const x of items) builder.Add(compound, x.wrapped);
|
||||
builder.delete();
|
||||
return compound;
|
||||
}
|
||||
|
||||
// (Views of the engine's memory are made after each call: when it grows, its buffer is a new one.)
|
||||
const floats = (ptr: number, size: number) => new Float32Array((getOC() as any).wasmMemory.buffer, ptr >>> 0, size).slice();
|
||||
const ints = (ptr: number, size: number) => new Int32Array((getOC() as any).wasmMemory.buffer, ptr >>> 0, size).slice();
|
||||
const indices = (ptr: number, size: number) => new Uint32Array((getOC() as any).wasmMemory.buffer, ptr >>> 0, size).slice();
|
||||
|
||||
/** The triangles of a shape handed to the mesher whole. */
|
||||
function read(wrapped: unknown, tolerance: number, angularTolerance: number): FaceMesh {
|
||||
const raw = (getOC() as any).ReplicadMeshExtractor.extract(wrapped, tolerance, angularTolerance, false);
|
||||
try {
|
||||
const groups = ints(raw.getFaceGroupsPtr(), raw.getFaceGroupsSize());
|
||||
const faceGroups: FaceMesh["faceGroups"] = [];
|
||||
for (let i = 0; i < groups.length; i += 3) faceGroups.push({ start: groups[i], count: groups[i + 1] });
|
||||
return {
|
||||
vertices: floats(raw.getVerticesPtr(), raw.getVerticesSize()),
|
||||
normals: floats(raw.getNormalsPtr(), raw.getNormalsSize()),
|
||||
triangles: indices(raw.getTrianglesPtr(), raw.getTrianglesSize()),
|
||||
faceGroups,
|
||||
};
|
||||
} finally {
|
||||
raw.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** Meshes one after another as one. */
|
||||
function joined(parts: FaceMesh[]): FaceMesh {
|
||||
if (parts.length === 1) return parts[0];
|
||||
const total = (pick: (m: FaceMesh) => { length: number }) => parts.reduce((n, m) => n + pick(m).length, 0);
|
||||
const out: FaceMesh = {
|
||||
vertices: new Float32Array(total((m) => m.vertices)),
|
||||
normals: new Float32Array(total((m) => m.normals)),
|
||||
triangles: new Uint32Array(total((m) => m.triangles)),
|
||||
faceGroups: [],
|
||||
};
|
||||
let points = 0;
|
||||
let corners = 0;
|
||||
for (const m of parts) {
|
||||
out.vertices.set(m.vertices, points * 3);
|
||||
out.normals.set(m.normals, points * 3);
|
||||
for (let k = 0; k < m.triangles.length; k++) out.triangles[corners + k] = m.triangles[k] + points;
|
||||
for (const g of m.faceGroups) out.faceGroups.push({ start: g.start + corners, count: g.count });
|
||||
points += m.vertices.length / 3;
|
||||
corners += m.triangles.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A body's faces as triangles, each face's own (none shared across an edge), in
|
||||
* the order of `shape.faces`.
|
||||
*/
|
||||
export function meshFaces(shape: Shape3D, tolerance: number, angularTolerance: number): FaceMesh {
|
||||
const faces = shape.faces;
|
||||
meshedAt.set(shape, `${tolerance}/${angularTolerance}`);
|
||||
linesReady.delete(shape);
|
||||
const flat = faces.map(manyHoled);
|
||||
if (flat.some(Boolean)) {
|
||||
const made = withFlatFaces(shape, faces, flat, tolerance, angularTolerance);
|
||||
if (made) return made;
|
||||
}
|
||||
if (faces.length <= LOT) return read(shape.wrapped, tolerance, angularTolerance);
|
||||
const parts: FaceMesh[] = [];
|
||||
for (let i = 0; i < faces.length; i += LOT) {
|
||||
const lot = faces.slice(i, i + LOT);
|
||||
const group = compoundOf(lot);
|
||||
try {
|
||||
let part = read(group, tolerance, angularTolerance);
|
||||
// A face that came to nothing left out of the count: each on its own, so the others keep their places.
|
||||
if (part.faceGroups.length !== lot.length)
|
||||
part = joined(
|
||||
lot.map((f) => {
|
||||
const one = read(f.wrapped, tolerance, angularTolerance);
|
||||
return one.faceGroups.length === 1 ? one : { ...one, faceGroups: [{ start: 0, count: one.triangles.length }] };
|
||||
}),
|
||||
);
|
||||
parts.push(part);
|
||||
} finally {
|
||||
group.delete();
|
||||
}
|
||||
}
|
||||
return joined(parts);
|
||||
}
|
||||
|
||||
/** Faces a few hundred at a time, as triangles (see LOT). */
|
||||
function inLots(faces: Face[], tolerance: number, angularTolerance: number): FaceMesh[] {
|
||||
const parts: FaceMesh[] = [];
|
||||
for (let i = 0; i < faces.length; i += LOT) {
|
||||
const lot = faces.slice(i, i + LOT);
|
||||
const group = compoundOf(lot);
|
||||
try {
|
||||
const part = read(group, tolerance, angularTolerance);
|
||||
if (part.faceGroups.length !== lot.length) throw new Error("a face without triangles");
|
||||
parts.push(part);
|
||||
} finally {
|
||||
group.delete();
|
||||
}
|
||||
}
|
||||
return parts;
|
||||
}
|
||||
|
||||
/**
|
||||
* A body with flat faces of very many holes (`flat`): those cut into triangles
|
||||
* here, between the points their neighbours' meshes have along their edges;
|
||||
* the rest by OpenCascade. Its edge lines are worked out with it (kept for
|
||||
* meshEdgeLines). Null when it can't be done this way (the usual way then).
|
||||
*/
|
||||
function withFlatFaces(shape: Shape3D, faces: Face[], flat: boolean[], tolerance: number, angularTolerance: number): FaceMesh | null {
|
||||
const trash: (() => void)[] = [];
|
||||
const rest = faces.filter((_, i) => !flat[i]);
|
||||
const others = rest.length ? compoundOf(rest) : null;
|
||||
try {
|
||||
// The other faces first: their meshes say where the points along the shared edges are.
|
||||
for (let i = 0; i < rest.length; i += LOT) {
|
||||
const group = compoundOf(rest.slice(i, i + LOT));
|
||||
try {
|
||||
(getOC() as any).ReplicadMeshExtractor.mesh(group, tolerance, angularTolerance);
|
||||
} finally {
|
||||
group.delete();
|
||||
}
|
||||
}
|
||||
const theirs: EdgeLines = others ? readLines(others, tolerance, angularTolerance) : { lines: new Float32Array(0), edgeGroups: [] };
|
||||
const known = others ? edgesOf(others) : null;
|
||||
if (known) trash.push(known.done);
|
||||
if (known && known.edges.length !== theirs.edgeGroups.length) return null;
|
||||
// Edges with no neighbour but such faces (the fold between two): their own lines.
|
||||
const all = edgesOf(shape.wrapped);
|
||||
trash.push(all.done);
|
||||
const lone = all.edges.filter((e) => !known || known.at(e) < 0);
|
||||
let own: EdgeLines | null = null;
|
||||
let ownAt: ReturnType<typeof edgesOf> | null = null;
|
||||
if (lone.length) {
|
||||
const group = compoundOf(lone.map((e) => ({ wrapped: e })));
|
||||
try {
|
||||
own = readLines(group, tolerance, angularTolerance);
|
||||
ownAt = edgesOf(group);
|
||||
trash.push(ownAt.done);
|
||||
if (ownAt.edges.length !== own.edgeGroups.length) return null;
|
||||
} finally {
|
||||
group.delete();
|
||||
}
|
||||
}
|
||||
const pointsOf = (edge: any): Float32Array | null => {
|
||||
const i = known ? known.at(edge) : -1;
|
||||
if (i >= 0) return lineOf(theirs, i);
|
||||
const j = ownAt ? ownAt.at(edge) : -1;
|
||||
return j >= 0 && own ? lineOf(own, j) : null;
|
||||
};
|
||||
const box = shape.boundingBox;
|
||||
const grain = (Math.hypot(box.width, box.height, box.depth) || 1) * 2e-6;
|
||||
// Each face in its place: runs of the others (in lots), the flat ones one by one.
|
||||
const parts: FaceMesh[] = [];
|
||||
let run: Face[] = [];
|
||||
const flush = () => {
|
||||
if (run.length) parts.push(...inLots(run, tolerance, angularTolerance));
|
||||
run = [];
|
||||
};
|
||||
for (const [i, face] of faces.entries()) {
|
||||
if (!flat[i]) {
|
||||
run.push(face);
|
||||
continue;
|
||||
}
|
||||
const mine = edgesOf(face.wrapped);
|
||||
let part: FaceMesh | null = null;
|
||||
try {
|
||||
const lines = mine.edges.map(pointsOf);
|
||||
const loops = lines.every(Boolean) ? outlines(lines as Float32Array[], grain) : null;
|
||||
part = loops && flatTriangles(loops, face.normalAt().toTuple() as [number, number, number]);
|
||||
} finally {
|
||||
mine.done();
|
||||
}
|
||||
if (!part) return null;
|
||||
flush();
|
||||
parts.push(part);
|
||||
}
|
||||
flush();
|
||||
// The body's edge lines, in the order of its edges.
|
||||
const each = all.edges.map(pointsOf);
|
||||
if (!each.every(Boolean)) return null;
|
||||
const lines = new Float32Array(each.reduce((n, l) => n + l!.length, 0));
|
||||
const edgeGroups: EdgeLines["edgeGroups"] = [];
|
||||
let at = 0;
|
||||
for (const l of each as Float32Array[]) {
|
||||
lines.set(l, at * 3);
|
||||
edgeGroups.push({ start: at, count: l.length / 3 });
|
||||
at += l.length / 3;
|
||||
}
|
||||
linesReady.set(shape, { key: `${tolerance}/${angularTolerance}`, lines: { lines, edgeGroups } });
|
||||
return joined(parts);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
for (const done of trash) done();
|
||||
others?.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A body's edges as lines, in the order of `shape.edges` - the lines its faces'
|
||||
* triangles meet along (so its faces are meshed first, if they aren't yet).
|
||||
*/
|
||||
export function meshEdgeLines(shape: Shape3D, tolerance: number, angularTolerance: number): EdgeLines {
|
||||
const oc = getOC() as any;
|
||||
const ready = linesReady.get(shape);
|
||||
if (ready?.key === `${tolerance}/${angularTolerance}`) return ready.lines;
|
||||
if (meshedAt.get(shape) !== `${tolerance}/${angularTolerance}`) {
|
||||
// (A body with faces cut into triangles here: its lines come with those.)
|
||||
const faces = shape.faces;
|
||||
if (faces.some(manyHoled)) {
|
||||
meshFaces(shape, tolerance, angularTolerance);
|
||||
const made = linesReady.get(shape);
|
||||
if (made) return made.lines;
|
||||
}
|
||||
// (In lots, as above: read off the whole body unmeshed, it is meshed whole.)
|
||||
for (let i = 0; faces.length > LOT && i < faces.length; i += LOT) {
|
||||
const group = compoundOf(faces.slice(i, i + LOT));
|
||||
try {
|
||||
oc.ReplicadMeshExtractor.mesh(group, tolerance, angularTolerance);
|
||||
} finally {
|
||||
group.delete();
|
||||
}
|
||||
}
|
||||
meshedAt.set(shape, `${tolerance}/${angularTolerance}`);
|
||||
}
|
||||
return readLines(shape.wrapped, tolerance, angularTolerance);
|
||||
}
|
||||
|
||||
/**
|
||||
* A body's triangles taken off it again, once whoever asked for them has
|
||||
* them. Left on, they stay for as long as the kernel holds the body - and the
|
||||
* tool that made a body holds it for good (release.ts): every shape ever
|
||||
* shown kept its mesh. Nothing reads them later: each edit works on a copy
|
||||
* of the body, which has none, and a face that wants its own asks for them.
|
||||
*/
|
||||
export function meshOff(shape: Shape3D): void {
|
||||
meshedAt.delete(shape);
|
||||
linesReady.delete(shape);
|
||||
try {
|
||||
(getOC() as any).BRepTools.Clean(shape.wrapped, true);
|
||||
} catch {
|
||||
// Left as they are.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One face's own triangles, for what wants points on it: its corners (x, y, z
|
||||
* each) and which three make each triangle. Made for that face alone when it
|
||||
* has none yet (`size`: its body's, which says how fine) - the whole body used
|
||||
* to be meshed for the one face, seconds on a big body - and read out in one
|
||||
* go: asked for corner by corner, each corner cost four small things in the
|
||||
* kernel that are never given back (release.ts), a megabyte and more with
|
||||
* each check of a shell's walls.
|
||||
*/
|
||||
export function faceTriangles(face: Face, size: number): { vertices: Float32Array; trianglesIndexes: Uint32Array } | null {
|
||||
// (A flat face of very many holes: cut into triangles here, between points along its own edges - see LOOPS.)
|
||||
if (manyHoled(face)) {
|
||||
const mine = edgesOf(face.wrapped);
|
||||
const group = compoundOf(mine.edges.map((e) => ({ wrapped: e })));
|
||||
try {
|
||||
const own = readLines(group, size * 1e-3, 0.3);
|
||||
if (own.edgeGroups.length === mine.edges.length) {
|
||||
const loops = outlines(mine.edges.map((_, i) => lineOf(own, i)), size * 2e-6);
|
||||
const part = loops && flatTriangles(loops, face.normalAt().toTuple() as [number, number, number]);
|
||||
if (part) return { vertices: part.vertices, trianglesIndexes: part.triangles };
|
||||
}
|
||||
} catch {
|
||||
// The usual way.
|
||||
} finally {
|
||||
mine.done();
|
||||
group.delete();
|
||||
}
|
||||
}
|
||||
const raw = (getOC() as any).ReplicadMeshExtractor.extract(face.wrapped, size * 1e-3, 0.3, true);
|
||||
try {
|
||||
const trianglesIndexes = indices(raw.getTrianglesPtr(), raw.getTrianglesSize());
|
||||
if (!trianglesIndexes.length) return null;
|
||||
return { vertices: floats(raw.getVerticesPtr(), raw.getVerticesSize()), trianglesIndexes };
|
||||
} finally {
|
||||
raw.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** Meshes as one binary STL file (each triangle with its own flat normal, as a slicer reads it). */
|
||||
export function binarySTL(meshes: FaceMesh[]): Uint8Array {
|
||||
const count = meshes.reduce((n, m) => n + m.triangles.length / 3, 0);
|
||||
const out = new Uint8Array(84 + count * 50);
|
||||
const view = new DataView(out.buffer);
|
||||
// (80 bytes of heading, never starting "solid": readers take that for the text kind.)
|
||||
out.set(new TextEncoder().encode("binary stl"), 0);
|
||||
view.setUint32(80, count, true);
|
||||
let at = 84;
|
||||
for (const m of meshes) {
|
||||
const p = m.vertices;
|
||||
for (let k = 0; k < m.triangles.length; k += 3) {
|
||||
const [a, b, c] = [m.triangles[k] * 3, m.triangles[k + 1] * 3, m.triangles[k + 2] * 3];
|
||||
const [ux, uy, uz] = [p[b] - p[a], p[b + 1] - p[a + 1], p[b + 2] - p[a + 2]];
|
||||
const [vx, vy, vz] = [p[c] - p[a], p[c + 1] - p[a + 1], p[c + 2] - p[a + 2]];
|
||||
let [nx, ny, nz] = [uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx];
|
||||
const l = Math.hypot(nx, ny, nz);
|
||||
if (l > 0) [nx, ny, nz] = [nx / l, ny / l, nz / l];
|
||||
view.setFloat32(at, nx, true);
|
||||
view.setFloat32(at + 4, ny, true);
|
||||
view.setFloat32(at + 8, nz, true);
|
||||
for (const [j, i] of [a, b, c].entries()) for (let x = 0; x < 3; x++) view.setFloat32(at + 12 + j * 12 + x * 4, p[i + x], true);
|
||||
at += 50;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,493 @@
|
||||
// A face's point and normal at a place on its surface, read straight off it.
|
||||
//
|
||||
// face.normalAt(point) finds where the point is on the surface first (a point
|
||||
// projection), and on a detailed spline surface each projection keeps about
|
||||
// half a megabyte of the engine's memory for good, freed or not. Tidying a
|
||||
// gear's outline swept with a twist (362 spline faces, 25 places each) ran
|
||||
// the engine out of memory (0.2 GB to 3.8 GB) and broke it. Where the place
|
||||
// on the surface is known, ask there.
|
||||
import { getOC, type Edge, type Face, type Shape3D } from "replicad";
|
||||
|
||||
type Tuple = [number, number, number];
|
||||
type Vec3 = Tuple;
|
||||
|
||||
/** Point and normal (outward, not of unit length) at (s, t), each 0..1 across the face's surface. */
|
||||
export function surfaceAt(face: Face, s: number, t: number): { p: Tuple; n: Tuple } {
|
||||
const oc = getOC();
|
||||
const { uMin, uMax, vMin, vMax } = face.UVBounds;
|
||||
const p = new oc.gp_Pnt();
|
||||
const n = new oc.gp_Vec();
|
||||
const g = new oc.BRepGProp_Face(face.wrapped, false);
|
||||
try {
|
||||
g.Normal(uMin + (uMax - uMin) * s, vMin + (vMax - vMin) * t, p, n);
|
||||
return { p: [p.X(), p.Y(), p.Z()], n: [n.X(), n.Y(), n.Z()] };
|
||||
} finally {
|
||||
g.delete();
|
||||
n.delete();
|
||||
p.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A face's normal (of unit length) where one of its edges is, at `s` (0..1)
|
||||
* along the edge (as edge.pointAt counts): read through the edge's own curve
|
||||
* on the face, so nothing is projected. Null if the edge isn't on the face.
|
||||
*/
|
||||
export function normalOnEdge(face: Face, edge: Edge, s: number): Tuple | null {
|
||||
const oc = getOC();
|
||||
let c: InstanceType<typeof oc.BRepAdaptor_Curve2d> | null = null;
|
||||
let uv: { X(): number; Y(): number; delete(): void } | null = null;
|
||||
const p = new oc.gp_Pnt();
|
||||
const n = new oc.gp_Vec();
|
||||
const g = new oc.BRepGProp_Face(face.wrapped, false);
|
||||
try {
|
||||
c = new oc.BRepAdaptor_Curve2d(edge.wrapped, face.wrapped);
|
||||
const t0 = c.FirstParameter();
|
||||
uv = c.Value(t0 + (c.LastParameter() - t0) * s);
|
||||
g.Normal(uv!.X(), uv!.Y(), p, n);
|
||||
const l = Math.hypot(n.X(), n.Y(), n.Z());
|
||||
return l > 0 ? [n.X() / l, n.Y() / l, n.Z() / l] : null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
uv?.delete();
|
||||
c?.delete();
|
||||
g.delete();
|
||||
n.delete();
|
||||
p.delete();
|
||||
}
|
||||
}
|
||||
|
||||
// Volumes and areas, measured to a millionth.
|
||||
//
|
||||
// replicad's measureVolume / measureArea integrate each face at a fixed
|
||||
// fineness, which on many-patched spline faces is well off: a propeller (lofted
|
||||
// blades, rounded roots) measured 203 698 mm³ for 201 310 (1.2 % over), its
|
||||
// centre of mass 0.2 mm off its axis. Asked to a relative accuracy instead,
|
||||
// OpenCascade keeps refining until it's there (about twice the time).
|
||||
const EPS = 1e-6;
|
||||
type Measurable = Shape3D | Face;
|
||||
|
||||
function props(s: Measurable, kind: "volume" | "area") {
|
||||
const oc = getOC();
|
||||
const p = new oc.GProp_GProps();
|
||||
let ok = true;
|
||||
try {
|
||||
const err = kind === "volume" ? oc.BRepGProp.VolumeProperties(s.wrapped, p, EPS, false, false) : oc.BRepGProp.SurfaceProperties(s.wrapped, p, EPS, false);
|
||||
ok = Number.isFinite(err) && Number.isFinite(p.Mass());
|
||||
} catch {
|
||||
ok = false;
|
||||
}
|
||||
if (ok) return p;
|
||||
// (Where the adaptive measure won't settle, the plain one.)
|
||||
p.delete();
|
||||
const q = new oc.GProp_GProps();
|
||||
if (kind === "volume") oc.BRepGProp.VolumeProperties(s.wrapped, q, false, false, false);
|
||||
else oc.BRepGProp.SurfaceProperties(s.wrapped, q, false, false);
|
||||
return q;
|
||||
}
|
||||
|
||||
/** 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();
|
||||
} finally {
|
||||
p.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
} finally {
|
||||
p.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** 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);
|
||||
const c = p.CentreOfMass();
|
||||
try {
|
||||
return { area: p.Mass(), center: [c.X(), c.Y(), c.Z()] };
|
||||
} finally {
|
||||
c.delete();
|
||||
p.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
return { volume: p.Mass(), centerOfMass: [c.X(), c.Y(), c.Z()] };
|
||||
} finally {
|
||||
c.delete();
|
||||
p.delete();
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,12 @@ export interface FaceInfo {
|
||||
plane?: PlaneDef;
|
||||
/** Set for round (cylindrical) faces: the radius, and whether it's a hole (material outside it). */
|
||||
round?: { r: number; hole: boolean };
|
||||
/** The step that made it (see provenance.ts). */
|
||||
step?: string;
|
||||
/** Which of that step's faces it is (the sketch curve it came from; see FaceRef.curve). */
|
||||
curve?: string;
|
||||
/** The step it used to be put down to (a Move its body went through, say): picks saved then name it by that. */
|
||||
was?: string;
|
||||
}
|
||||
|
||||
export interface EdgeInfo {
|
||||
@@ -23,11 +29,25 @@ export interface EdgeInfo {
|
||||
end: Vec3;
|
||||
/** LINE, CIRCLE, ELLIPSE, BSPLINE_CURVE… */
|
||||
type: string;
|
||||
/** The steps that made the faces either side (sorted). */
|
||||
steps?: string[];
|
||||
/** Which faces of those steps (see EdgeRef.curves). */
|
||||
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 {
|
||||
id: string;
|
||||
name: string;
|
||||
/**
|
||||
* Which mesh this is: the same key, the same geometry (a body the step
|
||||
* didn't change). The worker sends only the key for a mesh the page already
|
||||
* has, and the view keeps what it drew for it.
|
||||
*/
|
||||
key: number;
|
||||
positions: Float32Array;
|
||||
normals: Float32Array;
|
||||
indices: Uint32Array;
|
||||
@@ -63,12 +83,92 @@ export interface RegenResult {
|
||||
sketchPlanes: Record<string, PlaneDef>;
|
||||
/** Outline of the face each face-attached sketch sits on (takes part in its regions). */
|
||||
sketchBoundaries: Record<string, SketchEntity[]>;
|
||||
/** Sketches whose curves the engine moved (they follow a body's edge that changed): their curves as they are now. */
|
||||
sketchEntities?: Record<string, SketchEntity[]>;
|
||||
/** Subtract / Union / Delete steps that don't say yet which patterns they used whole: those, by step (the page keeps them with the step). */
|
||||
whole?: Record<string, string[]>;
|
||||
planes: ConstructionInfo[];
|
||||
axes: ConstructionInfo[];
|
||||
errors: FeatureError[];
|
||||
/** Steps that worked but had to give something up (a fillet that no longer fits…). */
|
||||
notes?: FeatureError[];
|
||||
ms: number;
|
||||
/** The engine's memory after it (MB): it never gives any back, so the page starts a fresh engine when it's big. */
|
||||
memoryMB?: number;
|
||||
}
|
||||
|
||||
/** A body's physical properties, measured on the solid itself (mm, mm², mm³). */
|
||||
export interface BodyProps {
|
||||
id: string;
|
||||
name: string;
|
||||
volume: number;
|
||||
area: number;
|
||||
/** Centre of mass (of the shape, as if all of one material). */
|
||||
center: Vec3;
|
||||
/** Its box: lowest corner, highest corner. */
|
||||
box: [Vec3, Vec3];
|
||||
}
|
||||
|
||||
/**
|
||||
* A body's health, measured on the solid (for checking a model from the
|
||||
* console or the command line): valid, closed, how many solids and faces.
|
||||
*/
|
||||
export interface BodyHealth {
|
||||
id: string;
|
||||
name: string;
|
||||
valid: boolean;
|
||||
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;
|
||||
faces: number;
|
||||
edges: number;
|
||||
/** Its box: lowest corner, highest corner. */
|
||||
box: [Vec3, Vec3];
|
||||
/** Valid, closed, no hair-thin faces, a real volume. */
|
||||
healthy: boolean;
|
||||
}
|
||||
|
||||
/** A view to draw: the model seen from `dir` (towards the viewer), `xAxis` to the right on the paper. */
|
||||
export interface ViewSpec {
|
||||
id: string;
|
||||
dir: Vec3;
|
||||
xAxis: Vec3;
|
||||
/** A section view: a point on the cut plane (square to `dir`); what lies between the eye and it is taken off. */
|
||||
cut?: Vec3;
|
||||
}
|
||||
|
||||
/** One body in a drawn view: SVG path data (mm on the paper at 1:1, y down). */
|
||||
export interface ViewBody {
|
||||
id: string;
|
||||
/** Edges seen. */
|
||||
visible: string;
|
||||
/** Where two faces meet smoothly (drawn thin). */
|
||||
tangent: string;
|
||||
/** Edges behind (drawn dashed). */
|
||||
hidden: string;
|
||||
/** A point on one of its seen edges, near its middle: where a balloon's leader ends. */
|
||||
anchor?: [number, number];
|
||||
/** For a body hidden whole in this view (inside a housing): a spot on its hidden edges. */
|
||||
under?: [number, number];
|
||||
/** Its seen straight edges and circles (arcs), to dimension by tapping them. */
|
||||
edges: ViewEdge[];
|
||||
/** A section view: the faces the cut made, as closed outlines (to hatch). */
|
||||
section?: string;
|
||||
}
|
||||
|
||||
/** A seen edge in a view (mm, y down): a line from a to b, or a circle (an arc from a through m to b; whole when a = b). */
|
||||
export type ViewEdge = { a: [number, number]; b: [number, number] } | { a: [number, number]; m: [number, number]; b: [number, number]; c: [number, number]; r: number };
|
||||
|
||||
/** A drawn view: each body, and the box around them all (2D, y down). */
|
||||
export interface ProjectedView {
|
||||
id: string;
|
||||
bodies: ViewBody[];
|
||||
box: [[number, number], [number, number]] | null;
|
||||
}
|
||||
|
||||
/** "mesh": each body as triangles, as finely as an STL (for a 3MF), JSON: { id, positions, indices }[]. */
|
||||
@@ -76,13 +176,19 @@ export type ExportFormat = "stl" | "step" | "mesh";
|
||||
|
||||
export type Request =
|
||||
| { type: "init" }
|
||||
| { type: "regenerate"; features: Feature[] }
|
||||
| { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] };
|
||||
| { type: "regenerate"; features: Feature[]; saved?: boolean }
|
||||
| { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] }
|
||||
| { type: "properties"; features: Feature[] }
|
||||
| { type: "health"; features: Feature[] }
|
||||
| { type: "drawing"; features: Feature[]; views: ViewSpec[]; bodies?: string[] };
|
||||
|
||||
export type Response =
|
||||
| { type: "ready" }
|
||||
| { type: "regenerated"; result: RegenResult }
|
||||
| { type: "exported"; blob: Blob }
|
||||
| { type: "properties"; bodies: BodyProps[] }
|
||||
| { type: "health"; bodies: BodyHealth[] }
|
||||
| { type: "drawing"; views: ProjectedView[] }
|
||||
| { type: "error"; message: string };
|
||||
|
||||
export interface Envelope<T> {
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
// Which step made each face (and so each edge) of a body.
|
||||
//
|
||||
// A step built on a face or edge remembers it by where it is and how big it
|
||||
// is; when an earlier step changes, the best match is taken. With nothing
|
||||
// better to go on, "best" could be a face of another kind altogether: the
|
||||
// screw bosses went onto the top of the box when the shell that made the
|
||||
// floor they stood on was switched off, and a fillet round the bosses' feet
|
||||
// rounded other edges once the bosses were gone - with no word.
|
||||
//
|
||||
// So every face is tagged with the step that made it: a face a step leaves
|
||||
// as it was, or only trims (a side face cut shorter by a fillet, a wall with
|
||||
// a hole cut through it), keeps its tag; a face it makes new gets the step's
|
||||
// id. A reference then looks only among faces from the same step, and when
|
||||
// there are none, says so instead of guessing.
|
||||
|
||||
import { getOC, type Face, type Shape3D } from "replicad";
|
||||
|
||||
interface Tagged {
|
||||
/** The step that made each face (in the order of shape.faces). */
|
||||
steps: string[];
|
||||
/** Each face's surface (plane, cylinder, …) as a key, for faces only trimmed. */
|
||||
keys: (string | null)[];
|
||||
/** Faces by hash, for faces a step left as they were. */
|
||||
byHash: Map<number, { face: Face; i: number }[]>;
|
||||
/**
|
||||
* The step a face used to be put down to, where that was another body's
|
||||
* (see tagBody) or a Move's (see movedTags): what projects saved before
|
||||
* then name it by.
|
||||
*/
|
||||
alias?: (string | undefined)[];
|
||||
/**
|
||||
* Where each face is now, against where its step made it: the moves, turns
|
||||
* and mirrorings its body has been through since (a 3 x 4 matrix, row by
|
||||
* row; none: where it was made).
|
||||
*/
|
||||
moves?: (Moved | undefined)[];
|
||||
}
|
||||
|
||||
/** A 3 x 4 matrix, row by row: where a point is after a move. */
|
||||
type Moved = number[];
|
||||
/** First m, then n. */
|
||||
function then(m: Moved, n: Moved): Moved {
|
||||
const out: number[] = [];
|
||||
for (let r = 0; r < 3; r++) {
|
||||
for (let c = 0; c < 3; c++) out.push(n[r * 4] * m[c] + n[r * 4 + 1] * m[4 + c] + n[r * 4 + 2] * m[8 + c]);
|
||||
out.push(n[r * 4] * m[3] + n[r * 4 + 1] * m[7] + n[r * 4 + 2] * m[11] + n[r * 4 + 3]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A point (or a direction a face looks) taken back to where it was before a move. */
|
||||
export type Back = (v: [number, number, number], direction?: boolean) => [number, number, number];
|
||||
function backOf(m: Moved): Back {
|
||||
const [a, b, c, d, e, f, g, h, i] = [m[0], m[1], m[2], m[4], m[5], m[6], m[8], m[9], m[10]];
|
||||
const det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
|
||||
// The matrix turned back (its inverse).
|
||||
const inv = [e * i - f * h, c * h - b * i, b * f - c * e, f * g - d * i, a * i - c * g, c * d - a * f, d * h - e * g, b * g - a * h, a * e - b * d].map((x) => x / det);
|
||||
return (v, direction) => {
|
||||
// (The way a face looks goes back by the matrix laid on its side: the same thing for a move, a turn, a mirroring.)
|
||||
if (direction) return [a * v[0] + d * v[1] + g * v[2], b * v[0] + e * v[1] + h * v[2], c * v[0] + f * v[1] + i * v[2]];
|
||||
const q = [v[0] - m[3], v[1] - m[7], v[2] - m[11]];
|
||||
return [inv[0] * q[0] + inv[1] * q[1] + inv[2] * q[2], inv[3] * q[0] + inv[4] * q[1] + inv[5] * q[2], inv[6] * q[0] + inv[7] * q[1] + inv[8] * q[2]];
|
||||
};
|
||||
}
|
||||
|
||||
const tags = new WeakMap<Shape3D, Tagged>();
|
||||
const edgeTags = new WeakMap<Shape3D, string[][]>();
|
||||
const oldEdgeTags = new WeakMap<Shape3D, string[][] | null>();
|
||||
|
||||
const r4 = (v: number) => {
|
||||
const x = Math.round(v * 1e4) / 1e4;
|
||||
return Object.is(x, -0) ? "0" : String(x);
|
||||
};
|
||||
|
||||
/** A face's surface, the same however much of it the face covers (null: no key for this kind). */
|
||||
function surfaceKey(face: Face): string | null {
|
||||
const oc = getOC();
|
||||
const s = new oc.BRepAdaptor_Surface(face.wrapped, true);
|
||||
try {
|
||||
const T = oc.GeomAbs_SurfaceType;
|
||||
const type = s.GetType();
|
||||
// A direction either way round (a face's orientation can flip in an edit).
|
||||
const dir = (d: { X(): number; Y(): number; Z(): number }) => {
|
||||
let v = [d.X(), d.Y(), d.Z()];
|
||||
const k = v.findIndex((x) => Math.abs(x) > 1e-9);
|
||||
if (k >= 0 && v[k] < 0) v = v.map((x) => -x);
|
||||
return v;
|
||||
};
|
||||
// The point of a line through p along d nearest the origin.
|
||||
const foot = (p: number[], d: number[]) => {
|
||||
const t = p[0] * d[0] + p[1] * d[1] + p[2] * d[2];
|
||||
return [p[0] - t * d[0], p[1] - t * d[1], p[2] - t * d[2]];
|
||||
};
|
||||
const pt = (p: { X(): number; Y(): number; Z(): number }) => [p.X(), p.Y(), p.Z()];
|
||||
if (type === T.GeomAbs_Plane) {
|
||||
const pl = s.Plane();
|
||||
const n = dir(pl.Axis().Direction());
|
||||
const p = pt(pl.Location());
|
||||
return `P ${n.map(r4)} ${r4(n[0] * p[0] + n[1] * p[1] + n[2] * p[2])}`;
|
||||
}
|
||||
if (type === T.GeomAbs_Cylinder) {
|
||||
const cy = s.Cylinder();
|
||||
const d = dir(cy.Axis().Direction());
|
||||
return `C ${d.map(r4)} ${foot(pt(cy.Location()), d).map(r4)} ${r4(cy.Radius())}`;
|
||||
}
|
||||
if (type === T.GeomAbs_Sphere) {
|
||||
const sp = s.Sphere();
|
||||
return `S ${pt(sp.Location()).map(r4)} ${r4(sp.Radius())}`;
|
||||
}
|
||||
if (type === T.GeomAbs_Cone) {
|
||||
const co = s.Cone() as any;
|
||||
const d = dir(co.Axis().Direction());
|
||||
return `K ${d.map(r4)} ${pt(co.Apex()).map(r4)} ${r4(Math.abs(co.SemiAngle()))}`;
|
||||
}
|
||||
if (type === T.GeomAbs_Torus) {
|
||||
const to = s.Torus() as any;
|
||||
const d = dir(to.Axis().Direction());
|
||||
return `T ${d.map(r4)} ${pt(to.Location()).map(r4)} ${r4(to.MajorRadius())} ${r4(to.MinorRadius())}`;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
s.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag the faces of a body a step made or changed. `from`: the bodies it was
|
||||
* made from (the same body before the step, and those the step worked on).
|
||||
*
|
||||
* `others`: bodies that were there but had no part in it. A new face on the
|
||||
* same plane as a face of one of them (every body standing on the ground, a
|
||||
* block as tall as the one beside it) used to be put down to that body's
|
||||
* step: change that body and steps on this one lost their faces. It is this
|
||||
* step's now; the old answer is kept beside it, for projects saved with it.
|
||||
*/
|
||||
export function tagBody(shape: Shape3D, step: string, from: Shape3D[], others: Shape3D[] = []): void {
|
||||
if (tags.has(shape)) return;
|
||||
const hashes = new Map<number, { face: Face; step: string; key: string | null; alias?: string; move?: Moved }[]>();
|
||||
const byKey = new Map<string, { step: string; alias?: string; move?: Moved }>();
|
||||
for (const s of from) {
|
||||
const t = tags.get(s);
|
||||
if (!t || s === shape) continue;
|
||||
for (const list of t.byHash.values())
|
||||
for (const { face, i } of list) {
|
||||
const h = face.hashCode;
|
||||
hashes.set(h, [...(hashes.get(h) ?? []), { face, step: t.steps[i], key: t.keys[i], alias: t.alias?.[i], move: t.moves?.[i] }]);
|
||||
}
|
||||
t.keys.forEach((k, i) => k && !byKey.has(k) && byKey.set(k, { step: t.steps[i], alias: t.alias?.[i], move: t.moves?.[i] }));
|
||||
}
|
||||
const oldKey = new Map<string, string>();
|
||||
for (const s of others) {
|
||||
const t = tags.get(s);
|
||||
if (!t || s === shape || from.includes(s)) continue;
|
||||
t.keys.forEach((k, i) => k && !oldKey.has(k) && oldKey.set(k, t.alias?.[i] ?? t.steps[i]));
|
||||
}
|
||||
const faces = shape.faces;
|
||||
const out: Tagged = { steps: [], keys: [], byHash: new Map() };
|
||||
const alias: (string | undefined)[] = [];
|
||||
const moves: (Moved | undefined)[] = [];
|
||||
faces.forEach((face, i) => {
|
||||
const h = face.hashCode;
|
||||
out.byHash.set(h, [...(out.byHash.get(h) ?? []), { face, i }]);
|
||||
const same = hashes.get(h)?.find((x) => x.face.isSame(face));
|
||||
if (same) {
|
||||
out.steps.push(same.step);
|
||||
out.keys.push(same.key);
|
||||
alias.push(same.alias);
|
||||
moves.push(same.move);
|
||||
return;
|
||||
}
|
||||
const key = surfaceKey(face);
|
||||
out.keys.push(key);
|
||||
const kept = key ? byKey.get(key) : undefined;
|
||||
out.steps.push(kept?.step ?? step);
|
||||
alias.push(kept ? kept.alias : key ? oldKey.get(key) : undefined);
|
||||
moves.push(kept?.move);
|
||||
});
|
||||
if (alias.some((a) => a !== undefined)) out.alias = alias;
|
||||
if (moves.some((m) => m !== undefined)) out.moves = moves;
|
||||
tags.set(shape, out);
|
||||
}
|
||||
|
||||
/**
|
||||
* A body moved, turned or mirrored whole - by a Move, or as a pattern's copy
|
||||
* (`m`: where each point went; the same faces in the same order). Every face
|
||||
* is still the step's that made it, and the same one of that step's faces:
|
||||
* it used to become the Move's, so a pick on a moved body knew no more than
|
||||
* where its face was - and a Move put in before a step lost the step its
|
||||
* picks. What was saved then names the faces by the Move (`step`): kept
|
||||
* beside, as the old answer.
|
||||
*/
|
||||
export function movedTags(from: Shape3D, moved: Shape3D, step: string, m: number[]): void {
|
||||
const t = tags.get(from);
|
||||
if (!t || tags.has(moved)) return;
|
||||
const faces = moved.faces;
|
||||
if (faces.length !== t.steps.length) return;
|
||||
const byHash = new Map<number, { face: Face; i: number }[]>();
|
||||
faces.forEach((face, i) => byHash.set(face.hashCode, [...(byHash.get(face.hashCode) ?? []), { face, i }]));
|
||||
tags.set(moved, {
|
||||
steps: t.steps,
|
||||
keys: faces.map(surfaceKey),
|
||||
byHash,
|
||||
alias: faces.map(() => step),
|
||||
moves: faces.map((_, i) => (t.moves?.[i] ? then(t.moves[i]!, m) : m)),
|
||||
});
|
||||
}
|
||||
|
||||
/** The step each face used to be put down to, where that differs (see tagBody); undefined: none does. */
|
||||
export function faceAliases(shape: Shape3D): (string | undefined)[] | undefined {
|
||||
return tags.get(shape)?.alias;
|
||||
}
|
||||
|
||||
/** The step that made each face of a body (undefined: not tagged). */
|
||||
export function faceSteps(shape: Shape3D): string[] | undefined {
|
||||
return tags.get(shape)?.steps;
|
||||
}
|
||||
|
||||
/** Edge steps as projects saved before faces were told apart from other bodies' name them (undefined: the same as edgeSteps). */
|
||||
export function oldEdgeSteps(shape: Shape3D): string[][] | undefined {
|
||||
const known = oldEdgeTags.get(shape);
|
||||
if (known !== undefined) return known ?? undefined;
|
||||
const t = tags.get(shape);
|
||||
const out = t?.alias ? stepsOfEdges(shape, t.steps.map((s, i) => t.alias![i] ?? s)) : null;
|
||||
oldEdgeTags.set(shape, out);
|
||||
return out ?? undefined;
|
||||
}
|
||||
|
||||
/** For each edge of a body, the steps of the faces it lies between (sorted; one for a seam). */
|
||||
export function edgeSteps(shape: Shape3D): string[][] | undefined {
|
||||
const known = edgeTags.get(shape);
|
||||
if (known) return known;
|
||||
const steps = faceSteps(shape);
|
||||
if (!steps) return undefined;
|
||||
const out = stepsOfEdges(shape, steps);
|
||||
edgeTags.set(shape, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
function stepsOfEdges(shape: Shape3D, steps: string[]): string[][] {
|
||||
const edges = shape.edges;
|
||||
const buckets = new Map<number, { i: number; s: Set<string> }[]>();
|
||||
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, s: new Set<string>() }]));
|
||||
shape.faces.forEach((f, fi) => {
|
||||
for (const fe of f.edges) {
|
||||
const list = buckets.get(fe.hashCode);
|
||||
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
|
||||
m?.s.add(steps[fi]);
|
||||
}
|
||||
});
|
||||
const out: string[][] = new Array(edges.length).fill(null).map(() => []);
|
||||
for (const list of buckets.values()) for (const { i, s } of list) out[i] = [...s].sort();
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of a step's faces a face is: told from the face itself and what the
|
||||
* step was made from (an extrusion's side by the sketch curve under it). One
|
||||
* per step that can tell; set by the engine as it replays the steps.
|
||||
*/
|
||||
export type OriginOf = (face: Face, back?: Back) => string | null;
|
||||
let originOf: Map<string, OriginOf> = new Map();
|
||||
export function setOrigins(of: Map<string, OriginOf>): void {
|
||||
originOf = of;
|
||||
}
|
||||
|
||||
const originTags = new WeakMap<Shape3D, (string | undefined)[]>();
|
||||
/** For each face of a body, which of its step's faces it is (undefined: can't be told). */
|
||||
export function faceOrigins(shape: Shape3D): (string | undefined)[] | undefined {
|
||||
const known = originTags.get(shape);
|
||||
if (known) return known;
|
||||
const steps = faceSteps(shape);
|
||||
if (!steps) return undefined;
|
||||
const moves = tags.get(shape)?.moves;
|
||||
const out = shape.faces.map((face, i) => {
|
||||
const of = originOf.get(steps[i]);
|
||||
if (!of) return undefined;
|
||||
try {
|
||||
// (Told where its step made it: a face moved since is taken back there.)
|
||||
return of(face, moves?.[i] ? backOf(moves[i]!) : undefined) ?? undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
originTags.set(shape, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
const edgeOriginTags = new WeakMap<Shape3D, (string[] | undefined)[]>();
|
||||
/** For each edge, the faces it lies between as "step|origin" (sorted); undefined when one of them can't be told. */
|
||||
export function edgeOrigins(shape: Shape3D): (string[] | undefined)[] | undefined {
|
||||
const known = edgeOriginTags.get(shape);
|
||||
if (known) return known;
|
||||
const steps = faceSteps(shape);
|
||||
const origins = faceOrigins(shape);
|
||||
if (!steps || !origins) return undefined;
|
||||
const edges = shape.edges;
|
||||
const buckets = new Map<number, { i: number; s: Set<string>; all: boolean }[]>();
|
||||
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, s: new Set<string>(), all: true }]));
|
||||
shape.faces.forEach((f, fi) => {
|
||||
for (const fe of f.edges) {
|
||||
const list = buckets.get(fe.hashCode);
|
||||
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
|
||||
if (!m) continue;
|
||||
if (origins[fi] === undefined) m.all = false;
|
||||
else m.s.add(`${steps[fi]}|${origins[fi]}`);
|
||||
}
|
||||
});
|
||||
const out: (string[] | undefined)[] = new Array(edges.length).fill(undefined);
|
||||
for (const list of buckets.values()) for (const { i, s, all } of list) out[i] = all && s.size ? [...s].sort() : undefined;
|
||||
edgeOriginTags.set(shape, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
const seamTags = new WeakMap<Shape3D, boolean[]>();
|
||||
|
||||
/**
|
||||
* Per edge: it has the same face on both sides (the seam of a cylinder or a
|
||||
* sphere). Nothing to round there - a fillet's corner that's gone mustn't
|
||||
* land on one (a lid's 4 corner edges all went to its seam when the lid
|
||||
* was made round: "radius too big", not "the edges are gone").
|
||||
*/
|
||||
export function seamEdges(shape: Shape3D): boolean[] {
|
||||
const known = seamTags.get(shape);
|
||||
if (known) return known;
|
||||
const edges = shape.edges;
|
||||
const buckets = new Map<number, { i: number; faces: Set<number> }[]>();
|
||||
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, faces: new Set<number>() }]));
|
||||
shape.faces.forEach((f, fi) => {
|
||||
for (const fe of f.edges) {
|
||||
const list = buckets.get(fe.hashCode);
|
||||
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
|
||||
m?.faces.add(fi);
|
||||
}
|
||||
});
|
||||
const out: boolean[] = new Array(edges.length).fill(false);
|
||||
for (const list of buckets.values()) for (const { i, faces } of list) out[i] = faces.size === 1;
|
||||
seamTags.set(shape, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Same steps, as stored in a reference. */
|
||||
|
||||
export function sameSteps(a: string[], b: string[]): boolean {
|
||||
return a.length === b.length && a.every((x, i) => x === b[i]);
|
||||
}
|
||||
|
||||
/** A copy made face for face (same order): the same tags. */
|
||||
export function inheritTags(from: Shape3D, copy: Shape3D): void {
|
||||
const t = tags.get(from);
|
||||
if (!t || tags.has(copy)) return;
|
||||
const faces = copy.faces;
|
||||
if (faces.length !== t.steps.length) return;
|
||||
const byHash = new Map<number, { face: Face; i: number }[]>();
|
||||
faces.forEach((face, i) => byHash.set(face.hashCode, [...(byHash.get(face.hashCode) ?? []), { face, i }]));
|
||||
tags.set(copy, { steps: t.steps, keys: t.keys, byHash, alias: t.alias, moves: t.moves });
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// Giving memory back to the kernel.
|
||||
//
|
||||
// This build of OpenCascade does not let go of most things when they are
|
||||
// deleted: `delete()` on a shape's handle, an explorer, a boolean, a checker
|
||||
// marks it deleted on this side and leaves it whole on the other. A deleted
|
||||
// handle still counted as a user of its shape, so no body the engine ever
|
||||
// made was freed, and each tool kept all it had worked out: the engine's
|
||||
// memory only grew - by a megabyte or so with every rebuild of an everyday
|
||||
// part - until it was replaced with a fresh one (worker.ts), every step built
|
||||
// again from nothing. (Read off the kernel's memory: five handles to a box
|
||||
// deleted, the box still had its five users; emptied first, none.)
|
||||
//
|
||||
// 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 { BoundingBox, getOC, Solid } from "replicad";
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
|
||||
/** The kernels (one at a time: a fresh one after a breakdown) whose classes are done. */
|
||||
const done = new WeakSet<object>();
|
||||
|
||||
/** The last handle to its object, not deleted yet? (A handle can be cloned: the object goes with the last.) */
|
||||
function last(handle: any): boolean {
|
||||
if (handle.isDeleted()) return false;
|
||||
const record = handle[Object.getOwnPropertyNames(handle)[0]];
|
||||
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);
|
||||
const nothing = new oc.TopoDS_Shape();
|
||||
const ANY = oc.TopAbs_ShapeEnum.TopAbs_SHAPE;
|
||||
const before = (name: string, release: (handle: any) => void): void => {
|
||||
const proto = oc[name]?.prototype;
|
||||
if (!proto || typeof proto.delete !== "function") return;
|
||||
const remove = proto.delete as (this: unknown) => unknown;
|
||||
proto.delete = function (this: any) {
|
||||
if (last(this)) {
|
||||
try {
|
||||
release(this);
|
||||
} catch {
|
||||
// Deleted as it is.
|
||||
}
|
||||
}
|
||||
return remove.call(this);
|
||||
};
|
||||
};
|
||||
// A shape's handle (a face's, an edge's... are its kinds): emptied, it no longer uses the shape.
|
||||
before("TopoDS_Shape", (h) => h.Nullify());
|
||||
// An explorer keeps the shape it went through.
|
||||
before("TopExp_Explorer", (h) => h.Init(nothing, ANY, ANY));
|
||||
// A boolean keeps all it worked out about where its shapes meet (165 KB for
|
||||
// a hole through a block) - cleared - and the bodies it was given and the
|
||||
// body it made, which it has no way to be told to drop: it is given a last
|
||||
// job instead, one point less another, and holds those two points from then on.
|
||||
const [a, b] = [new oc.gp_Pnt(0, 0, 0), new oc.gp_Pnt(1, 0, 0)];
|
||||
const speck = (p: unknown) => {
|
||||
const list = new oc.NCollection_List_TopoDS_Shape();
|
||||
list.Append(new oc.BRepBuilderAPI_MakeVertex(p).Vertex());
|
||||
return list;
|
||||
};
|
||||
const [one, other] = [speck(a), speck(b)];
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
for (const name of ["BRepAlgoAPI_Cut", "BRepAlgoAPI_Fuse", "BRepAlgoAPI_Common", "BRepAlgoAPI_Section", "BRepAlgoAPI_Splitter"])
|
||||
before(name, (h) => {
|
||||
h.Clear();
|
||||
h.SetArguments(one);
|
||||
h.SetTools(other);
|
||||
h.Build(progress);
|
||||
h.Clear();
|
||||
});
|
||||
}
|
||||
@@ -6,28 +6,32 @@
|
||||
// open edges, hair-thin faces dropped and their slot closed, faces split on
|
||||
// one surface merged, skins made solid, inside-out solids turned round.
|
||||
|
||||
import { assembleWire, cast, getOC, makeCompound, makeFace, measureArea, measureVolume, type Shape3D } from "replicad";
|
||||
import { assembleWire, cast, getOC, makeCompound, makeFace, makeLine, makeThreePointArc, measureArea, type Shape3D, type Wire } from "replicad";
|
||||
import { measureVolume, quickVolume } from "./ocFree";
|
||||
import { unify } from "./faceEdit";
|
||||
import { deepCopy, hairThin, 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 {
|
||||
@@ -43,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. */
|
||||
@@ -67,6 +71,83 @@ function sizeOf(s: Shape3D): number {
|
||||
type Fix = { label: string; run: (s: Shape3D, size: number) => Shape3D | null };
|
||||
|
||||
/** Faces → shell(s) by sewing at `tol`; every closed shell → a solid (turned outward). */
|
||||
/**
|
||||
* Flat faces with an edge next to nothing in length (the end of a sliver
|
||||
* that was closed: two roundings that meet, 4 mm each side of an 8 mm
|
||||
* block) made again without it, their outline's two neighbours brought
|
||||
* together. Left in, that speck is an edge to pick, and one the engine
|
||||
* stumbles on in every later cut and fillet there. Null: none to drop.
|
||||
*/
|
||||
function withoutSpecks(s: Shape3D, tol: number): Shape3D | null {
|
||||
type P = [number, number, number];
|
||||
const far = (p: P, q: P) => Math.hypot(p[0] - q[0], p[1] - q[1], p[2] - q[2]);
|
||||
const remade = (w: Wire): Wire => {
|
||||
const all = w.edges.map((e) => ({ e, a: e.startPoint.toTuple() as P, b: e.endPoint.toTuple() as P, m: e.pointAt(0.5).toTuple() as P, type: e.geomType as string, speck: e.length < tol, moved: false }));
|
||||
const specks = all.filter((x) => x.speck);
|
||||
if (!specks.length) return w;
|
||||
// The ends that were on a speck: both at its middle now.
|
||||
const snap = (p: P): P | null => {
|
||||
for (const k of specks) if (far(p, k.a) < tol || far(p, k.b) < tol) return [(k.a[0] + k.b[0]) / 2, (k.a[1] + k.b[1]) / 2, (k.a[2] + k.b[2]) / 2];
|
||||
return null;
|
||||
};
|
||||
const rest = all.filter((x) => !x.speck);
|
||||
for (const x of rest) {
|
||||
const [a, b] = [snap(x.a), snap(x.b)];
|
||||
if (!a && !b) continue;
|
||||
if (x.type !== "LINE" && x.type !== "CIRCLE") throw new Error("not a line or an arc");
|
||||
x.a = a ?? x.a;
|
||||
x.b = b ?? x.b;
|
||||
x.moved = true;
|
||||
}
|
||||
// In order round the outline (each begins where the one before ends).
|
||||
const chain = [rest.shift()!];
|
||||
while (rest.length) {
|
||||
const end = chain[chain.length - 1].b;
|
||||
let i = rest.findIndex((x) => far(x.a, end) < tol);
|
||||
if (i < 0) {
|
||||
i = rest.findIndex((x) => far(x.b, end) < tol);
|
||||
if (i < 0) throw new Error("the outline doesn't close");
|
||||
[rest[i].a, rest[i].b] = [rest[i].b, rest[i].a];
|
||||
}
|
||||
chain.push(rest.splice(i, 1)[0]);
|
||||
}
|
||||
return assembleWire(chain.map((x) => (!x.moved ? x.e : x.type === "LINE" ? makeLine(x.a, x.b) : makeThreePointArc(x.a, x.m, x.b))));
|
||||
};
|
||||
let any = false;
|
||||
const faces = s.faces.map((f) => {
|
||||
if (f.geomType !== "PLANE" || !f.edges.some((e) => e.length < tol)) return f.wrapped;
|
||||
try {
|
||||
const made = makeFace(remade(f.clone().outerWire()), f.clone().innerWires().map(remade));
|
||||
any = true;
|
||||
return made.wrapped;
|
||||
} catch {
|
||||
return f.wrapped;
|
||||
}
|
||||
});
|
||||
return any ? sewToSolid(faces, tol) : null;
|
||||
}
|
||||
|
||||
/** Faces on the same surface to within `tol` made one (null: it can't be done). */
|
||||
function merged(s: Shape3D, tol: number): Shape3D | null {
|
||||
const oc = getOC();
|
||||
const u = new oc.ShapeUpgrade_UnifySameDomain(s.wrapped, true, true, false);
|
||||
try {
|
||||
u.SetLinearTolerance(tol);
|
||||
u.SetAngularTolerance(1e-5);
|
||||
u.Build();
|
||||
const made = u.Shape();
|
||||
try {
|
||||
return cast(made) as Shape3D;
|
||||
} finally {
|
||||
made.delete();
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
u.delete();
|
||||
}
|
||||
}
|
||||
|
||||
function sewToSolid(faces: unknown[], tol: number): Shape3D | null {
|
||||
const oc = getOC();
|
||||
const sw = new oc.BRepBuilderAPI_Sewing(tol, true, true, true, false);
|
||||
@@ -195,7 +276,26 @@ const FIXES: Fix[] = [
|
||||
return Math.min(...[b.width, b.height, b.depth].filter((x) => x > 0), size * 1e-3);
|
||||
}));
|
||||
const kept = s.faces.filter((_, i) => !thin[i]).map((f) => f.wrapped);
|
||||
return sewToSolid(kept, Math.min(size * 1e-3, Math.max(size * 1e-6, width * 2)));
|
||||
const tol = Math.min(size * 1e-3, Math.max(size * 1e-6, width * 2));
|
||||
const closed = sewToSolid(kept, tol);
|
||||
if (!closed) return null;
|
||||
// The sliver's ends are still there, as edges next to nothing in length on the faces it ended at.
|
||||
try {
|
||||
const clean = withoutSpecks(closed, tol);
|
||||
if (clean && !clean.edges.some((e) => e.length < tol)) {
|
||||
// What the sliver lay between is one surface but for its width (the two
|
||||
// roundings of a full round: one half cylinder): one face, with no line down it.
|
||||
const joined = merged(clean, tol);
|
||||
const one = joined && FIXES[0].run(joined, size);
|
||||
const v = measureVolume(closed);
|
||||
const good = (x: Shape3D) => shapeValid(x) && !openEdges(x).length && Math.abs(measureVolume(x) - v) < Math.abs(v) * 1e-4;
|
||||
if (one && one.faces.length < clean.faces.length && good(one)) return one;
|
||||
if (good(clean)) return clean;
|
||||
}
|
||||
} catch {
|
||||
// as it is, then
|
||||
}
|
||||
return closed;
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -216,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;
|
||||
@@ -251,8 +351,35 @@ export function repairShape(input: Shape3D, o: RepairOptions = {}): { shape: Sha
|
||||
if (isHealthy(h, o)) return { shape: cur, fixes: [] };
|
||||
const size = sizeOf(input);
|
||||
const v0 = o.volume ?? (h.volume > 0 && h.valid ? h.volume : undefined);
|
||||
// Not valid: its measured volume can't be trusted, but one counted from a
|
||||
// mesh can (when it's closed). Without it, "fixed faces" was free to change
|
||||
// the shape: a slot cut into a drill's housing came back 764 mm³ bigger,
|
||||
// and the housing split in half later left pieces inside out.
|
||||
let m0: number | undefined;
|
||||
if (v0 === undefined && h.solids && !h.openEdges) {
|
||||
try {
|
||||
const m = meshVolume(input, size);
|
||||
if (m > 0) m0 = m;
|
||||
} catch {
|
||||
m0 = undefined;
|
||||
}
|
||||
}
|
||||
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;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (v0 === undefined || !(hs.volume > 0)) return true;
|
||||
return Math.abs(hs.volume - v0) <= v0 * 5e-3;
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ function run(kind: "fuse" | "cut" | "common", a: { wrapped: unknown }, b: { wrap
|
||||
const algo = kind === "fuse" ? new oc.BRepAlgoAPI_Fuse() : kind === "cut" ? new oc.BRepAlgoAPI_Cut() : new oc.BRepAlgoAPI_Common();
|
||||
const args = new oc.NCollection_List_TopoDS_Shape();
|
||||
const tools = new oc.NCollection_List_TopoDS_Shape();
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
try {
|
||||
args.Append(a.wrapped as never);
|
||||
tools.Append(b.wrapped as never);
|
||||
@@ -22,18 +23,60 @@ function run(kind: "fuse" | "cut" | "common", a: { wrapped: unknown }, b: { wrap
|
||||
algo.SetNonDestructive(true);
|
||||
if (opts.optimisation === "commonFace") algo.SetGlue(oc.BOPAlgo_GlueEnum.BOPAlgo_GlueShift);
|
||||
if (opts.optimisation === "sameFace") algo.SetGlue(oc.BOPAlgo_GlueEnum.BOPAlgo_GlueFull);
|
||||
algo.Build(new oc.Message_ProgressRange());
|
||||
algo.Build(progress);
|
||||
if (opts.simplify !== false) algo.SimplifyResult(true, true, 0.001);
|
||||
const out = cast(algo.Shape());
|
||||
if (!isShape3D(out)) throw new Error(`Could not ${kind} as a 3d shape`);
|
||||
return out;
|
||||
// (The kernel's handle to what it made is given back once the body has its own: release.ts.)
|
||||
const made = algo.Shape();
|
||||
try {
|
||||
const out = cast(withoutInternals(made));
|
||||
if (!isShape3D(out)) throw new Error(`Could not ${kind} as a 3d shape`);
|
||||
return out;
|
||||
} finally {
|
||||
made.delete();
|
||||
}
|
||||
} finally {
|
||||
algo.delete();
|
||||
args.delete();
|
||||
tools.delete();
|
||||
progress.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A boolean's result without the edges (and points) it left lying in a face,
|
||||
* bounding nothing: where an edge of one shape ran along a face of the other
|
||||
* (a prism's corner standing against a block's wall), the join kept it there
|
||||
* as a line across the wall - an edge with no face on its other side, taken
|
||||
* for a gap ("would tear the body open") though the solid was closed.
|
||||
* (Only faces the boolean made anew hold such edges: the shapes it was given
|
||||
* stay as they were.)
|
||||
*/
|
||||
export function withoutInternals<T>(wrapped: T): T {
|
||||
const oc = getOC();
|
||||
const INTERNAL = oc.TopAbs_Orientation.TopAbs_INTERNAL;
|
||||
const has = (kind: unknown): boolean => {
|
||||
const ex = new oc.TopExp_Explorer(wrapped as never, kind as never, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
|
||||
try {
|
||||
for (; ex.More(); ex.Next()) {
|
||||
const item = ex.Current();
|
||||
const inside = item.Orientation() === INTERNAL;
|
||||
item.delete();
|
||||
if (inside) return true;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
ex.delete();
|
||||
}
|
||||
};
|
||||
try {
|
||||
if ((wrapped as { IsNull?: () => boolean } | null)?.IsNull?.() !== false) return wrapped;
|
||||
if (has(oc.TopAbs_ShapeEnum.TopAbs_EDGE) || has(oc.TopAbs_ShapeEnum.TopAbs_VERTEX)) oc.BRepTools.RemoveInternals(wrapped as never, false);
|
||||
} catch {
|
||||
// As it came: the usual checks speak for it.
|
||||
}
|
||||
return wrapped;
|
||||
}
|
||||
|
||||
let done = false;
|
||||
export function useSafeBooleans(): void {
|
||||
if (done) return;
|
||||
@@ -54,32 +97,41 @@ export function useSafeBooleans(): void {
|
||||
const q = Shape.prototype as unknown as object;
|
||||
Object.defineProperty(q, "edges", { configurable: true, get(this: { wrapped: unknown }) {
|
||||
const oc = getOC();
|
||||
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE).map((x) => new Edge(oc.TopoDS.Edge(x)));
|
||||
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_EDGE, (x) => new Edge(oc.TopoDS.Edge(x as never)));
|
||||
} });
|
||||
Object.defineProperty(q, "faces", { configurable: true, get(this: { wrapped: unknown }) {
|
||||
const oc = getOC();
|
||||
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_FACE).map((x) => new Face(oc.TopoDS.Face(x)));
|
||||
return unique(this.wrapped, oc.TopAbs_ShapeEnum.TopAbs_FACE, (x) => new Face(oc.TopoDS.Face(x as never)));
|
||||
} });
|
||||
}
|
||||
|
||||
/** The sub-shapes of one kind, each once (the same one met again from another face is skipped). */
|
||||
function unique(shape: unknown, kind: unknown): any[] {
|
||||
/**
|
||||
* The sub-shapes of one kind, each once (the same one met again from another
|
||||
* face is skipped), as `wrap` makes them. (The explorer's own handles are
|
||||
* deleted here, each of them: left to lie, every one kept its face or edge
|
||||
* alive for good - see release.ts.)
|
||||
*/
|
||||
function unique<T>(shape: unknown, kind: unknown, wrap: (item: unknown) => T): T[] {
|
||||
const oc = getOC();
|
||||
const ex = new oc.TopExp_Explorer(shape as never, kind as never, oc.TopAbs_ShapeEnum.TopAbs_SHAPE);
|
||||
const buckets = new Map<number, any[]>();
|
||||
const out: any[] = [];
|
||||
const found: any[] = [];
|
||||
try {
|
||||
for (; ex.More(); ex.Next()) {
|
||||
const item = ex.Current();
|
||||
const h = oc.ReplicadShapeHasher.HashCode(item, HASH_CODE_MAX);
|
||||
const b = buckets.get(h);
|
||||
if (b?.some((x) => x.IsSame(item))) continue;
|
||||
if (b?.some((x) => x.IsSame(item))) {
|
||||
item.delete();
|
||||
continue;
|
||||
}
|
||||
if (b) b.push(item);
|
||||
else buckets.set(h, [item]);
|
||||
out.push(item);
|
||||
found.push(item);
|
||||
}
|
||||
return found.map(wrap);
|
||||
} finally {
|
||||
for (const item of found) item.delete();
|
||||
ex.delete();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -15,9 +15,9 @@ import {
|
||||
type Face,
|
||||
type Wire,
|
||||
} from "replicad";
|
||||
import type { PlaneDef, SketchEntity, Vec2 } from "../doc/types";
|
||||
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). */
|
||||
@@ -40,12 +40,36 @@ export function regionWire(entities: SketchEntity[], plane: PlaneDef, ref: Regio
|
||||
return loopWire(arr, r.outer, plane);
|
||||
}
|
||||
|
||||
/** The outlines of a region's holes (for sweeps that make the outer wire's body and cut these out). */
|
||||
export function regionHoleWires(entities: SketchEntity[], plane: PlaneDef, ref: RegionRef): Wire[] {
|
||||
const arr = arrangement(entities);
|
||||
const r = resolveRegion(arr, ref);
|
||||
if (!r) throw new Error("A profile it used no longer exists in its sketch");
|
||||
return r.holes.map((h) => loopWire(arr, h, plane));
|
||||
}
|
||||
|
||||
/** A wire along sketch entities (open or closed), used as a sweep path. */
|
||||
export function entitiesWire(entities: SketchEntity[], ids: string[], plane: PlaneDef): Wire {
|
||||
const edges: Edge[] = [];
|
||||
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));
|
||||
@@ -53,7 +77,48 @@ 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(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
|
||||
* built in list order - it stopped at the first gap, so a string swept over a
|
||||
* rounded saddle ended there (10 mm of a 650 mm path), with no error.
|
||||
*/
|
||||
function endToEnd(edges: Edge[]): Edge[] {
|
||||
if (edges.length < 3) return edges;
|
||||
const ends = edges.map((e) => [e.startPoint.toTuple(), e.endPoint.toTuple()] as Vec3[]);
|
||||
const size = Math.max(1, ...ends.flat().map((q) => Math.hypot(q[0], q[1], q[2])));
|
||||
const tol = size * 1e-7;
|
||||
const same = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]) < tol;
|
||||
const touching = (q: Vec3, skip: number) => ends.some((pair, j) => j !== skip && pair.some((x) => same(x, q)));
|
||||
// Start at a loose end (an open path), else anywhere (a closed one).
|
||||
let first = ends.findIndex((pair, i) => pair.some((q) => !touching(q, i)));
|
||||
if (first < 0) first = 0;
|
||||
const order = [first];
|
||||
const used = new Set(order);
|
||||
let tip = touching(ends[first][1], first) ? ends[first][1] : ends[first][0];
|
||||
while (order.length < edges.length) {
|
||||
const next = ends.findIndex((pair, j) => !used.has(j) && pair.some((q) => same(q, tip)));
|
||||
if (next < 0) return edges; // not one chain: as it was
|
||||
order.push(next);
|
||||
used.add(next);
|
||||
tip = same(ends[next][0], tip) ? ends[next][1] : ends[next][0];
|
||||
}
|
||||
return order.map((i) => edges[i]);
|
||||
}
|
||||
|
||||
function loopWire(arr: Arrangement, loop: Loop, plane: PlaneDef): Wire {
|
||||
@@ -248,6 +313,19 @@ function exactSpline(p: Prim, t0: number, t1: number, plane: PlaneDef, a?: Vec2,
|
||||
const curve = new oc.Geom_BSplineCurve(arr, knots, mults, 3, false);
|
||||
const tol = 1e-6 * Math.max(1, ...poles.map((q) => Math.hypot(q[0], q[1])));
|
||||
for (let i = 2; i <= m; i++) curve.RemoveKnot(i, 2, tol);
|
||||
// A whole closed spline: one periodic curve, smooth where it starts too.
|
||||
// Left as an open curve whose ends meet, its start was a seam - a fillet
|
||||
// round the bottom of a guitar body pulled up from it failed there.
|
||||
if (ctrl.closed && Math.abs(f1 - f0 - spans) < 1e-9 && Math.hypot(poles[0][0] - poles[poles.length - 1][0], poles[0][1] - poles[poles.length - 1][1]) < tol) {
|
||||
try {
|
||||
curve.SetPeriodic();
|
||||
curve.RemoveKnot(curve.FirstUKnotIndex(), 2, tol);
|
||||
const k0 = curve.FirstUKnotIndex();
|
||||
curve.SetOrigin((curve.Knot(k0) + curve.Knot(k0 + 1)) / 2, 1e-9);
|
||||
} catch {
|
||||
// (stays as it was)
|
||||
}
|
||||
}
|
||||
const mk = new oc.BRepBuilderAPI_MakeEdge(curve);
|
||||
const edge = cast(mk.Edge()) as Edge;
|
||||
mk.delete();
|
||||
|
||||
@@ -0,0 +1,516 @@
|
||||
// Drawing views from the bodies' meshes: hidden line removal by a depth
|
||||
// buffer, for models OpenCascade's exact one takes too long on (a freeform
|
||||
// body took it 20 s a view). The edges are the mesh's own edge lines (which lie
|
||||
// on its triangles), the outlines of curved faces come from the mesh normals.
|
||||
import type { Shape3D } from "replicad";
|
||||
import { getOC } from "replicad";
|
||||
import type { BodyMesh, ViewBody, ViewEdge, ViewSpec } from "./protocol";
|
||||
import { cylinderOf } from "./faceEdit";
|
||||
import { normalOnEdge } from "./ocFree";
|
||||
|
||||
type V3 = [number, number, number];
|
||||
type P2 = [number, number];
|
||||
|
||||
const r3 = (n: number) => String(Math.round(n * 1000) / 1000);
|
||||
const rr = (p: P2): P2 => [Math.round(p[0] * 1000) / 1000, Math.round(p[1] * 1000) / 1000];
|
||||
|
||||
/** A line, or a circle seen face on (its centre found from three of its points), as a view edge. */
|
||||
export function viewEdge(kind: "line" | "circle" | "other", pts: P2[]): ViewEdge | undefined {
|
||||
if (kind === "line") return { a: rr(pts[0]), b: rr(pts[pts.length - 1]) };
|
||||
if (kind !== "circle" || pts.length < 3) return undefined;
|
||||
const a = pts[0];
|
||||
const b = pts[pts.length - 1];
|
||||
const closed = Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-6;
|
||||
const p1 = pts[Math.round(pts.length / 3)];
|
||||
const p2 = pts[Math.min(pts.length - 1, Math.round((2 * pts.length) / 3))];
|
||||
const m = pts[Math.round(pts.length / 2)];
|
||||
// The circle through a, p1, p2.
|
||||
const [ax, ay] = a;
|
||||
const [bx, by] = p1;
|
||||
const [cx, cy] = p2;
|
||||
const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
|
||||
if (Math.abs(d) < 1e-12) return undefined;
|
||||
const ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d;
|
||||
const uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d;
|
||||
const r = Math.hypot(ax - ux, ay - uy);
|
||||
return { a: rr(a), m: rr(m), b: closed ? rr(a) : rr(b), c: rr([ux, uy]), r: Math.round(r * 1000) / 1000 };
|
||||
}
|
||||
|
||||
/** On the body's seen edges, the point nearest the middle of them (where a balloon's leader ends). */
|
||||
export function anchorOf(lines: P2[][]): P2 | undefined {
|
||||
if (!lines.length) return undefined;
|
||||
let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
|
||||
for (const l of lines) for (const [x, y] of l) (x0 = Math.min(x0, x)), (x1 = Math.max(x1, x)), (y0 = Math.min(y0, y)), (y1 = Math.max(y1, y));
|
||||
const c: P2 = [(x0 + x1) / 2, (y0 + y1) / 2];
|
||||
let best = lines[0][0];
|
||||
let bd = Infinity;
|
||||
for (const l of lines)
|
||||
for (let i = 1; i < l.length; i++) {
|
||||
const [a, b] = [l[i - 1], l[i]];
|
||||
const ab = [b[0] - a[0], b[1] - a[1]];
|
||||
const n = ab[0] * ab[0] + ab[1] * ab[1];
|
||||
const t = n ? Math.max(0, Math.min(1, ((c[0] - a[0]) * ab[0] + (c[1] - a[1]) * ab[1]) / n)) : 0;
|
||||
const p: P2 = [a[0] + t * ab[0], a[1] + t * ab[1]];
|
||||
const d = (p[0] - c[0]) ** 2 + (p[1] - c[1]) ** 2;
|
||||
if (d < bd) (bd = d), (best = p);
|
||||
}
|
||||
return rr(best);
|
||||
}
|
||||
|
||||
/** How an edge is drawn: where faces meet at an angle, where they meet smoothly (thin), or not (a seam). */
|
||||
type EdgeKind = "sharp" | "smooth" | "seam";
|
||||
const kindsOf = new WeakMap<Shape3D, EdgeKind[]>();
|
||||
|
||||
function edgeKinds(shape: Shape3D): EdgeKind[] {
|
||||
const known = kindsOf.get(shape);
|
||||
if (known) return known;
|
||||
const oc = getOC();
|
||||
const edges = shape.edges;
|
||||
const faces = shape.faces;
|
||||
const buckets = new Map<number, { i: number; faces: number[] }[]>();
|
||||
edges.forEach((e, i) => buckets.set(e.hashCode, [...(buckets.get(e.hashCode) ?? []), { i, faces: [] }]));
|
||||
faces.forEach((f, fi) => {
|
||||
for (const fe of f.edges) {
|
||||
const list = buckets.get(fe.hashCode);
|
||||
const m = list?.length === 1 ? list[0] : list?.find((x) => edges[x.i].isSame(fe));
|
||||
m?.faces.push(fi);
|
||||
}
|
||||
});
|
||||
const out: EdgeKind[] = new Array(edges.length).fill("sharp");
|
||||
for (const list of buckets.values())
|
||||
for (const { i, faces: fs } of list) {
|
||||
try {
|
||||
if (fs.length === 1) {
|
||||
// One face: the seam of a round one - or the open rim of a sheet.
|
||||
if (oc.BRep_Tool.IsClosed(edges[i].wrapped as never, faces[fs[0]].wrapped as never)) out[i] = "seam";
|
||||
} else if (fs.length === 2) {
|
||||
// Read through the edge's curve on each face (a point projected onto
|
||||
// a face per edge kept the engine's memory: a gear's ran it out).
|
||||
const n1 = normalOnEdge(faces[fs[0]], edges[i], 0.5);
|
||||
const n2 = normalOnEdge(faces[fs[1]], edges[i], 0.5);
|
||||
if (n1 && n2 && n1[0] * n2[0] + n1[1] * n2[1] + n1[2] * n2[2] > 0.9995) out[i] = "smooth";
|
||||
}
|
||||
} catch {
|
||||
// Kept sharp.
|
||||
}
|
||||
}
|
||||
kindsOf.set(shape, out);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Round faces' axes, by face (for outlines put right on them, not on the mesh's chords). */
|
||||
const cylsOf = new WeakMap<Shape3D, Map<number, ReturnType<typeof cylinderOf>>>();
|
||||
function cylinderAt(shape: Shape3D, face: number) {
|
||||
let m = cylsOf.get(shape);
|
||||
if (!m) cylsOf.set(shape, (m = new Map()));
|
||||
if (!m.has(face)) {
|
||||
let c: ReturnType<typeof cylinderOf> = null;
|
||||
try {
|
||||
c = cylinderOf(shape.faces[face]);
|
||||
} catch {
|
||||
// Left on the mesh.
|
||||
}
|
||||
m.set(face, c);
|
||||
}
|
||||
return m.get(face) ?? null;
|
||||
}
|
||||
|
||||
/** The faces the exact hidden line removal is slow on (anything but planes, cylinders, cones, spheres and tori). */
|
||||
export function freeformFaces(mesh: BodyMesh): number {
|
||||
return mesh.faces.filter((f) => !["PLANE", "CYLINDRE", "CONE", "SPHERE", "TORUS"].includes(f.type)).length;
|
||||
}
|
||||
|
||||
/** The views of the bodies, worked out on their meshes. Each view: its bodies, and the box of what it shows. */
|
||||
export function meshViews(bodies: { id: string; shape: Shape3D; mesh: BodyMesh }[], views: ViewSpec[]): { id: string; bodies: ViewBody[]; box: [P2, P2] | null }[] {
|
||||
const kinds = bodies.map((b) => edgeKinds(b.shape));
|
||||
return views.map((v) => meshView(bodies, kinds, v));
|
||||
}
|
||||
|
||||
function meshView(bodies: { id: string; shape: Shape3D; mesh: BodyMesh }[], kinds: EdgeKind[][], v: ViewSpec): { id: string; bodies: ViewBody[]; box: [P2, P2] | null } {
|
||||
const unit = (p: V3): V3 => {
|
||||
const l = Math.hypot(p[0], p[1], p[2]) || 1;
|
||||
return [p[0] / l, p[1] / l, p[2] / l];
|
||||
};
|
||||
const d = unit(v.dir as V3);
|
||||
const X = unit(v.xAxis as V3);
|
||||
const Y: V3 = [d[1] * X[2] - d[2] * X[1], d[2] * X[0] - d[0] * X[2], d[0] * X[1] - d[1] * X[0]];
|
||||
// On the paper: x along X, y down (-Y); depth towards the eye (+d).
|
||||
const px2 = (x: number, y: number, z: number): [number, number, number] => [x * X[0] + y * X[1] + z * X[2], -(x * Y[0] + y * Y[1] + z * Y[2]), x * d[0] + y * d[1] + z * d[2]];
|
||||
|
||||
// ---- The depth buffer.
|
||||
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity, z0 = Infinity, z1 = -Infinity;
|
||||
const proj = bodies.map(({ mesh }) => {
|
||||
const P = mesh.positions;
|
||||
const out = new Float64Array(P.length);
|
||||
for (let i = 0; i < P.length; i += 3) {
|
||||
const [a, b, c] = px2(P[i], P[i + 1], P[i + 2]);
|
||||
out[i] = a;
|
||||
out[i + 1] = b;
|
||||
out[i + 2] = c;
|
||||
if (a < x0) x0 = a;
|
||||
if (a > x1) x1 = a;
|
||||
if (b < y0) y0 = b;
|
||||
if (b > y1) y1 = b;
|
||||
if (c < z0) z0 = c;
|
||||
if (c > z1) z1 = c;
|
||||
}
|
||||
return out;
|
||||
});
|
||||
if (!(x1 >= x0)) return { id: v.id, bodies: bodies.map((b) => ({ id: b.id, visible: "", tangent: "", hidden: "", edges: [] })), box: null };
|
||||
const extent = Math.max(x1 - x0, y1 - y0, 1e-6);
|
||||
const px = extent / 2048;
|
||||
const gw = Math.ceil((x1 - x0) / px) + 5;
|
||||
const gh = Math.ceil((y1 - y0) / px) + 5;
|
||||
const ox = x0 - 2 * px;
|
||||
const oy = y0 - 2 * px;
|
||||
const zb = new Float32Array(gw * gh).fill(-Infinity);
|
||||
bodies.forEach(({ mesh }, bi) => {
|
||||
const T = mesh.indices;
|
||||
const Q = proj[bi];
|
||||
for (let t = 0; t < T.length; t += 3) {
|
||||
const a = T[t] * 3, b = T[t + 1] * 3, c = T[t + 2] * 3;
|
||||
const ax = (Q[a] - ox) / px, ay = (Q[a + 1] - oy) / px, az = Q[a + 2];
|
||||
const bx = (Q[b] - ox) / px, by = (Q[b + 1] - oy) / px, bz = Q[b + 2];
|
||||
const cx = (Q[c] - ox) / px, cy = (Q[c + 1] - oy) / px, cz = Q[c + 2];
|
||||
const area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
|
||||
if (Math.abs(area) < 1e-12) continue;
|
||||
const i0 = Math.max(0, Math.floor(Math.min(ax, bx, cx)));
|
||||
const i1 = Math.min(gw - 1, Math.ceil(Math.max(ax, bx, cx)));
|
||||
const j0 = Math.max(0, Math.floor(Math.min(ay, by, cy)));
|
||||
const j1 = Math.min(gh - 1, Math.ceil(Math.max(ay, by, cy)));
|
||||
// (The weights are fractions: a pixel's centre on a shared side belongs to both triangles.)
|
||||
const e = -1e-9;
|
||||
for (let j = j0; j <= j1; j++) {
|
||||
const y = j + 0.5;
|
||||
for (let i = i0; i <= i1; i++) {
|
||||
const x = i + 0.5;
|
||||
const w0 = ((bx - x) * (cy - y) - (by - y) * (cx - x)) / area;
|
||||
const w1 = ((cx - x) * (ay - y) - (cy - y) * (ax - x)) / area;
|
||||
const w2 = 1 - w0 - w1;
|
||||
if (w0 < e || w1 < e || w2 < e) continue;
|
||||
const z = w0 * az + w1 * bz + w2 * cz;
|
||||
const k = j * gw + i;
|
||||
if (z > zb[k]) zb[k] = z;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const eps = 2 * px + (z1 - z0) * 1e-6;
|
||||
/** Seen: nothing clearly in front of it (around it, a pixel either way: on an outline, the far side counts). */
|
||||
const seenAt = (x: number, y: number, z: number) => {
|
||||
const i = Math.floor((x - ox) / px);
|
||||
const j = Math.floor((y - oy) / px);
|
||||
let far = Infinity;
|
||||
for (let jj = j - 1; jj <= j + 1; jj++)
|
||||
for (let ii = i - 1; ii <= i + 1; ii++) {
|
||||
const q = ii >= 0 && jj >= 0 && ii < gw && jj < gh ? zb[jj * gw + ii] : -Infinity;
|
||||
if (q < far) far = q;
|
||||
}
|
||||
return z >= far - eps;
|
||||
};
|
||||
|
||||
const pathOf = (pts: P2[]) => pts.map((p, i) => `${i ? "L" : "M"}${r3(p[0])} ${r3(p[1])}`).join("");
|
||||
const straight = (pts: P2[]) => {
|
||||
const [a, b] = [pts[0], pts[pts.length - 1]];
|
||||
const L = Math.hypot(b[0] - a[0], b[1] - a[1]);
|
||||
if (L < 1e-6) return false;
|
||||
const tol = Math.max(px, L * 1e-3);
|
||||
return pts.every((p) => Math.abs((p[0] - a[0]) * (b[1] - a[1]) - (p[1] - a[1]) * (b[0] - a[0])) / L < tol);
|
||||
};
|
||||
|
||||
// ---- Every line to draw, sampled a pixel apart: the bodies' edges, and the
|
||||
// outlines of their curved faces (where the surface turns away from the eye).
|
||||
type Line = { body: number; kind: EdgeKind | "outline"; shape: "line" | "circle" | "other"; xyz: number[]; vert: boolean[]; state: Int8Array };
|
||||
const lines: Line[] = [];
|
||||
const addLine = (body: number, kind: Line["kind"], shape: Line["shape"], pts: [number, number, number][]) => {
|
||||
const xyz: number[] = [];
|
||||
const vert: boolean[] = [];
|
||||
pts.forEach((p, k) => {
|
||||
if (k > 0) {
|
||||
const q = pts[k - 1];
|
||||
const n = Math.max(1, Math.ceil(Math.hypot(p[0] - q[0], p[1] - q[1]) / px));
|
||||
for (let s = 1; s < n; s++) {
|
||||
const t = s / n;
|
||||
xyz.push(q[0] + (p[0] - q[0]) * t, q[1] + (p[1] - q[1]) * t, q[2] + (p[2] - q[2]) * t);
|
||||
vert.push(false);
|
||||
}
|
||||
}
|
||||
xyz.push(p[0], p[1], p[2]);
|
||||
vert.push(true);
|
||||
});
|
||||
lines.push({ body, kind, shape, xyz, vert, state: new Int8Array(vert.length) });
|
||||
};
|
||||
bodies.forEach(({ mesh }, bi) => {
|
||||
const E = mesh.edgePositions;
|
||||
mesh.edgeGroups.forEach((g, ei) => {
|
||||
const kind = kinds[bi][ei] ?? "sharp";
|
||||
if (kind === "seam" || g.count < 2) return;
|
||||
const pts: [number, number, number][] = [];
|
||||
for (let k = 0; k < g.count; k++) {
|
||||
const o = (g.start + k) * 3;
|
||||
const q = px2(E[o], E[o + 1], E[o + 2]);
|
||||
// (The mesh's edge lines come as pairs of points: each point twice.)
|
||||
const last = pts[pts.length - 1];
|
||||
if (!last || Math.abs(q[0] - last[0]) > 1e-9 || Math.abs(q[1] - last[1]) > 1e-9 || Math.abs(q[2] - last[2]) > 1e-9) pts.push(q);
|
||||
}
|
||||
if (pts.length < 2) return;
|
||||
if (pts.every((p) => Math.abs(p[0] - pts[0][0]) < 1e-9 && Math.abs(p[1] - pts[0][1]) < 1e-9 && Math.abs(p[2] - pts[0][2]) < 1e-9)) return;
|
||||
const info = mesh.edges[ei];
|
||||
// A circle shows as one only seen face on.
|
||||
let shape: Line["shape"] = info?.type === "LINE" ? "line" : "other";
|
||||
if (info?.type === "CIRCLE" && g.count >= 3) {
|
||||
const o = (i: number) => (g.start + i) * 3;
|
||||
const [a, b, c] = [o(0), o(Math.floor(g.count / 3)), o(Math.floor((2 * g.count) / 3))];
|
||||
const u: V3 = [E[b] - E[a], E[b + 1] - E[a + 1], E[b + 2] - E[a + 2]];
|
||||
const w: V3 = [E[c] - E[a], E[c + 1] - E[a + 1], E[c + 2] - E[a + 2]];
|
||||
const n = unit([u[1] * w[2] - u[2] * w[1], u[2] * w[0] - u[0] * w[2], u[0] * w[1] - u[1] * w[0]]);
|
||||
if (Math.abs(n[0] * d[0] + n[1] * d[1] + n[2] * d[2]) > 1 - 1e-6) shape = "circle";
|
||||
}
|
||||
addLine(bi, kind, shape, pts);
|
||||
});
|
||||
const N = mesh.normals;
|
||||
const T = mesh.indices;
|
||||
const P = mesh.positions;
|
||||
mesh.faceGroups.forEach((g) => {
|
||||
const type = mesh.faces[g.face]?.type;
|
||||
if (type === "PLANE") return;
|
||||
// On a round face, the outline lies on the surface, straight along it.
|
||||
const cyl = type === "CYLINDRE" ? cylinderAt(bodies[bi].shape, g.face) : null;
|
||||
const across = cyl ? unit([d[1] * cyl.a[2] - d[2] * cyl.a[1], d[2] * cyl.a[0] - d[0] * cyl.a[2], d[0] * cyl.a[1] - d[1] * cyl.a[0]]) : null;
|
||||
const onto = (p: V3): V3 => {
|
||||
if (!cyl || !across) return p;
|
||||
const a = unit(cyl.a as V3);
|
||||
const q: V3 = [p[0] - cyl.c[0], p[1] - cyl.c[1], p[2] - cyl.c[2]];
|
||||
const t = q[0] * a[0] + q[1] * a[1] + q[2] * a[2];
|
||||
const sg = q[0] * across[0] + q[1] * across[1] + q[2] * across[2] >= 0 ? 1 : -1;
|
||||
return [cyl.c[0] + a[0] * t + across[0] * cyl.r * sg, cyl.c[1] + a[1] * t + across[1] * cyl.r * sg, cyl.c[2] + a[2] * t + across[2] * cyl.r * sg];
|
||||
};
|
||||
// Crossing points, by the mesh edge they're on (so the pieces join up).
|
||||
const at = new Map<string, V3>();
|
||||
const links = new Map<string, string[]>();
|
||||
const link = (a: string, b: string) => {
|
||||
links.set(a, [...(links.get(a) ?? []), b]);
|
||||
links.set(b, [...(links.get(b) ?? []), a]);
|
||||
};
|
||||
const f = (i: number) => N[i * 3] * d[0] + N[i * 3 + 1] * d[1] + N[i * 3 + 2] * d[2];
|
||||
for (let t = g.start; t < g.start + g.count; t += 3) {
|
||||
const vs = [T[t], T[t + 1], T[t + 2]];
|
||||
const fs = vs.map(f);
|
||||
if (fs.every((x) => Math.abs(x) < 1e-7)) continue;
|
||||
const pos = fs.map((x) => x >= -1e-7);
|
||||
if (pos[0] === pos[1] && pos[1] === pos[2]) continue;
|
||||
const cross: string[] = [];
|
||||
for (const [i, j] of [
|
||||
[0, 1],
|
||||
[1, 2],
|
||||
[2, 0],
|
||||
]) {
|
||||
if (pos[i] === pos[j]) continue;
|
||||
const [va, vb] = vs[i] < vs[j] ? [vs[i], vs[j]] : [vs[j], vs[i]];
|
||||
const k = `${va}_${vb}`;
|
||||
if (!at.has(k)) {
|
||||
const fa = f(va);
|
||||
const fb = f(vb);
|
||||
const s = Math.abs(fa - fb) < 1e-12 ? 0.5 : Math.max(0, Math.min(1, fa / (fa - fb)));
|
||||
at.set(k, onto([P[va * 3] + (P[vb * 3] - P[va * 3]) * s, P[va * 3 + 1] + (P[vb * 3 + 1] - P[va * 3 + 1]) * s, P[va * 3 + 2] + (P[vb * 3 + 2] - P[va * 3 + 2]) * s]));
|
||||
}
|
||||
cross.push(k);
|
||||
}
|
||||
if (cross.length === 2) link(cross[0], cross[1]);
|
||||
}
|
||||
// Joined into polylines.
|
||||
const used = new Set<string>();
|
||||
const ends = [...links.keys()].sort((a, b) => (links.get(a)!.length === 1 ? 0 : 1) - (links.get(b)!.length === 1 ? 0 : 1));
|
||||
for (const start of ends) {
|
||||
if (used.has(start)) continue;
|
||||
const chain = [start];
|
||||
used.add(start);
|
||||
let cur = start;
|
||||
for (;;) {
|
||||
const next = links.get(cur)!.find((n) => !used.has(n));
|
||||
if (!next) break;
|
||||
used.add(next);
|
||||
chain.push(next);
|
||||
cur = next;
|
||||
}
|
||||
// A closed loop: back to its start.
|
||||
if (chain.length > 2 && links.get(cur)!.includes(start)) chain.push(start);
|
||||
if (chain.length < 2) continue;
|
||||
addLine(
|
||||
bi,
|
||||
"outline",
|
||||
"other",
|
||||
chain.map((k) => {
|
||||
const p = at.get(k)!;
|
||||
return px2(p[0], p[1], p[2]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// ---- Seen or hidden, each sample. Then, nearest lines first: a sample
|
||||
// lying right under a line already drawn is left out, seen or not (the back
|
||||
// edge of a box seen straight on, a hole's far rim under its near one).
|
||||
for (const l of lines) for (let k = 0; k < l.state.length; k++) l.state[k] = seenAt(l.xyz[k * 3], l.xyz[k * 3 + 1], l.xyz[k * 3 + 2]) ? 1 : 0;
|
||||
const ink = new Float32Array(gw * gh).fill(-Infinity);
|
||||
// Which line (and which of its samples) put the ink there: a line steep in
|
||||
// depth must not hide its own next samples.
|
||||
const inkLine = new Int32Array(gw * gh).fill(-1);
|
||||
const inkK = new Int32Array(gw * gh);
|
||||
const pix = (x: number, y: number) => [Math.floor((x - ox) / px), Math.floor((y - oy) / px)];
|
||||
const underInk = (x: number, y: number, z: number, li = -1, k = 0) => {
|
||||
const [i, j] = pix(x, y);
|
||||
for (let jj = j - 1; jj <= j + 1; jj++)
|
||||
for (let ii = i - 1; ii <= i + 1; ii++) {
|
||||
if (ii < 0 || jj < 0 || ii >= gw || jj >= gh) continue;
|
||||
const q = jj * gw + ii;
|
||||
if (ink[q] > z + eps && (inkLine[q] !== li || Math.abs(inkK[q] - k) > 8)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
/** Near a line's ends, where it meets the next one: never left out there. */
|
||||
const nearEnd = (l: Line, k: number) => {
|
||||
const n = l.state.length - 1;
|
||||
const x = l.xyz[k * 3];
|
||||
const y = l.xyz[k * 3 + 1];
|
||||
return Math.hypot(x - l.xyz[0], y - l.xyz[1]) < 2.5 * px || Math.hypot(x - l.xyz[n * 3], y - l.xyz[n * 3 + 1]) < 2.5 * px;
|
||||
};
|
||||
// Every seen sample, nearest first - the tangent lines after all the others:
|
||||
// one on a seen edge or outline (a face split in two, seen edge on) gives
|
||||
// way to it, nearer or not.
|
||||
const order: [number, number, number][] = [];
|
||||
lines.forEach((l, li) => {
|
||||
for (let k = 0; k < l.state.length; k++) if (l.state[k] === 1) order.push([l.xyz[k * 3 + 2], li, k]);
|
||||
});
|
||||
const soft = (li: number) => (lines[li].kind === "smooth" ? 1 : 0);
|
||||
order.sort((a, b) => soft(a[1]) - soft(b[1]) || b[0] - a[0]);
|
||||
for (const [z, li, k] of order) {
|
||||
const l = lines[li];
|
||||
const x = l.xyz[k * 3];
|
||||
const y = l.xyz[k * 3 + 1];
|
||||
if (!nearEnd(l, k) && underInk(x, y, l.kind === "smooth" ? -Infinity : z, li, k)) {
|
||||
l.state[k] = -1;
|
||||
continue;
|
||||
}
|
||||
const [i, j] = pix(x, y);
|
||||
if (i >= 0 && j >= 0 && i < gw && j < gh && z > ink[j * gw + i]) {
|
||||
const q = j * gw + i;
|
||||
ink[q] = z;
|
||||
inkLine[q] = li;
|
||||
inkK[q] = k;
|
||||
}
|
||||
}
|
||||
for (const l of lines)
|
||||
for (let k = 0; k < l.state.length; k++) if (l.state[k] === 0 && (l.kind === "smooth" || underInk(l.xyz[k * 3], l.xyz[k * 3 + 1], l.xyz[k * 3 + 2]))) l.state[k] = -1;
|
||||
|
||||
// ---- The runs, as paths and as edges to dimension.
|
||||
let lo: P2 = [Infinity, Infinity];
|
||||
let hi: P2 = [-Infinity, -Infinity];
|
||||
const out: ViewBody[] = bodies.map(({ id }) => ({ id, visible: "", tangent: "", hidden: "", edges: [] }));
|
||||
const seen = bodies.map(() => [] as P2[][]);
|
||||
const under = bodies.map(() => [] as P2[][]);
|
||||
for (const l of lines) {
|
||||
const b = out[l.body];
|
||||
let k = 0;
|
||||
while (k < l.state.length) {
|
||||
const st = l.state[k];
|
||||
let e = k;
|
||||
while (e + 1 < l.state.length && l.state[e + 1] === st) e++;
|
||||
// The run from the sample before it (no gap between a seen run and a hidden one).
|
||||
const from = k > 0 && l.state[k - 1] !== -1 ? k - 1 : k;
|
||||
if (st !== -1 && e > from) {
|
||||
const pts: P2[] = [];
|
||||
for (let q = from; q <= e; q++) if (q === from || q === e || (l.shape !== "line" && l.vert[q])) pts.push([l.xyz[q * 3], l.xyz[q * 3 + 1]]);
|
||||
for (const p of pts) {
|
||||
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 long = Math.hypot(pts[pts.length - 1][0] - pts[0][0], pts[pts.length - 1][1] - pts[0][1]) > 3 * px || pts.length > 3;
|
||||
if (st === 0) {
|
||||
b.hidden += pathOf(pts);
|
||||
under[l.body].push(pts);
|
||||
} else {
|
||||
if (l.kind === "smooth") b.tangent += pathOf(pts);
|
||||
else b.visible += pathOf(pts);
|
||||
seen[l.body].push(pts);
|
||||
if (long) {
|
||||
if (l.kind === "outline") {
|
||||
if (straight(pts)) b.edges.push({ a: rr(pts[0]), b: rr(pts[pts.length - 1]) });
|
||||
} else {
|
||||
const ve = viewEdge(l.shape, pts);
|
||||
if (ve) b.edges.push(ve);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
k = e + 1;
|
||||
}
|
||||
}
|
||||
out.forEach((b, i) => {
|
||||
b.anchor = anchorOf(seen[i]);
|
||||
if (!b.anchor && under[i].length) b.under = anchorOf(under[i]);
|
||||
});
|
||||
return { id: v.id, bodies: out, box: lo[0] <= hi[0] ? exactBox(bodies, X, Y) ?? [lo, hi] : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Looking along an axis, the view's box from the solids themselves (the mesh
|
||||
* lies a little inside round faces: an overall size came out 0.01 short).
|
||||
*/
|
||||
function exactBox(bodies: { shape: Shape3D }[], X: V3, Y: V3): [P2, P2] | null {
|
||||
const axial = (v: V3) => v.filter((c) => Math.abs(c) > 1e-9).length === 1;
|
||||
if (!axial(X) || !axial(Y)) return null;
|
||||
const lo3: V3 = [Infinity, Infinity, Infinity];
|
||||
const hi3: V3 = [-Infinity, -Infinity, -Infinity];
|
||||
for (const b of bodies) {
|
||||
const bb = boxOf(b.shape);
|
||||
if (!bb) return null;
|
||||
for (let c = 0; c < 3; c++) {
|
||||
lo3[c] = Math.min(lo3[c], bb[0][c]);
|
||||
hi3[c] = Math.max(hi3[c], bb[1][c]);
|
||||
}
|
||||
}
|
||||
if (!(lo3[0] <= hi3[0])) return null;
|
||||
const xs: number[] = [];
|
||||
const ys: number[] = [];
|
||||
for (const i of [0, 1])
|
||||
for (const j of [0, 1])
|
||||
for (const k of [0, 1]) {
|
||||
const c: V3 = [i ? hi3[0] : lo3[0], j ? hi3[1] : lo3[1], k ? hi3[2] : lo3[2]];
|
||||
xs.push(c[0] * X[0] + c[1] * X[1] + c[2] * X[2]);
|
||||
ys.push(-(c[0] * Y[0] + c[1] * Y[1] + c[2] * Y[2]));
|
||||
}
|
||||
return [
|
||||
[Math.min(...xs), Math.min(...ys)],
|
||||
[Math.max(...xs), Math.max(...ys)],
|
||||
];
|
||||
}
|
||||
|
||||
/** A body's exact box, worked out once (it's slow on a big body, and every view wants it). */
|
||||
const boxes = new WeakMap<Shape3D, [V3, V3] | null>();
|
||||
function boxOf(shape: Shape3D): [V3, V3] | null {
|
||||
if (boxes.has(shape)) return boxes.get(shape)!;
|
||||
const oc = getOC();
|
||||
const box = new oc.Bnd_Box();
|
||||
let out: [V3, V3] | null = null;
|
||||
try {
|
||||
oc.BRepBndLib.AddOptimal(shape.wrapped as never, box, false, false);
|
||||
if (!box.IsVoid()) {
|
||||
const p = box.CornerMin();
|
||||
const q = box.CornerMax();
|
||||
out = [
|
||||
[p.X(), p.Y(), p.Z()],
|
||||
[q.X(), q.Y(), q.Z()],
|
||||
];
|
||||
p.delete();
|
||||
q.delete();
|
||||
}
|
||||
} catch {
|
||||
out = null;
|
||||
} finally {
|
||||
box.delete();
|
||||
}
|
||||
boxes.set(shape, out);
|
||||
return out;
|
||||
}
|
||||
@@ -4,27 +4,76 @@
|
||||
import opencascade from "replicad-opencascadejs";
|
||||
import wasmUrl from "replicad-opencascadejs/wasm?url";
|
||||
import { setOC } from "replicad";
|
||||
import { errorText, exportBodies, regenerate } from "./engine";
|
||||
import type { Envelope, Request, Response } from "./protocol";
|
||||
import { bodyHealth, bodyProperties, projectViews, errorText, exportBodies, regenerate, resetKernel, withFreshKernel } from "./engine";
|
||||
import type { BodyMesh, Envelope, Request, Response } from "./protocol";
|
||||
|
||||
self.onmessage = async (e: MessageEvent<Envelope<Request>>) => {
|
||||
/**
|
||||
* The meshes the page has (it keeps the last answer's): those go back as their
|
||||
* key only - a step changes one body, and every body's triangles were copied
|
||||
* across on each move of a drag.
|
||||
*/
|
||||
let sent = new Set<number>();
|
||||
let oc: { wasmMemory?: WebAssembly.Memory } = {};
|
||||
/** Past this much memory the engine is replaced before the next rebuild (a phone's tab is killed not far above it). */
|
||||
const FRESH_ENGINE_MB = 1200;
|
||||
|
||||
/** OpenCascade loaded afresh (at the start, and after it broke down: its memory can't be trusted then). */
|
||||
async function load(): Promise<void> {
|
||||
oc = await opencascade({ locateFile: () => wasmUrl });
|
||||
setOC(oc as never);
|
||||
// Everything is new to the page again.
|
||||
sent = new Set();
|
||||
}
|
||||
|
||||
/**
|
||||
* One message at a time: a rebuild waits at points (it awaits), and another
|
||||
* message taken then (an export, the bodies' properties) ran the same steps
|
||||
* at once, on the same cache.
|
||||
*/
|
||||
let queue: Promise<void> = Promise.resolve();
|
||||
self.onmessage = (e: MessageEvent<Envelope<Request>>) => {
|
||||
queue = queue.then(() => handle(e));
|
||||
};
|
||||
|
||||
async function handle(e: MessageEvent<Envelope<Request>>): Promise<void> {
|
||||
const { id, msg } = e.data;
|
||||
const reply = (r: Response) => (self as DedicatedWorkerGlobalScope).postMessage({ id, msg: r } satisfies Envelope<Response>);
|
||||
try {
|
||||
switch (msg.type) {
|
||||
case "init":
|
||||
setOC(await opencascade({ locateFile: () => wasmUrl }));
|
||||
await load();
|
||||
reply({ type: "ready" });
|
||||
break;
|
||||
case "regenerate":
|
||||
reply({ type: "regenerated", result: await regenerate(msg.features) });
|
||||
case "regenerate": {
|
||||
// The engine's memory only grows (and some steps leak tens of MB a
|
||||
// rebuild: a long drag of a fillet's size). The page swaps in a spare
|
||||
// engine when it can; if it didn't get to, a fresh one here, before
|
||||
// this one runs out mid-step.
|
||||
if ((oc.wasmMemory?.buffer.byteLength ?? 0) / 2 ** 20 > FRESH_ENGINE_MB) {
|
||||
await load();
|
||||
resetKernel();
|
||||
}
|
||||
const result = await withFreshKernel(load, () => regenerate(msg.features, msg.saved));
|
||||
const bodies = result.bodies.map((b) => (sent.has(b.key) ? ({ id: b.id, name: b.name, key: b.key, same: true } as unknown as BodyMesh) : b));
|
||||
sent = new Set(result.bodies.map((b) => b.key));
|
||||
reply({ type: "regenerated", result: { ...result, bodies, memoryMB: (oc.wasmMemory?.buffer.byteLength ?? 0) / 2 ** 20 } });
|
||||
break;
|
||||
}
|
||||
case "export":
|
||||
reply({ type: "exported", blob: await exportBodies(msg.features, msg.format, msg.bodies) });
|
||||
reply({ type: "exported", blob: await withFreshKernel(load, () => exportBodies(msg.features, msg.format, msg.bodies)) });
|
||||
break;
|
||||
case "drawing":
|
||||
reply({ type: "drawing", views: await withFreshKernel(load, () => projectViews(msg.features, msg.views, msg.bodies)) });
|
||||
break;
|
||||
case "properties":
|
||||
reply({ type: "properties", bodies: await withFreshKernel(load, () => bodyProperties(msg.features)) });
|
||||
break;
|
||||
case "health":
|
||||
reply({ type: "health", bodies: await withFreshKernel(load, () => bodyHealth(msg.features)) });
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
reply({ type: "error", message: errorText(err) });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
// Sketches put onto a body's faces: Project as Edge (the curves drawn onto the
|
||||
// faces they land on, the faces split along them) and Wrap & Emboss (a sketch's
|
||||
// shapes wrapped round a round face, raised from it or sunk into it).
|
||||
|
||||
import { cast, draw, getOC, makeCompound, makeLine, makeVertex, type Drawing, type Edge, type Face, type Shape3D } from "replicad";
|
||||
import type { Vec3 } from "../doc/types";
|
||||
import { add, cross, dist, dot, len, norm, scale, sub } from "../geom";
|
||||
import { cylinderOf } from "./faceEdit";
|
||||
import { measureVolume, quickVolume } from "./ocFree";
|
||||
|
||||
const tup = (v: { toTuple(): number[] }) => v.toTuple() as Vec3;
|
||||
|
||||
type Src = { face: Face; normal: Vec3 }[];
|
||||
|
||||
/** A body's size: its bounding box's diagonal, and its middle. */
|
||||
function sizeOf(body: Shape3D): { d: number; c: Vec3 } {
|
||||
const bb = body.boundingBox;
|
||||
const c = bb.center as unknown as number[];
|
||||
return { d: Math.hypot(bb.width, bb.height, bb.depth), c: [c[0], c[1], c[2]] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Project as Edge: curves (a sketch's outlines, or edges) drawn onto the body
|
||||
* along a direction, the faces split along them. Which of the lines found are
|
||||
* kept is `keep`'s to say (those seen from the sketch, those on one face).
|
||||
* Nothing else changes: the new edges are there to push, pull, fillet or
|
||||
* sketch from.
|
||||
*/
|
||||
export function imprint(body: Shape3D, curves: Edge[], dir: Vec3, keep: (e: Edge) => boolean): Shape3D {
|
||||
const oc = getOC();
|
||||
const { d: D, c: mid } = sizeOf(body);
|
||||
const n = norm(dir);
|
||||
const kept: Edge[] = [];
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
const sec = new oc.BRepAlgoAPI_Section();
|
||||
try {
|
||||
// Each curve swept both ways through the whole body: where those walls cross the body's faces.
|
||||
const walls = curves.map((e) => {
|
||||
const far = D + dist(tup(e.pointAt(0.5)), mid) + 1;
|
||||
const v = new oc.gp_Vec(n[0] * 2 * far, n[1] * 2 * far, n[2] * 2 * far);
|
||||
const pr = new oc.BRepPrimAPI_MakePrism(e.clone().translate(scale(n, -far)).wrapped, v, false, true);
|
||||
try {
|
||||
return cast(pr.Shape());
|
||||
} finally {
|
||||
pr.delete();
|
||||
v.delete();
|
||||
}
|
||||
});
|
||||
sec.Init1(body.wrapped);
|
||||
sec.Init2(makeCompound(walls as never).wrapped);
|
||||
sec.Build(progress);
|
||||
const cut = cast(sec.Shape());
|
||||
for (const e of "edges" in cut ? (cut.edges as Edge[]) : []) if (keep(e)) kept.push(e);
|
||||
} finally {
|
||||
sec.delete();
|
||||
progress.delete();
|
||||
}
|
||||
if (!kept.length) throw new Error("Nothing lands on the body's faces seen from there");
|
||||
return splitFaces(body, kept);
|
||||
}
|
||||
|
||||
/** The lines seen from a sketch's plane (through o, square to n): not on the far side, nor behind other faces. */
|
||||
export function seenFrom(body: Shape3D, o: Vec3, n: Vec3): (e: Edge) => boolean {
|
||||
const eps = Math.max(1e-4, sizeOf(body).d * 1e-5);
|
||||
return (e) => seen(e, o, norm(n), body, eps);
|
||||
}
|
||||
|
||||
/** The lines on one face. */
|
||||
export function onFace(body: Shape3D, F: Face): (e: Edge) => boolean {
|
||||
const oc = getOC();
|
||||
const eps = Math.max(1e-4, sizeOf(body).d * 1e-5);
|
||||
return (e) => {
|
||||
const ds = new oc.BRepExtrema_DistShapeShape(makeVertex(tup(e.pointAt(0.5))).wrapped, F.wrapped);
|
||||
try {
|
||||
return ds.IsDone() && ds.Value() < eps;
|
||||
} finally {
|
||||
ds.delete();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an edge is seen from the sketch's plane: nothing of the body between
|
||||
* them along the normal (a step just off the edge towards the plane is in the
|
||||
* open, and so is the way on to the plane).
|
||||
*/
|
||||
function seen(e: Edge, o: Vec3, n: Vec3, body: Shape3D, eps: number): boolean {
|
||||
const oc = getOC();
|
||||
const pm = tup(e.pointAt(0.5));
|
||||
const h = dot(sub(pm, o), n);
|
||||
if (Math.abs(h) < 2 * eps) return true;
|
||||
const sg = Math.sign(h);
|
||||
const q = sub(pm, scale(n, sg * eps));
|
||||
const pp = sub(pm, scale(n, h - sg * eps));
|
||||
const seg = makeLine(q, pp);
|
||||
const ds = new oc.BRepExtrema_DistShapeShape(seg.wrapped, body.wrapped);
|
||||
try {
|
||||
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). */
|
||||
function splitFaces(body: Shape3D, edges: Edge[]): Shape3D {
|
||||
const oc = getOC();
|
||||
const sp = new oc.BRepAlgoAPI_Splitter();
|
||||
const args = new oc.NCollection_List_TopoDS_Shape();
|
||||
const tools = new oc.NCollection_List_TopoDS_Shape();
|
||||
const progress = new oc.Message_ProgressRange();
|
||||
try {
|
||||
args.Append(body.wrapped);
|
||||
tools.Append(makeCompound(edges).wrapped);
|
||||
sp.SetArguments(args);
|
||||
sp.SetTools(tools);
|
||||
sp.Build(progress);
|
||||
if (!sp.IsDone()) throw new Error("The faces couldn't be split along the sketch");
|
||||
const out = cast(sp.Shape()) as Shape3D;
|
||||
const solids = out.constructor.name === "Solid" ? [out] : ((out as unknown as { solids?: Shape3D[] }).solids ?? []);
|
||||
if (solids.length !== 1) throw new Error("The faces couldn't be split along the sketch");
|
||||
return solids[0];
|
||||
} finally {
|
||||
sp.delete();
|
||||
args.delete();
|
||||
tools.delete();
|
||||
progress.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap & Emboss: the sketch's shapes wrapped round a round face, lengths kept
|
||||
* (a line along the sketch goes as far round the face), then raised from it
|
||||
* (height > 0) or sunk into it (height < 0) square to the face. The sketch is
|
||||
* on a plane along the face's axis (touching it, or anywhere beside it): where
|
||||
* the plane is nearest the axis is where the wrap starts from.
|
||||
*/
|
||||
export function wrapOnto(body: Shape3D, round: Face, src: Src, height: number): Shape3D {
|
||||
if (Math.abs(height) < 1e-6) throw new Error("Height is zero");
|
||||
const cy = cylinderOf(round);
|
||||
if (!cy) throw new Error("Wrap goes on a round face (a cylinder)");
|
||||
const oc = getOC();
|
||||
const ad = new oc.BRepAdaptor_Surface(round.wrapped, true);
|
||||
const cyl = ad.Cylinder();
|
||||
const pos = cyl.Position();
|
||||
const Loc: Vec3 = [pos.Location().X(), pos.Location().Y(), pos.Location().Z()];
|
||||
const X = norm([pos.XDirection().X(), pos.XDirection().Y(), pos.XDirection().Z()]);
|
||||
const Z = norm([pos.Direction().X(), pos.Direction().Y(), pos.Direction().Z()]);
|
||||
const r = cyl.Radius();
|
||||
ad.delete();
|
||||
// The way the face's U goes round (replicad turns a left-handed one round).
|
||||
const Y = cross(Z, X);
|
||||
const n = norm(src[0].normal);
|
||||
if (Math.abs(dot(n, Z)) > 1e-6) throw new Error("Draw the sketch on a plane along the round face's axis");
|
||||
const o = tup(src[0].face.center);
|
||||
// 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)));
|
||||
// (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);
|
||||
// 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) {
|
||||
const loops = [face.clone().outerWire(), ...face.clone().innerWires()].map((w) => chain(w.edges as Edge[]));
|
||||
const all = loops.flat().flatMap((e) => [0, 0.5, 1].map((t) => map(e.at(t))[0]));
|
||||
const [lo, hi] = [Math.min(...all), Math.max(...all)];
|
||||
if (hi - lo > 2 * Math.PI * r - 1e-6) throw new Error("The sketch is longer than the way round the face");
|
||||
const shift = lo < 0 ? 2 * Math.PI * r : 0;
|
||||
const m = (p: Vec3): [number, number] => {
|
||||
const q = map(p);
|
||||
return [q[0] + shift, q[1]];
|
||||
};
|
||||
const drawings = loops.map((loop) => loopDrawing(loop, m));
|
||||
let dr = drawings[0];
|
||||
for (const h of drawings.slice(1)) dr = dr.cut(h);
|
||||
const sk = dr.sketchOnFace(round, "original") as unknown as { faces?: () => Face; face?: () => Face };
|
||||
const onFace = sk.faces ? sk.faces() : sk.face!();
|
||||
solids.push(thicken(onFace, height, cy));
|
||||
}
|
||||
let out = body;
|
||||
for (const s of solids) out = (height > 0 ? out.fuse(s) : out.cut(s)) as Shape3D;
|
||||
return out;
|
||||
}
|
||||
|
||||
type Run = { at: (t: number) => Vec3; kind: string };
|
||||
|
||||
/** A wire's edges one after another, each the way the loop goes. */
|
||||
function chain(edges: Edge[]): Run[] {
|
||||
const left = edges.map((e) => ({ e, a: tup(e.startPoint), b: tup(e.endPoint) }));
|
||||
const out: Run[] = [];
|
||||
let end: Vec3 | null = null;
|
||||
while (left.length) {
|
||||
let i = 0;
|
||||
let flip = false;
|
||||
if (end) {
|
||||
let best = Infinity;
|
||||
left.forEach((x, k) => {
|
||||
const [da, db] = [dist(x.a, end!), dist(x.b, end!)];
|
||||
if (da < best) [best, i, flip] = [da, k, false];
|
||||
if (db < best) [best, i, flip] = [db, k, true];
|
||||
});
|
||||
}
|
||||
const { e, a, b } = left.splice(i, 1)[0];
|
||||
const at = (t: number) => tup(e.pointAt(flip ? 1 - t : t));
|
||||
out.push({ at, kind: e.geomType });
|
||||
end = flip ? a : b;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A loop in the unrolled face (lengths round it, heights along it): lines stay lines, circles circles. */
|
||||
function loopDrawing(loop: Run[], m: (p: Vec3) => [number, number]): Drawing {
|
||||
let pen = draw(m(loop[0].at(0)));
|
||||
for (const run of loop) {
|
||||
const closed = dist(run.at(0), run.at(1)) < 1e-9;
|
||||
if (run.kind === "LINE") pen = pen.lineTo(m(run.at(1)));
|
||||
else if (run.kind === "CIRCLE") {
|
||||
if (closed) pen = pen.threePointsArcTo(m(run.at(0.5)), m(run.at(0.25))).threePointsArcTo(m(run.at(1)), m(run.at(0.75)));
|
||||
else pen = pen.threePointsArcTo(m(run.at(1)), m(run.at(0.5)));
|
||||
} else for (let k = 1; k <= 32; k++) pen = pen.lineTo(m(run.at(k / 32)));
|
||||
}
|
||||
return pen.close();
|
||||
}
|
||||
|
||||
/** A face on the round face made solid: `height` out from it (away from the material) or into it. */
|
||||
function thicken(face: Face, height: number, cy: { s: number }): Shape3D {
|
||||
const oc = getOC();
|
||||
// Away from the axis on a boss raised, or a hole sunk; towards it otherwise.
|
||||
const want = Math.sign(height) * cy.s;
|
||||
const make = (k: number): Shape3D | null => {
|
||||
const th = new oc.BRepOffsetAPI_MakeThickSolid();
|
||||
try {
|
||||
th.MakeThickSolidBySimple(face.wrapped, k);
|
||||
if (!th.IsDone()) return null;
|
||||
let s = cast(th.Shape()) as Shape3D;
|
||||
if (quickVolume(s) < 0) s = cast(s.wrapped.Reversed()) as Shape3D;
|
||||
return s;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
th.delete();
|
||||
}
|
||||
};
|
||||
// Made both ways: the one away from the axis is the bigger (it lies further out). (Not
|
||||
// told by its centre of mass: a slab bent round an arc has that nearer the axis than it is.)
|
||||
const both = [make(Math.abs(height)), make(-Math.abs(height))];
|
||||
if (both[0] && both[1]) {
|
||||
const [a, b] = both.map((s) => measureVolume(s!));
|
||||
const outer = a > b ? both[0] : both[1];
|
||||
const inner = a > b ? both[1] : both[0];
|
||||
return want > 0 ? outer! : inner!;
|
||||
}
|
||||
throw new Error("The wrapped shape couldn't be made solid");
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
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).
|
||||
@@ -12,9 +14,14 @@ import { outerScrollbars } from "./ui/scrollbars";
|
||||
}
|
||||
}
|
||||
|
||||
// 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();
|
||||
|
||||
const app = new App(document.getElementById("view") as HTMLCanvasElement);
|
||||
// Handy for debugging from the console.
|
||||
(window as unknown as { supergeometry: App }).supergeometry = app;
|
||||
// And sg: read and work the app from the console (sg.help()).
|
||||
installDebug(app);
|
||||
|
||||
@@ -23,6 +23,12 @@ export interface Settings {
|
||||
animateCamera: boolean;
|
||||
ortho: boolean;
|
||||
shader: "shaded" | "wireframe" | "xray";
|
||||
/** Surface analysis on the bodies (Display modes): zebra stripes or a curvature map. */
|
||||
analysis: "none" | "zebra" | "curvature";
|
||||
zebraStripes: number;
|
||||
zebraDirection: "vertical" | "horizontal";
|
||||
/** Curvature map: a curve this tight (radius, mm) shows fully red (domed) or blue (hollow). */
|
||||
curvatureRadius: number;
|
||||
showEdges: boolean;
|
||||
showHiddenEdges: boolean;
|
||||
showPinned: boolean;
|
||||
@@ -30,6 +36,8 @@ export interface Settings {
|
||||
showConstraints: boolean;
|
||||
/** Sketch: add Horizontal/Vertical/Coincident automatically while drawing. */
|
||||
autoConstrain: boolean;
|
||||
/** Sketch: when a constraint joins two things, the first or the last picked stays put (the anchored one). */
|
||||
sketchAnchor: "first" | "last";
|
||||
/** Sketch: draw the constraint badges (H, V, ∥, dimensions…) on the geometry. */
|
||||
showConstraintGlyphs: boolean;
|
||||
/** Bumped when defaults change for everyone (see the constructor). */
|
||||
@@ -40,6 +48,129 @@ export interface Settings {
|
||||
numpad: boolean;
|
||||
/** The guide text (what to tap next) - switched in More. */
|
||||
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 = {
|
||||
@@ -53,6 +184,10 @@ const DEFAULTS: Settings = {
|
||||
animateCamera: true,
|
||||
ortho: true,
|
||||
shader: "shaded",
|
||||
analysis: "none",
|
||||
zebraStripes: 16,
|
||||
zebraDirection: "vertical",
|
||||
curvatureRadius: 10,
|
||||
showEdges: true,
|
||||
showHiddenEdges: false,
|
||||
showPinned: true,
|
||||
@@ -61,11 +196,17 @@ const DEFAULTS: Settings = {
|
||||
// constraints themselves are in the card of what's selected.
|
||||
showConstraints: false,
|
||||
autoConstrain: true,
|
||||
sketchAnchor: "first",
|
||||
showConstraintGlyphs: true,
|
||||
// On by default on touch screens (phones, tablets, headsets).
|
||||
numpad: isTouchDevice,
|
||||
showHints: true,
|
||||
version: 4,
|
||||
offline: false,
|
||||
sentence: true,
|
||||
direct: true,
|
||||
mouse: "default",
|
||||
wheelReverse: false,
|
||||
version: 5,
|
||||
};
|
||||
|
||||
type Listener = (s: Settings) => void;
|
||||
@@ -89,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 [];
|
||||
}
|
||||
@@ -239,6 +276,57 @@ function residuals(c: SketchConstraint, get: Lookup): number[] {
|
||||
const a = c.pts?.[0] && P(c.pts[0]);
|
||||
return a && c.at ? [a[0] - c.at[0], a[1] - c.at[1]] : [];
|
||||
}
|
||||
case "pattern": {
|
||||
// A copy in a sketch pattern: each of its points is the original's,
|
||||
// moved by `at` (or turned round `at` by `value` degrees); sizes the same.
|
||||
const o = E(0);
|
||||
const k = E(1);
|
||||
if (!o || !k || o.kind !== k.kind || !c.at) return [];
|
||||
const t = ((c.value ?? 0) * Math.PI) / 180;
|
||||
const [cx, cy] = c.at;
|
||||
const map = (p: Vec2): Vec2 => (c.turn ? [cx + (p[0] - cx) * Math.cos(t) - (p[1] - cy) * Math.sin(t), cy + (p[0] - cx) * Math.sin(t) + (p[1] - cy) * Math.cos(t)] : [p[0] + cx, p[1] + cy]);
|
||||
const out: number[] = [];
|
||||
for (const q of pointsOf(o)) {
|
||||
const w = pointOf(k, q.p);
|
||||
if (!w) return [];
|
||||
const m = map(q.at);
|
||||
out.push(w[0] - m[0], w[1] - m[1]);
|
||||
}
|
||||
if ((o.kind === "circle" || o.kind === "polygon") && (k.kind === "circle" || k.kind === "polygon")) out.push(k.radius - o.radius);
|
||||
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.
|
||||
@@ -247,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] : [];
|
||||
}
|
||||
@@ -289,15 +388,55 @@ 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
|
||||
|
||||
/** How the id of a curve that follows a body's edge begins: it is where that edge is, and nothing in the sketch moves it. */
|
||||
export const LINKED = "ref-";
|
||||
|
||||
export interface SolveOptions {
|
||||
/** Points to pull towards a target (dragging), with a strong weight. */
|
||||
drag?: { ref: PointRef; to: Vec2 }[];
|
||||
@@ -321,6 +460,8 @@ export interface SolveResult {
|
||||
* whose constraints are already met, with nothing dragged in it, isn't touched.
|
||||
*/
|
||||
export function solve(entities: SketchEntity[], constraints: SketchConstraint[], opts: SolveOptions = {}): SolveResult {
|
||||
const held = entities.filter((e) => e.id.startsWith(LINKED));
|
||||
if (held.length) opts = { ...opts, fixed: new Set([...(opts.fixed ?? []), ...held.map((e) => e.id)]) };
|
||||
const ids = new Set(entities.map((e) => e.id));
|
||||
const live = constraints.filter((c) => refsOf(c).every((id) => ids.has(id)));
|
||||
const drags = opts.drag ?? [];
|
||||
@@ -392,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);
|
||||
@@ -471,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).
|
||||
@@ -516,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) };
|
||||
@@ -617,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)));
|
||||
@@ -705,6 +898,107 @@ function sameTurns(a: Map<string, number>, b: Map<string, number>): boolean {
|
||||
}
|
||||
|
||||
/** Entity ids a constraint refers to. */
|
||||
/**
|
||||
* Which curves the constraints hold completely - nothing about them can
|
||||
* change without breaking one (a sketch drawn green there) - and whether that's
|
||||
* all of them. From the rank of the constraints' Jacobian: a parameter is held
|
||||
* when no free direction of the system moves it. Null for a sketch too big
|
||||
* to work it out quickly.
|
||||
*/
|
||||
export function definedCurves(entities: SketchEntity[], constraints: SketchConstraint[]): { defined: Set<string>; all: boolean } | null {
|
||||
const ids = new Set(entities.map((e) => e.id));
|
||||
const live = constraints.filter((c) => refsOf(c).every((id) => ids.has(id)));
|
||||
// Curves that follow a body's edge are where the edge is: held already.
|
||||
const movers = entities.filter((e) => !e.id.startsWith(LINKED));
|
||||
const offsets: number[] = [];
|
||||
const counts: number[] = [];
|
||||
const x0: number[] = [];
|
||||
for (const e of movers) {
|
||||
const p = params(e);
|
||||
offsets.push(x0.length);
|
||||
counts.push(p.length);
|
||||
x0.push(...p);
|
||||
}
|
||||
const n = x0.length;
|
||||
const linked = new Set(entities.filter((e) => e.id.startsWith(LINKED)).map((e) => e.id));
|
||||
if (!n) return { defined: linked, all: true };
|
||||
if (n > 300) return null;
|
||||
const byId = new Map(entities.map((e) => [e.id, e]));
|
||||
const at = (id: string) => byId.get(id);
|
||||
const rowStart: number[] = [];
|
||||
let m = 0;
|
||||
for (const c of live) {
|
||||
rowStart.push(m);
|
||||
m += residuals(c, at).length;
|
||||
}
|
||||
const J: Float64Array[] = Array.from({ length: m }, () => new Float64Array(n));
|
||||
const moverOf = new Map(movers.map((e, i) => [e.id, i]));
|
||||
const usedBy: number[][] = movers.map(() => []);
|
||||
live.forEach((c, ci) => {
|
||||
for (const id of new Set(refsOf(c))) {
|
||||
const i = moverOf.get(id);
|
||||
if (i !== undefined) usedBy[i].push(ci);
|
||||
}
|
||||
});
|
||||
let big = 0;
|
||||
movers.forEach((e, i) => {
|
||||
const xs = x0.slice(offsets[i], offsets[i] + counts[i]);
|
||||
for (let k = 0; k < counts[i]; k++) {
|
||||
const j = offsets[i] + k;
|
||||
const h = 1e-6 * Math.max(1, Math.abs(xs[k]));
|
||||
const up = xs.slice();
|
||||
const down = xs.slice();
|
||||
up[k] += h;
|
||||
down[k] -= h;
|
||||
const ep = withParams(e, up);
|
||||
const em = withParams(e, down);
|
||||
for (const ci of usedBy[i]) {
|
||||
const rp = residuals(live[ci], (id) => (id === e.id ? ep : byId.get(id)));
|
||||
const rm = residuals(live[ci], (id) => (id === e.id ? em : byId.get(id)));
|
||||
for (let r = 0; r < rp.length; r++) {
|
||||
const v = (rp[r] - rm[r]) / (2 * h);
|
||||
if (Number.isFinite(v)) {
|
||||
J[rowStart[ci] + r][j] = v;
|
||||
big = Math.max(big, Math.abs(v));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
// Reduced row echelon form; the columns without a pivot are free directions.
|
||||
const tol = 1e-7 * Math.max(1, big);
|
||||
const pivotRow = new Int32Array(n).fill(-1);
|
||||
let row = 0;
|
||||
for (let col = 0; col < n && row < m; col++) {
|
||||
let p = row;
|
||||
for (let r = row + 1; r < m; r++) if (Math.abs(J[r][col]) > Math.abs(J[p][col])) p = r;
|
||||
if (Math.abs(J[p][col]) < tol) continue;
|
||||
[J[row], J[p]] = [J[p], J[row]];
|
||||
const R = J[row];
|
||||
const d = R[col];
|
||||
for (let c = col; c < n; c++) R[c] /= d;
|
||||
for (let r = 0; r < m; r++) {
|
||||
if (r === row) continue;
|
||||
const f = J[r][col];
|
||||
if (Math.abs(f) < 1e-15) continue;
|
||||
const Rr = J[r];
|
||||
for (let c = col; c < n; c++) Rr[c] -= f * R[c];
|
||||
}
|
||||
pivotRow[col] = row++;
|
||||
}
|
||||
const free: number[] = [];
|
||||
for (let j = 0; j < n; j++) if (pivotRow[j] < 0) free.push(j);
|
||||
// A pivot parameter is held when no free direction moves it.
|
||||
const held = (j: number) => pivotRow[j] >= 0 && free.every((f) => Math.abs(J[pivotRow[j]][f]) < 1e-6);
|
||||
const defined = new Set(linked);
|
||||
movers.forEach((e, i) => {
|
||||
let ok = true;
|
||||
for (let k = 0; k < counts[i] && ok; k++) ok = held(offsets[i] + k);
|
||||
if (ok) defined.add(e.id);
|
||||
});
|
||||
return { defined, all: defined.size === entities.length };
|
||||
}
|
||||
|
||||
export function refsOf(c: SketchConstraint): string[] {
|
||||
return [...(c.pts ?? []).map((p) => p.e), ...(c.curves ?? [])];
|
||||
}
|
||||
@@ -805,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":
|
||||
@@ -813,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;
|
||||
@@ -1017,6 +1313,8 @@ export function addForUser(
|
||||
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));
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
// Pure sketch-editing operations (no UI): trim, extend, offset, fillet,
|
||||
// transforms, projection of 3D edges, and text outlines.
|
||||
|
||||
import type { PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec3 } from "../doc/types";
|
||||
import { roundSig, toPlane } from "../geom";
|
||||
import type { OutlineOffset, PlaneDef, SketchConstraint, SketchEntity, Vec2, Vec3 } from "../doc/types";
|
||||
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);
|
||||
@@ -51,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": {
|
||||
@@ -82,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" }));
|
||||
@@ -165,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));
|
||||
@@ -306,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 };
|
||||
@@ -379,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;
|
||||
}
|
||||
|
||||
@@ -449,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;
|
||||
@@ -654,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;
|
||||
@@ -662,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;
|
||||
@@ -1035,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": {
|
||||
@@ -1072,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" };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1227,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];
|
||||
@@ -1244,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[] {
|
||||
@@ -1456,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);
|
||||
@@ -1573,3 +1806,73 @@ export function chamferConstraints(entities: SketchEntity[], constraints: Sketch
|
||||
export function lineMeet(p: LineE, q: LineE): Vec2 | null {
|
||||
return meetLines(p.a, [p.b[0] - p.a[0], p.b[1] - p.a[1]], q.a, q.b);
|
||||
}
|
||||
|
||||
/**
|
||||
* The curves of a sketch's linked offsets of its face outline (see
|
||||
* SketchFeature.outlineOffsets), made from the outline as it is now. Each
|
||||
* offsets the loop of the outline nearest where it was tapped.
|
||||
*/
|
||||
export function outlineOffsetCurves(boundary: SketchEntity[], links: OutlineOffset[] | undefined): SketchEntity[] {
|
||||
const out: SketchEntity[] = [];
|
||||
for (const o of links ?? []) {
|
||||
let seed: SketchEntity | null = null;
|
||||
let best = Infinity;
|
||||
for (const e of boundary) {
|
||||
for (const p of entityPrims(e)) {
|
||||
const d = closestOnPrim(p, o.at).d;
|
||||
if (d < best) [best, seed] = [d, e];
|
||||
}
|
||||
}
|
||||
if (!seed) continue;
|
||||
let made: SketchEntity[] = [];
|
||||
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];
|
||||
}
|
||||
made.forEach((e, k) => out.push({ ...e, id: `lnk-${o.id}-${k}` }));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* A sketch's shapes onto another plane, square to it: each outline (and hole)
|
||||
* of the regions, a run of one curve at a time (a whole circle stays a circle,
|
||||
* one squashed by the slant becomes a spline).
|
||||
*/
|
||||
export function projectRegions(arr: Arrangement, regions: Region[], from: PlaneDef, to: PlaneDef): SketchEntity[] {
|
||||
const kind = (prim: number) => ({ line: "LINE", circle: "CIRCLE" })[arr.prims[prim].t as "line" | "circle"] ?? "SPLINE";
|
||||
const out: SketchEntity[] = [];
|
||||
const seen = new Set<number>();
|
||||
for (const r of regions)
|
||||
for (const loop of [r.outer, ...r.holes]) {
|
||||
// Runs of pieces of one curve, the run started where the curve changes.
|
||||
const ps = loop.pieces;
|
||||
let start = ps.findIndex((x, i) => arr.pieces[x.piece].prim !== arr.pieces[ps[(i + ps.length - 1) % ps.length].piece].prim);
|
||||
if (start < 0) start = 0;
|
||||
let run: { prim: number; pts: Vec2[]; pieces: number[] } | null = null;
|
||||
const flush = () => {
|
||||
// A piece two regions share (a line between them) is drawn once.
|
||||
if (run && !run.pieces.every((k) => seen.has(k))) {
|
||||
run.pieces.forEach((k) => seen.add(k));
|
||||
const e = projectPolyline(run.pts.map((q) => toWorld(from, q)), to, kind(run.prim));
|
||||
if (e) out.push(e);
|
||||
}
|
||||
run = null;
|
||||
};
|
||||
for (let i = 0; i < ps.length; i++) {
|
||||
const ref = ps[(start + i) % ps.length];
|
||||
const pc = arr.pieces[ref.piece];
|
||||
const poly = ref.reversed ? pc.poly.slice().reverse() : pc.poly;
|
||||
if (run && (run as { prim: number }).prim === pc.prim && kind(pc.prim) !== "LINE") {
|
||||
(run as { pts: Vec2[] }).pts.push(...poly.slice(1));
|
||||
(run as { pieces: number[] }).pieces.push(ref.piece);
|
||||
} else {
|
||||
flush();
|
||||
run = { prim: pc.prim, pts: poly.slice(), pieces: [ref.piece] };
|
||||
}
|
||||
}
|
||||
flush();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// Curves of a sketch that follow a body's edge have moved (the body changed):
|
||||
// what is dimensioned to them is carried along before the sketch is solved
|
||||
// again. A distance says how far, not which side: a pin 8 mm from a wall that
|
||||
// moved 40 mm was left on the wall's other side, 8 mm from it there.
|
||||
import type { SketchConstraint, SketchEntity, Vec2 } from "../doc/types";
|
||||
import { refsOf } from "./constraints";
|
||||
import { transformEntity } from "./edit";
|
||||
|
||||
/** Where a curve is, as one point (a line's middle, a circle's centre, the mean of a curve's points). */
|
||||
function middle(e: SketchEntity): Vec2 {
|
||||
switch (e.kind) {
|
||||
case "line":
|
||||
return [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2];
|
||||
case "arc":
|
||||
return [(e.a[0] + e.m[0] + e.b[0]) / 3, (e.a[1] + e.m[1] + e.b[1]) / 3];
|
||||
case "spline":
|
||||
case "polyline": {
|
||||
const n = Math.max(1, e.points.length);
|
||||
return [e.points.reduce((s, p) => s + p[0], 0) / n, e.points.reduce((s, p) => s + p[1], 0) / n];
|
||||
}
|
||||
default:
|
||||
return e.center;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `now` (the sketch with its edge-following curves where the edges are now)
|
||||
* with the other curves moved along: each group of curves tied together by
|
||||
* constraints is shifted by what the followed curves it is tied to moved.
|
||||
* A line that moved along itself (the edge got longer) shifts nothing.
|
||||
*/
|
||||
export function carried(old: SketchEntity[], now: SketchEntity[], constraints: SketchConstraint[], held: Set<string>): SketchEntity[] {
|
||||
const was = new Map(old.map((e) => [e.id, e]));
|
||||
// What each followed curve asks of what is tied to it: a shift along a direction (a line: square to it), or a shift outright.
|
||||
const asks = new Map<string, { n?: Vec2; v: Vec2 }>();
|
||||
for (const e of now) {
|
||||
const o = was.get(e.id);
|
||||
if (!held.has(e.id) || !o || o === e) continue;
|
||||
const [m0, m1] = [middle(o), middle(e)];
|
||||
if (o.kind === "line" && e.kind === "line") {
|
||||
const L = Math.hypot(o.b[0] - o.a[0], o.b[1] - o.a[1]) || 1;
|
||||
const n: Vec2 = [-(o.b[1] - o.a[1]) / L, (o.b[0] - o.a[0]) / L];
|
||||
const d = n[0] * (m1[0] - o.a[0]) + n[1] * (m1[1] - o.a[1]);
|
||||
asks.set(e.id, { n, v: [n[0] * d, n[1] * d] });
|
||||
} else asks.set(e.id, { v: [m1[0] - m0[0], m1[1] - m0[1]] });
|
||||
}
|
||||
if (!asks.size) return now;
|
||||
// Groups of free curves tied to each other.
|
||||
const parent = new Map<string, string>();
|
||||
const find = (a: string): string => {
|
||||
let r = a;
|
||||
while (parent.has(r) && parent.get(r) !== r) r = parent.get(r)!;
|
||||
parent.set(a, r);
|
||||
return r;
|
||||
};
|
||||
const ids = new Set(now.map((e) => e.id));
|
||||
for (const c of constraints) {
|
||||
const free = refsOf(c).filter((id) => ids.has(id) && !held.has(id));
|
||||
for (const id of free) find(id);
|
||||
for (let i = 1; i < free.length; i++) parent.set(find(free[0]), find(free[i]));
|
||||
}
|
||||
// The shift that best gives each group what its followed curves ask (least squares, the smallest such shift).
|
||||
const sums = new Map<string, { a: number; b: number; c: number; x: number; y: number; seen: Set<string> }>();
|
||||
for (const c of constraints) {
|
||||
const refs = refsOf(c);
|
||||
const free = refs.find((id) => ids.has(id) && !held.has(id));
|
||||
if (!free) continue;
|
||||
const root = find(free);
|
||||
let s = sums.get(root);
|
||||
if (!s) sums.set(root, (s = { a: 0, b: 0, c: 0, x: 0, y: 0, seen: new Set() }));
|
||||
for (const id of refs) {
|
||||
const ask = asks.get(id);
|
||||
if (!ask || s.seen.has(id)) continue;
|
||||
s.seen.add(id);
|
||||
// (n n^T) t = n d for a line; t = v otherwise.
|
||||
const [nx, ny] = ask.n ?? [1, 0];
|
||||
if (ask.n) {
|
||||
s.a += nx * nx;
|
||||
s.b += nx * ny;
|
||||
s.c += ny * ny;
|
||||
} else {
|
||||
s.a += 1;
|
||||
s.c += 1;
|
||||
}
|
||||
s.x += ask.v[0];
|
||||
s.y += ask.v[1];
|
||||
}
|
||||
}
|
||||
const shift = new Map<string, Vec2>();
|
||||
for (const [root, s] of sums) {
|
||||
if (!s.seen.size) continue;
|
||||
const k = 1e-9;
|
||||
const [a, b, c] = [s.a + k, s.b, s.c + k];
|
||||
const det = a * c - b * b;
|
||||
const t: Vec2 = [(c * s.x - b * s.y) / det, (a * s.y - b * s.x) / det];
|
||||
if (Math.hypot(t[0], t[1]) > 1e-9) shift.set(root, t);
|
||||
}
|
||||
if (!shift.size) return now;
|
||||
return now.map((e) => {
|
||||
const t = !held.has(e.id) && parent.has(e.id) ? shift.get(find(e.id)) : undefined;
|
||||
return t ? transformEntity(e, (p) => [p[0] + t[0], p[1] + t[1]]) : e;
|
||||
});
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -148,7 +148,15 @@ function compute(entities: SketchEntity[]): Arrangement {
|
||||
for (let j = i + 1; j < segs.length && segs[j].x0 <= A.x1; j++) {
|
||||
const B = segs[j];
|
||||
if (B.y0 > A.y1 || B.y1 < A.y0) continue;
|
||||
if (A.p === B.p) continue; // self-intersections are ignored
|
||||
if (A.p === B.p) {
|
||||
// A spline crossing itself (a loop drawn by hand that runs past its
|
||||
// start, a figure 8) is split there like two curves crossing: it had
|
||||
// no region at all. Neighbouring pieces of it always touch, so skip those.
|
||||
if (prims[A.p].t !== "spline") continue;
|
||||
const n = samples[A.p].pts.length - 1;
|
||||
const gap = Math.abs(A.i - B.i);
|
||||
if (gap <= 1 || (isClosedPrim(prims[A.p]) && gap >= n - 1)) continue;
|
||||
}
|
||||
// Lines lying on each other (e.g. drawn over a face's edge): each is split
|
||||
// where the other one ends, and the doubled pieces merge below.
|
||||
const lap = overlap(A.a, A.b, B.a, B.b, eps);
|
||||
@@ -169,10 +177,23 @@ function compute(entities: SketchEntity[]): Arrangement {
|
||||
|
||||
// ---- pieces
|
||||
const nodes: Vec2[] = [];
|
||||
// (Looked up by the cell they're in, and the cells around it: a sketch of
|
||||
// hundreds of curves compared every end with every node.)
|
||||
const cells = new Map<string, number[]>();
|
||||
const nodeOf = (pt: Vec2): number => {
|
||||
const tol = eps * 50;
|
||||
for (let k = 0; k < nodes.length; k++) if (Math.abs(nodes[k][0] - pt[0]) < tol && Math.abs(nodes[k][1] - pt[1]) < tol) return k;
|
||||
const cx = Math.floor(pt[0] / tol);
|
||||
const cy = Math.floor(pt[1] / tol);
|
||||
let best = -1;
|
||||
for (let dx = -1; dx <= 1; dx++)
|
||||
for (let dy = -1; dy <= 1; dy++)
|
||||
for (const k of cells.get(`${cx + dx},${cy + dy}`) ?? []) if (Math.abs(nodes[k][0] - pt[0]) < tol && Math.abs(nodes[k][1] - pt[1]) < tol && (best < 0 || k < best)) best = k;
|
||||
if (best >= 0) return best;
|
||||
nodes.push(pt);
|
||||
const key = `${cx},${cy}`;
|
||||
const list = cells.get(key);
|
||||
if (list) list.push(nodes.length - 1);
|
||||
else cells.set(key, [nodes.length - 1]);
|
||||
return nodes.length - 1;
|
||||
};
|
||||
let pieces: Piece[] = [];
|
||||
@@ -206,13 +227,16 @@ function compute(entities: SketchEntity[]): Arrangement {
|
||||
|
||||
// ---- the same stretch drawn twice counts once
|
||||
{
|
||||
const seen = new Map<string, Vec2>();
|
||||
// (Kept by their two ends: only pieces between the same two nodes are compared.)
|
||||
const seen = new Map<string, Vec2[]>();
|
||||
pieces = pieces.filter((pc) => {
|
||||
const key = pc.n0 < pc.n1 ? `${pc.n0}:${pc.n1}` : `${pc.n1}:${pc.n0}`;
|
||||
const mid = pc.poly[Math.floor(pc.poly.length / 2)];
|
||||
const m = pc.poly.length > 2 ? mid : [(pc.poly[0][0] + pc.poly[1][0]) / 2, (pc.poly[0][1] + pc.poly[1][1]) / 2] as Vec2;
|
||||
for (const [k, q] of seen) if (k.split("#")[0] === key && Math.hypot(q[0] - m[0], q[1] - m[1]) < eps * 1e3) return false;
|
||||
seen.set(`${key}#${seen.size}`, m);
|
||||
const had = seen.get(key);
|
||||
if (had?.some((q) => Math.hypot(q[0] - m[0], q[1] - m[1]) < eps * 1e3)) return false;
|
||||
if (had) had.push(m);
|
||||
else seen.set(key, [m]);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -282,15 +306,36 @@ function compute(entities: SketchEntity[]): Arrangement {
|
||||
const faces = cycles.filter((c) => c.area > minArea);
|
||||
const outers = cycles.filter((c) => c.area <= minArea);
|
||||
const holes = new Map<(typeof faces)[number], typeof outers>();
|
||||
// (Each face's box first: a plate with hundreds of holes tested every hole's
|
||||
// outline against every other hole's, point by point.)
|
||||
const boxes = faces.map((f) => {
|
||||
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
||||
for (const [x, y] of f.poly) {
|
||||
if (x < x0) x0 = x;
|
||||
if (x > x1) x1 = x;
|
||||
if (y < y0) y0 = y;
|
||||
if (y > y1) y1 = y;
|
||||
}
|
||||
return [x0, y0, x1, y1];
|
||||
});
|
||||
const compOf = faces.map(comp);
|
||||
for (const o of outers) {
|
||||
const p = o.poly[0];
|
||||
const co = comp(o);
|
||||
let best: (typeof faces)[number] | null = null;
|
||||
for (const f of faces) {
|
||||
if (comp(f) === comp(o)) continue;
|
||||
for (let k = 0; k < faces.length; k++) {
|
||||
const f = faces[k];
|
||||
const b = boxes[k];
|
||||
if (p[0] < b[0] || p[0] > b[2] || p[1] < b[1] || p[1] > b[3]) continue;
|
||||
if (best && f.area >= best.area) continue;
|
||||
if (compOf[k] === co) continue;
|
||||
if (!pointInPoly(p, f.poly)) continue;
|
||||
if (!best || f.area < best.area) best = f;
|
||||
best = f;
|
||||
}
|
||||
if (best) holes.set(best, [...(holes.get(best) ?? []), o]);
|
||||
if (!best) continue;
|
||||
const list = holes.get(best);
|
||||
if (list) list.push(o);
|
||||
else holes.set(best, [o]);
|
||||
}
|
||||
|
||||
const toLoop = (c: { hs: number[]; poly: Vec2[] }): Loop => ({
|
||||
|
||||
@@ -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";
|
||||
@@ -90,8 +90,11 @@ export interface DimWidgetOptions {
|
||||
/**
|
||||
* Keep the value box off the geometry: "side" puts it beside the middle of
|
||||
* the dimension, "beyond" past its end b (e.g. outside a fillet arc).
|
||||
* "clear": beside the middle where the line is long enough on screen for
|
||||
* the box to sit there, else back past its start a (a line just drawn:
|
||||
* the way it came from, not over its end, where the next point is tapped).
|
||||
*/
|
||||
boxAt?: "middle" | "side" | "beyond";
|
||||
boxAt?: "middle" | "side" | "beyond" | "clear";
|
||||
/** Extra screen distance past the end for "beyond" (e.g. to clear a drag arrow there). */
|
||||
boxGap?: number;
|
||||
/** Which way "beyond" goes when the dimension has no length yet (e.g. the arrow's direction). */
|
||||
@@ -100,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;
|
||||
@@ -115,9 +125,10 @@ export class DimWidget {
|
||||
private input = document.createElement("input");
|
||||
private mid = new Vector3();
|
||||
private ends: [Vector3, Vector3] = [new Vector3(), new Vector3()];
|
||||
private boxAt: "middle" | "side" | "beyond";
|
||||
private boxAt: "middle" | "side" | "beyond" | "clear";
|
||||
private boxGap: number;
|
||||
private dir?: Vec3;
|
||||
private facing?: Vec3;
|
||||
private hook = () => this.layout();
|
||||
|
||||
constructor(
|
||||
@@ -128,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");
|
||||
@@ -232,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");
|
||||
}
|
||||
|
||||
@@ -272,7 +284,12 @@ export class DimWidget {
|
||||
}
|
||||
const l = Math.hypot(dx, dy) || 1;
|
||||
const half = { w: this.box.offsetWidth / 2 + 10, h: this.box.offsetHeight / 2 + 10 };
|
||||
if (this.boxAt === "beyond") {
|
||||
// Too short for the box beside it (it would cover both ends): behind the start.
|
||||
const behind = this.boxAt === "clear" && l < 2 * Math.hypot(half.w, half.h) + 24;
|
||||
if (behind) {
|
||||
const k = Math.abs((dx / l) * half.w) + Math.abs((dy / l) * half.h) + 6;
|
||||
s = [sa[0] - (dx / l) * k, sa[1] - (dy / l) * k];
|
||||
} else if (this.boxAt === "beyond") {
|
||||
// Past the end, far enough that the box's own size clears it.
|
||||
const k = Math.abs((dx / l) * half.w) + Math.abs((dy / l) * half.h) + this.boxGap;
|
||||
s = [sb[0] + (dx / l) * k, sb[1] + (dy / l) * k];
|
||||
@@ -284,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])}`;
|
||||
@@ -312,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[] = [];
|
||||
@@ -323,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();
|
||||
@@ -344,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";
|
||||
@@ -18,7 +20,13 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
|
||||
constructor(app: AppContext, op: "subtract" | "intersect", target = "", tools: string[] = [], existing?: BooleanFeature) {
|
||||
super(app, { ...app.store.newIdentity("boolean", cap(op)), type: "boolean", op, target, tools: tools.filter((t) => t !== target) }, existing);
|
||||
const sub = this.feature.op === "subtract";
|
||||
const bodyOf = (hit: { kind: string; body?: string }) => (hit.kind === "body" || hit.kind === "face" || hit.kind === "edge" || hit.kind === "vertex" ? hit.body ?? null : null);
|
||||
// Not this subtract's own result: with "Keep modified body" on, its preview
|
||||
// shows beside the original, and a tap on it made it one of its own tools.
|
||||
const own = (b: string) => b === this.feature.id || b.startsWith(`${this.feature.id}:`);
|
||||
const bodyOf = (hit: { kind: string; body?: string }) => {
|
||||
const b = hit.kind === "body" || hit.kind === "face" || hit.kind === "edge" || hit.kind === "vertex" ? hit.body ?? null : null;
|
||||
return b && !own(b) ? b : null;
|
||||
};
|
||||
const targetSlot: Slot = {
|
||||
label: sub ? "Remove from" : "Body",
|
||||
describe: () => (this.feature.target ? this.nameOf(this.feature.target) : "Tap a body"),
|
||||
@@ -30,6 +38,8 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
|
||||
if (!b) return false;
|
||||
this.feature.target = b;
|
||||
this.feature.tools = this.feature.tools.filter((t) => t !== b);
|
||||
// (Worked out again for the bodies as now picked.)
|
||||
this.feature.whole = undefined;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
@@ -45,26 +55,65 @@ export class BooleanOp extends FeatureOp<BooleanFeature> {
|
||||
if (!b || b === this.feature.target) return false;
|
||||
const t = this.feature.tools;
|
||||
this.feature.tools = t.includes(b) ? t.filter((x) => x !== b) : [...t, b];
|
||||
this.feature.whole = undefined;
|
||||
return true;
|
||||
},
|
||||
};
|
||||
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 {
|
||||
return this.feature.op === "subtract"
|
||||
? "Select a body to remove from, then a body to subtract from it."
|
||||
: "Select a body, then the bodies to intersect it with (what they share is kept).";
|
||||
? "Tap the body to cut, then the bodies to cut away from it."
|
||||
: "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()) },
|
||||
];
|
||||
@@ -77,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);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
// Freeform Face: a flat face of a body made a smooth surface. A cage is laid
|
||||
// over the face - a grid whose border runs round the face's edge - and shaped
|
||||
// in the Freeform tool: tap its points, edges or faces and move them with the
|
||||
// gimbal (along the face, or out of it). The border stays put, so the face's
|
||||
// edges, and the rest of the body, don't move.
|
||||
|
||||
import type { FaceFreeformFeature, FaceRef, Vec3 } from "../doc/types";
|
||||
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). */
|
||||
function faceTriangles(app: AppContext, body: string, i: number): [Vec3, Vec3, Vec3][] {
|
||||
const b = app.view.body(body);
|
||||
const g = b?.faceGroups.find((x) => x.face === i);
|
||||
if (!b || !g) return [];
|
||||
const P = (k: number): Vec3 => [b.positions[3 * k], b.positions[3 * k + 1], b.positions[3 * k + 2]];
|
||||
const out: [Vec3, Vec3, Vec3][] = [];
|
||||
for (let t = g.start; t < g.start + g.count; t += 3) out.push([P(b.indices[t]), P(b.indices[t + 1]), P(b.indices[t + 2])]);
|
||||
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;
|
||||
let d = Infinity;
|
||||
faces.forEach((f, k) => {
|
||||
if (f.normal[0] * ref.normal[0] + f.normal[1] * ref.normal[1] + f.normal[2] * ref.normal[2] < 0.999) return;
|
||||
const e = Math.hypot(f.center[0] - ref.center[0], f.center[1] - ref.center[1], f.center[2] - ref.center[2]);
|
||||
if (e < d) ((d = e), (best = k));
|
||||
});
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Freeform tool on a face: `face`, a flat face to shape (a new step), or
|
||||
* `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" }> | Extract<Sel, { kind: "face" }>[] | null, existing?: FaceFreeformFeature, keep?: EditKeep): Tool | null {
|
||||
if (existing) {
|
||||
const faces = app.view.body(existing.face.body)?.faces ?? [];
|
||||
// (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 = 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, 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, keep } });
|
||||
}
|
||||
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 } });
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
import { getPath, setPath } from "../doc/params";
|
||||
import { BETA_TYPES } from "../doc/store";
|
||||
import type { ExtrudeSource, Feature, SketchFeature, Vec2 } from "../doc/types";
|
||||
import type { FieldKind, PanelItem, ToolItem } from "../ui/ui";
|
||||
import { isExpression } from "../ui/ui";
|
||||
import type { ToolPointer } from "../view/input";
|
||||
import type { PickHit, PickOptions } from "../view/viewport";
|
||||
import { hitToSel, sourcesOf, type AppContext, type Sel, type Tool } from "./tool";
|
||||
import { hitToSel, sourcesOf, viewMenu, type AppContext, type Sel, type Tool } from "./tool";
|
||||
import { DragTyping } from "./dragTyping";
|
||||
import { screenClass } from "../device";
|
||||
import { arrangement, materialRegions, pointInRegion, resolveRegion, type Region } from "../sketch/regions";
|
||||
@@ -82,12 +83,105 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
this.app.ui.setTools(screenClass() === "phone" ? [{ id: "cancel", label: "Cancel", icon: "close", shortcut: "Esc", run: () => this.cancel() }] : []);
|
||||
this.app.ui.setBottom([]);
|
||||
this.active = this.slots.findIndex((s) => !s.filled());
|
||||
// A step opened again with everything picked: taps add to (or take from) its
|
||||
// list of picks, as they did when it was made. (They did nothing: the four
|
||||
// bolts left out of a Subtract couldn't be added without tapping its slot first.)
|
||||
if (this.active < 0) this.active = this.slots.reduce((last, s, i) => (s.multi ? i : last), -1);
|
||||
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);
|
||||
@@ -142,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) {
|
||||
@@ -157,8 +261,12 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
return;
|
||||
}
|
||||
if (!slot) return;
|
||||
if (!slot.accept(hit)) {
|
||||
// Not this one - but another body's face in the same place is (the bolts
|
||||
// flush with the flange they're to cut: the flange came first every time).
|
||||
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;
|
||||
}
|
||||
@@ -168,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;
|
||||
|
||||
@@ -184,9 +310,15 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
this.done();
|
||||
}
|
||||
|
||||
/** Right-click: back out of the tool (like Esc). */
|
||||
context(): void {
|
||||
this.cancel();
|
||||
/**
|
||||
* Right-click: Done and Cancel (and the view's switches) by the pointer -
|
||||
* a stray right-click no longer throws the tool's work away.
|
||||
*/
|
||||
context(p: ToolPointer): void {
|
||||
viewMenu(this.app, p.x, p.y, [
|
||||
{ label: "Done", shortcut: "Enter", disabled: !this.ready() || !!this.error, run: () => this.done() },
|
||||
{ label: "Cancel", shortcut: "Esc", run: () => this.cancel() },
|
||||
]);
|
||||
}
|
||||
|
||||
key(e: KeyboardEvent): boolean {
|
||||
@@ -206,6 +338,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
]);
|
||||
this.app.ui.showPanel({
|
||||
title: this.feature.name,
|
||||
beta: BETA_TYPES.has(this.feature.type),
|
||||
items: [...slotItems, ...this.items()],
|
||||
actions: this.actions(),
|
||||
onDone: () => this.done(),
|
||||
@@ -225,25 +358,60 @@ 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);
|
||||
this.app.ui.setPanelWarning(this.error);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the last preview asked for was: a drag snaps its value to steps and
|
||||
* asks again on every pointer move - the same draft on the same project is
|
||||
* on screen already (or on its way), not rebuilt and shown again.
|
||||
*/
|
||||
private asked: { key: string; base: readonly Feature[]; pending: boolean; result: unknown } | null = null;
|
||||
|
||||
/** Re-run the preview with the current draft. */
|
||||
protected update(): void {
|
||||
this.onDraftChanged();
|
||||
if (!this.ready()) {
|
||||
this.app.preview([...this.app.store.features]);
|
||||
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.)
|
||||
const list = ready ? this.featuresWith() : null;
|
||||
const own = new Set(base);
|
||||
const key = list ? JSON.stringify(list.filter((f) => !own.has(f))) : "";
|
||||
const was = this.asked;
|
||||
if (was && was.key === key && was.base === base && (was.pending || was.result === this.app.result)) return;
|
||||
const mine = { key, base, pending: true, result: null as unknown };
|
||||
this.asked = mine;
|
||||
const shown = (r: unknown) => {
|
||||
mine.pending = false;
|
||||
mine.result = r;
|
||||
// Overtaken by something else's rebuild: asked again next time.
|
||||
if (!r && this.asked === mine) this.asked = null;
|
||||
};
|
||||
if (!ready) {
|
||||
void this.app.preview([...base]).then(shown);
|
||||
return;
|
||||
}
|
||||
this.app.preview(this.featuresWith()).then((r) => {
|
||||
this.app.preview(list!).then((r) => {
|
||||
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 {}
|
||||
|
||||
@@ -261,12 +429,7 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
min: opts.min,
|
||||
expr: f.exprs?.[path],
|
||||
inBox: opts.inBox,
|
||||
onExpr: (expr) => {
|
||||
const exprs = { ...(f.exprs ?? {}) };
|
||||
if (expr) exprs[path] = expr;
|
||||
else delete exprs[path];
|
||||
f.exprs = Object.keys(exprs).length ? exprs : undefined;
|
||||
},
|
||||
onExpr: (expr) => this.setExpr(path, expr),
|
||||
onInput: (v) => {
|
||||
setPath(f, path, v);
|
||||
if (opts.onInput) opts.onInput(v);
|
||||
@@ -279,6 +442,15 @@ export abstract class FeatureOp<F extends Feature> implements Tool {
|
||||
* Text typed into a value box at the model: a formula with variables keeps
|
||||
* the value linked to them (as the panel's field does); a plain number unlinks it.
|
||||
*/
|
||||
/** The value at `path` follows this formula (null: just a number). */
|
||||
protected setExpr(path: string, expr: string | null): void {
|
||||
const f = this.feature as Feature;
|
||||
const exprs = { ...(f.exprs ?? {}) };
|
||||
if (expr) exprs[path] = expr;
|
||||
else delete exprs[path];
|
||||
f.exprs = Object.keys(exprs).length ? exprs : undefined;
|
||||
}
|
||||
|
||||
protected typedInto(path: string, text: string, wrap: (t: string) => string = (t) => t): void {
|
||||
const f = this.feature as Feature;
|
||||
const exprs = { ...(f.exprs ?? {}) };
|
||||
@@ -335,9 +507,31 @@ function allRegionsUsed(app: AppContext, sketch: string, features: Feature[]): b
|
||||
if (r) used.push(r);
|
||||
}
|
||||
};
|
||||
// A full turn's axis in the sketch: what's drawn across it (a whole circle
|
||||
// for a ball, its lower half never picked) is in the solid too.
|
||||
const mirrors: ((q: Vec2) => Vec2)[] = [];
|
||||
const pl = app.sketchPlane(sketch);
|
||||
for (const g of features) {
|
||||
if (g.type === "extrude" || g.type === "revolve" || g.type === "sweep") add(g.source);
|
||||
else if (g.type === "loft") g.sections.forEach(add);
|
||||
if (g.type === "revolve" && pl && Math.abs(g.angle) >= 360 - 1e-9 && g.source.kind === "profile" && g.source.sketch === sketch) {
|
||||
const n = pl.normal;
|
||||
const y: [number, number, number] = [n[1] * pl.xDir[2] - n[2] * pl.xDir[1], n[2] * pl.xDir[0] - n[0] * pl.xDir[2], n[0] * pl.xDir[1] - n[1] * pl.xDir[0]];
|
||||
const d3 = g.axis.dir;
|
||||
const dl = Math.hypot(d3[0], d3[1], d3[2]) || 1;
|
||||
const off = (d3[0] * n[0] + d3[1] * n[1] + d3[2] * n[2]) / dl;
|
||||
const rel = [g.axis.origin[0] - pl.origin[0], g.axis.origin[1] - pl.origin[1], g.axis.origin[2] - pl.origin[2]];
|
||||
if (Math.abs(off) > 1e-9 || Math.abs(rel[0] * n[0] + rel[1] * n[1] + rel[2] * n[2]) > 1e-6) continue;
|
||||
const dot2 = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
const o: Vec2 = [dot2(rel, pl.xDir), dot2(rel, y)];
|
||||
const du = dot2(d3, pl.xDir) / dl;
|
||||
const dv = dot2(d3, y) / dl;
|
||||
mirrors.push((q) => {
|
||||
const t = (q[0] - o[0]) * du + (q[1] - o[1]) * dv;
|
||||
const f: Vec2 = [o[0] + t * du, o[1] + t * dv];
|
||||
return [2 * f[0] - q[0], 2 * f[1] - q[1]];
|
||||
});
|
||||
}
|
||||
}
|
||||
// Every shape drawn has been made into something. (Matched shape by shape,
|
||||
// not piece by piece: where the drawing meets an edge in its plane - the
|
||||
@@ -346,14 +540,16 @@ function allRegionsUsed(app: AppContext, sketch: string, features: Feature[]): b
|
||||
// use; the sketch stayed in view and its face-wide region took every later
|
||||
// tap on that face.)
|
||||
const inside = (m: Region, q: Vec2) => pointInPoly(q, m.outer.poly) && !m.holes.some((h) => pointInPoly(q, h.poly));
|
||||
return drawn.every((m) => used.some((r) => inside(m, pointInRegion(r))));
|
||||
const covered = (m: Region) => used.some((r) => inside(m, pointInRegion(r)));
|
||||
const turnedIn = (m: Region) => mirrors.some((mir) => used.some((r) => inside(r, mir(pointInRegion(m)))));
|
||||
return drawn.every((m) => covered(m) || turnedIn(m));
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/** The sketches an extrude / revolve / sweep / loft was made from. */
|
||||
function sketchesUsed(f: Feature): string[] {
|
||||
export function sketchesUsed(f: Feature): string[] {
|
||||
const of = (s: ExtrudeSource) => (s.kind === "profile" ? [s.sketch] : []);
|
||||
switch (f.type) {
|
||||
case "extrude":
|
||||
@@ -363,6 +559,8 @@ function sketchesUsed(f: Feature): string[] {
|
||||
return [...of(f.source), ...(f.path.kind === "sketch" ? [f.path.sketch] : [])];
|
||||
case "loft":
|
||||
return f.sections.flatMap(of);
|
||||
case "fill":
|
||||
return [...f.boundary, ...(f.guides ?? [])].flatMap((p) => (p.kind === "sketch" ? [p.sketch] : []));
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -71,7 +85,15 @@ export class Handle {
|
||||
return this.view.toScreen(this.tip());
|
||||
}
|
||||
|
||||
/** Shown or not (a hidden one can't be grabbed). */
|
||||
setVisible(on: boolean): void {
|
||||
if (this.group.visible === on) return;
|
||||
this.group.visible = on;
|
||||
this.view.requestRender();
|
||||
}
|
||||
|
||||
hit(p: ToolPointer): boolean {
|
||||
if (!this.group.visible) return false;
|
||||
const s = this.grabPoint();
|
||||
return !!s && Math.hypot(s[0] - p.x, s[1] - p.y) < Math.max(30, p.tol * 1.8);
|
||||
}
|
||||
@@ -82,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 {
|
||||
@@ -105,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);
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ export class MeasureTool implements Tool {
|
||||
this.app.ui.setTools([{ id: "exit", label: "Exit Measure", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) }]);
|
||||
// The view tools stay, this one lit and pulsing (tap it again to close it).
|
||||
this.app.ui.setBottom(this.app.bottomTools());
|
||||
this.app.ui.setHint("Select objects to see their measurements. Double-tap for a whole body.");
|
||||
this.app.ui.setHint("Tap faces, edges or points to see their sizes. Double-tap for a whole body.");
|
||||
this.card = el("div", "measure-card");
|
||||
document.body.append(this.card);
|
||||
this.render();
|
||||
@@ -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, edge to edge. Type the distance (below 0: the other side of the edge).";
|
||||
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 } };
|
||||
}
|
||||
@@ -141,7 +141,7 @@ export class ThreePointPlaneOp extends PlaneFromPicks {
|
||||
return { origin: a, normal: norm(n), xDir: norm(sub(b, a)) };
|
||||
}
|
||||
protected hint(): string {
|
||||
return this.pts.every(Boolean) && !this.make() ? "⚠ The three points are on one line - pick another" : "Tap three points (corners, edge points, sketch points): the plane goes through all of them.";
|
||||
return this.pts.every(Boolean) && !this.make() ? "⚠ The three points are on one line - pick another" : "Tap three points (corners, points on edges or in sketches): the plane goes through all three.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ export class CurvePointPlaneOp extends PlaneFromPicks {
|
||||
return this.c && { origin: this.c.at, normal: this.c.tangent, xDir: xDirFor(this.c.tangent) };
|
||||
}
|
||||
protected hint(): string {
|
||||
return this.edgesOnly ? "Tap an edge at the point where the plane should cross it (at right angles)." : "Tap a curve or edge where the plane should cross it: it stands across the curve there.";
|
||||
return this.edgesOnly ? "Tap an edge where the plane should cross it, square to it." : "Tap a line or edge where the plane should cross it, square to it.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -166,12 +166,17 @@ export class EdgeAnglePlaneOp extends PlaneFromPicks {
|
||||
private c: CurvePick | null = null;
|
||||
private ref: PlaneDef | null = null;
|
||||
private angle = 45;
|
||||
constructor(app: AppContext) {
|
||||
/** `edge`: the straight edge picked before (Plane – Through Edge on an edge). */
|
||||
constructor(app: AppContext, edge?: { body: string; edge: number; point: Vec3 }) {
|
||||
super(app, "Plane at Angle", "angle");
|
||||
this.slots = [
|
||||
curveSlot(app, "Edge (the plane turns about it)", () => this.c, (c) => ((this.c = c), this.sync()), true),
|
||||
planeSlot(app, "From face or plane (0°)", () => this.ref, (p) => ((this.ref = p), this.sync())),
|
||||
];
|
||||
if (edge) {
|
||||
const c = curvePick(app, { kind: "edge", ...edge });
|
||||
if (c?.line) (this.c = c), this.sync();
|
||||
}
|
||||
}
|
||||
protected make(): PlaneDef | null {
|
||||
if (!this.c?.line) return null;
|
||||
@@ -191,7 +196,7 @@ export class EdgeAnglePlaneOp extends PlaneFromPicks {
|
||||
return [{ type: "number", label: "Angle", value: this.angle, kind: "angle", onInput: (v) => ((this.angle = v), this.sync(), this.update()) }];
|
||||
}
|
||||
protected hint(): string {
|
||||
return "Tap a straight edge, then the face (or plane) the angle is measured from, and type the angle.";
|
||||
return "Tap a straight edge, then the face to measure the angle from, then type the angle.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,6 +213,6 @@ export class FacePointPlaneOp extends PlaneFromPicks {
|
||||
return this.ref && this.at ? { ...this.ref, origin: this.at } : null;
|
||||
}
|
||||
protected hint(): string {
|
||||
return "Tap a face or plane, then the point the new plane goes through.";
|
||||
return "Tap a face or plane to copy its direction, then the point the new plane goes through.";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -12,6 +12,10 @@ export interface SectionState {
|
||||
flipped: boolean;
|
||||
/** Cut from a face: how far inside it the cut starts (a hair, so the face shows the cut); a plane placed there goes on the face. */
|
||||
inset?: number;
|
||||
/** Only the cut faces shown, the rest of the model gone. */
|
||||
only?: boolean;
|
||||
/** 2D: seen straight on, flat like a drawing, the edges beyond the cut drawn. */
|
||||
flat?: boolean;
|
||||
}
|
||||
|
||||
export interface SectionHost extends AppContext {
|
||||
@@ -53,7 +57,7 @@ export class SectionTool implements Tool {
|
||||
private askForPlane(): void {
|
||||
this.app.view.setOriginPlanesVisible(true);
|
||||
this.app.ui.showPanel(null);
|
||||
this.app.ui.setHint("Select a plane or a flat face to cut the view with.");
|
||||
this.app.ui.setHint("Tap a plane or a flat face to cut the view there, so you can see inside.");
|
||||
}
|
||||
|
||||
hover(p: ToolPointer | null): void {
|
||||
@@ -86,19 +90,46 @@ export class SectionTool implements Tool {
|
||||
const s = this.app.section!;
|
||||
this.handle ??= new Handle(this.app.view, "arrow");
|
||||
this.placeHandle();
|
||||
this.app.ui.setHint("Drag the arrow to move the cut. Section View stays on until you delete it.");
|
||||
this.app.ui.setHint("Drag the arrow to move the cut. It stays until you delete it in History.");
|
||||
this.app.ui.showPanel({
|
||||
title: "Section View",
|
||||
items: [
|
||||
{ type: "number", label: "Offset", value: s.offset, kind: "length", onInput: (v) => this.setOffset(v) },
|
||||
{ type: "button", label: "Flip", icon: "flip", onClick: () => (this.app.setSection({ ...s, flipped: !this.app.section!.flipped }), this.showControls()) },
|
||||
{ type: "button", label: "Place Plane", icon: "plane", onClick: () => this.placePlane() },
|
||||
{ type: "toggle", label: "Section only", value: !!s.only, onChange: (v) => this.restyle({ only: v || undefined, flat: v ? undefined : s.flat }) },
|
||||
{
|
||||
type: "toggle",
|
||||
label: "2D section",
|
||||
value: !!s.flat,
|
||||
onChange: (v) => {
|
||||
this.restyle({ flat: v || undefined, only: v ? undefined : s.only });
|
||||
if (v) this.lookAtCut();
|
||||
},
|
||||
},
|
||||
{ type: "button", label: "Normal to Section", icon: "normal", onClick: () => this.lookAtCut() },
|
||||
{ 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),
|
||||
});
|
||||
}
|
||||
|
||||
private restyle(patch: Partial<SectionState>): void {
|
||||
const s = this.app.section;
|
||||
if (!s) return;
|
||||
this.app.setSection({ ...s, ...patch });
|
||||
this.showControls();
|
||||
}
|
||||
|
||||
/** Look straight at the cut, from the side that's cut away. */
|
||||
private lookAtCut(): void {
|
||||
const s = this.app.section;
|
||||
if (!s) return;
|
||||
const p = sectionPlane(s);
|
||||
this.app.view.cam.lookAlong(p.normal, p.xDir);
|
||||
this.app.view.fitAll();
|
||||
}
|
||||
|
||||
/** A construction plane where the cut is now (to sketch on, split with...). */
|
||||
private placePlane(): void {
|
||||
const s = this.app.section;
|
||||
|
||||
@@ -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);
|
||||
@@ -171,6 +188,8 @@ export class ConstraintGlyphs {
|
||||
// Several badges at one spot are fanned out (further out) so they stay readable.
|
||||
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" || 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;
|
||||
@@ -269,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) {
|
||||
|
||||
@@ -47,7 +47,7 @@ export class SketchMoveOp extends FeatureOp<SketchFeature> {
|
||||
}
|
||||
|
||||
protected hint(): string {
|
||||
return "Drag the blue arrow to a parallel plane (red / green slide it in its plane), or type the distance. Tap empty space when done.";
|
||||
return "Drag the blue arrow to move the sketch forward or back, or red and green to slide it. Tap empty space when done.";
|
||||
}
|
||||
|
||||
protected items(): PanelItem[] {
|
||||
|
||||
@@ -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);
|
||||
@@ -80,9 +96,18 @@ export function axisSlot(app: AppContext, label: string, get: () => AxisRef | nu
|
||||
};
|
||||
}
|
||||
|
||||
export function planeSlot(app: AppContext, label: string, get: () => PlaneDef | null, set: (p: PlaneDef, face?: FaceRef) => void): Slot {
|
||||
export function planeSlot(
|
||||
app: AppContext,
|
||||
label: string,
|
||||
get: () => PlaneDef | null,
|
||||
set: (p: PlaneDef, face?: FaceRef) => void,
|
||||
// `named`: what's in it already, by name (a plane being edited: "XZ plane",
|
||||
// not "Plane"). `skip`: construction planes it can't be (a plane can't be
|
||||
// made from itself, nor from one made after it).
|
||||
opts: { named?: string; skip?: (planeId: string) => boolean } = {},
|
||||
): Slot {
|
||||
let shown: Sel | null = null;
|
||||
let name = "";
|
||||
let name = opts.named ?? "";
|
||||
return {
|
||||
label,
|
||||
describe: () => (get() ? name || "Plane" : "Tap a plane, flat face or sketched shape"),
|
||||
@@ -95,15 +120,15 @@ export function planeSlot(app: AppContext, label: string, get: () => PlaneDef |
|
||||
// a thin sheet among the bodies, easy to miss with a finger).
|
||||
presets: [
|
||||
...["XY", "XZ", "YZ"].map((id) => ({ label: id, apply: () => ((name = `${id} plane`), (shown = null), set(app.view.planeOf(id)!)) })),
|
||||
...app.view.construction.planes.map((c) => ({ label: c.name, apply: () => ((name = c.name), (shown = null), set(c.plane)) })),
|
||||
...app.view.construction.planes.filter((c) => !opts.skip?.(c.id)).map((c) => ({ label: c.name, apply: () => ((name = c.name), (shown = null), set(c.plane)) })),
|
||||
],
|
||||
shows: () => (shown ? [shown] : []),
|
||||
accept(hit) {
|
||||
if (hit.kind === "plane") {
|
||||
const p = app.view.planeOf(hit.id);
|
||||
if (!p) return false;
|
||||
if (!p || opts.skip?.(hit.id)) return false;
|
||||
set(p);
|
||||
name = ["XY", "XZ", "YZ"].includes(hit.id) ? `${hit.id} plane` : "Plane";
|
||||
name = ["XY", "XZ", "YZ"].includes(hit.id) ? `${hit.id} plane` : (app.view.construction.planes.find((c) => c.id === hit.id)?.name ?? "Plane");
|
||||
shown = { kind: "plane", id: hit.id };
|
||||
return true;
|
||||
}
|
||||
@@ -111,7 +136,7 @@ export function planeSlot(app: AppContext, label: string, get: () => PlaneDef |
|
||||
const info = app.view.body(hit.body)?.faces[hit.face];
|
||||
if (!info?.plane) return false;
|
||||
set(info.plane, faceRefOf(app, hit) ?? undefined);
|
||||
name = "Face";
|
||||
name = faceOfName(app, hit.body);
|
||||
shown = { kind: "face", body: hit.body, face: hit.face };
|
||||
return true;
|
||||
}
|
||||
@@ -130,6 +155,12 @@ export function planeSlot(app: AppContext, label: string, get: () => PlaneDef |
|
||||
};
|
||||
}
|
||||
|
||||
/** "Face of Body 3": which body a face is on, by the name it has in Items. */
|
||||
export function faceOfName(app: AppContext, body: string): string {
|
||||
const n = app.store.doc.names?.[body] ?? app.result?.bodies.find((b) => b.id === body)?.name;
|
||||
return n ? `Face of ${n}` : "Face";
|
||||
}
|
||||
|
||||
/** A direction: an edge, an axis, a face normal, or X/Y/Z. */
|
||||
export function directionSlot(app: AppContext, label: string, get: () => Vec3 | null, set: (d: Vec3) => void): Slot {
|
||||
let shown: Sel | null = null;
|
||||
@@ -213,6 +244,50 @@ export function pathSlot(app: AppContext, get: () => PathRef | null, set: (p: Pa
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Curves from any sketches and edges of any bodies, as a list of paths (one
|
||||
* per sketch, one for the edges): Fill's boundary and guides. Tapping one
|
||||
* again leaves it out.
|
||||
*/
|
||||
export function curvesSlot(app: AppContext, label: string, get: () => PathRef[], set: (p: PathRef[]) => void, optional = false): Slot {
|
||||
const count = () => get().reduce((n, p) => n + (p.kind === "sketch" ? p.entities.length : p.edges.length), 0);
|
||||
return {
|
||||
label,
|
||||
multi: true,
|
||||
describe: () => (count() ? `${count()} curve${count() > 1 ? "s" : ""}` : optional ? "None" : "Tap curves or edges"),
|
||||
filled: () => optional || count() > 0,
|
||||
pick: { profiles: false, curves: true, planes: false, axes: false },
|
||||
shows: () => get().flatMap((p) => (p.kind === "sketch" ? p.entities.map((entity) => ({ kind: "curve", sketch: p.sketch, entity }) as Sel) : [])),
|
||||
get presets() {
|
||||
return count() ? [{ label: "Clear", apply: () => set([]) }] : [];
|
||||
},
|
||||
accept(hit) {
|
||||
const paths = get();
|
||||
if (hit.kind === "curve") {
|
||||
const i = paths.findIndex((p) => p.kind === "sketch" && p.sketch === hit.sketch);
|
||||
if (i < 0) return set([...paths, { kind: "sketch", sketch: hit.sketch, entities: [hit.entity] }]), true;
|
||||
const p = paths[i] as Extract<PathRef, { kind: "sketch" }>;
|
||||
const entities = p.entities.includes(hit.entity) ? p.entities.filter((e) => e !== hit.entity) : [...p.entities, hit.entity];
|
||||
set(entities.length ? paths.map((x, k) => (k === i ? { ...p, entities } : x)) : paths.filter((_, k) => k !== i));
|
||||
return true;
|
||||
}
|
||||
if (hit.kind === "edge") {
|
||||
const ref = edgeRefOf(app, hit);
|
||||
if (!ref) return false;
|
||||
// One path per body (its face is found from its own body).
|
||||
const i = paths.findIndex((p) => p.kind === "edges" && p.edges[0]?.body === ref.body);
|
||||
if (i < 0) return set([...paths, { kind: "edges", edges: [ref] }]), true;
|
||||
const p = paths[i] as Extract<PathRef, { kind: "edges" }>;
|
||||
const same = (e: EdgeRef) => JSON.stringify(e) === JSON.stringify(ref);
|
||||
const edges = p.edges.some(same) ? p.edges.filter((e) => !same(e)) : [...p.edges, ref];
|
||||
set(edges.length ? paths.map((x, k) => (k === i ? { ...p, edges } : x)) : paths.filter((_, k) => k !== i));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Faces of one body (e.g. faces to open in Shell). */
|
||||
export function facesSlot(app: AppContext, label: string, get: () => FaceRef[], set: (f: FaceRef[]) => void, optional = false): Slot {
|
||||
const picked: Sel[] = [];
|
||||
|
||||