supergeometry.app

A free, open-source CAD modeler that runs in the browser on any device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
superGeometry
2026-11-05 01:58:43 +02:00
commit fd5ca47813
81 changed files with 23039 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
{
"version": "0.0.1",
"configurations": [
{
"name": "supergeometry-dev",
"runtimeExecutable": "C:\\Program Files\\nodejs\\npm.cmd",
"runtimeArgs": ["run", "dev", "--", "--port", "5173", "--strictPort"],
"port": 5173
},
{
"name": "supergeometry-preview",
"runtimeExecutable": "C:\\Program Files\\nodejs\\npm.cmd",
"runtimeArgs": ["run", "preview", "--", "--port", "4173", "--strictPort"],
"port": 4173
}
]
}
+4
View File
@@ -0,0 +1,4 @@
node_modules/
dist/
*.log
.wrangler/
+18
View File
@@ -0,0 +1,18 @@
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
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
SPDX-License-Identifier: AGPL-3.0-or-later
(Full license text: https://www.gnu.org/licenses/agpl-3.0.txt)
+56
View File
@@ -0,0 +1,56 @@
# supergeometry.app
A free 3D solid modeler that runs in the browser on any device: desktop, iPad (with
Apple Pencil), Android tablets and phones. No account, no server, no subscription.
The workflow is inspired by tablet-first CAD apps: you select something and the
tools for it appear; you drag a handle or type a number; every step lands in an
editable history. Geometry is computed by [OpenCascade](https://dev.opencascade.org/)
(via [replicad](https://replicad.xyz)) compiled to WebAssembly, running in a Web Worker.
## Run it
```bash
npm install
npm run dev
```
Open the printed URL. `--host` is on, so a tablet on the same Wi-Fi can open the
"Network" URL too.
## Build & publish
```bash
npm run build
```
`dist/` is a static site. Upload it anywhere: GitHub Pages, Cloudflare Pages,
Netlify, any web server. No backend needed.
## Using it
| | Mouse / keyboard | Touch / pen |
|---|---|---|
| Orbit | left-drag empty space | one-finger drag |
| Pan | right/middle-drag, shift+drag | two-finger drag |
| Zoom | wheel | pinch |
| Select | click (adds to selection) | tap (pen or finger) |
| Select body | double-click | double-tap |
| Clear selection | Esc / click empty | tap empty |
While the pen touches the screen, fingers are ignored (palm rejection).
Shortcuts: `S` sketch · in sketch `L` line, `R` rectangle, `C` circle, `G` polygon,
`V` select · `E` extrude · `F` fillet · `C` chamfer · `Del` delete · `Enter` done ·
`Esc` cancel/exit · `Ctrl Z / Ctrl Y` undo/redo · `Ctrl S` save.
## Docs
- [docs/FEATURES.md](docs/FEATURES.md): what exists and what's planned
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md): how it's built and why
## License
AGPL-3.0-or-later: anyone can use, study, change and host it, but modified
versions that are offered to the public must stay open source.
OpenCascade (via `replicad-opencascadejs`) is LGPL-2.1; replicad and three.js are MIT.
+104
View File
@@ -0,0 +1,104 @@
# Architecture
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.
```
┌──────────────── main thread ────────────────┐ ┌──────── Web Worker ────────┐
│ UI (toolbar, history, hints) │ │ Kernel adapter │
│ Tools (sketch, extrude, fillet, …) │ doc │ replicad + OpenCascade │
│ Document store ── features[] (JSON) ──────┼───────▶│ (WebAssembly) │
│ undo/redo, autosave │ │ Regenerate features[] │
│ Viewport (three.js) ◀── meshes + topology ─┼────────┤ → bodies → meshes │
│ Input (pointer events: pen/touch/mouse) │ │ feature cache │
└─────────────────────────────────────────────┘ └────────────────────────────┘
```
## Key decisions
1. **The document is a list of features, not geometry.** `src/doc/types.ts`.
A project file is small JSON (`{ features: [...] }`). Geometry is always
*regenerated* from features, which is what makes history editable. Undo/redo
is just snapshots of that JSON.
2. **The kernel runs in a Web Worker behind an interface.** `src/kernel/`.
The main thread never blocks on geometry. Only `worker.ts` knows about
replicad/OpenCascade; everything else talks to it through `protocol.ts`.
Swapping the kernel later means rewriting one file.
3. **References to faces/edges are geometric, not index-based.**
The "topological naming problem": after you edit an early feature, face #7
may not be face #7 anymore. Features therefore store a *signature* of the
face/edge they act on (center, normal, area / midpoint, direction, length),
and the kernel resolves it to the best-matching face/edge in the rebuilt
body (`resolveFace` / `resolveEdge` in `worker.ts`). This is simple and
survives most edits; it can be upgraded to a smarter naming scheme later
without changing the file format (the signature is just data).
4. **Incremental regeneration.** The worker caches the bodies produced after
each feature, keyed by a hash of all features up to that point. Editing
feature *k* rebuilds only from *k* onwards. Live previews (dragging an
extrude arrow) only rebuild the last feature.
5. **One input model for every device.** `src/view/input.ts`
- Pen or mouse-left: tool actions (tap = place/select, drag = handle).
- Touch: tap = place/select; one-finger drag on empty space = orbit;
two fingers = pan + pinch zoom. While a pen is touching the screen,
touches are ignored (palm rejection).
- Mouse: left-drag on empty = orbit, right/middle-drag = pan, wheel = zoom
to cursor.
6. **Z-up, millimetres.** World units are mm, Z is up, sketches live on planes
`{ origin, xDir, normal }`.
## Folder layout
```
src/
main.ts, app.ts bootstrap; app state (selection, tools, section, pins), menus
settings.ts per-device preferences (snapping, grid, display, camera)
units.ts units + expression evaluation (variables, unit suffixes)
doc/
types.ts feature & document types (the file format)
store.ts undo/redo, IndexedDB autosave, file migration
sketch/ pure 2D code, shared by UI and kernel
curves.ts entities → primitives (line/arc/ellipse/spline), evaluation
regions.ts planar arrangement → regions with holes (+ stable refs)
edit.ts trim, extend, offset, fillet, transforms, edge projection
text.ts text → outline curves (opentype.js + Roboto)
kernel/
protocol.ts messages between main thread and worker
engine.ts feature replay on OpenCascade/replicad (testable in Node)
sketchGeom.ts regions → exact OpenCascade faces/wires
worker.ts Web Worker entry
client.ts promise-based client for the worker
view/
viewport.ts three.js scene, display modes, section, picking
camera.ts orbit camera, ortho/perspective, plane-aligned views
grid.ts adaptive grid shader
viewcube.ts CSS-3D view cube
input.ts pointer-event router (pen/touch/mouse)
tools/
tool.ts tool interface, selection → reference helpers
featureOp.ts base for operations: pick slots + values + preview
slots.ts axis / plane / direction / path / faces / profiles slots
ops.ts extrude, fillet, revolve, sweep, loft, shell, transforms, split, plane, axis
select.ts selection-driven menus + default handles
sketch.ts the sketch tool (all drawing & editing tools)
section.ts, measure.ts
io/insert.ts STEP/STL/OBJ/DXF/project import, images, variables
ui/ DOM chrome: tool column + flyouts, right column, panel, history
tests/ Node tests (npx tsx tests/<name>.test.ts)
```
## Roadmap (order matters)
1. ✅ Skeleton: viewport, input, kernel worker, document + history.
2. ✅ Sketch (line/rect/circle/polygon) → extrude → push/pull → fillet/chamfer → booleans.
3. Sketch constraints + driving dimensions with PlaneGCS (`@salusoft89/planegcs`).
4. Region detection (overlapping sketch shapes split into selectable regions).
5. Revolve, sweep, loft, shell, offset face.
6. Transform tools (gizmo), patterns, mirror.
7. Construction planes/axes, variables.
8. Import (STEP/STL/images), measure, section view.
9. Service worker (offline), file handling, iPad polish (Apple Pencil hover).
+78
View File
@@ -0,0 +1,78 @@
# Feature catalog
Functionality list. Implemented from scratch on OpenCascade.
Visualization, cloud sync, XR, sharing and accounts are out of scope.
Legend: ✅ done · 🚧 partial · ⬜ planned
## Sketch
| Feature | Status |
|---|---|
| Sketch → origin planes (XY/XZ/YZ), flat faces, construction planes, existing sketches | ✅ |
| Camera turns normal to the plane, orthographic; Line armed | ✅ |
| Line (chains; tap first point to close) | ✅ |
| Arc (2 endpoints + bend point) | ✅ |
| Spline (fit points / control points, open or closed) | ✅ |
| Rectangle (diagonal / center / 3 points) | ✅ |
| Circle, Ellipse, Polygon (n sides) | ✅ |
| Text (outline font → regions) | ✅ |
| Project body edges onto the sketch | ✅ |
| Offset edge | ✅ |
| Sketch fillet (corner of two lines) | ✅ |
| Move/Rotate, Scale, Pattern linear/circular, Rotate around point, Mirror (with copy) | ✅ |
| Trim, Extend, Delete | ✅ |
| Construction geometry toggle | ✅ |
| Overlapping shapes split into selectable regions (with holes) | ✅ |
| Live dimensions + type exact values while drawing | ✅ |
| Edit size of a selected curve (length, W/H, radius, sides…) | ✅ |
| Snapping: grid, guide points (end/mid/center), guide lines (H/V alignment), 3D points, distant edges | ✅ |
| Constraints (parallel, tangent, coincident…) + driving dimensions | ⬜ next (PlaneGCS) |
## Selection-driven tools
| Selection | Tools | Status |
|---|---|---|
| Profile | Sketch, Move/Rotate, Scale Sketch, Patterns, **Extrude**, Axis ⊥, Plane offset, Text, Rotate, Mirror, Loft, Split, Revolve, Sweep, Offset Edge, Delete | ✅ |
| Profile | Fill, Project as Sketch/Edge, Wrap & Emboss | ⬜ |
| Face | Sketch, Move/Rotate, Scale, **Offset Face**, Fillet/Chamfer (face edges), Extrude, Shell, Axis ⊥, Plane offset, Patterns, Translate, Rotate, Mirror, Loft, Split, Revolve, Sweep, Project as Sketch, Offset Edge, Text, Delete | ✅ |
| Face | Align, Fill, Replace Face, Project as Edge | ⬜ |
| Edge | **Fillet**, Chamfer, Move/Rotate, Axis along edge, Plane ⊥ edge, Translate, Rotate | ✅ |
| Body | Move/Rotate, Scale, Translate, Patterns, Rotate, Mirror, Union/Subtract/Intersect, Split, Shell, Delete | ✅ |
| Plane / Axis | Sketch, Plane offset, Split, Delete | ✅ |
## Top-level menus
| Feature | Status |
|---|---|
| Insert → Variable (usable in every field: `width*2`, `1in + 3mm`) | ✅ |
| Insert → Image (reference on a plane) | ✅ |
| Insert → File: STEP/STP, STL, OBJ, DXF; DWG explains how to convert | ✅ |
| Insert → Project (append another .super history) | ✅ |
| Construct → Offset plane, Midplane, Axis | ✅ |
| Construct → Plane through 3 points / on curve | ⬜ |
| Transform → Move/Rotate, Scale, Translate, Pattern, Rotate Around Axis, Mirror | ✅ |
| Transform → Align | ⬜ |
| Tools → every solid tool (waits for the right selection) | ✅ |
| Section View: plane/face, drag, flip, caps, stays on | ✅ |
| Section View: 2D section, section only | ⬜ |
| Measure: area, length, radius, size, volume, distance, min distance, angle, XYZ deltas, pins | ✅ |
## Right column
| Feature | Status |
|---|---|
| Snapping toggles | ✅ |
| Units (mm/cm/m/in/ft), lock grid size, degree format | ✅ |
| Adaptive grid 0.001 mm … 1 000 000 mm, on the sketch plane while sketching | ✅ |
| Views: default, 6 presets, saved views; Appearance (animate, ortho, grid, axes, pins) | ✅ |
| Display modes: Shaded / X-Ray / Wireframe, edges, hidden edges | ✅ |
| Zebra / curvature analysis | ⬜ |
| Screenshot (PNG) | ✅ |
| View cube (click faces, drag to orbit, 90° roll) | ✅ |
| History (edit, suppress, delete any step) | ✅ |
## Document & platform
| Feature | Status |
|---|---|
| Editable history for every feature type | ✅ |
| Undo / redo, autosave (IndexedDB), open/save `.super`, export STL/STEP | ✅ |
| Migration of older project files | ✅ |
| Any browser; pen/finger/mouse; palm rejection; phone layout | ✅ |
| Offline service worker | ⬜ |
+93
View File
@@ -0,0 +1,93 @@
<!doctype html>
<html lang="en">
<head>
<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="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="description" content="supergeometry.app — a free 3D solid modeler that runs in your browser, on any device." />
<link rel="manifest" href="./manifest.webmanifest" />
<link rel="icon" href="./icon.svg" type="image/svg+xml" />
<link rel="apple-touch-icon" href="./icon.svg" />
<title>supergeometry.app</title>
</head>
<body>
<canvas id="view"></canvas>
<div id="pins"></div>
<header id="topbar">
<div class="brand">supergeometry<span class="brand-tld">.app</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="menu-wrap">
<button id="file-btn" class="text-btn">File</button>
<div id="file-menu" class="menu" hidden>
<button id="m-new">New project</button>
<button id="m-open">Open…</button>
<button id="m-save">Save project <kbd>Ctrl S</kbd></button>
<hr />
<button id="m-stl">Export STL</button>
<button id="m-step">Export STEP</button>
</div>
</div>
<button id="items-btn" class="text-btn" title="Items (bodies, sketches, planes)">Items</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-help">Help <span class="menu-soon">soon</span></button>
<button id="m-tutorial">Tutorial <span class="menu-soon">soon</span></button>
<button id="m-about">About supergeometry.app <span class="menu-soon">↗</span></button>
<button id="m-donate">Boost / Donate / Support <span class="menu-soon">↗</span></button>
<hr />
<div class="menu-note" id="m-version"></div>
</div>
</div>
</header>
<!-- Undo / redo: always at the bottom-left corner, in every mode. -->
<nav id="undo-dock" aria-label="Undo and redo">
<button id="undo-btn" class="dock-btn" title="Undo (Ctrl Z)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/></svg>
</button>
<button id="redo-btn" class="dock-btn" title="Redo (Ctrl Y)">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M15 14l5-5-5-5"/><path d="M20 9H10a6 6 0 0 0 0 12h3"/></svg>
</button>
</nav>
<div id="viewcube-host"></div>
<nav id="right-col" aria-label="View settings"></nav>
<div id="popover" hidden></div>
<nav id="toolbar" aria-label="Tools"></nav>
<nav id="bottom-left" aria-label="Section and measure"></nav>
<div id="flyout" hidden></div>
<div id="hint" hidden></div>
<div id="status" hidden></div>
<div id="panel" hidden></div>
<div id="label" hidden></div>
<div id="toast"></div>
<div id="warn" hidden></div>
<aside id="items">
<div class="history-head">
<span>Items</span>
<span class="items-head-btns">
<button id="items-pick" class="text-btn small" title="Tick items to put them in a folder (or Ctrl+click them)">Select</button>
<button id="items-close" class="icon-btn" title="Close"></button>
</span>
</div>
<ol id="items-list"></ol>
</aside>
<aside id="history">
<div class="history-head">
<span>History</span>
<button id="history-close" class="icon-btn" title="Close"></button>
</div>
<ol id="history-list"></ol>
</aside>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+1837
View File
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
{
"name": "supergeometry",
"private": true,
"version": "0.2.0",
"description": "Free, browser-based solid modeler for every device.",
"license": "AGPL-3.0-or-later",
"type": "module",
"scripts": {
"dev": "vite --host",
"build": "tsc --noEmit && vite build",
"preview": "vite preview --host",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@fontsource/roboto": "^5.3.0",
"opentype.js": "^2.0.0",
"replicad": "^1.2.0",
"replicad-opencascadejs": "^1.1.0",
"three": "^0.187.0"
},
"devDependencies": {
"@types/opentype.js": "^1.3.10",
"@types/three": "^0.187.0",
"tsx": "^4.23.15",
"typescript": "^7.0.2",
"vite": "^8.3.5"
}
}
+18
View File
@@ -0,0 +1,18 @@
# Cache rules for Cloudflare (copied into dist/ by the build).
#
# The page itself must always be fresh, so a push shows up right away.
# Everything in /assets/ has a content hash in its file name: a new build
# gets new names, so browsers may keep those files forever (fast repeat visits,
# and the 23 MB geometry engine is downloaded once).
/
Cache-Control: no-cache
/index.html
Cache-Control: no-cache
/manifest.webmanifest
Cache-Control: no-cache
/assets/*
Cache-Control: public, max-age=31536000, immutable
+6
View File
@@ -0,0 +1,6 @@
<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 10l19 11v22L32 54 13 43V21z" fill="#3d8bff"/>
<path d="M32 10l19 11-19 11-19-11z" fill="#8bb8ff"/>
<path d="M32 32v22L13 43V21z" fill="#2a63c4"/>
</svg>

After

Width:  |  Height:  |  Size: 289 B

+10
View File
@@ -0,0 +1,10 @@
{
"name": "supergeometry.app",
"short_name": "supergeometry",
"description": "Free 3D solid modeler for every device.",
"start_url": "./",
"display": "standalone",
"background_color": "#1f2125",
"theme_color": "#1f2125",
"icons": [{ "src": "icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" }]
}
+734
View File
@@ -0,0 +1,734 @@
import { DocStore, parseProject } from "./doc/store";
import type { EdgeFeature, ExtrudeFeature, ExtrudeSource, Feature, ImageFeature, LoftFeature, PinDef, PlaneDef, PlaneFeature, RevolveFeature, ShellFeature, SketchEntity, SketchFeature, SplitFeature, SweepFeature, TransformFeature, Units, Vec3 } from "./doc/types";
import { emptyDoc } from "./doc/types";
import { createVariable, editVariables, insertFile, insertImage } from "./io/insert";
import { KernelClient } from "./kernel/client";
import type { ExportFormat, RegenResult } from "./kernel/protocol";
import { settings } from "./settings";
import { PinLayer } from "./tools/annotate";
import { MeasureTool } from "./tools/measure";
import { ItemsPanel } from "./ui/items";
import { AxisOp, EdgeOp, ExtrudeOp, ImageOp, LoftOp, MidplaneOp, MoveFaceOp, PlaneOp, ReplaceFaceOp, ScaleFaceOp, ScaleOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./tools/ops";
import { toWorld, xDirFor } from "./geom";
import { entityPolylines } from "./sketch/curves";
import { FreeformTool } from "./tools/freeform";
import { sectionPlane, SectionTool, type SectionState } from "./tools/section";
import { SelectTool } from "./tools/select";
import { SketchTool } from "./tools/sketch";
import { bodiesOf, edgeRefOf, faceRefOf, sameSel, sourcesOf, type AppContext, type Sel, type Tool } from "./tools/tool";
import { setupRightColumn } from "./ui/panels";
import type { ToolItem } from "./ui/ui";
import { UI } from "./ui/ui";
import { setUnits, setVariables } from "./units";
import { InputRouter } from "./view/input";
import { ViewCube } from "./view/viewcube";
import { PivotButton } from "./ui/pivot";
import { Viewport } from "./view/viewport";
const SOON = "Coming soon";
export class App implements AppContext {
readonly store = new DocStore();
readonly kernel = new KernelClient();
readonly view: Viewport;
readonly ui = new UI();
private input: InputRouter;
result: RegenResult | null = null;
selection: Sel[] = [];
section: SectionState | null = null;
isolated: string[] | null = null;
private hover: Sel | null = null;
private selectTool: SelectTool;
private tool: Tool;
private shownErrors = "";
private pinLayer: PinLayer;
private items: ItemsPanel;
constructor(canvas: HTMLCanvasElement) {
this.view = new Viewport(canvas);
this.input = new InputRouter(this.view);
this.selectTool = new SelectTool(this);
this.tool = this.selectTool;
this.input.handler = this.tool;
// A spinner while the geometry engine works on something that takes a moment.
const busy = document.createElement("div");
busy.id = "busy";
busy.hidden = true;
busy.innerHTML = `<span class="spinner"></span><span>Working…</span>`;
document.body.append(busy);
let busyTimer = 0;
this.kernel.onBusy = (on) => {
clearTimeout(busyTimer);
// Only for waits you would notice (not every quick preview while dragging).
if (on) busyTimer = window.setTimeout(() => (busy.hidden = false), 300);
else busy.hidden = true;
};
document.getElementById("viewcube-host")!.append(new ViewCube(this.view).el, new PivotButton(this.view, (t) => this.ui.toast(t)).el);
setupRightColumn(this.ui, this.view, this.store, (u) => this.setUnits(u));
this.pinLayer = new PinLayer(this.view);
// ƒx buttons on number fields create named variables.
this.ui.variableFactory = (current) => createVariable(this, current);
settings.onChange(() => this.showPins());
this.items = new ItemsPanel(this.store, {
selectBody: (id) => (this.setTool(null), this.setSelection([{ kind: "body", body: id }])),
editSketch: (id) => this.setTool(new SketchTool(this, { sketchId: id })),
selectPlane: (id) => (this.setTool(null), this.setSelection([{ kind: "plane", id }])),
deleteBody: (id) => this.store.add({ ...this.store.newIdentity("delete"), type: "delete", bodies: [id] }),
deleteFeature: (id) => this.store.remove(id),
selectImage: (id) => (this.setTool(null), this.setSelection([{ kind: "image", id }])),
rename: async (id, current, isBody) => {
const v = await this.ui.dialog("Rename", [{ key: "name", label: "Name", value: current }]);
const name = v?.name.trim();
if (!name) return;
if (isBody) this.store.commit((d) => (d.names = { ...(d.names ?? {}), [id]: name }));
else this.store.update(id, { name });
},
askName: async (title, current) => (await this.ui.dialog(title, [{ key: "name", label: "Name", value: current }]))?.name.trim() || null,
isolated: () => this.isolated,
});
this.store.onChange(() => this.docChanged());
window.addEventListener("keydown", (e) => this.onKey(e));
this.wireTopbar();
this.tool.enter?.();
this.ui.setStatus("Loading geometry kernel…");
Promise.all([this.kernel.ready, this.store.load()])
.then(async () => {
this.ui.setStatus(null);
await this.regenerate();
this.view.cam.fit(this.view.bounds(), false);
})
.catch((err) => this.ui.setStatus(`Could not start the geometry kernel: ${err.message ?? err}`));
}
// ------------------------------------------------------------ state
setSelection(sel: Sel[]): void {
this.selection = sel;
this.refreshHighlights();
if (this.tool === this.selectTool) this.selectTool.refresh();
}
setHover(h: Sel | null): void {
if (h === this.hover || (h && this.hover && sameSel(h, this.hover))) return;
this.hover = h;
this.refreshHighlights();
}
setTool(tool: Tool | null): void {
const next = tool ?? this.selectTool;
const leavingOp = this.tool !== this.selectTool;
this.tool.exit?.();
this.tool = next;
this.input.handler = next;
this.hover = null;
this.ui.closeFlyout();
next.enter?.();
// Leaving an operation drops its preview.
if (leavingOp && next === this.selectTool) void this.regenerate();
else this.refreshSketches();
this.renderHistory();
}
/** The last section used: Section View off and on again brings it back. */
private lastSection: SectionState | null = null;
/**
* Section View button: on → off (remembered); off → the remembered section,
* or a new one — straight from a selected flat face if there is one.
*/
private toggleSection(): void {
if (this.section) {
const keep = this.section;
if (this.tool instanceof SectionTool) this.setTool(null);
this.setSection(null);
this.lastSection = keep;
this.refreshTools();
return;
}
const s = this.selection[0];
const face = s?.kind === "face" ? this.view.body(s.body)?.faces[s.face] : undefined;
if (face?.plane) {
// Cut a hair inside the face so the face itself shows the cut.
this.setSection({ plane: face.plane, offset: -this.view.cam.worldPerPixel(this.view.height), flipped: false });
} else if (this.lastSection) this.setSection(this.lastSection);
this.setTool(new SectionTool(this));
}
/** Re-draw the tool columns (e.g. after Section View changed). */
private refreshTools(): void {
if (this.tool === this.selectTool) this.selectTool.refresh();
else this.ui.setBottom(this.bottomTools());
}
setSection(s: SectionState | null): void {
this.section = s;
// A section on screen is the one to remember (a deleted one is forgotten).
if (s) this.lastSection = null;
this.view.setSection(s ? sectionPlane(s) : null);
}
get pins(): PinDef[] {
return this.store.doc.pins;
}
setPins(p: PinDef[]): void {
this.store.commit((d) => (d.pins = p));
}
addPin(pin: PinDef): void {
this.setPins([...this.pins, pin]);
this.ui.toast(`Pinned ${pin.text}`);
}
private showPins(): void {
this.pinLayer.set(this.pins, settings.value.showPinned);
}
isolate(bodies: string[] | null): void {
this.isolated = bodies?.length ? bodies : null;
this.applyVisibility();
// Isolated bodies are all there is: sketches, planes, axes and images step out too.
this.refreshConstruction();
this.refreshSketches();
if (this.tool === this.selectTool) this.selectTool.refresh();
this.items.render(this.result);
}
/** Hidden (Items) + not isolated → invisible and unpickable. */
private applyVisibility(): void {
const hidden = new Set(this.store.doc.hidden);
if (this.isolated) for (const b of this.result?.bodies ?? []) if (!this.isolated.includes(b.id)) hidden.add(b.id);
this.view.setHidden(hidden);
}
sketchPlane(id: string): PlaneDef | undefined {
return this.result?.sketchPlanes[id] ?? this.store.find<SketchFeature>(id)?.plane;
}
sketchCurves(id: string): SketchEntity[] {
return [...(this.store.find<SketchFeature>(id)?.entities ?? []), ...(this.result?.sketchBoundaries[id] ?? [])];
}
async preview(features: Feature[]): Promise<RegenResult | null> {
const r = await this.kernel.regenerate(features);
if (r) this.apply(r, features);
return r;
}
private docChanged(): void {
setUnits(this.store.doc.units);
setVariables(this.store.doc.variables);
this.ui.refreshRight();
this.showPins();
this.view.setBodyColors(this.store.doc.colors ?? {});
void this.regenerate();
}
private setUnits(u: Units): void {
this.store.commit((d) => (d.units = u));
}
private async regenerate(): Promise<void> {
const features = this.store.doc.features;
const r = await this.kernel.regenerate(features);
if (r) this.apply(r, features);
}
private apply(r: RegenResult, features: readonly Feature[]): void {
this.result = r;
if (this.isolated) this.isolated = this.isolated.filter((id) => r.bodies.some((b) => b.id === id));
if (!this.isolated?.length) this.isolated = null;
this.view.setBodies(r.bodies);
this.applyVisibility();
this.refreshConstruction(features);
this.refreshSketches(features);
// Drop selections that point at geometry that no longer exists.
this.selection = this.selection.filter((s) => {
if (s.kind === "profile" || s.kind === "curve" || s.kind === "point") return !!this.store.find(s.sketch) || features.some((f) => f.id === s.sketch);
if (s.kind === "plane" || s.kind === "axis") return !!this.view.planeOf(s.id) || !!this.view.axisOf(s.id);
if (s.kind === "image") return features.some((f) => f.id === s.id);
const b = this.view.body(s.body);
if (!b) return false;
if (s.kind === "face") return s.face < b.faces.length;
if (s.kind === "edge") return s.edge < b.edges.length;
if (s.kind === "vertex") return !!this.view.vertexOf(s.body, s.vertex);
return true;
});
this.refreshHighlights();
this.tool.refresh?.();
if (this.tool === this.selectTool) this.selectTool.refresh();
this.renderHistory();
this.items.render(r);
const open = this.openBodies(r);
this.ui.setWarning(
open.length
? `⚠ ${open.length === 1 ? (this.store.doc.names?.[open[0].id] ?? open[0].name) : `${open.length} bodies`} not closed — ${open.reduce((s, b) => s + b.openEdges.length, 0)} open edge(s) shown in orange`
: this.store.problems[0]
? `⚠ ${this.store.problems[0]}`
: null,
);
const errs = r.errors.map((e) => e.featureId + e.message).join();
if (errs && errs !== this.shownErrors && this.tool === this.selectTool) {
this.ui.toast(`${r.errors.length} step${r.errors.length > 1 ? "s" : ""} failed to rebuild — see History`, "error");
}
this.shownErrors = errs;
}
private refreshConstruction(features: readonly Feature[] = this.store.doc.features): void {
const r = this.result;
if (!r) return;
const hidden = new Set(this.store.doc.hidden);
const iso = !!this.isolated;
this.view.setConstruction(iso ? [] : r.planes.filter((p) => !hidden.has(p.id)), iso ? [] : r.axes.filter((a) => !hidden.has(a.id)));
this.view.setImages(iso ? [] : features.filter((f): f is ImageFeature => f.type === "image" && !f.suppressed && !hidden.has(f.id)));
}
private refreshSketches(features: readonly Feature[] = this.store.doc.features): void {
const hidden = new Set(this.store.doc.hidden);
const sketches = features
.filter((f): f is SketchFeature => f.type === "sketch" && !f.suppressed && ((!hidden.has(f.id) && !this.isolated) || f.id === this.tool.activeSketch))
.map((s) => ({ ...s, plane: this.result?.sketchPlanes[s.id] ?? s.plane, boundary: this.result?.sketchBoundaries[s.id] }));
this.view.setSketches(sketches, this.tool.activeSketch);
}
private refreshHighlights(): void {
this.view.setHighlights(this.selection, this.hover);
}
// ------------------------------------------------------------ history
/**
* Bodies with open edges — except freeform surfaces that are meant to be
* open sheets (not thickened): those aren't a problem.
*/
private openBodies(r: RegenResult | null) {
return (r?.bodies ?? []).filter((b) => {
if (!b.openEdges?.length) return false;
const f = this.store.find(b.id.split(":")[0]);
return !(f?.type === "freeform" && f.surface && !f.thickness);
});
}
private renderHistory(): void {
// The rows are rebuilt: a hover on an old row is over.
this.view.setStepHover(null);
const warnings = new Map<string, string>();
for (const b of this.openBodies(this.result)) warnings.set(b.id.split(":")[0], `${b.name}: not closed — ${b.openEdges.length} open edge(s)`);
this.ui.renderHistory(this.store.doc.features, this.result?.errors ?? [], this.tool.editingId ?? this.tool.activeSketch ?? null, {
edit: (id) => this.editFeature(id),
hover: (id) => this.view.setStepHover(id ? this.stepTargets(id) : null),
toggle: (id) => {
const f = this.store.find(id);
if (f) this.store.update(id, { suppressed: !f.suppressed });
},
remove: (id) => {
if (this.tool !== this.selectTool) this.setTool(null);
this.store.remove(id);
},
}, warnings);
}
/** What a History step works on: its bodies (made or changed), sketches, and the edges it names. */
private stepTargets(id: string): { bodies: string[]; lines: Vec3[][] } {
const f = this.store.find(id);
const bodies = new Set<string>();
const sketches = new Set<string>();
const edges: [Vec3, Vec3][] = [];
if (!f) return { bodies: [], lines: [] };
if (f.type === "sketch") sketches.add(f.id);
// Bodies this step made (its own id, or copies "id:…").
for (const b of this.result?.bodies ?? []) if (b.id === f.id || b.id.startsWith(`${f.id}:`)) bodies.add(b.id);
const walk = (v: unknown, key = ""): void => {
if (Array.isArray(v)) return v.forEach((x) => walk(x, key));
if (!v || typeof v !== "object") {
if (typeof v === "string" && (key === "body" || key === "bodies" || key === "target")) bodies.add(v);
if (typeof v === "string" && key === "sketch") sketches.add(v);
return;
}
const o = v as Record<string, unknown>;
// An edge reference: draw the edge itself.
if (Array.isArray(o.mid) && Array.isArray(o.dir) && typeof o.length === "number") {
const m = o.mid as Vec3;
const d = o.dir as Vec3;
const h = (o.length as number) / 2;
edges.push([[m[0] - d[0] * h, m[1] - d[1] * h, m[2] - d[2] * h], [m[0] + d[0] * h, m[1] + d[1] * h, m[2] + d[2] * h]]);
}
for (const [k, x] of Object.entries(o)) if (k !== "exprs") walk(x, k);
};
walk(f);
// Only what's still there.
const have = new Set((this.result?.bodies ?? []).map((b) => b.id));
// Sketch curves in 3D.
const lines: Vec3[][] = [...edges];
for (const sid of sketches) {
const plane = this.sketchPlane(sid);
const sk = this.store.find<SketchFeature>(sid);
if (!plane || !sk) continue;
for (const e of sk.entities) for (const pl of entityPolylines(e)) lines.push(pl.map((uv) => toWorld(plane, uv)));
}
return { bodies: [...bodies].filter((b) => have.has(b)), lines };
}
private editFeature(id: string): void {
const f = this.store.find(id);
if (!f) return;
this.setSelection([]);
switch (f.type) {
case "sketch":
return this.setTool(new SketchTool(this, { sketchId: f.id }));
case "extrude":
return this.setTool(new ExtrudeOp(this, f.source, f as ExtrudeFeature));
case "fillet":
case "chamfer":
return this.setTool(new EdgeOp(this, f.type, f.edges, f as EdgeFeature));
case "revolve":
return this.setTool(new RevolveOp(this, f.source, f as RevolveFeature));
case "sweep":
return this.setTool(new SweepOp(this, f.source, f as SweepFeature));
case "loft":
return this.setTool(new LoftOp(this, f.sections, [], f as LoftFeature));
case "shell":
return this.setTool(new ShellOp(this, f.body, f.faces, f as ShellFeature));
case "split":
return this.setTool(new SplitOp(this, f.body, f as SplitFeature));
case "plane":
return this.setTool(new PlaneOp(this, f.plane, f.face, f as PlaneFeature));
case "transform": {
if (f.op.kind === "scale" || f.op.kind === "scaleXYZ") return this.setTool(new ScaleOp(this, f.op.kind === "scaleXYZ", f.bodies, f as TransformFeature));
return this.setTool(new TransformOp(this, f.op.kind, f.bodies, f as TransformFeature));
}
case "scaleFace":
return this.setTool(new ScaleFaceOp(this, f.face, { origin: f.face.center, normal: f.face.normal, xDir: f.u }, f));
case "replaceFace":
return this.setTool(new ReplaceFaceOp(this, f.face, f));
case "image":
return this.setTool(new ImageOp(this, f as ImageFeature));
case "freeform":
return this.setTool(new FreeformTool(this, { feature: f }));
case "moveFace": {
const target = f.face ? { face: f.face, plane: { origin: f.face.center, normal: f.face.normal, xDir: xDirFor(f.face.normal) } } : f.edge ? { edge: f.edge } : f.vertex ? { vertex: f.vertex } : null;
if (target) return this.setTool(new MoveFaceOp(this, target, f));
break;
}
default:
this.ui.toast(`${f.name} has no values to edit. You can suppress or delete it.`);
}
}
// ------------------------------------------------------------ menus
/** Nothing selected: the top-level menu (the left tool column). */
mainTools(): ToolItem[] {
const wait = (label: string, accepts: Sel["kind"][], run: () => void) => () => {
this.selectTool.waitFor(label, accepts, run);
this.selectTool.refresh();
};
const bodies = () => bodiesOf(this.selection);
const transform = (kind: ConstructorParameters<typeof TransformOp>[1], label: string) =>
wait(label, ["body", "face", "edge"], () => this.setTool(new TransformOp(this, kind, bodies())));
const src = () => sourcesOf(this, this.selection)[0];
return [
{ id: "sketch", label: "Sketch", icon: "sketch", shortcut: "S", run: () => this.setTool(new SketchTool(this)) },
{
// Smooth shapes from a control cage.
id: "freeform",
label: "Freeform",
icon: "freeform",
children: (["box", "sphere", "cylinder", "plane"] as const).map((k) => ({
id: `ff-${k}`,
label: { box: "Box", sphere: "Sphere", cylinder: "Cylinder", plane: "Surface (plane)" }[k],
icon: "freeform" as const,
run: () => this.setTool(new FreeformTool(this, { primitive: k })),
})),
},
{
id: "insert",
label: "Insert",
icon: "insert",
children: [
{ id: "var", label: "Create Variable", icon: "variable", run: () => void createVariable(this) },
{ id: "vars", label: "Variables", icon: "variable", sub: `${this.store.doc.variables.length} defined`, run: () => void editVariables(this) },
{ id: "image", label: "Image", icon: "image", run: () => void insertImage(this) },
{ id: "file", label: "File", icon: "file", sub: "STEP, STL, OBJ, DXF, SVG", run: () => void insertFile(this) },
{ id: "project", label: "Project", icon: "file", sub: ".super", run: () => void insertFile(this) },
],
},
{
id: "construct",
label: "Construct",
icon: "construct",
children: [
{
id: "plane",
label: "Plane",
icon: "plane",
children: [
{ id: "offset", label: "Offset Plane", icon: "plane", run: () => this.setTool(new PlaneOp(this, null, undefined)) },
{ id: "mid", label: "Midplane", icon: "plane", run: () => this.setTool(new MidplaneOp(this)) },
{ id: "3pt", label: "Plane Through 3 Points", icon: "plane", disabled: true, why: SOON },
{ id: "curve", label: "Plane on Curve at Point", icon: "plane", disabled: true, why: SOON },
],
},
{
id: "axis",
label: "Axis",
icon: "axis",
run: wait("Axis", ["face", "edge"], () => {
const s = this.selection[0];
if (s.kind === "face") {
const f = this.view.body(s.body)?.faces[s.face];
if (f) this.setTool(new AxisOp(this, f.center, f.normal));
} else if (s.kind === "edge") {
const e = this.view.body(s.body)?.edges[s.edge];
if (e) this.setTool(new AxisOp(this, e.start, e.dir));
}
}),
},
],
},
{
id: "transform",
label: "Transform",
icon: "transform",
children: [
{ id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", run: transform("move", "Move/Rotate") },
{ id: "scale", label: "Scale", icon: "scale", run: wait("Scale", ["body", "face", "edge"], () => this.setTool(new ScaleOp(this, false, bodies()))) },
{ id: "translate", label: "Translate", icon: "translate", run: transform("translate", "Translate") },
{
id: "pattern",
label: "Pattern",
icon: "patternLinear",
children: [
{ id: "linear", label: "Linear", icon: "patternLinear", run: transform("linear", "Pattern – Linear") },
{ id: "circular", label: "Circular", icon: "patternCircular", run: transform("circular", "Pattern – Circular") },
],
},
{ id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: transform("rotate", "Rotate Around Axis") },
{ id: "align", label: "Align", icon: "align", disabled: true, why: SOON },
{ id: "mirror", label: "Mirror", icon: "mirror", run: transform("mirror", "Mirror") },
],
},
{
id: "tools",
label: "Tools",
icon: "tools",
children: [
{ id: "offsetFace", label: "Offset Face", icon: "offsetFace", run: wait("Offset Face", ["face"], () => src() && this.setTool(new ExtrudeOp(this, src()!))) },
{ id: "fillet", label: "Fillet", icon: "fillet", run: wait("Fillet", ["edge"], () => this.setTool(new EdgeOp(this, "fillet", this.selection.flatMap((s) => (s.kind === "edge" ? [edgeRefOf(this, s)!] : []))))) },
{ id: "chamfer", label: "Chamfer", icon: "chamfer", run: wait("Chamfer", ["edge"], () => this.setTool(new EdgeOp(this, "chamfer", this.selection.flatMap((s) => (s.kind === "edge" ? [edgeRefOf(this, s)!] : []))))) },
{ id: "extrude", label: "Extrude", icon: "extrude", run: wait("Extrude", ["profile", "face"], () => src() && this.setTool(new ExtrudeOp(this, src()!))) },
{ id: "shell", label: "Shell", icon: "shell", run: wait("Shell", ["face", "body"], () => {
const s = this.selection[0];
const faces = this.selection.flatMap((x) => (x.kind === "face" ? [faceRefOf(this, x)!] : []));
this.setTool(new ShellOp(this, bodiesOf([s])[0], faces));
}) },
{ id: "loft", label: "Loft", icon: "loft", run: wait("Loft", ["profile", "face"], () => this.setTool(new LoftOp(this, sourcesOf(this, this.selection).flatMap((s): ExtrudeSource[] => (s.kind === "profile" ? s.regions.map((r) => ({ ...s, regions: [r] })) : [s])), this.selection))) },
{ id: "union", label: "Union", icon: "union", run: wait("Union (double-tap bodies)", ["body"], () => this.selectTool.refresh()) },
{ id: "subtract", label: "Subtract", icon: "subtract", run: wait("Subtract (double-tap bodies)", ["body"], () => this.selectTool.refresh()) },
{ id: "intersect", label: "Intersect", icon: "intersect", run: wait("Intersect (double-tap bodies)", ["body"], () => this.selectTool.refresh()) },
{ id: "split", label: "Split Body", icon: "split", run: wait("Split Body", ["body", "face"], () => this.setTool(new SplitOp(this, bodiesOf(this.selection)[0]))) },
{ id: "revolve", label: "Revolve", icon: "revolve", run: wait("Revolve", ["profile", "face"], () => src() && this.setTool(new RevolveOp(this, src()!))) },
{ id: "sweep", label: "Sweep", icon: "sweep", run: wait("Sweep", ["profile", "face"], () => src() && this.setTool(new SweepOp(this, src()!))) },
{ id: "fill", label: "Fill", icon: "fill", disabled: true, why: SOON },
{ id: "replace", label: "Replace Face", icon: "replaceFace", disabled: true, why: SOON },
{ id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON },
{ id: "wrap", label: "Wrap & Emboss", icon: "wrap", disabled: true, why: SOON },
],
},
];
}
bottomTools(): ToolItem[] {
return [
{ id: "section", label: "Section View", icon: "section", sub: this.section ? "On" : this.lastSection ? "Off · tap to show" : "Off", active: !!this.section, run: () => this.toggleSection() },
{ id: "measure", label: "Measure", icon: "measure", run: () => this.setTool(new MeasureTool(this)) },
this.isolated
? { id: "isolate", label: "Isolate", icon: "isolate", sub: "On — tap to show all", active: true, run: () => this.isolate(null) }
: {
id: "isolate",
label: "Isolate",
icon: "isolate",
sub: "Off",
disabled: !bodiesOf(this.selection).length,
why: "Select a body, face or edge to isolate",
run: () => this.isolate(bodiesOf(this.selection)),
},
];
}
private onKey(e: KeyboardEvent): void {
// Typing while holding a drag sets an exact value; Enter applies it and finishes.
// (Checked first: a panel field may still have focus from before the drag.)
if (this.input.dragging && this.tool.dragKey?.(e)) {
e.preventDefault();
(document.activeElement as HTMLElement | null)?.blur?.();
if (e.key === "Enter") this.input.endDrag();
return;
}
const target = e.target as HTMLElement;
if (target.tagName === "INPUT" || target.tagName === "TEXTAREA") return;
const mod = e.ctrlKey || e.metaKey;
const k = e.key.toLowerCase();
if (mod && k === "z") {
e.preventDefault();
if (this.tool !== this.selectTool && !(this.tool instanceof SketchTool)) this.setTool(null);
if (e.shiftKey) this.store.redo();
else this.store.undo();
return;
}
if (mod && k === "y") {
e.preventDefault();
this.store.redo();
return;
}
if (mod && k === "s") {
e.preventDefault();
this.save();
return;
}
if (this.tool.key?.(e)) {
e.preventDefault();
return;
}
if (mod) return;
if (this.tool !== this.selectTool) return;
if (k === "s" && !this.selection.length) this.setTool(new SketchTool(this));
else if (k === "f" && !this.selection.length) this.fit();
}
private fit(): void {
this.view.cam.fit(this.view.bounds());
}
// ------------------------------------------------------------ files
private wireTopbar(): void {
const on = (id: string, fn: () => void) => document.getElementById(id)!.addEventListener("click", fn);
const menu = document.getElementById("file-menu")!;
const more = document.getElementById("more-menu")!;
on("file-btn", () => ((more.hidden = true), menu.toggleAttribute("hidden")));
on("more-btn", () => ((menu.hidden = true), more.toggleAttribute("hidden")));
document.getElementById("m-version")!.textContent = `Version ${__APP_VERSION__}`;
const moreItem = (id: string, fn: () => void) => on(id, () => ((more.hidden = true), fn()));
// Fullscreen (the label follows the state; Esc also leaves it).
const fs = document.getElementById("m-fullscreen")!;
const doc = document as Document & { webkitFullscreenElement?: Element; webkitExitFullscreen?: () => void };
const root = document.documentElement as HTMLElement & { webkitRequestFullscreen?: () => void };
const isFull = () => !!(document.fullscreenElement ?? doc.webkitFullscreenElement);
const paint = () => (fs.firstChild!.textContent = isFull() ? "Exit fullscreen" : "Fullscreen");
document.addEventListener("fullscreenchange", paint);
document.addEventListener("webkitfullscreenchange", paint);
moreItem("m-fullscreen", () => {
if (isFull()) return void (document.exitFullscreen?.() ?? doc.webkitExitFullscreen?.());
if (root.requestFullscreen) void root.requestFullscreen().catch(() => this.ui.toast("This browser won't go fullscreen here"));
else if (root.webkitRequestFullscreen) root.webkitRequestFullscreen();
// iPhone Safari has no fullscreen for pages: the Home Screen app is.
else this.ui.toast("Tip: Share → Add to Home Screen opens supergeometry.app full screen");
});
// Help and Tutorial: placeholders for now.
moreItem("m-help", () => {});
moreItem("m-tutorial", () => {});
// About → the project on GitHub; support → MakerWorld (new tab, no access back to this page).
const openTab = (url: string) => window.open(url, "_blank", "noopener");
moreItem("m-about", () => openTab("https://github.com/superGeometry/supergeometry.app"));
moreItem("m-donate", () => openTab("https://makerworld.com/en/@supergeometry/upload"));
document.addEventListener("pointerdown", (e) => {
if (!(e.target as HTMLElement).closest("#file-menu, #file-btn")) menu.hidden = true;
if (!(e.target as HTMLElement).closest("#more-menu, #more-btn")) more.hidden = true;
});
const item = (id: string, fn: () => void) =>
on(id, () => {
menu.hidden = true;
fn();
});
item("m-new", () => {
if (this.store.features.length && !confirm("Start a new project? (You can undo this.)")) return;
this.setTool(null);
this.setSection(null);
this.store.replace(emptyDoc());
});
item("m-open", () => this.open());
item("m-save", () => this.save());
item("m-stl", () => void this.export("stl"));
item("m-step", () => void this.export("step"));
on("undo-btn", () => this.store.undo());
on("redo-btn", () => this.store.redo());
this.store.onChange(() => this.updateUndo());
this.updateUndo();
// Project name: click and type; Enter or leaving the field renames.
const name = document.getElementById("project-name") as HTMLInputElement;
const show = () => {
if (document.activeElement !== name) name.value = this.store.doc.name;
document.title = `${this.store.doc.name} – supergeometry.app`;
};
const rename = () => {
const v = name.value.trim();
if (v && v !== this.store.doc.name) this.store.commit((d) => (d.name = v));
else name.value = this.store.doc.name;
};
name.addEventListener("change", rename);
name.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "Enter") name.blur();
if (e.key === "Escape") (name.value = this.store.doc.name), name.blur();
});
name.addEventListener("focus", () => name.select());
this.store.onChange(show);
show();
}
private updateUndo(): void {
(document.getElementById("undo-btn") as HTMLButtonElement).disabled = !this.store.canUndo;
(document.getElementById("redo-btn") as HTMLButtonElement).disabled = !this.store.canRedo;
}
private save(): void {
download(new Blob([JSON.stringify(this.store.doc)], { type: "application/json" }), `${this.store.doc.name}.super`);
}
private open(): void {
const input = document.createElement("input");
input.type = "file";
input.accept = ".super,.tessel,application/json";
input.onchange = async () => {
const file = input.files?.[0];
if (!file) return;
try {
const doc = parseProject(await file.text());
doc.name = file.name.replace(/\.(super|tessel)$/i, "");
this.setTool(null);
this.store.replace(doc);
setTimeout(() => this.fit(), 400);
} catch (err) {
this.ui.toast(`Could not open: ${(err as Error).message}`, "error");
}
};
input.click();
}
private async export(format: ExportFormat): Promise<void> {
// Selected bodies win; otherwise what's isolated; otherwise everything.
const picked = bodiesOf(this.selection);
const bodies = picked.length ? picked : (this.isolated ?? []);
try {
this.ui.setStatus(`Exporting ${bodies.length ? `${bodies.length} bod${bodies.length > 1 ? "ies" : "y"} as ` : ""}${format.toUpperCase()}…`);
const blob = await this.kernel.export(this.store.doc.features, format, bodies.length ? bodies : undefined);
download(blob, `${this.store.doc.name}.${format === "step" ? "step" : "stl"}`);
} catch (err) {
this.ui.toast(`Export failed: ${(err as Error).message}`, "error");
} finally {
this.ui.setStatus(null);
}
}
}
function download(blob: Blob, name: string): void {
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
}
+53
View File
@@ -0,0 +1,53 @@
// Parametric document: evaluate expressions (variables) into feature values and
// re-solve sketch constraints, so the document's numbers are always consistent.
import { solve } from "../sketch/constraints";
import { evaluate, setVariables } from "../units";
import type { Feature, ProjectDoc } from "./types";
/** Kind of value stored at a path (for units: lengths are mm, angles degrees). */
export function kindOfPath(path: string): "length" | "angle" | "number" {
const last = path.split(".").pop() ?? "";
if (/angle|rot/i.test(last) || /rotate/.test(path)) return "angle";
if (/count|factor|sides|opacity/i.test(last)) return "number";
return "length";
}
export function getPath(obj: unknown, path: string): unknown {
return path.split(".").reduce<unknown>((o, k) => (o == null ? undefined : (o as Record<string, unknown>)[k]), obj);
}
export function setPath(obj: unknown, path: string, value: unknown): void {
const keys = path.split(".");
let o = obj as Record<string, unknown>;
for (const k of keys.slice(0, -1)) {
if (o[k] == null) return;
o = o[k] as Record<string, unknown>;
}
o[keys[keys.length - 1]] = value;
}
/** Recompute every expression-driven value and re-solve constrained sketches (in place). */
export function resolveDoc(doc: ProjectDoc): string[] {
const problems: string[] = [];
setVariables(doc.variables ?? []);
for (const f of doc.features as Feature[]) {
for (const [path, expr] of Object.entries(f.exprs ?? {})) {
const v = evaluate(expr, kindOfPath(path));
if (v === null) problems.push(`${f.name}: "${expr}" can't be evaluated`);
else setPath(f, path, v);
}
if (f.type === "sketch" && f.constraints?.length) {
for (const c of f.constraints) {
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 = solve(f.entities, f.constraints);
f.entities = r.entities;
if (!r.ok) problems.push(`${f.name}: constraints can't all be met`);
}
}
return problems;
}
+263
View File
@@ -0,0 +1,263 @@
import { entityPolylines } from "../sketch/curves";
import { arrangement, regionRef } from "../sketch/regions";
import { pointInPoly } from "../sketch/curves";
import { resolveDoc } from "./params";
import { emptyDoc, type Feature, type FeatureType, type ProjectDoc, type SketchEntity } from "./types";
// Earlier builds were called "Tessel": their autosave is still picked up.
const LEGACY_KEY = "tessel.autosave.v1";
const DB_NAME = "supergeometry";
const OLD_DB_NAME = "tessel";
const MAX_UNDO = 200;
type Listener = () => void;
const LABELS: Record<FeatureType, string> = {
sketch: "Sketch",
extrude: "Extrude",
fillet: "Fillet",
chamfer: "Chamfer",
boolean: "Boolean",
delete: "Delete",
revolve: "Revolve",
sweep: "Sweep",
loft: "Loft",
shell: "Shell",
transform: "Transform",
split: "Split",
plane: "Plane",
axis: "Axis",
import: "Import",
image: "Image",
deleteGeom: "Delete",
moveFace: "Move Face",
freeform: "Freeform",
scaleFace: "Scale Face",
replaceFace: "Replace Face",
};
/**
* Holds the document and its undo/redo history. Every change goes through
* `commit`, which snapshots the previous state, so undo is exact.
*/
export class DocStore {
doc: ProjectDoc = emptyDoc();
private undoStack: string[] = [];
private redoStack: string[] = [];
private listeners = new Set<Listener>();
private saveTimer = 0;
/** Restore the autosaved project (IndexedDB, or the old localStorage slot). */
async load(): Promise<void> {
const saved = (await idbGet("autosave")) ?? (await idbGet("autosave", OLD_DB_NAME)) ?? legacyAutosave();
if (saved) {
try {
this.doc = migrate(JSON.parse(saved));
} catch {
// A broken autosave must never block the app.
}
}
this.listeners.forEach((fn) => fn());
}
onChange(fn: Listener): () => void {
this.listeners.add(fn);
return () => this.listeners.delete(fn);
}
get features(): readonly Feature[] {
return this.doc.features;
}
find<T extends Feature = Feature>(id: string): T | undefined {
return this.doc.features.find((f) => f.id === id) as T | undefined;
}
/** Unique id + "Extrude 03"-style name for a new feature. */
newIdentity(type: FeatureType, label = LABELS[type]): { id: string; name: string } {
const n = this.doc.features.filter((f) => f.name.startsWith(label + " ")).length + 1;
return { id: newId(type), name: `${label} ${String(n).padStart(2, "0")}` };
}
/** Expressions that couldn't be evaluated / sketches that can't be solved. */
problems: string[] = [];
private transientBase: string | null = null;
/** Apply a mutation as one undoable step. */
commit(mutate: (doc: ProjectDoc) => void): void {
const before = this.transientBase ?? JSON.stringify(this.doc);
const next = JSON.parse(JSON.stringify(this.doc)) as ProjectDoc;
mutate(next);
this.problems = resolveDoc(next);
this.transientBase = null;
if (JSON.stringify(next) === before) return;
this.undoStack.push(before);
if (this.undoStack.length > MAX_UNDO) this.undoStack.shift();
this.redoStack = [];
this.doc = next;
this.changed();
}
/**
* Live edits during a drag: update the document and notify, but leave undo
* alone; the next `commit` records everything since the drag began as one step.
*/
transient(mutate: (doc: ProjectDoc) => void): void {
this.transientBase ??= JSON.stringify(this.doc);
const next = JSON.parse(JSON.stringify(this.doc)) as ProjectDoc;
mutate(next);
this.doc = next;
this.listeners.forEach((fn) => fn());
}
add(feature: Feature): void {
this.commit((d) => d.features.push(feature));
}
update(id: string, patch: Partial<Feature>): void {
this.commit((d) => {
const i = d.features.findIndex((f) => f.id === id);
if (i >= 0) d.features[i] = { ...d.features[i], ...patch } as Feature;
});
}
remove(id: string): void {
this.commit((d) => {
d.features = d.features.filter((f) => f.id !== id);
});
}
get canUndo(): boolean {
return this.undoStack.length > 0;
}
get canRedo(): boolean {
return this.redoStack.length > 0;
}
undo(): void {
const prev = this.undoStack.pop();
if (!prev) return;
this.redoStack.push(JSON.stringify(this.doc));
this.doc = JSON.parse(prev);
this.changed();
}
redo(): void {
const next = this.redoStack.pop();
if (!next) return;
this.undoStack.push(JSON.stringify(this.doc));
this.doc = JSON.parse(next);
this.changed();
}
/** Replace the whole document (open file / new project). Undoable. */
replace(doc: ProjectDoc): void {
this.commit((d) => {
// Drop every key first: anything the new document doesn't have (folders,
// colours, custom names…) must not linger from the old one.
for (const k of Object.keys(d)) delete (d as unknown as Record<string, unknown>)[k];
Object.assign(d, structuredClone(doc));
});
}
private changed(): void {
this.listeners.forEach((fn) => fn());
clearTimeout(this.saveTimer);
this.saveTimer = window.setTimeout(() => void idbSet("autosave", JSON.stringify(this.doc)), 400);
}
}
export function newId(prefix: string): string {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
}
export function parseProject(text: string): ProjectDoc {
return migrate(JSON.parse(text));
}
// ------------------------------------------------------------------ migration
/** Bring any saved project up to the current format. */
export function migrate(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.version === 2) return { ...emptyDoc(), ...doc, format: "super" };
// v1: rect {a, b}; extrude profiles referenced entity ids.
const sketches = new Map<string, SketchEntity[]>();
for (const f of doc.features as unknown as Array<Record<string, any>>) {
if (f.type === "sketch") {
f.entities = f.entities.map((e: any) => {
if (e.kind === "rect" && e.a) {
return { id: e.id, kind: "rect", center: [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2], w: Math.abs(e.b[0] - e.a[0]), h: Math.abs(e.b[1] - e.a[1]), rotation: 0 };
}
return e;
});
sketches.set(f.id, f.entities);
}
if (f.type === "extrude" && f.source?.kind === "profile" && f.source.entities) {
const entities = sketches.get(f.source.sketch) ?? [];
f.source = { kind: "profile", sketch: f.source.sketch, regions: regionsForEntities(entities, f.source.entities) };
}
}
return { ...emptyDoc(), ...doc, format: "super", version: 2 } as ProjectDoc;
}
/** v1 profiles were "entity minus what's inside it": pick the regions that matches. */
function regionsForEntities(entities: SketchEntity[], ids: string[]) {
const arr = arrangement(entities);
const outline = (e: SketchEntity) => entityPolylines(e).flat();
const areaOf = (pts: [number, number][]) => {
let a = 0;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) a += (pts[j][0] + pts[i][0]) * (pts[j][1] - pts[i][1]);
return Math.abs(a / 2);
};
return arr.regions
.filter((r) => {
const owners = entities.filter((e) => pointInPoly(r.centroid, outline(e)));
if (!owners.length) return false;
const smallest = owners.reduce((a, b) => (areaOf(outline(a)) < areaOf(outline(b)) ? a : b));
return ids.includes(smallest.id);
})
.map(regionRef);
}
// ---------------------------------------------------------------- IndexedDB
function db(name = DB_NAME): Promise<IDBDatabase | null> {
return new Promise((resolve) => {
try {
const req = indexedDB.open(name, 1);
req.onupgradeneeded = () => req.result.createObjectStore("kv");
req.onsuccess = () => resolve(req.result);
req.onerror = () => resolve(null);
} catch {
resolve(null);
}
});
}
async function idbGet(key: string, dbName = DB_NAME): Promise<string | null> {
const d = await db(dbName);
if (!d) return null;
return new Promise((resolve) => {
const req = d.transaction("kv").objectStore("kv").get(key);
req.onsuccess = () => resolve((req.result as string) ?? null);
req.onerror = () => resolve(null);
});
}
async function idbSet(key: string, value: string): Promise<void> {
const d = await db();
if (!d) return;
d.transaction("kv", "readwrite").objectStore("kv").put(value, key);
}
function legacyAutosave(): string | null {
try {
return localStorage.getItem(LEGACY_KEY);
} catch {
return null;
}
}
+408
View File
@@ -0,0 +1,408 @@
// The project file format. Everything the user builds is a list of features;
// geometry is always regenerated from these, which is what makes history editable.
export type Vec2 = [number, number];
export type Vec3 = [number, number, number];
/** A plane in world space. xDir and normal are unit vectors, perpendicular. */
export interface PlaneDef {
origin: Vec3;
xDir: Vec3;
normal: Vec3;
}
interface EntityBase {
id: string;
/** Construction geometry is drawn dashed and never forms regions. */
construction?: boolean;
}
export type SketchEntity = EntityBase &
(
| { kind: "line"; a: Vec2; b: Vec2 }
/** 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" }
| { 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;
a: number;
}
/**
* Geometric signature of a face. Features store this instead of a face index so
* the reference survives edits to earlier features (see docs/ARCHITECTURE.md).
*/
export interface FaceRef {
body: string;
center: Vec3;
normal: Vec3;
area: number;
}
export interface EdgeRef {
body: string;
mid: Vec3;
dir: Vec3;
length: number;
}
export type ExtrudeSource =
| { kind: "profile"; sketch: string; regions: RegionRef[] }
| { kind: "face"; face: FaceRef };
interface FeatureBase {
id: string;
name: string;
/** Suppressed features are skipped during regeneration. */
suppressed?: boolean;
/**
* Parametric values: field path → expression (e.g. "distance": "depth*2").
* The number at that path is recomputed from the expression on every change.
*/
exprs?: Record<string, string>;
}
/** A point of a sketch entity: "a"/"b" ends, "m" arc mid, "c" centre, "k<i>" i-th corner/point. */
export interface PointRef {
e: string;
p: string;
}
export type ConstraintType =
| "coincident"
| "horizontal"
| "vertical"
| "parallel"
| "perpendicular"
| "equal"
| "tangent"
| "concentric"
| "midpoint"
| "symmetric"
| "fix"
| "distance"
| "dim";
/**
* Sketch constraint. Geometry refs: `pts` (points) and `curves` (entity ids).
* Dimensions ("distance", "dim") carry a value, optionally driven by `expr`.
*/
export interface SketchConstraint {
id: string;
type: ConstraintType;
pts?: PointRef[];
curves?: string[];
/** dim: which size — length, radius, diameter, w, h, rx, ry, angle. */
prop?: string;
value?: number;
expr?: string;
/** fix: where the point is held. */
at?: Vec2;
}
export interface SketchFeature extends FeatureBase {
type: "sketch";
plane: PlaneDef;
/** When drawn on a body face, the sketch follows that face when it moves. */
attachedTo?: FaceRef;
entities: SketchEntity[];
constraints?: SketchConstraint[];
/** What was done in the sketch, in order (shown under it in History); repeats are counted. */
log?: { op: string; n: number }[];
}
export interface ExtrudeFeature extends FeatureBase {
type: "extrude";
source: ExtrudeSource;
distance: number;
/** auto: join `target` when distance > 0, cut it when < 0; new body without a target. */
mode: "auto" | "new" | "join" | "cut";
target?: string;
}
export interface EdgeFeature extends FeatureBase {
type: "fillet" | "chamfer";
edges: EdgeRef[];
radius: number;
}
export interface BooleanFeature extends FeatureBase {
type: "boolean";
op: "union" | "subtract" | "intersect";
target: string;
tools: string[];
}
export interface DeleteFeature extends FeatureBase {
type: "delete";
bodies: string[];
}
/**
* An axis in space. When `ref` is set the axis follows that sketch line or
* construction axis; origin/dir are the fallback (and the value at creation).
*/
export interface AxisRef {
origin: Vec3;
dir: Vec3;
ref?: { kind: "sketchLine"; sketch: string; entity: string } | { kind: "axis"; feature: string };
}
export type PathRef = { kind: "sketch"; sketch: string; entities: string[] } | { kind: "edges"; edges: EdgeRef[] };
type BodyMode = "auto" | "new" | "join" | "cut";
export interface RevolveFeature extends FeatureBase {
type: "revolve";
source: ExtrudeSource;
axis: AxisRef;
/** Degrees (more than 360 winds round again: with travel, a thread or spring). */
angle: number;
/** Distance moved along the axis over the whole angle (0: a plain revolve). */
travel?: number;
mode: BodyMode;
target?: string;
}
export interface SweepFeature extends FeatureBase {
type: "sweep";
source: ExtrudeSource;
path: PathRef;
mode: BodyMode;
target?: string;
}
export interface LoftFeature extends FeatureBase {
type: "loft";
sections: ExtrudeSource[];
ruled: boolean;
mode: BodyMode;
target?: string;
}
export interface ShellFeature extends FeatureBase {
type: "shell";
body: string;
/** Faces to open (removed); may be empty for a hollow closed body. */
faces: FaceRef[];
thickness: number;
}
/** Move/rotate/scale/mirror/pattern bodies. With `copy`, the originals stay. */
export interface TransformFeature extends FeatureBase {
type: "transform";
bodies: string[];
copy: boolean;
op:
| { kind: "move"; translate: Vec3; rotate?: { origin: Vec3; axis: Vec3; angle: number } }
| { kind: "scale"; center: Vec3; factor: number }
/** Different factors along X, Y and Z (freeform bodies: rebuilt from their cage). */
| { kind: "scaleXYZ"; center: Vec3; factors: Vec3 }
| { kind: "mirror"; plane: PlaneDef }
| { kind: "linear"; dir: Vec3; spacing: number; count: number }
| { kind: "circular"; axis: AxisRef; count: number; angle: number };
}
export interface SplitFeature extends FeatureBase {
type: "split";
body: string;
plane: PlaneDef;
}
/** Construction plane. Optionally follows a face (offset along its normal). */
export interface PlaneFeature extends FeatureBase {
type: "plane";
plane: PlaneDef;
face?: FaceRef;
offset: number;
}
export interface AxisFeature extends FeatureBase {
type: "axis";
origin: Vec3;
dir: Vec3;
}
/** A body imported from a file. The file content travels inside the project. */
export interface ImportFeature extends FeatureBase {
type: "import";
format: "step" | "stl";
fileName: string;
/** Base64 of the file. */
data: string;
}
/** A reference image placed on a plane (for tracing). */
export interface ImageFeature extends FeatureBase {
type: "image";
plane: PlaneDef;
/** data: URL */
src: string;
width: number;
height: number;
opacity: number;
}
/**
* Remove faces/edges/vertices from a body; the surrounding faces extend to
* close the gap (fillets, chamfers, holes, imprinted edges).
*/
export interface DeleteGeomFeature extends FeatureBase {
type: "deleteGeom";
body: string;
faces: FaceRef[];
edges: EdgeRef[];
vertices: Vec3[];
}
/**
* Move/tilt one flat face — or one straight edge between two flat faces (both
* faces turn to follow it). The neighbouring faces extend or trim.
*/
export interface MoveFaceFeature extends FeatureBase {
type: "moveFace";
face?: FaceRef;
edge?: EdgeRef;
/** One corner moves; the flat faces meeting there turn about their far edge to follow. */
vertex?: { body: string; at: Vec3 };
translate: Vec3;
rotate?: { origin: Vec3; axis: Vec3; angle: number };
}
/**
* A freeform body: a quad control cage whose smooth subdivision surface
* becomes the body (a solid when the cage is closed, a surface otherwise).
*/
export interface FreeformFeature extends FeatureBase {
type: "freeform";
cage: { verts: Vec3[]; faces: [number, number, 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). */
thickness?: number;
/** Which way the thickness goes from the surface (its normal side is "up"). */
thickSide?: "up" | "down" | "both";
}
/**
* 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.
*/
export interface ScaleFaceFeature extends FeatureBase {
type: "scaleFace";
face: FaceRef;
/** The face's in-plane u axis (v = normal × u). */
u: Vec3;
factors: [number, number];
}
/** Move a flat face onto another plane / flat face (the neighbours follow). */
export interface ReplaceFaceFeature extends FeatureBase {
type: "replaceFace";
face: FaceRef;
plane: PlaneDef;
/** Follow this face when it moves (else `plane` is used as is). */
target?: FaceRef;
}
export type Feature =
| ScaleFaceFeature
| ReplaceFaceFeature
| FreeformFeature
| DeleteGeomFeature
| MoveFaceFeature
| SketchFeature
| ExtrudeFeature
| EdgeFeature
| BooleanFeature
| DeleteFeature
| RevolveFeature
| SweepFeature
| LoftFeature
| ShellFeature
| TransformFeature
| SplitFeature
| PlaneFeature
| AxisFeature
| ImportFeature
| ImageFeature;
export type FeatureType = Feature["type"];
export interface Variable {
name: string;
/** Expression; may reference other variables. */
expr: string;
}
export interface SavedView {
name: string;
target: Vec3;
distance: number;
azimuth: number;
elevation: number;
ortho: boolean;
}
export type Units = "mm" | "cm" | "m" | "in" | "ft";
/** A measurement pinned in 3D: a label, optionally with a dimension line a→b. */
export interface PinDef {
text: string;
at: Vec3;
a?: Vec3;
b?: Vec3;
}
export interface ProjectDoc {
format: "super";
version: 2;
name: string;
features: Feature[];
variables: Variable[];
views: SavedView[];
units: Units;
/** Ids of bodies / sketches / planes hidden from the Items panel. */
hidden: string[];
pins: PinDef[];
/** Custom names for bodies (by body id), set from Items. */
names: Record<string, string>;
/** Items folders: any bodies / sketches / planes / images, grouped. */
folders?: ItemFolder[];
/** Body colours (by body id), "#rrggbb"; missing = the default grey. */
colors?: Record<string, string>;
}
/** The body colours offered by the Color tool (first = default). */
export const BODY_COLORS: { name: string; hex: string }[] = [
{ name: "Grey", hex: "#b9bec7" },
{ name: "Red", hex: "#e05a4f" },
{ name: "Orange", hex: "#f08c3a" },
{ name: "Yellow", hex: "#e8c547" },
{ name: "Green", hex: "#5fbf5a" },
{ name: "Teal", hex: "#3fb6a8" },
{ name: "Blue", hex: "#4f8ce0" },
{ name: "Violet", hex: "#8a6be0" },
{ name: "Pink", hex: "#e06bb5" },
{ name: "Brown", hex: "#9a7454" },
];
export interface ItemFolder {
id: string;
name: string;
/** Body ids and feature ids. */
items: string[];
}
export function emptyDoc(): ProjectDoc {
return { format: "super", version: 2, name: "Untitled", features: [], variables: [], views: [], units: "mm", hidden: [], pins: [], names: {} };
}
+2
View File
@@ -0,0 +1,2 @@
/** The package.json version, filled in by Vite (see vite.config.ts). */
declare const __APP_VERSION__: string;
+98
View File
@@ -0,0 +1,98 @@
// Uniform cubic B-spline interpolation of a point grid (pure math).
//
// Every freeform patch is an equal-sized grid with the same uniform
// parameters, so the knots and the interpolation matrix are shared — and two
// patches with the same border points get exactly the same border curve.
import type { Vec3 } from "../doc/types";
export interface CubicKnots {
/** Distinct knot values and their multiplicities (clamped: ends ×4). */
knots: number[];
mults: number[];
/** The full knot vector, for evaluation. */
full: number[];
}
/** Knots for interpolating m+1 points at uniform parameters (de Boor averaging). */
export function cubicKnots(count: number): CubicKnots {
const m = count - 1;
const t = Array.from({ length: count }, (_, k) => k / m);
const inner: number[] = [];
for (let j = 1; j <= m - 3; j++) inner.push((t[j] + t[j + 1] + t[j + 2]) / 3);
const full = [0, 0, 0, 0, ...inner, 1, 1, 1, 1];
return { knots: [0, ...inner, 1], mults: [4, ...inner.map(() => 1), 4], full };
}
/** Cox–de Boor: value of basis function i (degree 3) at u. */
function basis(full: number[], i: number, u: number): number {
const N = (j: number, p: number): number => {
if (p === 0) {
// The last span includes its right end.
const last = u === 1 && full[j + 1] === 1 && full[j] < 1;
return (full[j] <= u && u < full[j + 1]) || last ? 1 : 0;
}
const a = full[j + p] - full[j];
const b = full[j + p + 1] - full[j + 1];
return (a ? ((u - full[j]) / a) * N(j, p - 1) : 0) + (b ? ((full[j + p + 1] - u) / b) * N(j + 1, p - 1) : 0);
};
return N(i, 3);
}
/** Inverse of the interpolation matrix A[k][i] = N_i(t_k) for `count` uniform points. */
const inverses = new Map<number, number[][]>();
function interpolationInverse(count: number): number[][] {
let inv = inverses.get(count);
if (inv) return inv;
const { full } = cubicKnots(count);
const A = Array.from({ length: count }, (_, k) => Array.from({ length: count }, (_, i) => basis(full, i, k / (count - 1))));
inv = invert(A);
inverses.set(count, inv);
return inv;
}
function invert(A: number[][]): number[][] {
const n = A.length;
const M = A.map((row, i) => [...row, ...Array.from({ length: n }, (_, j) => (i === j ? 1 : 0))]);
for (let c = 0; c < n; c++) {
let p = c;
for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
[M[c], M[p]] = [M[p], M[c]];
const d = M[c][c];
for (let k = 0; k < 2 * n; k++) M[c][k] /= d;
for (let r = 0; r < n; r++) {
if (r === c) continue;
const f = M[r][c];
if (f) for (let k = 0; k < 2 * n; k++) M[r][k] -= f * M[c][k];
}
}
return M.map((row) => row.slice(n));
}
/** Poles of the bicubic surface through grid[i][j] (both directions uniform). */
export function interpolateGrid(grid: Vec3[][]): Vec3[][] {
const rows = grid.length;
const cols = grid[0].length;
const iu = interpolationInverse(rows);
const iv = interpolationInverse(cols);
// Rows first (along j), then columns (along i).
const R = grid.map((row) => iv.map((w) => w.reduce((s, x, k) => [s[0] + x * row[k][0], s[1] + x * row[k][1], s[2] + x * row[k][2]] as Vec3, [0, 0, 0] as Vec3)));
return iu.map((w) => Array.from({ length: cols }, (_, j) => w.reduce((s, x, k) => [s[0] + x * R[k][j][0], s[1] + x * R[k][j][1], s[2] + x * R[k][j][2]] as Vec3, [0, 0, 0] as Vec3)));
}
/** Evaluate the interpolating surface (for tests): S(u, v). */
export function evalSurface(poles: Vec3[][], u: number, v: number): Vec3 {
const ku = cubicKnots(poles.length).full;
const kv = cubicKnots(poles[0].length).full;
const out: Vec3 = [0, 0, 0];
for (let i = 0; i < poles.length; i++) {
const bu = basis(ku, i, u);
if (!bu) continue;
for (let j = 0; j < poles[0].length; j++) {
const w = bu * basis(kv, j, v);
if (!w) continue;
for (let q = 0; q < 3; q++) out[q] += w * poles[i][j][q];
}
}
return out;
}
+372
View File
@@ -0,0 +1,372 @@
// Freeform control cages and Catmull–Clark subdivision (pure math, no OCCT).
//
// A cage is a quad mesh. The smooth shape is its subdivision surface; after a
// few levels every cage quad has become an n×n grid of points ("patch") that
// the kernel interpolates with one B-spline surface. Neighbouring patches share
// their boundary points exactly, so the surfaces sew into a clean shell/solid.
import type { Vec3 } from "../doc/types";
export interface Cage {
verts: Vec3[];
/** Quads, as vertex indices in order around the face. */
faces: [number, number, number, number][];
}
export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere";
// ------------------------------------------------------------- primitives
/** Box of w×d×h centred on the XY plane at `at` (bottom on z = at.z), n faces per side. */
export function boxCage(size: Vec3 = [40, 40, 40], n = 2, at: Vec3 = [0, 0, 0]): Cage {
const pts = new Map<string, number>();
const verts: Vec3[] = [];
const faces: Cage["faces"] = [];
const vid = (p: Vec3) => {
const k = p.map((x) => Math.round(x * 1e6)).join(",");
let i = pts.get(k);
if (i === undefined) {
i = verts.push(p) - 1;
pts.set(k, i);
}
return i;
};
// Unit cube [-1, 1]³; each side is an n×n grid, wound so normals point out.
const sides: { o: Vec3; u: Vec3; v: Vec3 }[] = [
{ o: [-1, -1, 1], u: [2, 0, 0], v: [0, 2, 0] }, // top
{ o: [-1, 1, -1], u: [2, 0, 0], v: [0, -2, 0] }, // bottom
{ o: [-1, -1, -1], u: [2, 0, 0], v: [0, 0, 2] }, // front (−y)
{ o: [1, 1, -1], u: [-2, 0, 0], v: [0, 0, 2] }, // back (+y)
{ o: [1, -1, -1], u: [0, 2, 0], v: [0, 0, 2] }, // right (+x)
{ o: [-1, 1, -1], u: [0, -2, 0], v: [0, 0, 2] }, // left (−x)
];
const place = (q: Vec3): Vec3 => [at[0] + (q[0] * size[0]) / 2, at[1] + (q[1] * size[1]) / 2, at[2] + ((q[2] + 1) * size[2]) / 2];
for (const { o, u, v } of sides) {
const P = (i: number, j: number): Vec3 => [o[0] + (u[0] * i + v[0] * j) / n, o[1] + (u[1] * i + v[1] * j) / n, o[2] + (u[2] * i + v[2] * j) / n];
for (let i = 0; i < n; i++)
for (let j = 0; j < n; j++) faces.push([vid(P(i, j)), vid(P(i + 1, j)), vid(P(i + 1, j + 1)), vid(P(i, j + 1))]);
}
// Positions are placed after de-duplication (keys use the unit cube).
return { verts: verts.map(place), faces };
}
/** Sphere of diameter `d`: a box cage pushed onto a sphere. */
export function sphereCage(d = 40, at: Vec3 = [0, 0, 0]): Cage {
const c = boxCage([2, 2, 2], 2, [0, 0, -1]);
// A cage a little bigger than the sphere: subdivision shrinks it.
const r = (d / 2) * 1.22;
return { faces: c.faces, verts: c.verts.map((p) => {
const l = Math.hypot(...p) || 1;
return [at[0] + (p[0] / l) * r, at[1] + (p[1] / l) * r, at[2] + d / 2 + (p[2] / l) * r];
}) };
}
/** Flat n×n sheet of w×d on the XY plane at `at` (an open surface). */
export function planeCage(size: [number, number] = [40, 40], n = 4, at: Vec3 = [0, 0, 0]): Cage {
const verts: Vec3[] = [];
for (let j = 0; j <= n; j++) for (let i = 0; i <= n; i++) verts.push([at[0] + (i / n - 0.5) * size[0], at[1] + (j / n - 0.5) * size[1], at[2]]);
const id = (i: number, j: number) => j * (n + 1) + i;
const faces: Cage["faces"] = [];
for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) faces.push([id(i, j), id(i + 1, j), id(i + 1, j + 1), id(i, j + 1)]);
return { verts, faces };
}
/** Cylinder of diameter d and height h standing on `at`: 8 around, `rows` up, quad caps. */
export function cylinderCage(d = 40, h = 40, rows = 2, at: Vec3 = [0, 0, 0]): Cage {
const N = 8;
const r = (d / 2) * 1.08;
const verts: Vec3[] = [];
const ring = (k: number) => k * N;
for (let k = 0; k <= rows; k++)
for (let i = 0; i < N; i++) {
const a = (i / N) * Math.PI * 2;
verts.push([at[0] + Math.cos(a) * r, at[1] + Math.sin(a) * r, at[2] + (k / rows) * h]);
}
const faces: Cage["faces"] = [];
for (let k = 0; k < rows; k++)
for (let i = 0; i < N; i++) {
const a = ring(k) + i;
const b = ring(k) + ((i + 1) % N);
faces.push([a, b, b + N, a + N]);
}
// Caps: a 2×2 grid of quads each, closing the bottom and top rings.
capGrid(verts, faces, ring(0), N, at[2], false, at);
capGrid(verts, faces, ring(rows), N, at[2] + h, true, at);
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.
*/
function capGrid(verts: Vec3[], faces: Cage["faces"], R: number, N: number, z: number, up: boolean, at: Vec3): void {
const c = verts.push([at[0], at[1], z]) - 1;
// 2×2 grid: corner points = rim 1, 3, 5, 7; edge mid points = rim 0, 2, 4, 6; centre = c.
for (let q = 0; q < 4; q++) {
const mid0 = R + ((2 * q) % N);
const corner = R + ((2 * q + 1) % N);
const mid1 = R + ((2 * q + 2) % N);
const quad: [number, number, number, number] = [c, mid0, corner, mid1];
faces.push(up ? quad : [quad[0], quad[3], quad[2], quad[1]]);
}
}
export function primitiveCage(kind: CagePrimitive, at: Vec3 = [0, 0, 0]): Cage {
switch (kind) {
case "box":
return boxCage([40, 40, 40], 2, at);
case "plane":
return planeCage([60, 60], 4, at);
case "cylinder":
return cylinderCage(40, 40, 2, at);
case "sphere":
return sphereCage(40, at);
}
}
// ------------------------------------------------------------ subdivision
/** The subdivided surface: points, and per cage face the (n+1)×(n+1) grid of point indices. */
export interface Subdivided {
points: Vec3[];
/** grids[f][i][j]: point index; i runs from the face's corner 0 towards 1, j towards 3. */
grids: number[][][];
/** Size of each grid side in cells (2^levels). */
n: number;
}
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 {
let points = cage.verts.map((p) => [...p] as Vec3);
let grids = cage.faces.map((f) => [
[f[0], f[3]],
[f[1], f[2]],
]);
let n = 1;
for (let lvl = 0; lvl < levels; lvl++) {
// Every current cell (quad) and the edges between grid points.
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},${b}` : `${b},${a}`);
const edgeFaces = new Map<string, number[]>();
quads.forEach((q, qi) => {
for (let k = 0; k < 4; k++) {
const key = ekey(q[k], q[(k + 1) % 4]);
const l = edgeFaces.get(key);
if (l) l.push(qi);
else edgeFaces.set(key, [qi]);
}
});
const facePt = quads.map((q) => mul3(q.reduce((s, i) => add3(s, points[i]), [0, 0, 0] as Vec3), 0.25));
// New point list: old vertices (moved), then edge points, then face points.
const next: Vec3[] = [];
const edgeIdx = new Map<string, number>();
const faceIdx: number[] = [];
// Edge points.
const edgePos = new Map<string, Vec3>();
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);
}
// Vertex points.
const vFaces = new Map<number, number[]>();
const vEdges = new Map<number, string[]>();
quads.forEach((q, qi) => q.forEach((v) => vFaces.set(v, [...(vFaces.get(v) ?? []), qi])));
for (const key of edgeFaces.keys()) for (const v of key.split(",").map(Number)) vEdges.set(v, [...(vEdges.get(v) ?? []), key]);
const moved = points.map((p, v) => {
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);
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;
const others = boundary.slice(0, 2).map((k) => {
const [a, b] = k.split(",").map(Number);
return points[a === v ? b : a];
});
return add3(mul3(p, 0.75), mul3(add3(others[0], others[1]), 0.125));
}
const m = es.length;
const F = mul3(fs.reduce((s, f) => add3(s, facePt[f]), [0, 0, 0] as Vec3), 1 / fs.length);
const R = mul3(es.reduce((s, k) => {
const [a, b] = k.split(",").map(Number);
return add3(s, mul3(add3(points[a], points[b]), 0.5));
}, [0, 0, 0] as Vec3), 1 / m);
return mul3(add3(add3(F, mul3(R, 2)), mul3(p, m - 3)), 1 / m);
});
next.push(...moved);
for (const [key, pos] of edgePos) edgeIdx.set(key, next.push(pos) - 1);
for (const fp of facePt) faceIdx.push(next.push(fp) - 1);
// New grids, twice as fine.
let qi = 0;
const N = 2 * n;
grids = grids.map((g) => {
const ng: number[][] = Array.from({ length: N + 1 }, () => new Array<number>(N + 1));
for (let i = 0; i <= n; i++) for (let j = 0; j <= n; j++) ng[2 * i][2 * j] = g[i][j];
for (let i = 0; i <= n; i++) for (let j = 0; j < n; j++) ng[2 * i][2 * j + 1] = edgeIdx.get(ekey(g[i][j], g[i][j + 1]))!;
for (let i = 0; i < n; i++) for (let j = 0; j <= n; j++) ng[2 * i + 1][2 * j] = edgeIdx.get(ekey(g[i][j], g[i + 1][j]))!;
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;
});
points = next;
n = N;
}
return { points, grids, n };
}
/** 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>();
const out: [number, 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 key = a < b ? `${a},${b}` : `${b},${a}`;
if (!seen.has(key)) (seen.add(key), out.push([a, b]));
}
return out;
}
/** Does every cage edge have two faces (a closed shape → a solid)? */
export function isClosed(cage: Cage): boolean {
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 key = a < b ? `${a},${b}` : `${b},${a}`;
count.set(key, (count.get(key) ?? 0) + 1);
}
return [...count.values()].every((c) => c === 2);
}
// ------------------------------------------------------------ cage editing
/** 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)) });
}
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 ekey = (a: number, b: number) => (a < b ? `${a},${b}` : `${b},${a}`);
/** Edges used by only one face (the rim of a sheet or of a hole), as that face winds them. */
export function boundaryEdges(cage: Cage): [number, number][] {
const count = new Map<string, { n: number; dir: [number, 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 = count.get(ekey(a, b));
if (e) e.n++;
else count.set(ekey(a, b), { n: 1, dir: [a, b] });
}
return [...count.values()].filter((e) => e.n === 1).map((e) => e.dir);
}
/**
* Closed loops among the chosen boundary edges, each walked the opposite way
* to the face it borders — the winding a new face filling it needs.
*/
export function holeLoops(cage: Cage, chosen: Set<string>): number[][] {
const edges = boundaryEdges(cage).filter(([a, b]) => chosen.has(ekey(a, b)));
// Reverse each: from b to a.
const next = new Map<number, number>();
for (const [a, b] of edges) next.set(b, a);
const loops: number[][] = [];
const seen = new Set<number>();
for (const start of next.keys()) {
if (seen.has(start)) continue;
const loop: number[] = [];
let v: number | undefined = start;
while (v !== undefined && !seen.has(v)) {
seen.add(v);
loop.push(v);
v = next.get(v);
}
if (v === start && loop.length >= 3) loops.push(loop);
}
return loops;
}
/** Fill a hole: 4 edges → one quad; an even number above 4 → quads around a new centre point. */
export function fillLoop(cage: Cage, loop: number[]): Cage | null {
const n = loop.length;
if (n === 4) return { verts: cage.verts, faces: [...cage.faces, [loop[0], loop[1], loop[2], loop[3]]] };
if (n < 4 || n % 2) return null;
const c = loop.reduce((s, v) => [s[0] + cage.verts[v][0] / n, s[1] + cage.verts[v][1] / n, s[2] + cage.verts[v][2] / n] as Vec3, [0, 0, 0] as Vec3);
const ci = cage.verts.length;
const faces = [...cage.faces];
for (let k = 0; k < n; k += 2) faces.push([ci, loop[k], loop[(k + 1) % n], loop[(k + 2) % n]]);
return { verts: [...cage.verts, c], faces };
}
/**
* Bridge two holes with the same number of edges by a ring of quads (e.g. a
* tunnel between a front and a back opening). The second loop is turned and
* rotated to line up with the first so the quads don't twist.
*/
export function bridgeLoops(cage: Cage, a: number[], b: number[]): Cage | null {
const n = a.length;
if (b.length !== n) return null;
// Facing holes run opposite ways round: walk b backwards, then pick the start that lines up best.
const rb = [...b].reverse();
const d = (p: number, q: number) => Math.hypot(...[0, 1, 2].map((k) => cage.verts[p][k] - cage.verts[q][k]));
let best = 0;
let bestCost = Infinity;
for (let s = 0; s < n; s++) {
let cost = 0;
for (let i = 0; i < n; i++) cost += d(a[i], rb[(i + s) % n]);
if (cost < bestCost) (bestCost = cost), (best = s);
}
const B = (i: number) => rb[(i + best) % n];
const faces = [...cage.faces];
// Each a-edge (a_i → a_i+1) already runs as the new face needs it; the b side runs back.
for (let i = 0; i < n; i++) faces.push([a[i], a[(i + 1) % n], B(i + 1), B(i)]);
return { verts: cage.verts, faces };
}
export { ekey as cageEdgeKey };
+54
View File
@@ -0,0 +1,54 @@
// Small vector / plane helpers shared by the UI and the kernel worker.
import type { PlaneDef, Vec2, Vec3 } from "./doc/types";
export const add = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
export const sub = (a: Vec3, b: Vec3): Vec3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
export const scale = (a: Vec3, s: number): Vec3 => [a[0] * s, a[1] * s, a[2] * s];
export const dot = (a: Vec3, b: Vec3): number => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
export 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],
];
export const len = (a: Vec3): number => Math.hypot(a[0], a[1], a[2]);
export const norm = (a: Vec3): Vec3 => {
const l = len(a) || 1;
return [a[0] / l, a[1] / l, a[2] / l];
};
export const dist = (a: Vec3, b: Vec3): number => len(sub(a, b));
export const GROUND: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
export const FRONT: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] };
export const RIGHT: PlaneDef = { origin: [0, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] };
export function planeY(p: PlaneDef): Vec3 {
return cross(p.normal, p.xDir);
}
export function toWorld(p: PlaneDef, uv: Vec2): Vec3 {
const y = planeY(p);
return add(p.origin, add(scale(p.xDir, uv[0]), scale(y, uv[1])));
}
export function toPlane(p: PlaneDef, w: Vec3): Vec2 {
const d = sub(w, p.origin);
return [dot(d, p.xDir), dot(d, planeY(p))];
}
/** Pick a stable in-plane x direction for a face normal (world X if possible). */
export function xDirFor(normal: Vec3): Vec3 {
const ref: Vec3 = Math.abs(normal[2]) > 0.9 ? [1, 0, 0] : [0, 0, 1];
// Project ref onto the plane; for vertical faces this gives a horizontal x axis.
const x = Math.abs(normal[2]) > 0.9 ? ref : cross(ref, normal);
const proj = sub(x, scale(normal, dot(x, normal)));
return norm(proj);
}
/** Round to a "nice" step (0.1, 0.5, 1, 5, 10, …) close to `raw`. */
export function niceStep(raw: number): number {
const p = Math.pow(10, Math.floor(Math.log10(raw)));
const m = raw / p;
return (m < 2 ? 1 : m < 7 ? 5 : 10) * p;
}
+250
View File
@@ -0,0 +1,250 @@
// Insert menu: files (STEP/STL/OBJ/DXF/projects), images, variables.
import { migrate, newId } 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 { evaluate, fmtLen, setVariables } from "../units";
import { parseSVG } from "./svg";
export function pickFile(accept: string): Promise<File | null> {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = accept;
input.onchange = () => resolve(input.files?.[0] ?? null);
input.click();
});
}
export async function insertFile(app: AppContext): Promise<void> {
const file = await pickFile(".step,.stp,.stl,.obj,.dxf,.svg,.dwg,.super,.tessel");
if (!file) return;
const ext = file.name.split(".").pop()!.toLowerCase();
try {
if (ext === "dwg") {
app.ui.toast("DWG is a closed format. Save it as DXF (e.g. with LibreCAD or ODA File Converter, both free) and insert that.", "error");
return;
}
if (ext === "dxf") {
const entities = parseDXF(await file.text());
if (!entities.length) throw new Error("No lines, arcs, circles, polylines or splines found");
const sk: SketchFeature = { ...app.store.newIdentity("sketch", file.name.replace(/\.dxf$/i, "")), type: "sketch", plane: GROUND, entities };
app.store.add(sk);
app.ui.toast(`Inserted ${entities.length} curves as a sketch on the ground plane`);
return;
}
if (ext === "svg") {
// Outlines (logos, laser/vinyl cut files…) as a sketch, centred on the origin.
const { entities, size } = parseSVG(await file.text());
const sk: SketchFeature = { ...app.store.newIdentity("sketch", file.name.replace(/\.svg$/i, "")), type: "sketch", plane: GROUND, entities };
app.store.add(sk);
app.ui.toast(`Inserted ${entities.length} curves (${fmtLen(size[0])} × ${fmtLen(size[1])}) as a sketch on the ground plane`);
return;
}
if (ext === "super" || ext === "tessel") {
insertProject(app, migrate(JSON.parse(await file.text())).features, file.name);
return;
}
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";
}
app.ui.setStatus(`Importing ${file.name}…`);
app.store.add({ ...app.store.newIdentity("import"), type: "import", format, fileName: file.name, data: toBase64(bytes) });
app.ui.setStatus(null);
} catch (err) {
app.ui.setStatus(null);
app.ui.toast(`Could not insert ${file.name}: ${(err as Error).message}`, "error");
}
}
/** Append another project's history (ids are renamed so nothing collides). */
function insertProject(app: AppContext, features: Feature[], name: string): void {
const map = new Map(features.map((f) => [f.id, newId(f.type)]));
let json = JSON.stringify(features);
for (const [from, to] of map) json = json.split(`"${from}"`).join(`"${to}"`);
const renamed = JSON.parse(json) as Feature[];
app.store.commit((d) => d.features.push(...renamed));
app.ui.toast(`Inserted ${renamed.length} steps from ${name}`);
}
export async function insertImage(app: AppContext, plane: PlaneDef = GROUND): Promise<void> {
const file = await pickFile("image/*");
if (!file) return;
const 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();
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);
app.ui.toast("Image placed on the ground plane (100 mm wide). Edit it from History.");
}
/** Create a named variable (optionally from a field's current value); returns its name. */
export async function createVariable(app: AppContext, value = ""): Promise<string | null> {
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: "expr", label: "Value", value, placeholder: "40 or 1.5in or depth/2" },
], note);
if (!v) return 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");
return null;
}
const next = [...list.filter((x) => x.name !== name), { name, expr: v.expr.trim() || "0" }];
setVariables(next);
if (evaluate(v.expr || "0") === null) {
setVariables(list);
app.ui.toast(`"${v.expr}" isn't a valid value`, "error");
return null;
}
app.store.commit((d) => (d.variables = next));
app.ui.toast(`${name} = ${v.expr}`);
return name;
}
/** Edit every variable at once; changing one rebuilds everything that uses it. */
export async function editVariables(app: AppContext): Promise<void> {
const list = app.store.doc.variables;
if (!list.length) return void createVariable(app);
const v = await app.ui.dialog(
"Variables",
list.map((x) => ({ key: x.name, label: x.name, value: x.expr })),
"Change a value to update every feature that uses it. Clear a value to delete the variable.",
);
if (!v) return;
const next = list.filter((x) => v[x.name]?.trim()).map((x) => ({ name: x.name, expr: v[x.name].trim() }));
setVariables(next);
const bad = next.find((x) => evaluate(x.expr) === null);
if (bad) {
setVariables(list);
return app.ui.toast(`"${bad.expr}" isn't a valid value for ${bad.name}`, "error");
}
app.store.commit((d) => (d.variables = next));
}
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) },
]);
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)) });
}
// -------------------------------------------------------------------- DXF
/** Minimal ASCII DXF reader: LINE, CIRCLE, ARC, LWPOLYLINE, POLYLINE, SPLINE, ELLIPSE. */
export function parseDXF(text: string): SketchEntity[] {
const lines = text.split(/\r?\n/);
const pairs: [number, string][] = [];
for (let i = 0; i + 1 < lines.length; i += 2) pairs.push([parseInt(lines[i].trim(), 10), lines[i + 1].trim()]);
const start = pairs.findIndex((p, i) => p[0] === 2 && p[1] === "ENTITIES" && pairs[i - 1]?.[1] === "SECTION");
if (start < 0) return [];
const out: SketchEntity[] = [];
let i = start + 1;
const num = (codes: [number, string][], c: number, d = 0) => Number(codes.find((x) => x[0] === c)?.[1] ?? d);
while (i < pairs.length && !(pairs[i][0] === 0 && pairs[i][1] === "ENDSEC")) {
if (pairs[i][0] !== 0) {
i++;
continue;
}
const type = pairs[i][1];
const codes: [number, string][] = [];
i++;
while (i < pairs.length && pairs[i][0] !== 0) codes.push(pairs[i++]);
if (type === "LINE") out.push({ id: uid(), kind: "line", a: [num(codes, 10), num(codes, 20)], b: [num(codes, 11), num(codes, 21)] });
else if (type === "CIRCLE") out.push({ id: uid(), kind: "circle", center: [num(codes, 10), num(codes, 20)], radius: num(codes, 40) });
else if (type === "ARC") {
const c: [number, number] = [num(codes, 10), num(codes, 20)];
const r = num(codes, 40);
const a0 = (num(codes, 50) * Math.PI) / 180;
let a1 = (num(codes, 51) * Math.PI) / 180;
if (a1 <= a0) a1 += Math.PI * 2;
const at = (t: number): [number, number] => [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)];
out.push({ id: uid(), kind: "arc", a: at(a0), m: at((a0 + a1) / 2), b: at(a1) });
} else if (type === "ELLIPSE") {
const mx = num(codes, 11);
const my = num(codes, 21);
const rx = Math.hypot(mx, my);
out.push({ id: uid(), kind: "ellipse", center: [num(codes, 10), num(codes, 20)], rx, ry: rx * num(codes, 40, 1), rotation: Math.atan2(my, mx) });
} else if (type === "LWPOLYLINE") {
const xs = codes.filter((c) => c[0] === 10).map((c) => Number(c[1]));
const ys = codes.filter((c) => c[0] === 20).map((c) => Number(c[1]));
const closed = (num(codes, 70) & 1) === 1;
const pts = xs.map((x, k) => [x, ys[k]] as [number, number]);
if (pts.length >= 2) out.push({ id: uid(), kind: "polyline", points: pts, closed });
} else if (type === "SPLINE") {
const fx = codes.filter((c) => c[0] === 11).map((c) => Number(c[1]));
const fy = codes.filter((c) => c[0] === 21).map((c) => Number(c[1]));
const cx = codes.filter((c) => c[0] === 10).map((c) => Number(c[1]));
const cy = codes.filter((c) => c[0] === 20).map((c) => Number(c[1]));
const closed = (num(codes, 70) & 1) === 1;
if (fx.length >= 2) out.push({ id: uid(), kind: "spline", points: fx.map((x, k) => [x, fy[k]]), closed, mode: "fit" });
else if (cx.length >= 2) out.push({ id: uid(), kind: "spline", points: cx.map((x, k) => [x, cy[k]]), closed, mode: "control" });
} else if (type === "POLYLINE") {
const closed = (num(codes, 70) & 1) === 1;
const pts: [number, number][] = [];
while (i < pairs.length && pairs[i][1] === "VERTEX") {
i++;
const v: [number, string][] = [];
while (i < pairs.length && pairs[i][0] !== 0) v.push(pairs[i++]);
pts.push([num(v, 10), num(v, 20)]);
}
if (pts.length >= 2) out.push({ id: uid(), kind: "polyline", points: pts, closed });
}
}
return out;
}
// -------------------------------------------------------------------- OBJ
/** OBJ (triangles/polygons) → binary STL, so the kernel can import it. */
export function objToStl(text: string): Uint8Array {
const v: number[][] = [];
const tris: number[][] = [];
for (const line of text.split(/\r?\n/)) {
const p = line.trim().split(/\s+/);
if (p[0] === "v") v.push([Number(p[1]), Number(p[2]), Number(p[3])]);
else if (p[0] === "f") {
const idx = p.slice(1).map((s) => {
const n = parseInt(s.split("/")[0], 10);
return n < 0 ? v.length + n : n - 1;
});
for (let k = 1; k + 1 < idx.length; k++) tris.push([idx[0], idx[k], idx[k + 1]]);
}
}
if (!tris.length) throw new Error("No faces in the OBJ file");
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; // normal left as zero; readers recompute it
for (const k of t) {
for (let c = 0; c < 3; c++) dv.setFloat32(o + c * 4, v[k][c], true);
o += 12;
}
o += 2;
}
return new Uint8Array(buf);
}
function toBase64(bytes: Uint8Array): string {
let s = "";
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s);
}
+408
View File
@@ -0,0 +1,408 @@
// SVG → sketch curves. Lines stay lines, circular arcs become arcs, circles /
// ellipses / rectangles become those shapes (when not skewed), and Bézier or
// elliptical curves become splines through points on them. Units follow the
// SVG's width/viewBox (mm, cm, in, pt, px); y is flipped so up stays up, and
// the drawing is centred on the sketch origin.
//
// Self-contained (no DOM), so it works in tests and workers alike.
import type { SketchEntity, Vec2 } from "../doc/types";
import { uid } from "../sketch/edit";
/** 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];
const I: M = [1, 0, 0, 1, 0, 0];
const mul = (p: M, q: M): M => [p[0] * q[0] + p[2] * q[1], p[1] * q[0] + p[3] * q[1], p[0] * q[2] + p[2] * q[3], p[1] * q[2] + p[3] * q[3], p[0] * q[4] + p[2] * q[5] + p[4], p[1] * q[4] + p[3] * q[5] + p[5]];
const ap = (m: M, [x, y]: Vec2): Vec2 => [m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]];
/** Rotation + uniform scale (+ mirror) only: circles stay circles. */
function similarity(m: M): { k: number; rot: number } | null {
const k1 = Math.hypot(m[0], m[1]);
const k2 = Math.hypot(m[2], m[3]);
const dotp = m[0] * m[2] + m[1] * m[3];
if (Math.abs(k1 - k2) > 1e-9 * Math.max(k1, k2) || Math.abs(dotp) > 1e-9 * k1 * k2) return null;
return { k: k1, rot: Math.atan2(m[1], m[0]) };
}
function parseTransform(s: string | undefined): M {
let m = I;
if (!s) return m;
for (const [, fn, args] of s.matchAll(/(\w+)\s*\(([^)]*)\)/g)) {
const v = nums(args);
let t: M = I;
switch (fn) {
case "matrix":
if (v.length === 6) t = v as M;
break;
case "translate":
t = [1, 0, 0, 1, v[0] ?? 0, v[1] ?? 0];
break;
case "scale":
t = [v[0] ?? 1, 0, 0, v[1] ?? v[0] ?? 1, 0, 0];
break;
case "rotate": {
const a = ((v[0] ?? 0) * Math.PI) / 180;
const r: M = [Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0];
t = v.length >= 3 ? mul(mul([1, 0, 0, 1, v[1], v[2]], r), [1, 0, 0, 1, -v[1], -v[2]]) : r;
break;
}
case "skewX":
t = [1, 0, Math.tan(((v[0] ?? 0) * Math.PI) / 180), 1, 0, 0];
break;
case "skewY":
t = [1, Math.tan(((v[0] ?? 0) * Math.PI) / 180), 0, 1, 0, 0];
break;
}
m = mul(m, t);
}
return m;
}
function nums(s: string): number[] {
return (s.match(/[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? []).map(Number);
}
// ---------------------------------------------------------------- XML
interface El {
name: string;
attrs: Record<string, string>;
children: El[];
}
/** Tiny XML reader: elements and attributes only (enough for SVG geometry). */
function parseXml(text: string): El {
const root: El = { name: "#root", attrs: {}, children: [] };
const stack = [root];
const src = text.replace(/<!--[\s\S]*?-->/g, "").replace(/<!\[CDATA\[[\s\S]*?\]\]>/g, "").replace(/<\?[\s\S]*?\?>/g, "").replace(/<!DOCTYPE[\s\S]*?>/gi, "");
for (const [, close, name, rest, selfClose] of src.matchAll(/<(\/?)([\w:.-]+)([^>]*?)(\/?)>/g)) {
if (close) {
if (stack.length > 1) stack.pop();
continue;
}
const attrs: Record<string, string> = {};
for (const [, k, , v1, v2] of rest.matchAll(/([\w:.-]+)\s*=\s*("([^"]*)"|'([^']*)')/g)) attrs[k] = v1 ?? v2 ?? "";
// style="stroke:…; transform:…" isn't geometry, except display:none.
const el: El = { name: name.replace(/^svg:/, ""), attrs, children: [] };
stack[stack.length - 1].children.push(el);
if (!selfClose) stack.push(el);
}
return root;
}
// ---------------------------------------------------------------- units
const UNIT_MM: Record<string, number> = { mm: 1, cm: 10, in: 25.4, pt: 25.4 / 72, pc: 25.4 / 6, px: 25.4 / 96, "": 25.4 / 96 };
function lengthMM(s: string | undefined): number | null {
const m = s?.trim().match(/^([-+]?[\d.]+(?:e[-+]?\d+)?)\s*(mm|cm|in|pt|pc|px)?$/i);
return m ? Number(m[1]) * UNIT_MM[(m[2] ?? "").toLowerCase()] : null;
}
// ---------------------------------------------------------------- import
export interface SvgImport {
entities: SketchEntity[];
/** Size of the drawing in mm. */
size: Vec2;
}
export function parseSVG(text: string): SvgImport {
const doc = parseXml(text);
const svg = findFirst(doc, "svg");
if (!svg) throw new Error("Not an SVG file");
// User units → mm, from width + viewBox (no width: 96 px per inch).
const vb = svg.attrs.viewBox ? nums(svg.attrs.viewBox) : null;
const w = lengthMM(svg.attrs.width);
const h = lengthMM(svg.attrs.height);
// Without a viewBox one user unit is one CSS pixel; with one, width (or height) sets the scale.
let k = UNIT_MM.px;
if (vb && vb.length === 4 && vb[2] > 0 && vb[3] > 0) k = w !== null ? w / vb[2] : h !== null ? h / vb[3] : UNIT_MM.px;
const [kx, ky] = [k, k];
const ox = vb?.[0] ?? 0;
const oy = vb?.[1] ?? 0;
// SVG y points down; the sketch's y points up.
const base: M = mul([kx, 0, 0, -ky, 0, 0], [1, 0, 0, 1, -ox, -oy]);
const out: SketchEntity[] = [];
walk(svg, base, out);
if (!out.length) throw new Error("No shapes found (text has to be converted to paths first)");
// Centre on the origin.
const pts = out.flatMap(samplePoints);
const lo: Vec2 = [Math.min(...pts.map((p) => p[0])), Math.min(...pts.map((p) => p[1]))];
const hi: Vec2 = [Math.max(...pts.map((p) => p[0])), Math.max(...pts.map((p) => p[1]))];
const c: Vec2 = [(lo[0] + hi[0]) / 2, (lo[1] + hi[1]) / 2];
return { entities: out.map((e) => shift(e, -c[0], -c[1])), size: [hi[0] - lo[0], hi[1] - lo[1]] };
}
function findFirst(el: El, name: string): El | null {
if (el.name === name) return el;
for (const c of el.children) {
const f = findFirst(c, name);
if (f) return f;
}
return null;
}
const SKIP = new Set(["defs", "clipPath", "mask", "symbol", "marker", "pattern", "style", "title", "desc", "metadata", "text", "linearGradient", "radialGradient", "filter", "image"]);
function walk(el: El, parent: M, out: SketchEntity[]): void {
for (const c of el.children) {
if (SKIP.has(c.name) || /display\s*:\s*none/.test(c.attrs.style ?? "") || c.attrs.display === "none") continue;
const m = mul(parent, parseTransform(c.attrs.transform));
const n = (k: string, d = 0) => (c.attrs[k] !== undefined ? Number(nums(c.attrs[k])[0] ?? d) : d);
switch (c.name) {
case "g":
case "svg":
case "a":
case "switch":
walk(c, c.name === "svg" ? mul(m, [1, 0, 0, 1, n("x"), n("y")]) : m, out);
break;
case "path":
out.push(...pathEntities(c.attrs.d ?? "", m));
break;
case "line":
out.push(line(ap(m, [n("x1"), n("y1")]), ap(m, [n("x2"), n("y2")])));
break;
case "polyline":
case "polygon": {
const v = nums(c.attrs.points ?? "");
const p: Vec2[] = [];
for (let i = 0; i + 1 < v.length; i += 2) p.push(ap(m, [v[i], v[i + 1]]));
for (let i = 0; i + 1 < p.length; i++) out.push(line(p[i], p[i + 1]));
if (c.name === "polygon" && p.length > 2) out.push(line(p[p.length - 1], p[0]));
break;
}
case "rect": {
const [x, y, w, h] = [n("x"), n("y"), n("width"), n("height")];
if (w <= 0 || h <= 0) break;
const rx = Math.min(n("rx", n("ry")), w / 2);
const ry = Math.min(n("ry", rx), h / 2);
const sim = similarity(m);
if (!rx && !ry && sim) {
const ctr = ap(m, [x + w / 2, y + h / 2]);
out.push({ id: uid(), kind: "rect", center: ctr, w: w * sim.k, h: h * sim.k, rotation: Math.atan2(m[1], m[0]) });
} else {
// Rounded (or skewed): as a path.
const d = rx || ry
? `M${x + rx},${y}H${x + w - rx}A${rx},${ry} 0 0 1 ${x + w},${y + ry}V${y + h - ry}A${rx},${ry} 0 0 1 ${x + w - rx},${y + h}H${x + rx}A${rx},${ry} 0 0 1 ${x},${y + h - ry}V${y + ry}A${rx},${ry} 0 0 1 ${x + rx},${y}Z`
: `M${x},${y}H${x + w}V${y + h}H${x}Z`;
out.push(...pathEntities(d, m));
}
break;
}
case "circle":
case "ellipse": {
const cx = n("cx");
const cy = n("cy");
const rx = c.name === "circle" ? n("r") : n("rx");
const ry = c.name === "circle" ? n("r") : n("ry", rx);
if (rx <= 0 || ry <= 0) break;
const sim = similarity(m);
const ctr = ap(m, [cx, cy]);
if (sim && Math.abs(rx - ry) < 1e-12) out.push({ id: uid(), kind: "circle", center: ctr, radius: rx * sim.k });
else if (sim) out.push({ id: uid(), kind: "ellipse", center: ctr, rx: rx * sim.k, ry: ry * sim.k, rotation: sim.rot });
else out.push(closedSpline(Array.from({ length: 24 }, (_, i) => ap(m, [cx + rx * Math.cos((i / 24) * Math.PI * 2), cy + ry * Math.sin((i / 24) * Math.PI * 2)]))));
break;
}
}
}
}
// ---------------------------------------------------------------- paths
/** One SVG path's curves. */
export function pathEntities(d: string, m: M = I): SketchEntity[] {
const out: SketchEntity[] = [];
const toks = d.match(/[a-df-z]|[-+]?(?:\d*\.\d+|\d+\.?)(?:e[-+]?\d+)?/gi) ?? [];
let i = 0;
let cmd = "";
let cur: Vec2 = [0, 0];
let start: Vec2 = [0, 0];
let lastCtrl: Vec2 | null = null;
let lastQ: Vec2 | null = null;
const num = () => Number(toks[i++]);
const more = () => i < toks.length && !/^[a-z]$/i.test(toks[i]);
const P = (p: Vec2) => ap(m, p);
const sim = similarity(m);
while (i < toks.length) {
if (/^[a-z]$/i.test(toks[i])) cmd = toks[i++];
const rel = cmd === cmd.toLowerCase();
const R = (p: Vec2): Vec2 => (rel ? [cur[0] + p[0], cur[1] + p[1]] : p);
const C = cmd.toUpperCase();
if (C === "Z") {
if (Math.hypot(cur[0] - start[0], cur[1] - start[1]) > 1e-12) out.push(line(P(cur), P(start)));
cur = start;
lastCtrl = lastQ = null;
if (!more()) continue;
cmd = rel ? "l" : "L";
continue;
}
if (!more()) break;
switch (C) {
case "M": {
cur = R([num(), num()]);
start = cur;
cmd = rel ? "l" : "L";
lastCtrl = lastQ = null;
continue;
}
case "L":
case "H":
case "V": {
const p: Vec2 = C === "L" ? R([num(), num()]) : C === "H" ? [rel ? cur[0] + num() : num(), cur[1]] : [cur[0], rel ? cur[1] + num() : num()];
if (Math.hypot(p[0] - cur[0], p[1] - cur[1]) > 1e-12) out.push(line(P(cur), P(p)));
cur = p;
lastCtrl = lastQ = null;
break;
}
case "C":
case "S": {
const c1: Vec2 = C === "C" ? R([num(), num()]) : lastCtrl ? [2 * cur[0] - lastCtrl[0], 2 * cur[1] - lastCtrl[1]] : cur;
const c2 = R([num(), num()]);
const p = R([num(), num()]);
out.push(bezierSpline([cur, c1, c2, p].map(P)));
lastCtrl = c2;
lastQ = null;
cur = p;
break;
}
case "Q":
case "T": {
const q: Vec2 = C === "Q" ? R([num(), num()]) : lastQ ? [2 * cur[0] - lastQ[0], 2 * cur[1] - lastQ[1]] : cur;
const p = R([num(), num()]);
// Quadratic → cubic.
const c1: Vec2 = [cur[0] + (2 / 3) * (q[0] - cur[0]), cur[1] + (2 / 3) * (q[1] - cur[1])];
const c2: Vec2 = [p[0] + (2 / 3) * (q[0] - p[0]), p[1] + (2 / 3) * (q[1] - p[1])];
out.push(bezierSpline([cur, c1, c2, p].map(P)));
lastQ = q;
lastCtrl = null;
cur = p;
break;
}
case "A": {
const rx0 = Math.abs(num());
const ry0 = Math.abs(num());
const phi = (num() * Math.PI) / 180;
const large = num() !== 0;
const sweep = num() !== 0;
const p = R([num(), num()]);
out.push(...arcEntities(cur, p, rx0, ry0, phi, large, sweep, m, sim));
cur = p;
lastCtrl = lastQ = null;
break;
}
default:
i++;
}
}
return out;
}
/** SVG endpoint arc → one arc (circular, under a similarity) or a spline through it. */
function arcEntities(a: Vec2, b: Vec2, rx: number, ry: number, phi: number, large: boolean, sweep: boolean, m: M, sim: { k: number } | null): SketchEntity[] {
if (Math.hypot(b[0] - a[0], b[1] - a[1]) < 1e-12) return [];
if (!rx || !ry) return [line(ap(m, a), ap(m, b))];
// Endpoint → centre parameterisation (SVG spec, F.6.5).
const cs = Math.cos(phi);
const sn = Math.sin(phi);
const dx = (a[0] - b[0]) / 2;
const dy = (a[1] - b[1]) / 2;
const x1 = cs * dx + sn * dy;
const y1 = -sn * dx + cs * dy;
const lam = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
if (lam > 1) {
rx *= Math.sqrt(lam);
ry *= Math.sqrt(lam);
}
const num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
const den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
const co = (large !== sweep ? 1 : -1) * Math.sqrt(Math.max(0, num / den));
const cx1 = (co * rx * y1) / ry;
const cy1 = (-co * ry * x1) / rx;
const cx = cs * cx1 - sn * cy1 + (a[0] + b[0]) / 2;
const cy = sn * cx1 + cs * cy1 + (a[1] + b[1]) / 2;
const ang = (ux: number, uy: number, vx: number, vy: number) => Math.atan2(ux * vy - uy * vx, ux * vx + uy * vy);
const t1 = ang(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry);
let dt = ang((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry);
if (!sweep && dt > 0) dt -= 2 * Math.PI;
if (sweep && dt < 0) dt += 2 * Math.PI;
const at = (t: number): Vec2 => ap(m, [cx + rx * Math.cos(t) * cs - ry * Math.sin(t) * sn, cy + rx * Math.cos(t) * sn + ry * Math.sin(t) * cs]);
if (sim && Math.abs(rx - ry) < 1e-9 * rx) {
// A full-ish circle is split in two so each arc's three points stay well apart.
if (Math.abs(dt) > Math.PI * 1.5) {
const h = dt / 2;
return [arc3(at(t1), at(t1 + h / 2), at(t1 + h)), arc3(at(t1 + h), at(t1 + h * 1.5), at(t1 + dt))];
}
return [arc3(at(t1), at(t1 + dt / 2), at(t1 + dt))];
}
const n = Math.max(4, Math.ceil((Math.abs(dt) / (Math.PI / 2)) * 4));
return [{ id: uid(), kind: "spline", mode: "fit", closed: false, points: Array.from({ length: n + 1 }, (_, k) => at(t1 + (dt * k) / n)) }];
}
/** A cubic Bézier as a fit spline through points on it (ends exact). */
function bezierSpline([p0, p1, p2, p3]: Vec2[]): SketchEntity {
// Straight "curves" stay lines.
const off = (p: Vec2) => {
const dx = p3[0] - p0[0];
const dy = p3[1] - p0[1];
const l = Math.hypot(dx, dy) || 1;
return Math.abs((p[0] - p0[0]) * dy - (p[1] - p0[1]) * dx) / l;
};
if (off(p1) < 1e-9 && off(p2) < 1e-9) return line(p0, p3);
const N = 8;
const pts = Array.from({ length: N + 1 }, (_, k): Vec2 => {
const t = k / N;
const u = 1 - t;
return [u * u * u * p0[0] + 3 * u * u * t * p1[0] + 3 * u * t * t * p2[0] + t * t * t * p3[0], u * u * u * p0[1] + 3 * u * u * t * p1[1] + 3 * u * t * t * p2[1] + t * t * t * p3[1]];
});
return { id: uid(), kind: "spline", mode: "fit", closed: false, points: pts };
}
const line = (a: Vec2, b: Vec2): SketchEntity => ({ id: uid(), kind: "line", a, b });
const arc3 = (a: Vec2, m: Vec2, b: Vec2): SketchEntity => ({ id: uid(), kind: "arc", a, m, b });
const closedSpline = (points: Vec2[]): SketchEntity => ({ id: uid(), kind: "spline", mode: "fit", closed: true, points });
function samplePoints(e: SketchEntity): Vec2[] {
switch (e.kind) {
case "line":
return [e.a, e.b];
case "arc":
return [e.a, e.m, e.b];
case "circle":
return [[e.center[0] - e.radius, e.center[1] - e.radius], [e.center[0] + e.radius, e.center[1] + e.radius]];
case "ellipse": {
const r = Math.max(e.rx, e.ry);
return [[e.center[0] - r, e.center[1] - r], [e.center[0] + r, e.center[1] + r]];
}
case "rect": {
const c = Math.cos(e.rotation);
const s = Math.sin(e.rotation);
return [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([u, v]): Vec2 => [e.center[0] + (u * e.w * c - v * e.h * s) / 2, e.center[1] + (u * e.w * s + v * e.h * c) / 2]);
}
case "spline":
case "polyline":
return e.points;
default:
return [];
}
}
function shift(e: SketchEntity, dx: number, dy: number): SketchEntity {
const s = (p: Vec2): Vec2 => [p[0] + dx, p[1] + dy];
switch (e.kind) {
case "line":
return { ...e, a: s(e.a), b: s(e.b) };
case "arc":
return { ...e, a: s(e.a), m: s(e.m), b: s(e.b) };
case "circle":
case "ellipse":
case "rect":
case "polygon":
return { ...e, center: s(e.center) };
case "spline":
case "polyline":
return { ...e, points: e.points.map(s) };
default:
return e;
}
}
+75
View File
@@ -0,0 +1,75 @@
import type { Feature } from "../doc/types";
import type { Envelope, ExportFormat, RegenResult, Request, Response } from "./protocol";
/** Promise-based wrapper around the kernel worker. */
export class KernelClient {
private worker: Worker;
private nextId = 1;
private pending = new Map<number, (r: Response) => void>();
readonly ready: Promise<void>;
// 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;
constructor() {
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.ready = this.call({ type: "init" }).then((r) => {
if (r.type === "error") throw new Error(r.message);
});
}
/** Told when the kernel starts and stops being busy (to show a busy indicator). */
onBusy: ((busy: boolean) => void) | null = null;
private call(msg: Request): Promise<Response> {
const id = this.nextId++;
if (this.pending.size === 0) this.onBusy?.(true);
return new Promise((resolve) => {
this.pending.set(id, (r) => {
resolve(r);
if (this.pending.size === 0 && !this.regenQueued) this.onBusy?.(false);
});
this.worker.postMessage({ id, msg } satisfies Envelope<Request>);
});
}
/**
* 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> {
return new Promise((resolve) => {
if (this.regenRunning) {
this.regenQueued?.resolve(null);
this.regenQueued = { features, resolve };
return;
}
this.runRegen(features, resolve);
});
}
private async runRegen(features: Feature[], resolve: (r: RegenResult | null) => void) {
this.regenRunning = true;
await this.ready;
const r = await this.call({ type: "regenerate", features });
resolve(r.type === "regenerated" ? r.result : null);
if (r.type === "error") console.error(r.message);
this.regenRunning = false;
const q = this.regenQueued;
this.regenQueued = null;
if (q) this.runRegen(q.features, q.resolve);
}
async export(features: Feature[], format: ExportFormat, bodies?: string[]): Promise<Blob> {
await this.ready;
const r = await this.call({ type: "export", features, format, bodies });
if (r.type === "exported") return r.blob;
throw new Error(r.type === "error" ? r.message : "Export failed");
}
}
+1154
View File
File diff suppressed because it is too large Load Diff
+472
View File
@@ -0,0 +1,472 @@
// Direct face editing with booleans: offset a face (neighbours extend along their
// own surfaces), move/tilt a flat face, delete a face (neighbours close the gap).
//
// The trick: near face F the body equals E ∩ "behind F", where E is the
// intersection of the *extended* neighbouring surfaces — each taken on the side
// 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, makeBSplineApproximation, makeCylinder, makeLine, makePolygon, measureArea, measureVolume, cast, Vector, type Face, type Shape3D } from "replicad";
import type { PlaneDef, Vec3 } from "../doc/types";
import { add, cross, dist, dot, len, norm, scale, sub, xDirFor } from "../geom";
interface Cyl {
c: Vec3;
a: Vec3;
r: number;
/** +1: material inside (boss), −1: material outside (hole). */
s: number;
}
const tup = (v: { toTuple(): number[] }) => v.toTuple() as Vec3;
function sizeOf(body: Shape3D): number {
const bb = body.boundingBox;
return Math.hypot(bb.width, bb.height, bb.depth) || 1;
}
// 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;
const vary = (L: number) => L * (1 + 0.0137 * (jitter = (jitter + 1) % 37));
/** Solid on the positive side of a plane, big enough for `L`. */
export function halfSpace(plane: PlaneDef, L0: number): Shape3D {
const L = vary(L0);
const x = norm(plane.xDir);
const y = cross(plane.normal, x);
const o = plane.origin;
const corner = (u: number, v: number): Vec3 => add(o, add(scale(x, u * L), scale(y, v * L)));
// Off-centre on purpose (see `vary`).
const face = makePolygon([corner(-1.09, -0.93), corner(0.97, -0.93), corner(0.97, 1.05), corner(-1.09, 1.05)]);
return basicFaceExtrusion(face, new Vector(plane.normal).multiply(L));
}
/** Axis, radius and orientation of a cylindrical face (from surface samples). */
export function cylinderOf(f: Face): Cyl | null {
if (f.geomType !== "CYLINDRE") return null;
// pointOnSurface takes UV normalised to the face's bounds.
const at = (u: number, v: number) => {
const p = tup(f.pointOnSurface(u, v));
return { p, n: norm(tup(f.normalAt(p))) };
};
// Two points at the same height, apart around the axis.
const s1 = at(0.25, 0.5);
const s2 = at(0.6, 0.5);
const ax = cross(s1.n, s2.n);
if (len(ax) < 1e-9) return null;
const a = norm(ax);
const dn = len(sub(s1.n, s2.n));
const r = len(sub(s1.p, s2.p)) / (dn || 1);
// Normals point away from the axis on a boss, towards it in a hole.
const cOut = sub(s1.p, scale(s1.n, r));
const cIn = add(s1.p, scale(s1.n, r));
const out2 = sub(s2.p, scale(s2.n, r));
const s = dist(cOut, out2) < dist(cIn, add(s2.p, scale(s2.n, r))) ? 1 : -1;
const c = s > 0 ? cOut : cIn;
return { c, a, r, s };
}
/**
* A point that lies on face F itself (its center may be off the face — e.g. on
* a cylinder's axis or inside a ring) and the outward normal there.
*/
export function onFace(body: Shape3D, F: Face): { p: Vec3; n: Vec3 } {
// Curved faces: the middle of the face's own parameter range sits well inside
// it (a fillet's mid-arc), away from the edges where its neighbours start.
if (F.geomType !== "PLANE") {
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) {
// 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);
let area = -1;
for (let k = 0; k < t.trianglesIndexes.length; k += 3) {
const [a, b, c] = [0, 1, 2].map((j) => v(t!.trianglesIndexes[k + j]));
const ar = len(cross(sub(b, a), sub(c, a)));
if (ar > area) {
area = ar;
best = scale(add(add(a, b), c), 1 / 3);
}
}
return { p: best, n: norm(tup(F.normalAt(best))) };
}
const p = tup(F.pointOnSurface(0.5, 0.5));
return { p, n: norm(tup(F.normalAt(p))) };
}
/** The exact plane of a flat face (a surface point, not a mesh point). */
export function planeOf(F: Face): PlaneDef {
const origin = tup(F.pointOnSurface(0.5, 0.5));
const normal = norm(tup(F.normalAt(origin)));
return { origin, normal, xDir: xDirFor(normal) };
}
function infiniteCylinder(cy: Cyl, r: number, L0: number): Shape3D {
const L = vary(L0);
return makeCylinder(r, 2 * L, sub(cy.c, scale(cy.a, L)), cy.a) as Shape3D;
}
/** Faces sharing an edge with F. */
function neighbours(body: Shape3D, F: Face): Face[] {
const edges = F.edges;
return body.faces.filter((g) => !g.isSame(F) && g.edges.some((e) => edges.some((fe) => fe.isSame(e))));
}
/**
* 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 {
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);
const keep: Shape3D[] = [];
const remove: Shape3D[] = [];
for (const g of neighbours(body, F)) {
if (g.geomType === "PLANE") {
const { origin: p, normal: n } = planeOf(g);
// Keep the side of g's plane that contains q.
const side = dot(sub(q, p), n) < 0 ? scale(n, -1) : n;
keep.push(halfSpace({ origin: p, normal: side, xDir: xDirFor(side) }, L));
} else if (g.geomType === "CYLINDRE") {
const cy = cylinderOf(g);
if (!cy) continue;
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));
}
// Other surface types are left unbounded (rare next to a face being edited).
}
let E = keep.length ? keep[0] : big();
for (const k of keep.slice(1)) E = E.intersect(k);
for (const r of remove) E = E.cut(r);
return E;
}
/**
* Replace flat face F's plane with `to` (move/tilt); neighbours extend or trim.
* Round blends (fillets) on F are taken off first and put back at the same
* radius afterwards — extending a fillet's cylinder through the body would
* carve a tunnel into it.
*/
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);
if (blends.length) {
try {
return aroundBlends(body, F, blends, to);
} catch {
// Couldn't rebuild the fillets: fall back to editing straight through them.
}
}
return replacePlaneDirect(body, F, to);
}
interface Blend {
r: number;
/** The two flat faces the fillet runs between; `null` stands for the face being moved. */
sides: [PlaneDef | null, PlaneDef];
/** The blend's own signature, to find it again after earlier edits. */
sig: { center: Vec3; area: number };
}
/** Is cylinder `cy` tangent to plane `pl` (a fillet's support face)? */
function tangentTo(cy: Cyl, pl: PlaneDef, tol: number): boolean {
return Math.abs(dot(cy.a, pl.normal)) < 1e-6 && Math.abs(Math.abs(dot(sub(cy.c, pl.origin), pl.normal)) - cy.r) < cy.r * 1e-4 + tol;
}
/**
* Fillets touching F: round faces next to it that run between two flat faces
* (F itself may be one of them). They get taken off and put back around an edit.
*/
function blendsOf(body: Shape3D, F: Face): Blend[] {
const tol = sizeOf(body) * 1e-7;
const out: Blend[] = [];
for (const g of neighbours(body, F)) {
if (g.geomType !== "CYLINDRE") continue;
const cy = cylinderOf(g);
if (!cy) continue;
const supports = neighbours(body, g).filter((h) => h.geomType === "PLANE" && tangentTo(cy, planeOf(h), tol));
if (supports.length !== 2) continue;
const planes = supports.map((h) => (h.isSame(F) ? null : planeOf(h)));
// Keep F (if it is one) first.
const sides = (planes[1] === null ? [planes[1], planes[0]] : planes) as [PlaneDef | null, PlaneDef];
if (sides[1] === null) continue;
out.push({ r: cy.r, sides, sig: { center: tup(g.center), area: measureArea(g) } });
}
return out;
}
function aroundBlends(body: Shape3D, F: Face, blends: Blend[], to: PlaneDef): Shape3D {
const fp = planeOf(F);
let b = body;
// 1. Take the fillets off (their faces meet in sharp edges again).
for (const bl of blends) {
const g = findFace(b, (h) => h.geomType === "CYLINDRE", bl.sig.center, bl.sig.area);
if (!g) throw new Error("blend lost");
b = deleteFace(b, g);
}
// 2. Move the face, now bounded by flat neighbours only.
const F1 = findFace(b, (h) => h.geomType === "PLANE" && Math.abs(dot(planeOf(h).normal, fp.normal)) > 1 - 1e-9 && Math.abs(dot(sub(planeOf(h).origin, fp.origin), fp.normal)) < sizeOf(b) * 1e-7, tup(F.center), measureArea(F));
if (!F1) throw new Error("face lost");
b = replacePlaneDirect(b, F1, to);
// 3. Round the edges between each fillet's two faces again, same radius.
const moved: PlaneDef = { ...to, normal: norm(to.normal) };
const tol = sizeOf(b) * 1e-6;
const on = (m: Vec3, pl: PlaneDef) => Math.abs(dot(sub(m, pl.origin), norm(pl.normal))) < tol;
for (const bl of blends) {
const p1 = bl.sides[0] ?? moved;
const p2 = bl.sides[1];
const edges = b.edges.filter((e) => {
const m = tup(e.pointAt(0.5));
return on(m, p1) && on(m, p2);
});
if (!edges.length) throw new Error("edge lost");
b = b.fillet(bl.r, (finder) => finder.inList(edges)) as Shape3D;
}
return sanity(body, b);
}
/** The face that passes `ok`, nearest a remembered centre (and area). */
function findFace(body: Shape3D, ok: (f: Face) => boolean, center: Vec3, area: number): Face | null {
let best: { f: Face; s: number } | null = null;
const size = Math.sqrt(area) || 1;
for (const f of body.faces) {
if (!ok(f)) continue;
const s = dist(tup(f.center), center) / size + Math.abs(Math.log((measureArea(f) + 1e-12) / (area + 1e-12)));
if (!best || s < best.s) best = { f, s };
}
return best?.f ?? null;
}
function replacePlaneDirect(body: Shape3D, F: Face, to: PlaneDef): Shape3D {
const L = sizeOf(body) * 4;
const { p, n } = onFace(body, F);
const q = sub(p, scale(n, sizeOf(body) * 1e-3));
const E = extendedRegion(body, F, q, L);
const behind = (pl: PlaneDef) => halfSpace({ ...pl, normal: scale(pl.normal, -1), xDir: xDirFor(scale(pl.normal, -1)) }, L);
const front = (pl: PlaneDef) => halfSpace(pl, L);
const old = planeOf(F);
const neu: PlaneDef = { ...to, normal: norm(to.normal), xDir: xDirFor(norm(to.normal)) };
let out = body;
const grow = E.intersect(front(old)).intersect(behind(neu));
if (!isEmpty(grow)) out = out.fuse(grow);
const shrink = E.intersect(behind(old)).intersect(front(neu));
if (!isEmpty(shrink)) out = out.cut(shrink);
return sanity(body, out);
}
/**
* Neighbours that the half-space trick can't extend: curved surfaces other
* than cylinders standing straight on F (cones, lofted and revolved sides…).
*/
function needsContinuation(body: Shape3D, F: Face): boolean {
const n = planeOf(F).normal;
return neighbours(body, F).some((g) => {
if (g.geomType === "PLANE") return false;
if (g.geomType === "CYLINDRE") {
const cy = cylinderOf(g);
// Upright walls, or fillets running along F (taken off and put back).
return !cy || (Math.abs(Math.abs(dot(cy.a, n)) - 1) > 1e-6 && Math.abs(dot(cy.a, n)) > 1e-6);
}
return true;
});
}
/**
* Offset flat face F by d when its neighbours are curved: each point of F's
* outline carries on along its neighbour surface (the way that surface is
* 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).
*/
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, moved the same way for both (halfway between their two estimates).
const m = order.length;
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);
return 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 });
const out = d > 0 ? body.fuse(slab) : body.cut(slab);
return sanity(body, out);
}
/** Offset a face along its normal: flat faces move, cylinders change radius. */
export function offsetFace(body: Shape3D, F: Face, d: number): Shape3D {
if (F.geomType === "PLANE" && needsContinuation(body, F)) {
try {
return offsetByContinuation(body, F, d);
} catch {
// fall through to the plane trick
}
}
if (F.geomType === "PLANE") {
const { origin, normal } = planeOf(F);
return replaceFacePlane(body, F, { origin: add(origin, scale(normal, d)), normal, xDir: xDirFor(normal) });
}
const cy = cylinderOf(F);
if (!cy) throw new Error("Offset works on flat and cylindrical faces");
const r2 = cy.r + cy.s * d;
if (r2 <= 1e-6) throw new Error("That offset would remove the whole round face");
const L = sizeOf(body) * 4;
// q: just inside the material next to the face.
const { p, n } = onFace(body, F);
const q = sub(p, scale(n, sizeOf(body) * 1e-3));
const E = extendedRegion(body, F, q, L);
const ring = infiniteCylinder(cy, Math.max(cy.r, r2), L).cut(infiniteCylinder(cy, Math.min(cy.r, r2), L));
const slab = E.intersect(ring);
if (isEmpty(slab)) throw new Error("Nothing to offset");
return sanity(body, d > 0 ? body.fuse(slab) : body.cut(slab));
}
/** Remove a face; its neighbours extend to close the gap (fillets, chamfers, holes). */
export function deleteFace(body: Shape3D, F: Face): Shape3D {
const L = sizeOf(body) * 4;
const { p, n } = onFace(body, F);
const q = sub(p, scale(n, sizeOf(body) * 1e-3));
// Only fill within the face's own box: the gap a face leaves lies inside it, and
// any slack either falls inside the material or is cut off by a neighbour.
const b = F.boundingBox;
const lo = b.bounds[0] as number[];
const hi = b.bounds[1] as number[];
const pad = sizeOf(body) * 1e-3;
const box = makePolygon([
[lo[0] - pad, lo[1] - pad, lo[2] - pad],
[hi[0] + pad, lo[1] - pad, lo[2] - pad],
[hi[0] + pad, hi[1] + pad, lo[2] - pad],
[lo[0] - pad, hi[1] + pad, lo[2] - pad],
]);
const local = basicFaceExtrusion(box, new Vector([0, 0, hi[2] - lo[2] + 2 * pad]));
const region = extendedRegion(body, F, q, L).intersect(local);
// Still has the face (or a copy of it a hair away): that way doesn't close the gap.
const fn = norm(tup(F.normalAt()));
const gone = (out: Shape3D) =>
!out.faces.some((g) => g.geomType === F.geomType && dot(norm(tup(g.normalAt())), fn) > 0.999 && dist(tup(g.center), tup(F.center)) < sizeOf(body) * 0.02);
// A face on an outside corner (convex fillet, chamfer, hole wall) left material
// out: fill it back in. One in an inside corner (concave fillet) added material:
// take it away. Both are tried; the smallest change that removes the face wins.
const v0 = measureVolume(body);
const tries: { out: Shape3D; change: number }[] = [];
for (const make of [() => body.fuse(region), () => body.cut(region)]) {
try {
const out = unify(make());
// Removing a face never needs new faces: one that adds some cut a new shape in.
if (!isEmpty(out) && gone(out) && out.faces.length < body.faces.length) tries.push({ out, change: Math.abs(measureVolume(out) - v0) });
} catch {
// that way doesn't work here
}
}
if (!tries.length) throw new Error("This face can't be removed — its neighbours don't close the gap");
tries.sort((a, b) => a.change - b.change);
return sanity(body, tries[0].out);
}
/** Merge faces/edges that lie on the same surface (removes imprinted edges). */
export function unify(body: Shape3D): Shape3D {
const oc = getOC();
const u = new oc.ShapeUpgrade_UnifySameDomain(body.wrapped, true, true, false);
// Surfaces rebuilt from samples match the originals only to ~1e-9 relative.
u.SetLinearTolerance(sizeOf(body) * 1e-6);
u.SetAngularTolerance(1e-6);
u.Build();
return cast(u.Shape()) as Shape3D;
}
function isEmpty(s: Shape3D): boolean {
try {
return s.faces.length === 0;
} catch {
return true;
}
}
/** Reject results that exploded (an unbounded region leaked out). */
function sanity(before: Shape3D, after: Shape3D): Shape3D {
if (isEmpty(after)) throw new Error("The result would be empty");
if (sizeOf(after) > sizeOf(before) * 3 + 1) throw new Error("This change can't be made cleanly here (the neighbouring faces don't enclose it)");
return unify(after);
}
+91
View File
@@ -0,0 +1,91 @@
// Freeform cage → OpenCascade shape: each subdivided cage quad becomes one
// 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 { cubicKnots, interpolateGrid } from "../freeform/bspline";
import { isClosed, subdivide, type Cage } from "../freeform/cage";
export interface Thicken {
thickness: number;
side: "up" | "down" | "both";
}
export function cageToShape(cage: Cage, levels = 3, thicken?: Thicken): Shape3D {
if (!cage.faces.length) throw new Error("The freeform has no faces");
const oc = getOC();
const s = subdivide(cage, levels);
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);
const gc: { delete(): void }[] = [sewing];
// Shared by every patch: same size, same uniform parameters.
const k = cubicKnots(N);
const uKnots = new oc.NCollection_Array1_double(1, k.knots.length);
const uMults = new oc.NCollection_Array1_int(1, k.mults.length);
k.knots.forEach((x, i) => uKnots.SetValue(i + 1, x));
k.mults.forEach((x, i) => uMults.SetValue(i + 1, x));
gc.push(uKnots, uMults);
for (const g of s.grids) {
// Our own uniform interpolation: patches with the same border points get
// identical border curves, so they sew exactly.
const poles = interpolateGrid(g.map((row) => row.map((i) => s.points[i])));
const arr = new oc.NCollection_Array2_gp_Pnt(1, N, 1, N);
gc.push(arr);
for (let i = 0; i < N; i++)
for (let j = 0; j < N; j++) {
const p = poles[i][j];
const pt = new oc.gp_Pnt(p[0], p[1], p[2]);
arr.SetValue(i + 1, j + 1, pt);
pt.delete();
}
const surf = new oc.Geom_BSplineSurface(arr, uKnots, uKnots, uMults, uMults, 3, 3, false, false);
const mk = new oc.BRepBuilderAPI_MakeFace(surf, 1e-6);
gc.push(mk);
sewing.Add(mk.Face());
}
sewing.Perform();
const sewed = sewing.SewedShape();
try {
if (isClosed(cage)) {
if (sewed.ShapeType() !== oc.TopAbs_ShapeEnum.TopAbs_SHELL) throw new Error("The freeform surfaces didn't close up into one piece");
const fix = new oc.ShapeFix_Solid();
gc.push(fix);
const solid = cast(fix.SolidFromShell(oc.TopoDS.Shell(sewed)));
return solid as Shape3D;
}
if (thicken && thicken.thickness > 0) return thickenSheet(sewed, thicken);
return cast(sewed) as Shape3D;
} finally {
for (const o of gc) o.delete();
}
}
/** An open sheet → a solid: grown along its normals (up), against them (down) or half each way. */
function thickenSheet(sheet: unknown, { thickness: t, side }: Thicken): Shape3D {
const oc = getOC();
const thick = (d: number): Shape3D => {
const mk = new oc.BRepOffsetAPI_MakeThickSolid();
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;
} finally {
mk.delete();
}
};
if (side === "up") return thick(t);
if (side === "down") return thick(-t);
return thick(t / 2).fuse(thick(-t / 2));
}
function sizeOf(pts: number[][]): number {
let lo = [Infinity, Infinity, Infinity];
let hi = [-Infinity, -Infinity, -Infinity];
for (const p of pts) {
lo = lo.map((v, k) => Math.min(v, p[k]));
hi = hi.map((v, k) => Math.max(v, p[k]));
}
return Math.hypot(hi[0] - lo[0], hi[1] - lo[1], hi[2] - lo[2]) || 1;
}
+84
View File
@@ -0,0 +1,84 @@
// Messages between the main thread and the kernel worker. This file is the
// whole contract: the UI never touches kernel objects directly.
import type { Feature, PlaneDef, SketchEntity, Vec3 } from "../doc/types";
export interface FaceInfo {
center: Vec3;
normal: Vec3;
area: number;
/** OpenCascade surface type: PLANE, CYLINDRE (sic), CONE, SPHERE, BSPLINE_SURFACE… */
type: string;
/** Set for flat faces: the plane a sketch on this face would use. */
plane?: PlaneDef;
}
export interface EdgeInfo {
mid: Vec3;
dir: Vec3;
length: number;
start: Vec3;
end: Vec3;
/** LINE, CIRCLE, ELLIPSE, BSPLINE_CURVE… */
type: string;
}
export interface BodyMesh {
id: string;
name: string;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
/** Triangle ranges (in index units) per face. */
faceGroups: { start: number; count: number; face: number }[];
/** Line-segment vertex pairs for all edges. */
edgePositions: Float32Array;
/** Ranges (in vertex units of edgePositions) per edge. */
edgeGroups: { start: number; count: number; edge: number }[];
faces: FaceInfo[];
edges: EdgeInfo[];
/** Edges with fewer than two faces: the body isn't closed there (not watertight). */
openEdges: number[];
}
/** A construction plane or axis (for an axis, plane.normal is its direction). */
export interface ConstructionInfo {
id: string;
name: string;
plane: PlaneDef;
}
export interface FeatureError {
featureId: string;
message: string;
}
export interface RegenResult {
bodies: BodyMesh[];
/** Current plane of every sketch (sketches on faces follow the face). */
sketchPlanes: Record<string, PlaneDef>;
/** Outline of the face each face-attached sketch sits on (takes part in its regions). */
sketchBoundaries: Record<string, SketchEntity[]>;
planes: ConstructionInfo[];
axes: ConstructionInfo[];
errors: FeatureError[];
ms: number;
}
export type ExportFormat = "stl" | "step";
export type Request =
| { type: "init" }
| { type: "regenerate"; features: Feature[] }
| { type: "export"; features: Feature[]; format: ExportFormat; bodies?: string[] };
export type Response =
| { type: "ready" }
| { type: "regenerated"; result: RegenResult }
| { type: "exported"; blob: Blob }
| { type: "error"; message: string };
export interface Envelope<T> {
id: number;
msg: T;
}
+167
View File
@@ -0,0 +1,167 @@
// Sketch regions → exact OpenCascade geometry (worker only).
import {
addHolesInFace,
assembleWire,
cast,
getOC,
makeBSplineApproximation,
makeCircle,
makeEllipse,
makeFace,
makeLine,
makeThreePointArc,
type Edge,
type Face,
type Wire,
} from "replicad";
import type { PlaneDef, SketchEntity, Vec2 } from "../doc/types";
import { toWorld } from "../geom";
import { entityPrims, evalPrim, isClosedPrim, SPLINE_PER_SPAN, splineSpanAt, splineSpans, type Prim } from "../sketch/curves";
import { arrangement, resolveRegion, type Arrangement, type Loop, type Piece, type RegionRef } from "../sketch/regions";
/** Faces for the referenced regions of a sketch (one face per region, holes included). */
export function regionFaces(entities: SketchEntity[], plane: PlaneDef, refs: RegionRef[]): Face[] {
const arr = arrangement(entities);
return refs.map((ref) => {
const r = resolveRegion(arr, ref);
if (!r) throw new Error("A profile it used no longer exists in its sketch");
const face = makeFace(loopWire(arr, r.outer, plane));
// addHolesInFace orients hole wires correctly (makeFace's holes arg does not).
return r.holes.length ? addHolesInFace(face, r.holes.map((h) => loopWire(arr, h, plane))) : face;
});
}
/** Outer wire of a region (for sweeps/lofts that need a wire). */
export function regionWire(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 loopWire(arr, r.outer, 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");
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));
else if (p.t === "circle") edges.push(makeThreePointArc(w(plane, evalPrim(p, 0)), w(plane, evalPrim(p, 0.5)), w(plane, evalPrim(p, 1))));
else edges.push(exactSpline(p, 0, 1, plane) ?? bspline(Array.from({ length: 65 }, (_, i) => evalPrim(p, i / 64)), plane));
}
}
return assembleWire(edges);
}
function loopWire(arr: Arrangement, loop: Loop, plane: PlaneDef): Wire {
// A loop that is a whole circle/ellipse on its own: use the exact closed curve.
const prims = new Set(loop.pieces.map((r) => arr.pieces[r.piece].prim));
if (prims.size === 1) {
const p = arr.prims[[...prims][0]];
if (p.t === "circle" && isClosedPrim(p)) return assembleWire([makeCircle(p.r, toWorld(plane, p.c), plane.normal)]);
if (p.t === "ellipse" && isClosedPrim(p)) {
const major = p.rx >= p.ry;
const rot = p.rot + (major ? 0 : Math.PI / 2);
const xDir = toWorld({ ...plane, origin: [0, 0, 0] }, [Math.cos(rot), Math.sin(rot)]);
return assembleWire([makeEllipse(Math.max(p.rx, p.ry), Math.min(p.rx, p.ry), toWorld(plane, p.c), plane.normal, xDir)]);
}
}
return assembleWire(loop.pieces.map((r) => pieceEdge(arr, arr.pieces[r.piece], plane)));
}
function pieceEdge(arr: Arrangement, pc: Piece, plane: PlaneDef): Edge {
const p = arr.prims[pc.prim];
const a = pc.poly[0];
const b = pc.poly[pc.poly.length - 1];
switch (p.t) {
case "line":
return makeLine(w(plane, a), w(plane, b));
case "circle":
// Through the (shared) end nodes, so neighbouring pieces meet exactly.
return makeThreePointArc(w(plane, a), w(plane, evalPrim(p, (pc.t0 + pc.t1) / 2)), w(plane, b));
default:
return exactSpline(p, pc.t0, pc.t1, plane, a, b) ?? bspline(pc.poly, plane);
}
}
/**
* The spline exactly as drawn, from parameter t0 to t1: each span of the
* sketch spline is a cubic, so it becomes one Bezier piece of a C1 B-spline —
* no fitting, so no ripples (in revolves and lofts especially).
* `a`/`b` pin the ends onto the arrangement's nodes so neighbours meet.
*/
function exactSpline(p: Prim, t0: number, t1: number, plane: PlaneDef, a?: Vec2, b?: Vec2): Edge | null {
if (p.t !== "spline" || !p.ctrl) return null;
const spans = splineSpans(p.ctrl);
const n = p.pts.length - 1;
if (n !== spans * SPLINE_PER_SPAN) return null;
// Closed pieces can run past the seam (t1 > 1).
const f0 = t0 * spans;
const f1 = t1 * spans;
if (f1 - f0 < 1e-9) return null;
// Span s (wrapping round a closed spline) at local parameter u.
const spanAt = (s: number, u: number): Vec2 => splineSpanAt(p.ctrl!, ((s % spans) + spans) % spans, u);
// Break at the span joints inside [f0, f1].
const cuts = [f0];
for (let k = Math.floor(f0) + 1; k < f1 - 1e-9; k++) if (k > f0 + 1e-9) cuts.push(k);
cuts.push(f1);
const poles: Vec2[] = [];
for (let i = 0; i < cuts.length - 1; i++) {
const [u0, u1] = [cuts[i], cuts[i + 1]];
// A cubic through four of its own points is that cubic: solve for its Bezier.
// (Sampled inside the span, so a joint isn't read from the next span's formula.)
const s = Math.min(Math.floor(u0 + 1e-9), Math.ceil(u1 - 1e-9) - 1);
const q = [0, 1 / 3, 2 / 3, 1].map((x) => spanAt(s, u0 + (u1 - u0) * x - s));
const P0 = q[0];
const P3 = q[3];
const A: Vec2 = [27 * q[1][0] - 8 * P0[0] - P3[0], 27 * q[1][1] - 8 * P0[1] - P3[1]];
const B: Vec2 = [27 * q[2][0] - P0[0] - 8 * P3[0], 27 * q[2][1] - P0[1] - 8 * P3[1]];
const P1: Vec2 = [(2 * A[0] - B[0]) / 18, (2 * A[1] - B[1]) / 18];
const P2: Vec2 = [(2 * B[0] - A[0]) / 18, (2 * B[1] - A[1]) / 18];
if (i === 0) poles.push(P0);
poles.push(P1, P2, P3);
}
if (a) poles[0] = a;
if (b) poles[poles.length - 1] = b;
const oc = getOC();
const m = cuts.length - 1;
const arr = new oc.NCollection_Array1_gp_Pnt(1, poles.length);
const knots = new oc.NCollection_Array1_double(1, m + 1);
const mults = new oc.NCollection_Array1_int(1, m + 1);
try {
poles.forEach((q, i) => {
const w3 = w(plane, q);
const pt = new oc.gp_Pnt(w3[0], w3[1], w3[2]);
arr.SetValue(i + 1, pt);
pt.delete();
});
for (let i = 0; i <= m; i++) {
knots.SetValue(i + 1, i);
mults.SetValue(i + 1, i === 0 || i === m ? 4 : 3);
}
const curve = new oc.Geom_BSplineCurve(arr, knots, mults, 3, false);
const mk = new oc.BRepBuilderAPI_MakeEdge(curve);
const edge = cast(mk.Edge()) as Edge;
mk.delete();
return edge;
} catch {
return null;
} finally {
arr.delete();
knots.delete();
mults.delete();
}
}
function bspline(pts: Vec2[], plane: PlaneDef): Edge {
// Thin out dense samples; the approximation is smooth anyway.
const step = Math.max(1, Math.floor(pts.length / 48));
const kept = pts.filter((_, i) => i % step === 0 || i === pts.length - 1);
if (kept.length < 3) return makeLine(w(plane, kept[0]), w(plane, kept[kept.length - 1]));
return makeBSplineApproximation(kept.map((q) => w(plane, q)), { tolerance: 1e-4, degMax: 5, degMin: 2 });
}
const w = (plane: PlaneDef, q: Vec2) => toWorld(plane, q);
+30
View File
@@ -0,0 +1,30 @@
/// <reference lib="webworker" />
// Web Worker entry: loads OpenCascade and serves engine.ts over postMessage.
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";
self.onmessage = async (e: MessageEvent<Envelope<Request>>) => {
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 }));
reply({ type: "ready" });
break;
case "regenerate":
reply({ type: "regenerated", result: await regenerate(msg.features) });
break;
case "export":
reply({ type: "exported", blob: await exportBodies(msg.features, msg.format, msg.bodies) });
break;
}
} catch (err) {
console.error(err);
reply({ type: "error", message: errorText(err) });
}
};
+6
View File
@@ -0,0 +1,6 @@
import "./style.css";
import { App } from "./app";
const app = new App(document.getElementById("view") as HTMLCanvasElement);
// Handy for debugging from the console.
(window as unknown as { supergeometry: App }).supergeometry = app;
+98
View File
@@ -0,0 +1,98 @@
// Per-device preferences (not part of the project file).
const KEY = "supergeometry.settings.v1";
const OLD_KEY = "tessel.settings.v1";
export interface Settings {
snap: {
grid: boolean;
guidePoints: boolean;
guideLines: boolean;
points3d: boolean;
distantEdges: boolean;
};
showGuidePoints: boolean;
showSnapHints: boolean;
gridLocked: boolean;
/** Grid step (mm) used when the grid is locked. */
gridStep: number;
showGrid: boolean;
showAxes: boolean;
animateCamera: boolean;
ortho: boolean;
shader: "shaded" | "wireframe" | "xray";
showEdges: boolean;
showHiddenEdges: boolean;
showPinned: boolean;
/** Sketch mode: show the constraint column. */
showConstraints: boolean;
/** Sketch: add Horizontal/Vertical/Coincident automatically while drawing. */
autoConstrain: boolean;
/** Sketch: draw the constraint badges (H, V, ∥, dimensions…) on the geometry. */
showConstraintGlyphs: boolean;
/** Bumped when defaults change for everyone (see the constructor). */
version: number;
/** Angle display: decimal degrees or degrees + minutes. */
degrees: "decimal" | "fractional";
}
const DEFAULTS: Settings = {
snap: { grid: true, guidePoints: true, guideLines: true, points3d: true, distantEdges: false },
showGuidePoints: true,
showSnapHints: true,
gridLocked: false,
gridStep: 1,
showGrid: true,
showAxes: true,
animateCamera: true,
ortho: true,
shader: "shaded",
showEdges: true,
showHiddenEdges: false,
showPinned: true,
degrees: "decimal",
showConstraints: true,
autoConstrain: true,
showConstraintGlyphs: true,
version: 2,
};
type Listener = (s: Settings) => void;
class SettingsStore {
value: Settings;
private listeners = new Set<Listener>();
constructor() {
let saved: Partial<Settings> = {};
try {
saved = JSON.parse(localStorage.getItem(KEY) ?? localStorage.getItem(OLD_KEY) ?? "{}");
} catch {
// Unavailable storage just means defaults.
}
this.value = { ...DEFAULTS, ...saved, snap: { ...DEFAULTS.snap, ...(saved.snap ?? {}) } };
// v2: orthographic view and the sketch constraint column are on by default —
// also for anyone whose saved preferences still hold the old defaults.
if ((saved.version ?? 1) < 2) this.value = { ...this.value, ortho: true, showConstraints: true, version: 2 };
}
set<K extends keyof Settings>(key: K, v: Settings[K]): void {
this.value = { ...this.value, [key]: v };
try {
localStorage.setItem(KEY, JSON.stringify(this.value));
} catch {
// Ignore: preferences are a convenience.
}
this.listeners.forEach((fn) => fn(this.value));
}
onChange(fn: Listener): void {
this.listeners.add(fn);
}
offChange(fn: Listener): void {
this.listeners.delete(fn);
}
}
export const settings = new SettingsStore();
+459
View File
@@ -0,0 +1,459 @@
// Sketch constraint solver: every entity is a short parameter vector; each
// constraint is one or more residuals; Levenberg–Marquardt drives them to zero
// while a weak pull towards the current shape keeps under-constrained sketches
// 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";
// ------------------------------------------------------------- parameters
/** Entity → flat parameter list (and back). */
function params(e: SketchEntity): number[] {
switch (e.kind) {
case "line":
return [...e.a, ...e.b];
case "arc":
return [...e.a, ...e.m, ...e.b];
case "circle":
return [...e.center, e.radius];
case "ellipse":
return [...e.center, e.rx, e.ry, e.rotation];
case "rect":
return [...e.center, e.w, e.h, e.rotation];
case "polygon":
return [...e.center, e.radius, e.angle];
case "spline":
case "polyline":
return e.points.flat();
}
}
function withParams(e: SketchEntity, x: number[]): SketchEntity {
switch (e.kind) {
case "line":
return { ...e, a: [x[0], x[1]], b: [x[2], x[3]] };
case "arc":
return { ...e, a: [x[0], x[1]], m: [x[2], x[3]], b: [x[4], x[5]] };
case "circle":
return { ...e, center: [x[0], x[1]], radius: Math.abs(x[2]) };
case "ellipse":
return { ...e, center: [x[0], x[1]], rx: Math.abs(x[2]), ry: Math.abs(x[3]), rotation: x[4] };
case "rect":
return { ...e, center: [x[0], x[1]], w: Math.abs(x[2]), h: Math.abs(x[3]), rotation: x[4] };
case "polygon":
return { ...e, center: [x[0], x[1]], radius: Math.abs(x[2]), angle: x[3] };
case "spline":
case "polyline": {
const pts: Vec2[] = [];
for (let i = 0; i < x.length; i += 2) pts.push([x[i], x[i + 1]]);
return { ...e, points: pts };
}
}
}
/** Named points of an entity (what constraints can grab). */
export function pointsOf(e: SketchEntity): { p: string; at: Vec2 }[] {
switch (e.kind) {
case "line":
return [{ p: "a", at: e.a }, { p: "b", at: e.b }];
case "arc": {
const c = arcFrom3(e.a, e.m, e.b);
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 "rect":
case "polygon":
return [{ p: "c", at: e.center }, ...entityCorners(e).map((at, i) => ({ p: `k${i}`, at }))];
case "spline":
case "polyline":
return e.points.map((at, i) => ({ p: `k${i}`, at }));
}
}
export function pointOf(e: SketchEntity, p: string): Vec2 | null {
return pointsOf(e).find((q) => q.p === p)?.at ?? null;
}
/** Size of an entity by name, for dimension constraints and size fields. */
export function sizeOf(e: SketchEntity, prop: string): number | null {
switch (prop) {
case "length":
if (e.kind === "line") return Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1]);
return null;
case "radius":
case "diameter": {
const r = e.kind === "circle" || e.kind === "polygon" ? e.radius : e.kind === "arc" ? (arcFrom3(e.a, e.m, e.b)?.r ?? null) : null;
return r === null ? null : prop === "diameter" ? 2 * r : r;
}
case "w":
return e.kind === "rect" ? e.w : null;
case "h":
return e.kind === "rect" ? e.h : null;
case "rx":
return e.kind === "ellipse" ? e.rx : null;
case "ry":
return e.kind === "ellipse" ? e.ry : null;
// Ellipse axis lengths (full widths, like a circle's diameter).
case "dx":
return e.kind === "ellipse" ? 2 * e.rx : null;
case "dy":
return e.kind === "ellipse" ? 2 * e.ry : null;
case "angle":
return e.kind === "line" ? (Math.atan2(e.b[1] - e.a[1], e.b[0] - e.a[0]) * 180) / Math.PI : null;
}
return null;
}
/** Direction of a straight entity (line), or null. */
function dirOf(e: SketchEntity): Vec2 | null {
if (e.kind !== "line") return null;
return [e.b[0] - e.a[0], e.b[1] - e.a[1]];
}
/** Centre and radius of round entities. */
function roundOf(e: SketchEntity): { c: Vec2; r: number } | null {
if (e.kind === "circle") return { c: e.center, r: e.radius };
if (e.kind === "arc") {
const a = arcFrom3(e.a, e.m, e.b);
return a ? { c: a.c, r: a.r } : null;
}
return null;
}
// --------------------------------------------------------------- residuals
type Lookup = (id: string) => SketchEntity | undefined;
/** Residuals of one constraint (empty if it refers to something missing). */
function residuals(c: SketchConstraint, get: Lookup): number[] {
const P = (r: PointRef) => {
const e = get(r.e);
return e ? pointOf(e, r.p) : null;
};
const E = (i: number) => (c.curves?.[i] ? get(c.curves[i]) : undefined);
const unit = (v: Vec2) => {
const l = Math.hypot(v[0], v[1]) || 1;
return [v[0] / l, v[1] / l] as Vec2;
};
switch (c.type) {
case "coincident": {
const [a, b] = (c.pts ?? []).map(P);
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)];
return [];
}
case "horizontal":
case "vertical": {
const e = E(0);
const d = e && dirOf(e);
if (d) return [c.type === "horizontal" ? d[1] : d[0]];
const [a, b] = (c.pts ?? []).map(P);
if (a && b) return [c.type === "horizontal" ? a[1] - b[1] : a[0] - b[0]];
return [];
}
case "parallel":
case "perpendicular": {
const [d1, d2] = [E(0), E(1)].map((e) => (e ? dirOf(e) : null));
if (!d1 || !d2) return [];
const u = unit(d1);
const v = unit(d2);
return [c.type === "parallel" ? u[0] * v[1] - u[1] * v[0] : u[0] * v[0] + u[1] * v[1]];
}
case "equal": {
const [e1, e2] = [E(0), E(1)];
if (!e1 || !e2) return [];
const s = (e: SketchEntity) => sizeOf(e, e.kind === "line" ? "length" : "radius");
const a = s(e1);
const b = s(e2);
return a !== null && b !== null ? [a - b] : [];
}
case "tangent": {
const [e1, e2] = [E(0), E(1)];
if (!e1 || !e2) return [];
const r1 = roundOf(e1);
const r2 = roundOf(e2);
const line = e1.kind === "line" ? e1 : e2.kind === "line" ? e2 : null;
const round = r1 ?? r2;
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)))];
}
return [];
}
case "concentric": {
const c1 = E(0) && centreOf(E(0)!);
const c2 = E(1) && centreOf(E(1)!);
return c1 && c2 ? [c1[0] - c2[0], c1[1] - c2[1]] : [];
}
case "midpoint": {
const a = c.pts?.[0] && P(c.pts[0]);
const e = E(0);
if (!a || e?.kind !== "line") return [];
return [a[0] - (e.a[0] + e.b[0]) / 2, a[1] - (e.a[1] + e.b[1]) / 2];
}
case "symmetric": {
const [a, b] = (c.pts ?? []).map(P);
const e = E(0);
if (!a || !b || e?.kind !== "line") return [];
const m: Vec2 = [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2];
const d = unit(dirOf(e)!);
// Midpoint on the line, and a–b perpendicular to it.
return [distPointLineSigned(m, e.a, e.b), (b[0] - a[0]) * d[0] + (b[1] - a[1]) * d[1]];
}
case "fix": {
const a = c.pts?.[0] && P(c.pts[0]);
return a && c.at ? [a[0] - c.at[0], a[1] - c.at[1]] : [];
}
case "distance": {
if (c.value === undefined) return [];
// Point to line: perpendicular distance.
if (c.pts?.length === 1 && c.curves?.length === 1) {
const p = P(c.pts[0]);
const l = E(0);
return p && l?.kind === "line" ? [distPointLine(p, l.a, l.b) - c.value] : [];
}
const [a, b] = (c.pts ?? []).map(P);
return a && b ? [Math.hypot(a[0] - b[0], a[1] - b[1]) - c.value] : [];
}
case "dim": {
const e = E(0);
if (!e || !c.prop || c.value === undefined) return [];
if (c.prop === "angle" && c.curves?.length === 2) {
const d1 = dirOf(e);
const d2 = E(1) && dirOf(E(1)!);
if (!d1 || !d2) return [];
const ang = Math.atan2(d1[0] * d2[1] - d1[1] * d2[0], d1[0] * d2[0] + d1[1] * d2[1]);
return [wrap(Math.abs(ang) - (c.value * Math.PI) / 180)];
}
const s = sizeOf(e, c.prop);
if (s === null) return [];
return c.prop === "angle" ? [wrap(((s - c.value) * Math.PI) / 180)] : [s - c.value];
}
}
}
function wrap(a: number): number {
while (a > Math.PI) a -= 2 * Math.PI;
while (a < -Math.PI) a += 2 * Math.PI;
return a;
}
function centreOf(e: SketchEntity): Vec2 | null {
if (e.kind === "circle" || e.kind === "ellipse" || e.kind === "rect" || e.kind === "polygon") return e.center;
return roundOf(e)?.c ?? null;
}
function distPointLine(p: Vec2, a: Vec2, b: Vec2): number {
return Math.abs(distPointLineSigned(p, a, b));
}
function distPointLineSigned(p: Vec2, a: Vec2, b: Vec2): number {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const l = Math.hypot(dx, dy) || 1;
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);
const r = roundOf(e);
if (r) return Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r;
return 0;
}
// ------------------------------------------------------------------ solver
export interface SolveOptions {
/** Points to pull towards a target (dragging), with a strong weight. */
drag?: { ref: PointRef; to: Vec2 }[];
/** Entities that must not move (e.g. the face outline). */
fixed?: Set<string>;
}
export interface SolveResult {
entities: SketchEntity[];
/** Largest remaining residual (≈0 when every constraint is met). */
error: number;
ok: boolean;
}
/** Solve constraints; returns updated entities (unchanged ones are kept). */
export function solve(entities: SketchEntity[], constraints: SketchConstraint[], opts: SolveOptions = {}): SolveResult {
const live = constraints.filter((c) => refsOf(c).every((id) => entities.some((e) => e.id === id)));
if (!live.length && !opts.drag?.length) return { entities, error: 0, ok: true };
// Only entities that take part move; everything else is left as is.
const involved = new Set<string>(live.flatMap(refsOf));
for (const d of opts.drag ?? []) involved.add(d.ref.e);
for (const id of opts.fixed ?? []) involved.delete(id);
const movers = entities.filter((e) => involved.has(e.id));
const offsets: number[] = [];
const x0: number[] = [];
for (const e of movers) {
offsets.push(x0.length);
x0.push(...params(e));
}
const byId = new Map(entities.map((e) => [e.id, e]));
const build = (x: number[]) => {
const m = new Map(byId);
movers.forEach((e, i) => m.set(e.id, withParams(e, x.slice(offsets[i], offsets[i] + params(e).length))));
return m;
};
const scale = Math.max(1, ...x0.map(Math.abs));
// Two passes: a noticeable pull first (smallest change), then almost none (exact constraints).
let xs = x0;
for (const w of [1e-3, 1e-8]) xs = lm(xs, w);
const m = build(xs);
const get = (id: string) => m.get(id);
const error = Math.max(0, ...live.flatMap((c) => residuals(c, get).map(Math.abs)));
return { entities: entities.map((e) => m.get(e.id) ?? e), error, ok: error < 1e-6 * Math.max(1, scale) };
function lm(start: number[], weight: number): number[] {
const x0 = start;
const R = (x: number[]) => {
const m = build(x);
const get = (id: string) => m.get(id);
const out: number[] = [];
for (const c of live) out.push(...residuals(c, get));
for (const d of opts.drag ?? []) {
const e = m.get(d.ref.e);
const p = e && pointOf(e, d.ref.p);
// The drag target is "soft but strong": constraints still win where they conflict.
if (p) out.push((p[0] - d.to[0]) * 0.3, (p[1] - d.to[1]) * 0.3);
}
// Weak pull towards the start: picks the smallest change for free directions.
for (let i = 0; i < x.length; i++) out.push((x[i] - x0[i]) * weight);
return out;
};
let x = x0.slice();
let r = R(x);
let cost = dot(r, r);
let lambda = 1e-3;
const n = x.length;
for (let it = 0; it < 60 && cost > 1e-20; it++) {
// Numeric Jacobian.
const J: number[][] = [];
for (let j = 0; j < n; j++) {
const h = 1e-6 * Math.max(1, Math.abs(x[j]), scale * 1e-3);
const xp = x.slice();
xp[j] += h;
const rp = R(xp);
J.push(rp.map((v, i) => (v - r[i]) / h));
}
// (JᵀJ + λ diag) dx = -Jᵀ r
const A: number[][] = Array.from({ length: n }, () => new Array(n).fill(0));
const g = new Array(n).fill(0);
for (let a = 0; a < n; a++) {
for (let b = a; b < n; b++) {
let s = 0;
const Ja = J[a];
const Jb = J[b];
for (let i = 0; i < r.length; i++) s += Ja[i] * Jb[i];
A[a][b] = A[b][a] = s;
}
let s = 0;
for (let i = 0; i < r.length; i++) s += J[a][i] * r[i];
g[a] = -s;
}
let improved = false;
for (let tries = 0; tries < 8; tries++) {
const M = A.map((row, i) => row.map((v, j) => (i === j ? v * (1 + lambda) + 1e-12 : v)));
const dx = solveLinear(M, g);
if (!dx) {
lambda *= 10;
continue;
}
const xn = x.map((v, i) => v + dx[i]);
const rn = R(xn);
const cn = dot(rn, rn);
if (cn < cost) {
x = xn;
r = rn;
cost = cn;
lambda = Math.max(1e-9, lambda / 3);
improved = true;
break;
}
lambda *= 10;
}
if (!improved) break;
}
return x;
}
}
/** Entity ids a constraint refers to. */
export function refsOf(c: SketchConstraint): string[] {
return [...(c.pts ?? []).map((p) => p.e), ...(c.curves ?? [])];
}
function dot(a: number[], b: number[]): number {
let s = 0;
for (let i = 0; i < a.length; i++) s += a[i] * b[i];
return s;
}
/** Gaussian elimination with partial pivoting. */
function solveLinear(A: number[][], b: number[]): number[] | null {
const n = b.length;
const M = A.map((row, i) => [...row, b[i]]);
for (let c = 0; c < n; c++) {
let p = c;
for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r;
if (Math.abs(M[p][c]) < 1e-18) return null;
[M[c], M[p]] = [M[p], M[c]];
for (let r = c + 1; r < n; r++) {
const f = M[r][c] / M[c][c];
if (!f) continue;
for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k];
}
}
const x = new Array(n).fill(0);
for (let r = n - 1; r >= 0; r--) {
let s = M[r][n];
for (let k = r + 1; k < n; k++) s -= M[r][k] * x[k];
x[r] = s / M[r][r];
}
return x;
}
// ------------------------------------------------------------- utilities
/** Which constraints the current selection allows (for enabling buttons). */
export function applicable(type: ConstraintType, pts: PointRef[], curves: SketchEntity[]): boolean {
const lines = curves.filter((e) => e.kind === "line");
const rounds = curves.filter((e) => e.kind === "circle" || e.kind === "arc");
switch (type) {
case "coincident":
return pts.length === 2 || (pts.length === 1 && curves.length === 1);
case "horizontal":
case "vertical":
return (lines.length === 1 && curves.length === 1 && !pts.length) || (pts.length === 2 && !curves.length);
case "parallel":
case "perpendicular":
return lines.length === 2 && curves.length === 2;
case "equal":
return curves.length === 2 && (lines.length === 2 || rounds.length === 2);
case "tangent":
return curves.length === 2 && rounds.length >= 1;
case "concentric":
return curves.length === 2 && curves.every((e) => e.kind !== "line" && e.kind !== "spline" && e.kind !== "polyline");
case "midpoint":
return pts.length === 1 && lines.length === 1 && curves.length === 1;
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);
case "fix":
// Points, or whole curves (all their points).
return pts.length >= 1 || curves.length >= 1;
default:
return false;
}
}
+284
View File
@@ -0,0 +1,284 @@
// Sketch curve math, shared by the UI and the kernel worker.
// 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";
export type Prim =
| { t: "line"; a: Vec2; b: Vec2; src: string }
| { t: "circle"; c: Vec2; r: number; a0: number; sweep: number; src: string }
| { t: "ellipse"; c: Vec2; rx: number; ry: number; rot: number; a0: number; sweep: number; src: string }
| { t: "spline"; pts: Vec2[]; closed: boolean; src: string; ctrl?: SplineDef };
/** The points a spline was drawn with (its samples are 16 per span of these). */
export interface SplineDef {
points: Vec2[];
closed: boolean;
mode: "fit" | "control";
}
export const SPLINE_PER_SPAN = 16;
const TAU = Math.PI * 2;
export function evalPrim(p: Prim, t: number): Vec2 {
switch (p.t) {
case "line":
return [p.a[0] + (p.b[0] - p.a[0]) * t, p.a[1] + (p.b[1] - p.a[1]) * t];
case "circle": {
const ang = p.a0 + p.sweep * t;
return [p.c[0] + p.r * Math.cos(ang), p.c[1] + p.r * Math.sin(ang)];
}
case "ellipse": {
const ang = p.a0 + p.sweep * t;
const x = p.rx * Math.cos(ang);
const y = p.ry * Math.sin(ang);
const c = Math.cos(p.rot);
const s = Math.sin(p.rot);
return [p.c[0] + x * c - y * s, p.c[1] + x * s + y * c];
}
case "spline": {
const n = p.pts.length - 1;
const f = Math.min(Math.max(t, 0), 1) * n;
const i = Math.min(Math.floor(f), n - 1);
const u = f - i;
const a = p.pts[i];
const b = p.pts[i + 1];
return [a[0] + (b[0] - a[0]) * u, a[1] + (b[1] - a[1]) * u];
}
}
}
export function isClosedPrim(p: Prim): boolean {
if (p.t === "circle" || p.t === "ellipse") return Math.abs(Math.abs(p.sweep) - TAU) < 1e-9;
if (p.t === "spline") return p.closed;
return false;
}
/** Number of straight segments used to approximate a primitive. */
export function primSegments(p: Prim): number {
switch (p.t) {
case "line":
return 1;
case "circle":
case "ellipse":
return Math.max(6, Math.ceil((Math.abs(p.sweep) / TAU) * 96));
case "spline":
return p.pts.length - 1;
}
}
/** Break an entity into primitives. Construction geometry still yields prims (for drawing). */
export function entityPrims(e: SketchEntity): Prim[] {
const src = e.id;
switch (e.kind) {
case "line":
return [{ t: "line", a: e.a, b: e.b, src }];
case "arc": {
const arc = arcFrom3(e.a, e.m, e.b);
if (!arc) return [{ t: "line", a: e.a, b: e.b, src }];
return [{ t: "circle", c: arc.c, r: arc.r, a0: arc.a0, sweep: arc.sweep, src }];
}
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 }];
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":
case "polygon":
case "polyline": {
const pts = entityCorners(e);
const closed = e.kind !== "polyline" || e.closed;
const out: Prim[] = [];
for (let i = 0; i < pts.length - (closed ? 0 : 1); i++) {
out.push({ t: "line", a: pts[i], b: pts[(i + 1) % pts.length], src });
}
return out;
}
}
}
/** Corner points of straight-sided entities. */
export function entityCorners(e: Extract<SketchEntity, { kind: "rect" | "polygon" | "polyline" }>): Vec2[] {
if (e.kind === "polyline") return e.points;
if (e.kind === "polygon") {
return Array.from({ length: e.sides }, (_, i) => {
const t = e.angle + (i / e.sides) * TAU;
return [e.center[0] + e.radius * Math.cos(t), e.center[1] + e.radius * Math.sin(t)] as Vec2;
});
}
const c = Math.cos(e.rotation);
const s = Math.sin(e.rotation);
const hw = e.w / 2;
const hh = e.h / 2;
return ([
[-hw, -hh],
[hw, -hh],
[hw, hh],
[-hw, hh],
] as Vec2[]).map(([x, y]) => [e.center[0] + x * c - y * s, e.center[1] + x * s + y * c] as Vec2);
}
/** Dense polyline for drawing an entity. */
export function entityPolylines(e: SketchEntity): Vec2[][] {
return entityPrims(e).map((p) => samplePrim(p, 0, 1));
}
export function samplePrim(p: Prim, t0: number, t1: number, segs?: number): Vec2[] {
const n = segs ?? Math.max(1, Math.ceil(primSegments(p) * Math.abs(t1 - t0)));
if (p.t === "spline") {
// Follow the stored samples exactly so pieces line up with the full curve.
const N = p.pts.length - 1;
const out: Vec2[] = [evalPrim(p, t0)];
const lo = Math.min(t0, t1) * N;
const hi = Math.max(t0, t1) * N;
const inner: Vec2[] = [];
for (let i = Math.floor(lo) + 1; i < hi - 1e-9; i++) inner.push(p.pts[i]);
if (t1 < t0) inner.reverse();
out.push(...inner, evalPrim(p, t1));
return out;
}
return Array.from({ length: n + 1 }, (_, i) => evalPrim(p, t0 + ((t1 - t0) * i) / n));
}
/** Circle through three points, with the sweep that passes through the middle one. */
export function arcFrom3(a: Vec2, m: Vec2, b: Vec2): { c: Vec2; r: number; a0: number; sweep: number } | null {
const ax = a[0];
const ay = a[1];
const bx = m[0];
const by = m[1];
const cx = b[0];
const cy = b[1];
const d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
if (Math.abs(d) < 1e-12) return null;
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);
const a0 = Math.atan2(ay - uy, ax - ux);
const am = Math.atan2(by - uy, bx - ux);
const a1 = Math.atan2(cy - uy, cx - ux);
const ccw = (x: number) => ((x % TAU) + TAU) % TAU;
const toM = ccw(am - a0);
const toB = ccw(a1 - a0);
const sweep = toM < toB ? toB : toB - TAU;
return { c: [ux, uy], r, a0, sweep };
}
/**
* Densely sampled spline. "fit" passes through the points (centripetal
* Catmull-Rom); "control" treats them as B-spline control points.
*/
export function splinePoints(pts: Vec2[], closed: boolean, mode: "fit" | "control", perSpan = 16): Vec2[] {
if (pts.length < 2) return pts.slice();
if (pts.length === 2) return [pts[0], pts[1]];
const n = pts.length;
const get = (i: number): Vec2 => (closed ? pts[((i % n) + n) % n] : pts[Math.max(0, Math.min(n - 1, i))]);
const spans = closed ? n : n - 1;
const out: Vec2[] = [];
for (let s = 0; s < spans; s++) {
for (let k = 0; k < perSpan; k++) {
const u = k / perSpan;
out.push(mode === "fit" ? catmull(get(s - 1), get(s), get(s + 1), get(s + 2), u) : bspline(get(s - 1), get(s), get(s + 1), get(s + 2), u));
}
}
if (closed) out.push(out[0]);
else out.push(mode === "fit" ? pts[n - 1] : bspline(get(n - 3), get(n - 2), get(n - 1), get(n - 1), 1));
if (!closed && mode === "control") out[0] = bspline(get(-1), get(0), get(1), get(2), 0);
return out;
}
/** Exact point on span `s` of a spline (each span is one cubic), u in [0, 1]. */
export function splineSpanAt(d: SplineDef, s: number, u: number): Vec2 {
const n = d.points.length;
const get = (i: number): Vec2 => (d.closed ? d.points[((i % n) + n) % n] : d.points[Math.max(0, Math.min(n - 1, i))]);
return d.mode === "fit" ? catmull(get(s - 1), get(s), get(s + 1), get(s + 2), u) : bspline(get(s - 1), get(s), get(s + 1), get(s + 2), u);
}
/** Number of cubic spans of a spline. */
export function splineSpans(d: SplineDef): number {
return d.closed ? d.points.length : d.points.length - 1;
}
function catmull(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, u: number): Vec2 {
// Centripetal parameterisation avoids cusps and self-intersections.
const d = (a: Vec2, b: Vec2) => Math.max(1e-9, Math.sqrt(Math.hypot(a[0] - b[0], a[1] - b[1])));
const t0 = 0;
const t1 = t0 + d(p0, p1);
const t2 = t1 + d(p1, p2);
const t3 = t2 + d(p2, p3);
const t = t1 + (t2 - t1) * u;
const lerp = (a: Vec2, b: Vec2, ta: number, tb: number): Vec2 => {
const w = (t - ta) / (tb - ta || 1e-9);
return [a[0] + (b[0] - a[0]) * w, a[1] + (b[1] - a[1]) * w];
};
const a1 = lerp(p0, p1, t0, t1);
const a2 = lerp(p1, p2, t1, t2);
const a3 = lerp(p2, p3, t2, t3);
const b1 = lerp(a1, a2, t0, t2);
const b2 = lerp(a2, a3, t1, t3);
return lerp(b1, b2, t1, t2);
}
function bspline(p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2, u: number): Vec2 {
const u2 = u * u;
const u3 = u2 * u;
const b0 = (1 - 3 * u + 3 * u2 - u3) / 6;
const b1 = (4 - 6 * u2 + 3 * u3) / 6;
const b2 = (1 + 3 * u + 3 * u2 - 3 * u3) / 6;
const b3 = u3 / 6;
return [b0 * p0[0] + b1 * p1[0] + b2 * p2[0] + b3 * p3[0], b0 * p0[1] + b1 * p1[1] + b2 * p2[1] + b3 * p3[1]];
}
/** Closest parameter on a primitive to a point (coarse sample + refinement). */
export function closestOnPrim(p: Prim, q: Vec2): { t: number; d: number; pt: Vec2 } {
const n = Math.max(16, primSegments(p) * 2);
let best = { t: 0, d: Infinity, pt: evalPrim(p, 0) };
for (let i = 0; i <= n; i++) {
const t = i / n;
const pt = evalPrim(p, t);
const d = Math.hypot(pt[0] - q[0], pt[1] - q[1]);
if (d < best.d) best = { t, d, pt };
}
let step = 1 / n;
for (let k = 0; k < 30; k++) {
step /= 2;
for (const t of [best.t - step, best.t + step]) {
if (t < 0 || t > 1) continue;
const pt = evalPrim(p, t);
const d = Math.hypot(pt[0] - q[0], pt[1] - q[1]);
if (d < best.d) best = { t, d, pt };
}
}
return best;
}
export function polyArea(poly: Vec2[]): number {
let a = 0;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) a += (poly[j][0] + poly[i][0]) * (poly[j][1] - poly[i][1]);
return -a / 2;
}
export function polyCentroid(poly: Vec2[]): Vec2 {
let a = 0;
let cx = 0;
let cy = 0;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const f = poly[j][0] * poly[i][1] - poly[i][0] * poly[j][1];
a += f;
cx += (poly[j][0] + poly[i][0]) * f;
cy += (poly[j][1] + poly[i][1]) * f;
}
if (Math.abs(a) < 1e-12) return poly[0] ?? [0, 0];
return [cx / (3 * a), cy / (3 * a)];
}
export function pointInPoly(p: Vec2, poly: Vec2[]): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const [xi, yi] = poly[i];
const [xj, yj] = poly[j];
if (yi > p[1] !== yj > p[1] && p[0] < ((xj - xi) * (p[1] - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
+837
View File
@@ -0,0 +1,837 @@
// 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 { toPlane } from "../geom";
import { arcFrom3, closestOnPrim, entityCorners, entityPrims, evalPrim, isClosedPrim, primSegments, samplePrim, type Prim } from "./curves";
export function uid(): string {
return Math.random().toString(36).slice(2, 10);
}
// ------------------------------------------------------------- transforms
export type Xf = (p: Vec2) => Vec2;
export const translateXf = (dx: number, dy: number): Xf => (p) => [p[0] + dx, p[1] + dy];
export const rotateXf = (c: Vec2, ang: number): Xf => {
const cs = Math.cos(ang);
const sn = Math.sin(ang);
return (p) => [c[0] + (p[0] - c[0]) * cs - (p[1] - c[1]) * sn, c[1] + (p[0] - c[0]) * sn + (p[1] - c[1]) * cs];
};
export const scaleXf = (c: Vec2, k: number): Xf => (p) => [c[0] + (p[0] - c[0]) * k, c[1] + (p[1] - c[1]) * k];
export const mirrorXf = (a: Vec2, b: Vec2): Xf => {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const l2 = dx * dx + dy * dy || 1;
return (p) => {
const t = ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / l2;
const fx = a[0] + dx * t;
const fy = a[1] + dy * t;
return [2 * fx - p[0], 2 * fy - p[1]];
};
};
/** Apply a point transform to an entity, keeping its kind where possible. */
export function transformEntity(e: SketchEntity, xf: Xf, newId = false): SketchEntity {
const id = newId ? uid() : e.id;
const base = { id, construction: e.construction };
const o = xf([0, 0]);
const ux = xf([1, 0]);
const k = Math.hypot(ux[0] - o[0], ux[1] - o[1]); // uniform scale factor
const rot = Math.atan2(ux[1] - o[1], ux[0] - o[0]);
const vy = xf([0, 1]);
const mirrored = (ux[0] - o[0]) * (vy[1] - o[1]) - (ux[1] - o[1]) * (vy[0] - o[0]) < 0;
switch (e.kind) {
case "line":
return { ...base, kind: "line", a: xf(e.a), b: xf(e.b) };
case "arc":
return { ...base, kind: "arc", a: xf(e.a), m: xf(e.m), b: xf(e.b) };
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 };
case "spline":
return { ...base, kind: "spline", points: e.points.map(xf), closed: e.closed, mode: e.mode };
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": {
const corner = xf(entityCorners(e)[0]);
const c = xf(e.center);
return { ...base, kind: "polygon", center: c, radius: e.radius * k, sides: e.sides, angle: Math.atan2(corner[1] - c[1], corner[0] - c[0]) };
}
case "polyline":
return { ...base, kind: "polyline", points: e.points.map(xf), closed: e.closed };
}
}
/** Characteristic points: endpoints, midpoints, centres (for snapping). */
export function guidePoints(e: SketchEntity): { p: Vec2; kind: "end" | "mid" | "center" }[] {
const out: { p: Vec2; kind: "end" | "mid" | "center" }[] = [];
switch (e.kind) {
case "line":
out.push({ p: e.a, kind: "end" }, { p: e.b, kind: "end" }, { p: [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2], kind: "mid" });
break;
case "arc": {
out.push({ p: e.a, kind: "end" }, { p: e.b, kind: "end" });
const c = arcFrom3(e.a, e.m, e.b);
if (c) out.push({ p: c.c, kind: "center" });
break;
}
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" });
break;
case "spline":
e.points.forEach((p) => out.push({ p, kind: "end" }));
break;
case "rect":
case "polygon":
case "polyline": {
const pts = entityCorners(e);
pts.forEach((p) => out.push({ p, kind: "end" }));
for (let i = 0; i < pts.length - (e.kind === "polyline" && !e.closed ? 1 : 0); i++) {
const a = pts[i];
const b = pts[(i + 1) % pts.length];
out.push({ p: [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2], kind: "mid" });
}
if (e.kind !== "polyline") out.push({ p: e.center, kind: "center" });
}
}
return out;
}
// -------------------------------------------------------- trim & extend
/** Turn rects/polygons/polylines into separate lines (needed before trimming one side). */
export function explode(e: SketchEntity): SketchEntity[] {
if (e.kind !== "rect" && e.kind !== "polygon" && e.kind !== "polyline") return [e];
return entityPrims(e).map((p) => ({ id: uid(), kind: "line", a: (p as { a: Vec2 }).a, b: (p as { b: Vec2 }).b, construction: e.construction }));
}
/** Parameters where other entities cross primitive `p`. */
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));
for (const q of others) {
const m = Math.max(primSegments(q), 1) * 4;
const B = Array.from({ length: m + 1 }, (_, i) => evalPrim(q, i / m));
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
const h = segHit(A[i], A[i + 1], B[j], B[j + 1]);
if (h) ts.push((i + h) / n);
}
}
}
return ts.sort((a, b) => a - b);
}
function segHit(a: Vec2, b: Vec2, c: Vec2, d: Vec2): number | null {
const rx = b[0] - a[0];
const ry = b[1] - a[1];
const sx = d[0] - c[0];
const sy = d[1] - c[1];
const den = rx * sy - ry * sx;
if (Math.abs(den) < 1e-14) return null;
const qx = c[0] - a[0];
const qy = c[1] - a[1];
const u = (qx * sy - qy * sx) / den;
const v = (qx * ry - qy * rx) / den;
return u >= -1e-9 && u <= 1 + 1e-9 && v >= -1e-9 && v <= 1 + 1e-9 ? u : null;
}
/** Remove the piece of `id` under `at` that lies between crossings. Returns the new entity list. */
export function trim(entities: SketchEntity[], id: string, at: Vec2): SketchEntity[] {
let list = entities;
let target = list.find((e) => e.id === id);
if (!target) return entities;
// Straight-sided shapes: trim the one side that was tapped.
if (target.kind === "rect" || target.kind === "polygon" || target.kind === "polyline") {
const parts = explode(target);
list = list.flatMap((e) => (e.id === id ? parts : [e]));
target = parts.reduce((best, e) => (closestOnPrim(entityPrims(e)[0], at).d < closestOnPrim(entityPrims(best)[0], at).d ? e : best));
}
const prim = entityPrims(target)[0];
const others = list.filter((e) => e.id !== target!.id && !e.construction).flatMap(entityPrims);
const ts = crossings(prim, others).filter((t, i, a) => i === 0 || t - a[i - 1] > 1e-6);
const tap = closestOnPrim(prim, at).t;
const closed = isClosedPrim(prim);
const keep: [number, number][] = [];
if (closed) {
if (ts.length < 2) return list.filter((e) => e.id !== target!.id);
// The removed piece is between the crossings around the tap (cyclically).
let lo = ts[ts.length - 1] - 1;
let hi = ts[0];
for (let i = 0; i < ts.length - 1; i++) if (tap >= ts[i] && tap <= ts[i + 1]) ((lo = ts[i]), (hi = ts[i + 1]));
if (tap > ts[ts.length - 1]) ((lo = ts[ts.length - 1]), (hi = ts[0] + 1));
keep.push([hi, lo + 1]);
} else {
const cuts = [0, ...ts.filter((t) => t > 1e-6 && t < 1 - 1e-6), 1];
for (let i = 0; i < cuts.length - 1; i++) if (!(tap >= cuts[i] && tap <= cuts[i + 1])) keep.push([cuts[i], cuts[i + 1]]);
}
const pieces = keep.map(([t0, t1]) => pieceEntity(prim, t0, t1, target!.construction));
return list.flatMap((e) => (e.id === target!.id ? pieces : [e]));
}
/** 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 {
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 };
// Ellipses and splines: keep shape as a fit spline through samples.
const n = 12;
const pts = Array.from({ length: n + 1 }, (_, i) => at(t0 + ((t1 - t0) * i) / n));
return { id: uid(), kind: "spline", points: pts, closed: false, mode: "fit", construction };
}
/** Extend the end of a line nearest `at` to the next curve it would hit. */
export function extend(entities: SketchEntity[], id: string, at: Vec2): SketchEntity[] | null {
const e = entities.find((x) => x.id === id);
if (!e || e.kind !== "line") return null;
const endB = Math.hypot(at[0] - e.b[0], at[1] - e.b[1]) < Math.hypot(at[0] - e.a[0], at[1] - e.a[1]);
const from = endB ? e.b : e.a;
const other = endB ? e.a : e.b;
const dx = from[0] - other[0];
const dy = from[1] - other[1];
const L = Math.hypot(dx, dy) || 1;
const far: Vec2 = [from[0] + (dx / L) * 1e6, from[1] + (dy / L) * 1e6];
let best = Infinity;
for (const q of entities.filter((x) => x.id !== id && !x.construction).flatMap(entityPrims)) {
const m = Math.max(primSegments(q), 1) * 4;
for (let j = 0; j < m; j++) {
const u = segHit(from, far, evalPrim(q, j / m), evalPrim(q, (j + 1) / m));
if (u !== null && u * 1e6 > 1e-6) best = Math.min(best, u * 1e6);
}
}
if (!Number.isFinite(best)) return null;
const to: Vec2 = [from[0] + (dx / L) * best, from[1] + (dy / L) * best];
return entities.map((x) => (x.id === id ? { ...e, ...(endB ? { b: to } : { a: to }) } : x));
}
/** Which end of an open curve the pick is nearer to ("a" or "b"); null for closed curves. */
export function endNear(e: SketchEntity, at: Vec2): "a" | "b" | null {
const se = splineEnds(e);
if (se) return Math.hypot(at[0] - se[0][0], at[1] - se[0][1]) <= Math.hypot(at[0] - se[1][0], at[1] - se[1][1]) ? "a" : "b";
if (e.kind !== "line" && e.kind !== "arc") return null;
return Math.hypot(at[0] - e.a[0], at[1] - e.a[1]) <= Math.hypot(at[0] - e.b[0], at[1] - e.b[1]) ? "a" : "b";
}
type Carrier = { kind: "line"; p: Vec2; d: Vec2 } | { kind: "circle"; c: Vec2; r: number };
type Piece = Extract<SketchEntity, { kind: "line" | "arc" | "spline" }>;
/** Where an open spline starts and ends (its real curve ends). */
export function splineEnds(e: SketchEntity): [Vec2, Vec2] | null {
if (e.kind !== "spline" || e.closed || e.points.length < 2) return null;
const p = entityPrims(e)[0];
return [evalPrim(p, 0), evalPrim(p, 1)];
}
/** The same curve run the other way. */
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() };
return e;
}
/** Point on a circle in the direction of q. */
function towards(c: Vec2, q: Vec2, r: number): Vec2 {
const L = Math.hypot(q[0] - c[0], q[1] - c[1]) || 1;
return [c[0] + ((q[0] - c[0]) / L) * r, c[1] + ((q[1] - c[1]) / L) * r];
}
/** A spline end's tangent as a line carrier (to carry it on straight). */
function splineEndCarrier(e: SketchEntity, end: "a" | "b"): Carrier | null {
if (e.kind !== "spline") return null;
const p = entityPrims(e)[0];
const q = evalPrim(p, end === "a" ? 0 : 1);
const r = evalPrim(p, end === "a" ? 0.01 : 0.99);
return { kind: "line", p: q, d: [q[0] - r[0], q[1] - r[1]] };
}
function carrierOf(e: SketchEntity): Carrier | null {
if (e.kind === "line") return { kind: "line", p: e.a, d: [e.b[0] - e.a[0], e.b[1] - e.a[1]] };
if (e.kind === "arc") {
const c = arcFrom3(e.a, e.m, e.b);
return c ? { kind: "circle", c: c.c, r: c.r } : null;
}
return null;
}
/** Where two infinite lines / full circles cross. */
function carrierCrossings(u: Carrier, v: Carrier): Vec2[] {
if (u.kind === "circle" && v.kind === "line") return carrierCrossings(v, u);
if (u.kind === "line" && v.kind === "line") {
const det = u.d[0] * v.d[1] - u.d[1] * v.d[0];
if (Math.abs(det) < 1e-12 * (Math.hypot(...u.d) * Math.hypot(...v.d) || 1)) return [];
const t = ((v.p[0] - u.p[0]) * v.d[1] - (v.p[1] - u.p[1]) * v.d[0]) / det;
return [[u.p[0] + u.d[0] * t, u.p[1] + u.d[1] * t]];
}
if (u.kind === "line" && v.kind === "circle") {
const L = Math.hypot(...u.d) || 1;
const d: Vec2 = [u.d[0] / L, u.d[1] / L];
const f: Vec2 = [u.p[0] - v.c[0], u.p[1] - v.c[1]];
const b = f[0] * d[0] + f[1] * d[1];
const disc = b * b - (f[0] * f[0] + f[1] * f[1] - v.r * v.r);
if (disc < -1e-12) return [];
const s = Math.sqrt(Math.max(0, disc));
return [-b - s, -b + s].map((t) => [u.p[0] + d[0] * t, u.p[1] + d[1] * t] as Vec2);
}
if (u.kind === "circle" && v.kind === "circle") {
const dx = v.c[0] - u.c[0];
const dy = v.c[1] - u.c[1];
const D = Math.hypot(dx, dy);
if (D < 1e-12 || D > u.r + v.r + 1e-9 || D < Math.abs(u.r - v.r) - 1e-9) return [];
const a = (u.r * u.r - v.r * v.r + D * D) / (2 * D);
const h = Math.sqrt(Math.max(0, u.r * u.r - a * a));
const m: Vec2 = [u.c[0] + (dx * a) / D, u.c[1] + (dy * a) / D];
return [
[m[0] - (dy * h) / D, m[1] + (dx * h) / D],
[m[0] + (dy * h) / D, m[1] - (dx * h) / D],
];
}
return [];
}
/** Move one end of a line/arc to `to` (an arc keeps its circle and its other end). */
function moveEnd(e: SketchEntity, end: "a" | "b", to: Vec2): SketchEntity {
if (e.kind === "line") return { ...e, [end]: to };
if (e.kind === "spline" && !e.closed) {
// The end fit point moves there.
const pts = [...e.points];
pts[end === "a" ? 0 : pts.length - 1] = to;
return { ...e, points: pts };
}
if (e.kind !== "arc") return e;
const c = arcFrom3(e.a, e.m, e.b);
if (!c) return e;
const ang = (q: Vec2) => Math.atan2(q[1] - c.c[1], q[0] - c.c[0]);
const a = end === "a" ? to : e.a;
const b = end === "b" ? to : e.b;
// Keep the arc's turning direction; the new mid point halves the new sweep.
const dir = Math.sign(c.sweep) || 1;
let sweep = ang(b) - ang(a);
while (dir > 0 && sweep <= 1e-9) sweep += 2 * Math.PI;
while (dir < 0 && sweep >= -1e-9) sweep -= 2 * Math.PI;
const t = ang(a) + sweep / 2;
return { ...e, a, b, m: [c.c[0] + c.r * Math.cos(t), c.c[1] + c.r * Math.sin(t)] };
}
/**
* Extend (or trim) two open curves so the picked ends meet: each pick says
* which end (the half that was tapped). Lines run along their direction,
* arcs along their circle. Picking both halves of one arc closes it into a circle.
*/
export function joinEnds(entities: SketchEntity[], first: { id: string; at: Vec2 }, second: { id: string; at: Vec2 }): SketchEntity[] | null {
const e1 = entities.find((x) => x.id === first.id);
const e2 = entities.find((x) => x.id === second.id);
if (!e1 || !e2) return null;
const end1 = endNear(e1, first.at);
const end2 = endNear(e2, second.at);
if (!end1 || !end2) return null;
if (e1.id === e2.id) {
if (e1.kind !== "arc" || end1 === end2) return null;
const c = arcFrom3(e1.a, e1.m, e1.b);
if (!c) return null;
const circle: SketchEntity = { id: e1.id, kind: "circle", center: c.c, radius: c.r, construction: e1.construction };
return entities.map((x) => (x.id === e1.id ? circle : x));
}
// A spline end carries on along its end tangent.
const k1 = carrierOf(e1) ?? splineEndCarrier(e1, end1);
const k2 = carrierOf(e2) ?? splineEndCarrier(e2, end2);
if (!k1 || !k2) return null;
const endPt = (e: SketchEntity, k: "a" | "b"): Vec2 => splineEnds(e)?.[k === "a" ? 0 : 1] ?? (e as Extract<SketchEntity, { kind: "line" | "arc" }>)[k];
const p1 = endPt(e1, end1);
const p2 = endPt(e2, end2);
// A line running into a spline (as it is, or carried on): it stops on the spline itself.
if ((e1.kind === "spline") !== (e2.kind === "spline")) {
const [ln, lnEnd, sp] = e1.kind === "spline" ? [e2, end2, e1] : [e1, end1, e2];
if (ln.kind === "line") {
const from = ln[lnEnd];
const other = lnEnd === "a" ? ln.b : ln.a;
const L = Math.hypot(from[0] - other[0], from[1] - other[1]) || 1;
const dir: Vec2 = [(from[0] - other[0]) / L, (from[1] - other[1]) / L];
const A: Vec2 = [other[0] - dir[0] * 1e6, other[1] - dir[1] * 1e6];
const B: Vec2 = [from[0] + dir[0] * 1e6, from[1] + dir[1] * 1e6];
const pts = samplePrim(entityPrims(sp)[0], 0, 1);
let best: Vec2 | null = null;
let bd = Infinity;
for (let i = 0; i < pts.length - 1; i++) {
const u = segHit(A, B, pts[i], pts[i + 1]);
if (u === null) continue;
const q: Vec2 = [A[0] + (B[0] - A[0]) * u, A[1] + (B[1] - A[1]) * u];
const dd = Math.hypot(q[0] - from[0], q[1] - from[1]);
if (dd < bd) [bd, best] = [dd, q];
}
if (best) return entities.map((x) => (x.id === ln.id ? moveEnd(ln, lnEnd, best!) : x));
}
}
const cands = carrierCrossings(k1, k2);
if (!cands.length) return null;
// The meeting point nearest both picked ends.
const cost = (q: Vec2) => Math.hypot(q[0] - p1[0], q[1] - p1[1]) + Math.hypot(q[0] - p2[0], q[1] - p2[1]);
const to = cands.reduce((m, q) => (cost(q) < cost(m) ? q : m), cands[0]);
// A spline carries on to the meeting point (it becomes its new end point).
const reach = (e: SketchEntity, end: "a" | "b"): SketchEntity => {
if (e.kind !== "spline") return moveEnd(e, end, to);
return { ...e, points: end === "a" ? [to, ...e.points] : [...e.points, to] };
};
return entities.map((x) => (x.id === e1.id ? reach(e1, end1) : x.id === e2.id ? reach(e2, end2) : x));
}
/**
* Cut a line or arc in two: at its midpoint, or at the point nearest `at`.
* The second piece gets `newId`; returns null for other curves.
*/
export function splitEntity(entities: SketchEntity[], id: string, newId: string, at?: Vec2): SketchEntity[] | null {
const e = entities.find((x) => x.id === id);
if (!e) return null;
if (e.kind === "line") {
const d: Vec2 = [e.b[0] - e.a[0], e.b[1] - e.a[1]];
const L2 = d[0] * d[0] + d[1] * d[1];
let t = 0.5;
if (at && L2 > 0) t = ((at[0] - e.a[0]) * d[0] + (at[1] - e.a[1]) * d[1]) / L2;
if (!(t > 1e-6 && t < 1 - 1e-6)) return null;
const m: Vec2 = [e.a[0] + d[0] * t, e.a[1] + d[1] * t];
return entities.flatMap((x) => (x.id === id ? [{ ...e, b: m }, { ...e, id: newId, a: m }] : [x]));
}
if (e.kind === "arc") {
const c = arcFrom3(e.a, e.m, e.b);
if (!c) return null;
let t = 0.5;
if (at) {
const ang = Math.atan2(at[1] - c.c[1], at[0] - c.c[0]);
let f = (ang - c.a0) / c.sweep;
// Bring the angle into the arc's own sweep.
const turn = (2 * Math.PI) / Math.abs(c.sweep);
while (f < 0) f += turn;
while (f > 1 && f - turn >= 0) f -= turn;
t = f;
}
if (!(t > 1e-6 && t < 1 - 1e-6)) return null;
const pt = (u: number): Vec2 => [c.c[0] + c.r * Math.cos(c.a0 + c.sweep * u), c.c[1] + c.r * Math.sin(c.a0 + c.sweep * u)];
const m = pt(t);
return entities.flatMap((x) => (x.id === id ? [{ ...e, m: pt(t / 2), b: m }, { ...e, id: newId, a: m, m: pt((1 + t) / 2) }] : [x]));
}
return null;
}
/**
* Fillet two lines picked by their halves: first they're extended/trimmed to
* meet (like `joinEnds`), then the corner is rounded with radius `r`.
*/
export function filletEnds(entities: SketchEntity[], first: { id: string; at: Vec2 }, second: { id: string; at: Vec2 }, r: number): SketchEntity[] | null {
const e1 = entities.find((x) => x.id === first.id);
const e2 = entities.find((x) => x.id === second.id);
if (e1?.kind !== "line" || e2?.kind !== "line" || e1.id === e2.id) return null;
const joined = joinEnds(entities, first, second);
if (!joined) return null;
const end = endNear(e1, first.at)!;
const corner = (joined.find((x) => x.id === e1.id) as Extract<SketchEntity, { kind: "line" }>)[end];
const size = Math.max(Math.hypot(e1.b[0] - e1.a[0], e1.b[1] - e1.a[1]), Math.hypot(e2.b[0] - e2.a[0], e2.b[1] - e2.a[1]), 1);
return filletCorner(joined, corner, r, size * 1e-7);
}
/**
* Turn line `id2` so it makes `deg` degrees with line `id1`, about its end
* nearest to line 1. Both lines are re-oriented to point away from where they
* (would) meet, so their a→b directions span exactly that angle; `swapped`
* lists lines whose ends were exchanged (point refs a/b must follow).
*/
export function angleLines(entities: SketchEntity[], id1: string, id2: string, deg: number): { entities: SketchEntity[]; swapped: string[] } | null {
const l1 = entities.find((e) => e.id === id1);
const l2 = entities.find((e) => e.id === id2);
if (l1?.kind !== "line" || l2?.kind !== "line" || id1 === id2) return null;
const d1raw: Vec2 = [l1.b[0] - l1.a[0], l1.b[1] - l1.a[1]];
const L1 = Math.hypot(...d1raw);
if (L1 < 1e-12) return null;
// Pivot: the end of line 2 closest to line 1 (its infinite line).
const off = (q: Vec2) => Math.abs((q[0] - l1.a[0]) * d1raw[1] - (q[1] - l1.a[1]) * d1raw[0]) / L1;
const pivotIsA = off(l2.a) <= off(l2.b);
const pivot = pivotIsA ? l2.a : l2.b;
const far = pivotIsA ? l2.b : l2.a;
const d2: Vec2 = [far[0] - pivot[0], far[1] - pivot[1]];
const L2 = Math.hypot(...d2);
if (L2 < 1e-12) return null;
// Line 1 points away from the meeting point (its far end from line 2's pivot).
const da = Math.hypot(l1.a[0] - pivot[0], l1.a[1] - pivot[1]);
const db = Math.hypot(l1.b[0] - pivot[0], l1.b[1] - pivot[1]);
const flip1 = db < da;
const u: Vec2 = flip1 ? [-d1raw[0] / L1, -d1raw[1] / L1] : [d1raw[0] / L1, d1raw[1] / L1];
// Keep the side line 2 is on now (counter-clockwise or clockwise from line 1).
const side = u[0] * d2[1] - u[1] * d2[0] >= 0 ? 1 : -1;
const t = Math.atan2(u[1], u[0]) + side * (deg * Math.PI) / 180;
const nf: Vec2 = [pivot[0] + Math.cos(t) * L2, pivot[1] + Math.sin(t) * L2];
const swapped: string[] = [];
if (flip1) swapped.push(id1);
if (!pivotIsA) swapped.push(id2);
return {
entities: entities.map((e) => (e.id === id1 && flip1 ? { ...l1, a: l1.b, b: l1.a } : e.id === id2 ? { ...l2, a: pivot, b: nf } : e)),
swapped,
};
}
/** A curve with open ends (line/arc), walked in the chain's direction. */
export interface ChainLink {
id: string;
/** Walked b→a rather than a→b. */
reversed: boolean;
}
/**
* Curves joined end to end with `id` (lines and arcs), in order. `closed`
* when the last one comes back to where the first started.
*/
export function connectedChain(entities: SketchEntity[], id: string): { links: ChainLink[]; closed: boolean } | null {
// Lines, arcs and open splines, by their two ends.
type Open = { id: string; a: Vec2; b: Vec2 };
const open: Open[] = entities.flatMap((e) => {
if (e.construction) return [];
if (e.kind === "line" || e.kind === "arc") return [{ id: e.id, a: e.a, b: e.b }];
const ends = splineEnds(e);
return ends ? [{ id: e.id, a: ends[0], b: ends[1] }] : [];
});
const start = open.find((e) => e.id === id);
if (!start) return null;
const size = Math.max(1, ...open.flatMap((e) => [Math.abs(e.a[0]), Math.abs(e.a[1]), Math.abs(e.b[0]), Math.abs(e.b[1])]));
const tol = size * 1e-7;
const same = (p: Vec2, q: Vec2) => Math.hypot(p[0] - q[0], p[1] - q[1]) < tol;
const used = new Set([start.id]);
const walk = (from: Vec2): ChainLink[] => {
const out: ChainLink[] = [];
let at = from;
for (;;) {
const next = open.find((e) => !used.has(e.id) && (same(e.a, at) || same(e.b, at)));
if (!next) return out;
used.add(next.id);
const reversed = !same(next.a, at);
out.push({ id: next.id, reversed });
at = reversed ? next.a : next.b;
}
};
const forward = walk(start.b);
const last = forward.length ? open.find((e) => e.id === forward[forward.length - 1].id)! : start;
const lastEnd = forward.length ? (forward[forward.length - 1].reversed ? last.a : last.b) : start.b;
const closed = forward.length > 0 && same(lastEnd, start.a);
// Not closed: also walk backwards from the start, then flip that part.
const backward = closed ? [] : walk(start.a).reverse().map((l) => ({ ...l, reversed: !l.reversed }));
return { links: [...backward, { id: start.id, reversed: false }, ...forward], closed };
}
/**
* Offset a whole chain (e.g. a closed outline made of lines and arcs) by `d`:
* each piece moves sideways and neighbours are trimmed/extended to meet again,
* so a closed shape stays closed. Positive `d` grows a closed shape outward.
*/
export function offsetChain(entities: SketchEntity[], id: string, d: number): SketchEntity[] | null {
const chain = connectedChain(entities, id);
if (!chain) return null;
const byId = new Map(entities.map((e) => [e.id, e]));
// Walk direction: flip pieces walked backwards so every piece runs along the chain.
const pieces = chain.links.map((l) => reverseIf(byId.get(l.id)!, l.reversed) as Piece);
// Outward is to the right of a counter-clockwise loop (offsetEntity goes left).
let side = 1;
if (chain.closed) {
const poly = pieces.flatMap((e) => (e.kind === "arc" ? [e.a, e.m] : e.kind === "spline" ? samplePrim(entityPrims(e)[0], 0, 1).slice(0, -1) : [e.a]));
let area = 0;
for (let i = 0; i < poly.length; i++) {
const p = poly[i];
const q = poly[(i + 1) % poly.length];
area += p[0] * q[1] - q[0] * p[1];
}
side = area > 0 ? -1 : 1;
}
// offsetEntity moves lines to their left but arcs always outward: an arc
// turning left (counter-clockwise) has its left side towards its centre.
const leftOf = (e: Piece) => (e.kind === "arc" && (arcFrom3(e.a, e.m, e.b)?.sweep ?? 0) > 0 ? -1 : 1);
const moved = pieces.map((e) => offsetEntity(e, leftOf(e) * side * d) as Piece | null);
if (moved.some((m) => !m)) return null;
const out = moved as Piece[];
const endOf = (e: Piece, k: "a" | "b"): Vec2 => (e.kind === "spline" ? splineEnds(e)![k === "a" ? 0 : 1] : e[k]);
// Re-join neighbours where their offset carriers cross, nearest the original corner.
const n = out.length;
for (let i = 0; i < (chain.closed ? n : n - 1); i++) {
const j = (i + 1) % n;
const k1 = carrierOf(out[i]);
const k2 = carrierOf(out[j]);
const corner = endOf(pieces[i], "b");
let meet: Vec2 | null = null;
if (k1 && k2) {
const cands = carrierCrossings(k1, k2);
if (cands.length) meet = cands.reduce((m, q) => (Math.hypot(q[0] - corner[0], q[1] - corner[1]) < Math.hypot(m[0] - corner[0], m[1] - corner[1]) ? q : m), cands[0]);
} else if (k1 || k2) {
// A spline next to a line/arc: the spline's offset end, brought onto the other's carrier.
const k = (k1 ?? k2)!;
const q = k1 ? endOf(out[j], "a") : endOf(out[i], "b");
meet = k.kind === "line" ? projectOnLine(q, k.p, [k.p[0] + k.d[0], k.p[1] + k.d[1]]) : towards(k.c, q, k.r);
} else {
// Two splines: halfway between their offset ends.
const p = endOf(out[i], "b");
const q = endOf(out[j], "a");
meet = [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2];
}
// Tangent neighbours (e.g. line into a fillet) already meet: keep the offset end.
if (!meet) meet = endOf(out[i], "b");
out[i] = moveEnd(out[i], "b", meet) as (typeof out)[number];
out[j] = moveEnd(out[j], "a", meet) as (typeof out)[number];
}
return [...entities, ...out.map((e) => ({ ...e, id: uid() }))];
}
// --------------------------------------------------------------- offset
/** Offset copy of an entity (outward for closed shapes, to the left for open ones). */
export function offsetEntity(e: SketchEntity, d: number): SketchEntity | null {
const base = { id: uid(), construction: e.construction };
switch (e.kind) {
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;
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": {
const r = e.radius + d / Math.cos(Math.PI / e.sides);
return r > 0 ? { ...base, kind: "polygon", center: e.center, radius: r, sides: e.sides, angle: e.angle } : null;
}
case "line": {
const dx = e.b[0] - e.a[0];
const dy = e.b[1] - e.a[1];
const L = Math.hypot(dx, dy) || 1;
const nx = (-dy / L) * d;
const ny = (dx / L) * d;
return { ...base, kind: "line", a: [e.a[0] + nx, e.a[1] + ny], b: [e.b[0] + nx, e.b[1] + ny] };
}
case "arc": {
const c = arcFrom3(e.a, e.m, e.b);
if (!c) return null;
const k = (c.r + d) / c.r;
if (k <= 0) return null;
const s = scaleXf(c.c, k);
return { ...base, kind: "arc", a: s(e.a), m: s(e.m), b: s(e.b) };
}
case "spline":
case "polyline": {
const pts = e.kind === "spline" ? samplePrim(entityPrims(e)[0], 0, 1) : e.points;
const closed = e.closed;
const sign = closed && signedArea(pts) < 0 ? -1 : 1;
const out = pts.map((p, i) => {
const prev = pts[i === 0 ? (closed ? pts.length - 2 : 0) : i - 1];
const next = pts[i === pts.length - 1 ? (closed ? 1 : i) : i + 1];
const tx = next[0] - prev[0];
const ty = next[1] - prev[1];
const L = Math.hypot(tx, ty) || 1;
// 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 };
}
}
}
function signedArea(p: Vec2[]): number {
let a = 0;
for (let i = 0, j = p.length - 1; i < p.length; j = i++) a += (p[j][0] + p[i][0]) * (p[j][1] - p[i][1]);
return -a / 2;
}
function thin(pts: Vec2[], n: number): Vec2[] {
if (pts.length <= n) return pts;
const step = (pts.length - 1) / (n - 1);
return Array.from({ length: n }, (_, i) => pts[Math.round(i * step)]);
}
// --------------------------------------------------------------- fillet
/**
* Round the corner nearest `at` where two lines meet. Rects/polygons are
* turned into lines first. Returns null if no corner is near.
*/
export function filletCorner(entities: SketchEntity[], at: Vec2, radius: number, tol: number): SketchEntity[] | null {
let list = entities.flatMap((e) => (e.kind === "rect" || e.kind === "polygon" || e.kind === "polyline" ? cornerNear(e, at, tol) ? explode(e) : [e] : [e]));
const lines = list.filter((e): e is Extract<SketchEntity, { kind: "line" }> => e.kind === "line");
const ends: { e: (typeof lines)[number]; end: "a" | "b" }[] = [];
for (const e of lines) for (const end of ["a", "b"] as const) if (Math.hypot(e[end][0] - at[0], e[end][1] - at[1]) < tol) ends.push({ e, end });
if (ends.length < 2) return null;
const [p, q] = ends;
const corner = p.e[p.end];
const farP = p.e[p.end === "a" ? "b" : "a"];
const farQ = q.e[q.end === "a" ? "b" : "a"];
const u = unit(sub2(farP, corner));
const v = unit(sub2(farQ, corner));
const cos = u[0] * v[0] + u[1] * v[1];
const half = Math.acos(Math.max(-1, Math.min(1, cos))) / 2;
if (half < 1e-3 || Math.PI / 2 - half < 1e-3) return null;
const dist = radius / Math.tan(half);
if (dist > Math.hypot(...sub2(farP, corner)) || dist > Math.hypot(...sub2(farQ, corner))) return null;
const tp: Vec2 = [corner[0] + u[0] * dist, corner[1] + u[1] * dist];
const tq: Vec2 = [corner[0] + v[0] * dist, corner[1] + v[1] * dist];
const bis = unit([u[0] + v[0], u[1] + v[1]]);
const cdist = radius / Math.sin(half);
const c: Vec2 = [corner[0] + bis[0] * cdist, corner[1] + bis[1] * cdist];
const mid: Vec2 = [c[0] - bis[0] * radius, c[1] - bis[1] * radius];
list = list.map((e) => (e === p.e ? { ...p.e, [p.end]: tp } : e === q.e ? { ...q.e, [q.end]: tq } : e));
list.push({ id: uid(), kind: "arc", a: tp, m: mid, b: tq, construction: p.e.construction });
return list;
}
function cornerNear(e: Extract<SketchEntity, { kind: "rect" | "polygon" | "polyline" }>, at: Vec2, tol: number): boolean {
return entityCorners(e).some((p) => Math.hypot(p[0] - at[0], p[1] - at[1]) < tol);
}
const sub2 = (a: Vec2, b: Vec2): Vec2 => [a[0] - b[0], a[1] - b[1]];
const unit = (a: Vec2): Vec2 => {
const l = Math.hypot(a[0], a[1]) || 1;
return [a[0] / l, a[1] / l];
};
// --------------------------------------------------- projection of edges
/**
* 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 {
const pts = dedupe(pts3.map((p) => toPlane(plane, p)));
if (pts.length < 2) return null;
const a = pts[0];
const b = pts[pts.length - 1];
const closed = Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-6 * (1 + span(pts));
if (type === "LINE" || pts.length === 2) return { id: uid(), kind: "line", a, b };
if (type === "CIRCLE") {
const m = pts[Math.floor(pts.length / 2)];
const q = pts[Math.floor(pts.length / 3)];
const c = arcFrom3(pts[0], q, m);
if (c) {
// Only a true circle if the projection didn't squash it (plane parallel to the edge's circle).
const ok = pts.every((p) => Math.abs(Math.hypot(p[0] - c.c[0], p[1] - c.c[1]) - c.r) < c.r * 1e-3);
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" };
}
function dedupe(pts: Vec2[]): Vec2[] {
const out: Vec2[] = [];
for (const p of pts) {
const q = out[out.length - 1];
if (!q || Math.hypot(p[0] - q[0], p[1] - q[1]) > 1e-9) out.push(p);
}
return out;
}
function span(pts: Vec2[]): number {
let m = 0;
for (const p of pts) m = Math.max(m, Math.abs(p[0]), Math.abs(p[1]));
return m;
}
/**
* After a fillet: the lines no longer meet at the old corner, so the
* Coincident that joined them there would pull them back. Replace it with
* Coincident + Tangent between each line and the new arc.
*/
export function filletConstraints(entities: SketchEntity[], constraints: SketchConstraint[], before: Set<string>): SketchConstraint[] {
const arcs = entities.filter((e): e is Extract<SketchEntity, { kind: "arc" }> => e.kind === "arc" && !before.has(e.id));
let cs = constraints;
for (const arc of arcs) {
const touching: { e: string; p: "a" | "b"; arcEnd: "a" | "b" }[] = [];
for (const l of entities)
if (l.kind === "line")
for (const p of ["a", "b"] as const)
for (const arcEnd of ["a", "b"] as const) if (Math.hypot(l[p][0] - arc[arcEnd][0], l[p][1] - arc[arcEnd][1]) < 1e-9) touching.push({ e: l.id, p, arcEnd });
if (touching.length < 2) continue;
const ends = new Set(touching.map((t) => `${t.e}:${t.p}`));
// Drop constraints that tie these moved ends to each other.
cs = cs.filter((c) => !(c.type === "coincident" && c.pts?.length === 2 && c.pts.every((q) => ends.has(`${q.e}:${q.p}`))));
for (const t of touching) {
cs = [...cs, { id: uid(), type: "coincident", pts: [{ e: t.e, p: t.p }, { e: arc.id, p: t.arcEnd }] }, { id: uid(), type: "tangent", curves: [t.e, arc.id] }];
}
}
return cs;
}
// ------------------------------------------------------------ align / join
type LineE = Extract<SketchEntity, { kind: "line" }>;
const near2 = (p: Vec2, q: Vec2, tol: number) => Math.hypot(p[0] - q[0], p[1] - q[1]) < tol;
/** Where the infinite line p + t·d meets the infinite line through a, b (null if parallel). */
function meetLines(p: Vec2, d: Vec2, a: Vec2, b: Vec2): Vec2 | null {
const e: Vec2 = [b[0] - a[0], b[1] - a[1]];
const den = d[0] * e[1] - d[1] * e[0];
if (Math.abs(den) < 1e-12 * Math.hypot(...d) * Math.hypot(...e)) return null;
const t = ((a[0] - p[0]) * e[1] - (a[1] - p[1]) * e[0]) / den;
return [p[0] + d[0] * t, p[1] + d[1] * t];
}
function projectOnLine(p: Vec2, a: Vec2, b: Vec2): Vec2 {
const d: Vec2 = [b[0] - a[0], b[1] - a[1]];
const l2 = d[0] * d[0] + d[1] * d[1] || 1;
const t = ((p[0] - a[0]) * d[0] + (p[1] - a[1]) * d[1]) / l2;
return [a[0] + d[0] * t, a[1] + d[1] * t];
}
/**
* Align: line `id` moves onto the infinite line of `target` (it ends up lying
* on it). Lines joined to its ends keep their direction and stretch to follow,
* like the neighbouring faces of a replaced face.
*/
export function alignLine(entities: SketchEntity[], id: string, target: SketchEntity): SketchEntity[] | null {
const ln = entities.find((e) => e.id === id);
if (ln?.kind !== "line" || target.kind !== "line" || target.id === id) return null;
const [ta, tb] = [target.a, target.b];
const size = Math.hypot(ln.b[0] - ln.a[0], ln.b[1] - ln.a[1]) + Math.hypot(tb[0] - ta[0], tb[1] - ta[1]);
const tol = size * 1e-6 + 1e-9;
const moved = new Map<string, LineE>();
const ends: Record<"a" | "b", Vec2> = { a: ln.a, b: ln.b };
for (const k of ["a", "b"] as const) {
const p = ln[k];
// A line joined here (not the target itself) slides its end along its own direction.
const nb = entities.find((e): e is LineE => e.kind === "line" && e.id !== id && e.id !== target.id && !e.construction && (near2(e.a, p, tol) || near2(e.b, p, tol)));
let q: Vec2 | null = null;
if (nb) {
const end = near2(nb.a, p, tol) ? "a" : "b";
const other = end === "a" ? nb.b : nb.a;
q = meetLines(other, [p[0] - other[0], p[1] - other[1]], ta, tb);
if (q) moved.set(nb.id, { ...(moved.get(nb.id) ?? nb), [end]: q });
}
ends[k] = q ?? projectOnLine(p, ta, tb);
}
if (near2(ends.a, ends.b, tol)) return null;
return entities.map((e) => (e.id === id ? { ...ln, a: ends.a, b: ends.b } : moved.get(e.id) ?? e));
}
/**
* Join: line `id` and a line on the same axis that shares one of its ends
* become a single line. Returns the new entities and the id that was merged away.
*/
export function joinCollinear(entities: SketchEntity[], id: string, prefer?: Vec2): { entities: SketchEntity[]; removed: string } | null {
const ln = entities.find((e) => e.id === id);
if (ln?.kind !== "line") return null;
const len = Math.hypot(ln.b[0] - ln.a[0], ln.b[1] - ln.a[1]);
const tol = len * 1e-6 + 1e-9;
const d: Vec2 = [(ln.b[0] - ln.a[0]) / len, (ln.b[1] - ln.a[1]) / len];
const onAxis = (p: Vec2) => Math.abs((p[0] - ln.a[0]) * d[1] - (p[1] - ln.a[1]) * d[0]) < tol * 10;
const cands = entities.filter(
(e): e is LineE => e.kind === "line" && e.id !== id && !!e.construction === !!ln.construction && onAxis(e.a) && onAxis(e.b) && [e.a, e.b].some((p) => near2(p, ln.a, tol) || near2(p, ln.b, tol)),
);
if (!cands.length) return null;
// Two candidates (one at each end): the one on the side that was tapped.
const along = (p: Vec2) => (p[0] - ln.a[0]) * d[0] + (p[1] - ln.a[1]) * d[1];
const pick = prefer && cands.length > 1 ? cands.reduce((x, y) => (Math.abs(along(mid(x)) - along(prefer)) < Math.abs(along(mid(y)) - along(prefer)) ? x : y)) : cands[0];
const pts = [ln.a, ln.b, pick.a, pick.b].sort((p, q) => along(p) - along(q));
const joined: LineE = { ...ln, a: pts[0], b: pts[3] };
return { entities: entities.filter((e) => e.id !== pick.id).map((e) => (e.id === id ? joined : e)), removed: pick.id };
}
function mid(l: LineE): Vec2 {
return [(l.a[0] + l.b[0]) / 2, (l.a[1] + l.b[1]) / 2];
}
+390
View File
@@ -0,0 +1,390 @@
// Planar arrangement of sketch curves → selectable regions.
//
// All curves are split where they cross, the pieces form a planar graph, and
// every bounded face of that graph is a region (with holes for anything nested
// inside it). This is what lets overlapping shapes be extruded piece by piece.
import type { SketchEntity, Vec2 } from "../doc/types";
import { closestOnPrim, entityPrims, evalPrim, isClosedPrim, pointInPoly, polyArea, polyCentroid, primSegments, samplePrim, type Prim } from "./curves";
export interface Piece {
prim: number;
t0: number;
t1: number;
n0: number;
n1: number;
/** Polyline from node n0 to node n1 (endpoints are the node positions). */
poly: Vec2[];
}
export interface LoopRef {
piece: number;
reversed: boolean;
}
export interface Loop {
pieces: LoopRef[];
poly: Vec2[];
}
export interface Region {
index: number;
outer: Loop;
holes: Loop[];
area: number;
centroid: Vec2;
}
export interface Arrangement {
prims: Prim[];
nodes: Vec2[];
pieces: Piece[];
regions: Region[];
}
export interface RegionRef {
c: Vec2;
a: number;
}
const cache = new Map<string, Arrangement>();
/** Regions of a sketch. Memoised on the entity list, so callers can call freely. */
export function arrangement(entities: SketchEntity[]): Arrangement {
const key = JSON.stringify(entities);
const hit = cache.get(key);
if (hit) return hit;
const result = compute(entities.filter((e) => !e.construction));
cache.set(key, result);
if (cache.size > 64) cache.delete(cache.keys().next().value!);
return result;
}
export function regionRef(r: Region): RegionRef {
return { c: r.centroid, a: r.area };
}
/** The region best matching a stored reference (survives edits that move it a bit). */
export function resolveRegion(arr: Arrangement, ref: RegionRef): Region | null {
let best: { r: Region; s: number } | null = null;
for (const r of arr.regions) {
const scale = Math.sqrt(Math.max(ref.a, 1e-9));
const s = Math.hypot(r.centroid[0] - ref.c[0], r.centroid[1] - ref.c[1]) / scale + Math.abs(Math.log((r.area + 1e-12) / (ref.a + 1e-12)));
if (!best || s < best.s) best = { r, s };
}
return best && best.s < 3 ? best.r : null;
}
function compute(entities: SketchEntity[]): Arrangement {
const prims = entities.flatMap(entityPrims);
const empty: Arrangement = { prims, nodes: [], pieces: [], regions: [] };
if (!prims.length) return empty;
// ---- discretise
const samples = prims.map((p) => {
const n = primSegments(p);
const ts = Array.from({ length: n + 1 }, (_, i) => i / n);
return { ts, pts: ts.map((t) => evalPrim(p, t)) };
});
let minX = Infinity;
let minY = Infinity;
let maxX = -Infinity;
let maxY = -Infinity;
for (const s of samples)
for (const [x, y] of s.pts) {
minX = Math.min(minX, x);
minY = Math.min(minY, y);
maxX = Math.max(maxX, x);
maxY = Math.max(maxY, y);
}
const size = Math.hypot(maxX - minX, maxY - minY) || 1;
const eps = size * 1e-7;
// ---- intersections (sweep over segments sorted by min x)
interface Seg {
p: number;
i: number;
a: Vec2;
b: Vec2;
x0: number;
x1: number;
y0: number;
y1: number;
}
const segs: Seg[] = [];
samples.forEach((s, p) => {
for (let i = 0; i < s.pts.length - 1; i++) {
const a = s.pts[i];
const b = s.pts[i + 1];
segs.push({ p, i, a, b, x0: Math.min(a[0], b[0]) - eps, x1: Math.max(a[0], b[0]) + eps, y0: Math.min(a[1], b[1]) - eps, y1: Math.max(a[1], b[1]) + eps });
}
});
segs.sort((u, v) => u.x0 - v.x0);
const splits: number[][] = prims.map(() => []);
const tParam = (p: number, i: number, u: number) => samples[p].ts[i] + (samples[p].ts[i + 1] - samples[p].ts[i]) * u;
for (let i = 0; i < segs.length; i++) {
const A = segs[i];
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
// 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);
if (lap) {
for (const u of lap[0]) splits[A.p].push(tParam(A.p, A.i, u));
for (const v of lap[1]) splits[B.p].push(tParam(B.p, B.i, v));
continue;
}
const hit = segHit(A.a, A.b, B.a, B.b, eps);
if (!hit) continue;
let ta = tParam(A.p, A.i, hit[0]);
let tb = tParam(B.p, B.i, hit[1]);
[ta, tb] = refine(prims[A.p], prims[B.p], ta, tb);
splits[A.p].push(ta);
splits[B.p].push(tb);
}
}
// ---- pieces
const nodes: Vec2[] = [];
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;
nodes.push(pt);
return nodes.length - 1;
};
let pieces: Piece[] = [];
prims.forEach((p, pi) => {
const closed = isClosedPrim(p);
let ts = [...splits[pi]].map((t) => Math.min(1, Math.max(0, t))).sort((a, b) => a - b);
if (closed) {
ts = ts.map((t) => (t >= 1 - 1e-9 ? 0 : t)).sort((a, b) => a - b);
if (ts.length === 0) ts = [0, 0.5];
else if (ts.length === 1) ts.push(ts[0] + 0.5 > 1 ? ts[0] - 0.5 : ts[0] + 0.5), ts.sort((a, b) => a - b);
} else {
ts.unshift(0);
ts.push(1);
}
const uniq = ts.filter((t, k) => k === 0 || t - ts[k - 1] > 1e-9);
const bounds: [number, number][] = [];
for (let k = 0; k < uniq.length - 1; k++) bounds.push([uniq[k], uniq[k + 1]]);
if (closed) bounds.push([uniq[uniq.length - 1], uniq[0] + 1]);
for (const [t0, t1] of bounds) {
const a = evalPrim(p, t0 % 1);
const b = evalPrim(p, t1 > 1 ? t1 - 1 : t1);
const poly = closed && t1 > 1 ? [...samplePrim(p, t0, 1).slice(0, -1), ...samplePrim(p, 0, t1 - 1)] : samplePrim(p, t0, t1);
if (polyLength(poly) < eps * 10) continue;
const n0 = nodeOf(a);
const n1 = nodeOf(b);
poly[0] = nodes[n0];
poly[poly.length - 1] = nodes[n1];
pieces.push({ prim: pi, t0, t1, n0, n1, poly });
}
});
// ---- the same stretch drawn twice counts once
{
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);
return true;
});
}
// ---- drop dangling pieces (they can't bound a region)
for (;;) {
const deg = new Array(nodes.length).fill(0);
for (const pc of pieces) {
deg[pc.n0]++;
deg[pc.n1]++;
}
const keep = pieces.filter((pc) => deg[pc.n0] > 1 && deg[pc.n1] > 1);
if (keep.length === pieces.length) break;
pieces = keep;
}
if (!pieces.length) return { prims, nodes, pieces, regions: [] };
// ---- half-edge traversal
const H = pieces.length * 2;
const from = (h: number) => (h % 2 === 0 ? pieces[h >> 1].n0 : pieces[h >> 1].n1);
const hpoly = (h: number) => (h % 2 === 0 ? pieces[h >> 1].poly : [...pieces[h >> 1].poly].reverse());
const angleOf = (h: number) => {
const pl = hpoly(h);
const a = pl[0];
const b = pl[1];
const c = pl[Math.min(2, pl.length - 1)];
const main = Math.atan2(b[1] - a[1], b[0] - a[0]);
// Tie-break tangent pieces by where they head next.
const next = Math.atan2(c[1] - a[1], c[0] - a[0]);
return main + angleDiff(main, next) * 1e-3;
};
const out: number[][] = nodes.map(() => []);
for (let h = 0; h < H; h++) out[from(h)].push(h);
const ang = new Float64Array(H);
for (let h = 0; h < H; h++) ang[h] = angleOf(h);
for (const list of out) list.sort((x, y) => ang[x] - ang[y]);
const next = (h: number) => {
const twin = h ^ 1;
const list = out[from(twin)];
const k = list.indexOf(twin);
return list[(k - 1 + list.length) % list.length];
};
const seen = new Uint8Array(H);
const cycles: { hs: number[]; poly: Vec2[]; area: number }[] = [];
for (let h0 = 0; h0 < H; h0++) {
if (seen[h0]) continue;
const hs: number[] = [];
let h = h0;
let guard = 0;
while (!seen[h] && guard++ < H + 1) {
seen[h] = 1;
hs.push(h);
h = next(h);
}
const poly: Vec2[] = [];
for (const x of hs) poly.push(...hpoly(x).slice(0, -1));
cycles.push({ hs, poly, area: polyArea(poly) });
}
// ---- components (union-find over nodes)
const parent = nodes.map((_, i) => i);
const find = (i: number): number => (parent[i] === i ? i : (parent[i] = find(parent[i])));
for (const pc of pieces) parent[find(pc.n0)] = find(pc.n1);
const comp = (c: { hs: number[] }) => find(from(c.hs[0]));
const minArea = eps * eps * 100;
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>();
for (const o of outers) {
const p = o.poly[0];
let best: (typeof faces)[number] | null = null;
for (const f of faces) {
if (comp(f) === comp(o)) continue;
if (!pointInPoly(p, f.poly)) continue;
if (!best || f.area < best.area) best = f;
}
if (best) holes.set(best, [...(holes.get(best) ?? []), o]);
}
const toLoop = (c: { hs: number[]; poly: Vec2[] }): Loop => ({
pieces: c.hs.map((h) => ({ piece: h >> 1, reversed: h % 2 === 1 })),
poly: c.poly,
});
const regions: Region[] = faces.map((f, index) => {
const hs = holes.get(f) ?? [];
const holeArea = hs.reduce((s, o) => s + Math.abs(o.area), 0);
const area = f.area - holeArea;
// Area-weighted centroid of the face minus its holes.
const c0 = polyCentroid(f.poly);
let cx = c0[0] * f.area;
let cy = c0[1] * f.area;
for (const o of hs) {
const ch = polyCentroid(o.poly);
cx -= ch[0] * Math.abs(o.area);
cy -= ch[1] * Math.abs(o.area);
}
return { index, outer: toLoop(f), holes: hs.map(toLoop), area, centroid: [cx / area, cy / area] };
});
return { prims, nodes, pieces, regions };
}
/**
* Two collinear, overlapping segments → where (as fractions along each) the
* other one's ends fall inside it. Null when they don't lie on each other.
*/
function overlap(a: Vec2, b: Vec2, c: Vec2, d: Vec2, eps: number): [number[], number[]] | null {
const rx = b[0] - a[0];
const ry = b[1] - a[1];
const sx = d[0] - c[0];
const sy = d[1] - c[1];
const lu = Math.hypot(rx, ry);
const lv = Math.hypot(sx, sy);
if (lu < eps || lv < eps) return null;
if (Math.abs(rx * sy - ry * sx) > lu * lv * 1e-6) return null;
// Both ends of cd on the line through ab?
const off = (p: Vec2) => Math.abs((p[0] - a[0]) * ry - (p[1] - a[1]) * rx) / lu;
if (off(c) > eps * 10 || off(d) > eps * 10) return null;
const along = (p: Vec2, o: Vec2, x: number, y: number, l: number) => ((p[0] - o[0]) * x + (p[1] - o[1]) * y) / (l * l);
const inside = (u: number, l: number) => u > (eps * 10) / l && u < 1 - (eps * 10) / l;
const ua = [along(c, a, rx, ry, lu), along(d, a, rx, ry, lu)].filter((u) => inside(u, lu));
const vb = [along(a, c, sx, sy, lv), along(b, c, sx, sy, lv)].filter((v) => inside(v, lv));
const lo = Math.min(along(c, a, rx, ry, lu), along(d, a, rx, ry, lu));
const hi = Math.max(along(c, a, rx, ry, lu), along(d, a, rx, ry, lu));
if (hi < 0 || lo > 1) return null;
return [ua, vb];
}
function segHit(a: Vec2, b: Vec2, c: Vec2, d: Vec2, eps: number): [number, number] | null {
const rx = b[0] - a[0];
const ry = b[1] - a[1];
const sx = d[0] - c[0];
const sy = d[1] - c[1];
const den = rx * sy - ry * sx;
if (Math.abs(den) < 1e-18) return null; // parallel / collinear overlaps ignored
const qx = c[0] - a[0];
const qy = c[1] - a[1];
const u = (qx * sy - qy * sx) / den;
const v = (qx * ry - qy * rx) / den;
const lu = Math.hypot(rx, ry) || 1;
const lv = Math.hypot(sx, sy) || 1;
const tu = eps / lu;
const tv = eps / lv;
if (u < -tu || u > 1 + tu || v < -tv || v > 1 + tv) return null;
return [Math.min(1, Math.max(0, u)), Math.min(1, Math.max(0, v))];
}
/** Newton-refine an intersection on the exact curves. */
function refine(p: Prim, q: Prim, t: number, s: number): [number, number] {
if (p.t === "spline" && q.t === "spline") return [t, s];
const h = 1e-7;
for (let k = 0; k < 8; k++) {
const P = evalPrim(p, t);
const Q = evalPrim(q, s);
const fx = P[0] - Q[0];
const fy = P[1] - Q[1];
if (Math.abs(fx) + Math.abs(fy) < 1e-12) break;
const Pt = evalPrim(p, Math.min(1, t + h));
const Qs = evalPrim(q, Math.min(1, s + h));
const a = (Pt[0] - P[0]) / h;
const c = (Pt[1] - P[1]) / h;
const b = -(Qs[0] - Q[0]) / h;
const d = -(Qs[1] - Q[1]) / h;
const det = a * d - b * c;
if (Math.abs(det) < 1e-14) break;
const dt = (d * fx - b * fy) / det;
const ds = (-c * fx + a * fy) / det;
t = Math.min(1, Math.max(0, t - dt));
s = Math.min(1, Math.max(0, s - ds));
}
return [t, s];
}
function polyLength(p: Vec2[]): number {
let l = 0;
for (let i = 1; i < p.length; i++) l += Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]);
return l;
}
function angleDiff(a: number, b: number): number {
let d = b - a;
while (d > Math.PI) d -= Math.PI * 2;
while (d < -Math.PI) d += Math.PI * 2;
return d;
}
/** Parameter + distance of the closest point on any primitive of an entity. */
export function closestOnEntity(e: SketchEntity, q: Vec2): { t: number; d: number; pt: Vec2; prim: number } {
const prims = entityPrims(e);
let best = { t: 0, d: Infinity, pt: q, prim: 0 };
prims.forEach((p, i) => {
const c = closestOnPrim(p, q);
if (c.d < best.d) best = { ...c, prim: i };
});
return best;
}
+88
View File
@@ -0,0 +1,88 @@
// Text → closed outline polylines (each glyph contour; holes come out as regions).
// Font: Roboto (Apache-2.0), parsed with opentype.js (MIT).
import { parse, type Font } from "opentype.js";
import fontUrl from "@fontsource/roboto/files/roboto-latin-400-normal.woff?url";
import type { SketchEntity, Vec2 } from "../doc/types";
import { uid } from "./edit";
let font: Promise<Font> | null = null;
function loadFont(): Promise<Font> {
font ??= fetch(fontUrl)
.then((r) => r.arrayBuffer())
.then((b) => parse(b));
return font;
}
/** Outline entities for `text` with its baseline-left at `at`, cap height ≈ size. */
export async function textEntities(text: string, at: Vec2, size: number, angle = 0): Promise<SketchEntity[]> {
const f = await loadFont();
// opentype sizes are em; Roboto caps are ~0.71 em.
const fontSize = size / 0.711;
// Lay glyphs out ourselves: opentype's text shaper chokes on some of Roboto's
// substitution tables ("substFormat 2 not supported").
const scale = fontSize / f.unitsPerEm;
const commands: { type: string; x?: number; y?: number; x1?: number; y1?: number; x2?: number; y2?: number }[] = [];
let x = 0;
let prev: ReturnType<Font["charToGlyph"]> | null = null;
for (const ch of text) {
const g = f.charToGlyph(ch);
if (prev) x += f.getKerningValue(prev, g) * scale;
commands.push(...g.getPath(x, 0, fontSize).commands);
x += (g.advanceWidth ?? 0) * scale;
prev = g;
}
const path = { commands } as { commands: Array<{ type: string; x: number; y: number; x1: number; y1: number; x2: number; y2: number }> };
const contours: Vec2[][] = [];
let cur: Vec2[] = [];
let last: Vec2 = [0, 0];
const push = (p: Vec2) => {
cur.push(p);
last = p;
};
const steps = 8;
for (const c of path.commands) {
if (c.type === "M") {
if (cur.length > 2) contours.push(cur);
cur = [];
push([c.x, -c.y]);
} else if (c.type === "L") push([c.x, -c.y]);
else if (c.type === "Q") {
const p0 = last;
for (let i = 1; i <= steps; i++) {
const t = i / steps;
const u = 1 - t;
push([u * u * p0[0] + 2 * u * t * c.x1 + t * t * c.x, u * u * p0[1] + 2 * u * t * -c.y1 + t * t * -c.y]);
}
} else if (c.type === "C") {
const p0 = last;
for (let i = 1; i <= steps; i++) {
const t = i / steps;
const u = 1 - t;
push([
u * u * u * p0[0] + 3 * u * u * t * c.x1 + 3 * u * t * t * c.x2 + t * t * t * c.x,
u * u * u * p0[1] + 3 * u * u * t * -c.y1 + 3 * u * t * t * -c.y2 + t * t * t * -c.y,
]);
}
} else if (c.type === "Z") {
if (cur.length > 2) contours.push(cur);
cur = [];
}
}
if (cur.length > 2) contours.push(cur);
const cs = Math.cos(angle);
const sn = Math.sin(angle);
return contours.map((pts) => {
// Drop a duplicated closing point.
const a = pts[0];
const b = pts[pts.length - 1];
if (Math.hypot(a[0] - b[0], a[1] - b[1]) < 1e-9) pts.pop();
return {
id: uid(),
kind: "polyline" as const,
closed: true,
points: pts.map(([x, y]) => [at[0] + x * cs - y * sn, at[1] + x * sn + y * cs] as Vec2),
};
});
}
+1654
View File
File diff suppressed because it is too large Load Diff
+292
View File
@@ -0,0 +1,292 @@
// 3D dimension annotations: a dimension line with arrowheads, an optional
// floating input (Total/Offset + value + pin), and the layer of pinned measurements.
import { BufferGeometry, ConeGeometry, Group, Line, LineBasicMaterial, LineDashedMaterial, Mesh, MeshBasicMaterial, Vector3 } from "three";
import type { PinDef, Vec3 } from "../doc/types";
import { el } from "../ui/ui";
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
import type { Viewport } from "../view/viewport";
const COLOR = 0xdfe6f3;
/** Dashed line a→b with screen-constant arrowheads at both ends. */
class DimLine {
readonly group = new Group();
private line: Line;
private heads: Mesh[];
private a = new Vector3();
private b = new Vector3();
constructor(
private view: Viewport,
color = COLOR,
private solid = false,
) {
const opts = { color, depthTest: false, transparent: true };
this.line = new Line(new BufferGeometry(), solid ? new LineBasicMaterial(opts) : new LineDashedMaterial({ ...opts, dashSize: 1, gapSize: 1 }));
this.line.renderOrder = 11;
const mat = new MeshBasicMaterial({ color, depthTest: false, transparent: true });
this.heads = [0, 1].map(() => {
const m = new Mesh(new ConeGeometry(0.35, 1, 12), mat);
m.renderOrder = 11;
return m;
});
this.group.add(this.line, ...this.heads);
}
set(a: Vec3, b: Vec3): void {
this.a.set(...a);
this.b.set(...b);
this.line.geometry.setFromPoints([this.a, this.b]);
this.layout();
}
layout(): void {
const wpp = this.view.cam.worldPerPixel(this.view.height);
if (!this.solid) {
const mat = this.line.material as LineDashedMaterial;
mat.dashSize = wpp * 6;
mat.gapSize = wpp * 4;
this.line.computeLineDistances();
}
const dir = this.b.clone().sub(this.a);
const len = dir.length();
const show = len > wpp * 20;
dir.normalize();
const s = wpp * 11;
for (const [i, h] of this.heads.entries()) {
h.visible = show;
h.scale.setScalar(s);
// Cone points +Y; tips sit on the ends, pointing outwards.
const out = i === 0 ? dir.clone().negate() : dir.clone();
h.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), out);
h.position.copy(i === 0 ? this.a : this.b).addScaledVector(out, -s / 2);
}
}
dispose(): void {
this.line.geometry.dispose();
this.heads.forEach((h) => h.geometry.dispose());
}
}
export interface DimWidgetOptions {
value: number;
modes?: { id: string; label: string }[];
mode?: string;
onMode?(id: string): void;
onInput?(v: number): void;
onCommit?(): void;
onPin?(): void;
/** Text to restore into the input (when another tool takes over while typing). */
typed?: string;
focus?: boolean;
/** Draw the dimension as a solid line of this colour (it *is* the geometry, e.g. a line being drawn). */
solidColor?: number;
/**
* 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).
*/
boxAt?: "middle" | "side" | "beyond";
/** 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). */
dir?: Vec3;
}
/**
* A dimension in the viewport: dashed line with arrows and, at its middle,
* a small editable value with an optional mode dropdown and a pin button.
*/
export class DimWidget {
private line: DimLine;
private box = el("div", "dim-widget");
private input = document.createElement("input");
private mid = new Vector3();
private ends: [Vector3, Vector3] = [new Vector3(), new Vector3()];
private boxAt: "middle" | "side" | "beyond";
private boxGap: number;
private dir?: Vec3;
private hook = () => this.layout();
constructor(
private view: Viewport,
opts: DimWidgetOptions,
) {
this.line = opts.solidColor !== undefined ? new DimLine(view, opts.solidColor, true) : new DimLine(view);
this.boxAt = opts.boxAt ?? "middle";
this.boxGap = opts.boxGap ?? 0;
this.dir = opts.dir;
view.overlay.add(this.line.group);
if (opts.modes) {
const sel = document.createElement("select");
for (const m of opts.modes) {
const o = document.createElement("option");
o.value = m.id;
o.textContent = m.label;
sel.append(o);
}
sel.value = opts.mode ?? opts.modes[0].id;
sel.addEventListener("change", () => opts.onMode?.(sel.value));
this.box.append(sel);
}
this.input.inputMode = "decimal";
this.input.spellcheck = false;
this.input.value = opts.typed ?? trim(toDisplay(opts.value), 3);
this.input.readOnly = !opts.onInput;
this.input.addEventListener("input", () => {
const v = evaluate(this.input.value, "length");
this.input.classList.toggle("invalid", v === null);
if (v !== null) opts.onInput?.(v);
});
this.input.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "Enter") opts.onCommit?.();
if (e.key === "Escape") this.input.blur();
});
this.box.append(this.input, el("span", "dim-unit", UNIT_LABEL[units()]));
if (opts.onPin) {
const pin = el("button", "dim-pin", "📌");
pin.title = "Pin this measurement";
pin.addEventListener("click", () => opts.onPin!());
this.box.append(pin);
}
// Clicks on the widget must not reach the viewport.
this.box.addEventListener("pointerdown", (e) => e.stopPropagation());
document.body.append(this.box);
view.frameHooks.add(this.hook);
view.helpers.add(this);
if (opts.focus) {
setTimeout(() => {
this.input.focus();
const n = this.input.value.length;
this.input.setSelectionRange(n, n);
}, 0);
}
}
get text(): string {
return this.input.value;
}
set(a: Vec3, b: Vec3): void {
this.line.set(a, b);
this.ends[0].set(...a);
this.ends[1].set(...b);
this.mid.set((a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2);
this.layout();
this.view.requestRender();
}
setValue(v: number): void {
if (document.activeElement !== this.input) this.input.value = trim(toDisplay(v), 3);
this.box.classList.remove("typing", "invalid");
}
/** Start typing into the box with this first character (keys pressed elsewhere). */
focusWith(ch: string): void {
this.input.value = ch;
this.input.focus();
this.input.setSelectionRange(1, 1);
this.input.dispatchEvent(new Event("input"));
}
/** Mark the value as not usable (e.g. a fillet radius too big for the lines). */
markInvalid(bad: boolean): void {
this.box.classList.toggle("invalid", bad);
}
/** Text typed elsewhere (keys while drawing), shown in the box with a caret. */
setText(text: string, invalid = false): void {
if (document.activeElement === this.input) return;
this.input.value = text;
this.box.classList.add("typing");
this.box.classList.toggle("invalid", invalid);
}
private layout(): void {
this.line.layout();
let s = this.view.toScreen(this.mid);
const sa = this.view.toScreen(this.ends[0]);
const sb = this.view.toScreen(this.ends[1]);
if (s && sa && sb && this.boxAt !== "middle") {
let dx = sb[0] - sa[0];
let dy = sb[1] - sa[1];
// No length yet: use the given direction on screen.
if (Math.hypot(dx, dy) < 2 && this.dir) {
const e = this.view.toScreen(this.ends[1].clone().add(new Vector3(...this.dir).multiplyScalar(this.view.cam.worldPerPixel(this.view.height) * 50)));
if (e) [dx, dy] = [e[0] - sb[0], e[1] - sb[1]];
}
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") {
// 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];
} else {
// Beside the middle, on the upper side of the line.
let n: [number, number] = [-dy / l, dx / l];
if (n[1] > 0) n = [-n[0], -n[1]];
const k = Math.abs(n[0] * half.w) + Math.abs(n[1] * half.h);
s = [s[0] + n[0] * k, s[1] + n[1] * k];
}
}
this.box.hidden = !s;
if (s) this.box.style.transform = `translate(${Math.round(s[0])}px, ${Math.round(s[1])}px) translate(-50%, -50%)`;
}
dispose(): void {
this.view.helpers.delete(this);
this.view.frameHooks.delete(this.hook);
this.view.overlay.remove(this.line.group);
this.line.dispose();
this.box.remove();
this.view.requestRender();
}
}
/** Pinned measurements: label + (optional) dimension line, always on top. */
export class PinLayer {
private group = new Group();
private lines: DimLine[] = [];
private labels: HTMLElement[] = [];
private pins: PinDef[] = [];
private visible = true;
private host = document.getElementById("pins")!;
constructor(private view: Viewport) {
view.overlay.add(this.group);
view.frameHooks.add(() => this.layout());
}
set(pins: PinDef[], visible: boolean): void {
this.lines.forEach((l) => (this.group.remove(l.group), l.dispose()));
this.labels.forEach((l) => l.remove());
this.pins = pins;
this.visible = visible;
this.lines = [];
this.labels = pins.map((p) => {
if (p.a && p.b) {
const l = new DimLine(this.view, 0x8fb4ff);
l.set(p.a, p.b);
this.group.add(l.group);
this.lines.push(l);
}
const tag = el("div", "pin", p.text);
this.host.append(tag);
return tag;
});
this.group.visible = visible;
this.view.requestRender();
}
private layout(): void {
this.lines.forEach((l) => l.layout());
this.pins.forEach((p, i) => {
const s = this.view.toScreen(p.at);
const tag = this.labels[i];
tag.hidden = !this.visible || !s;
if (s) tag.style.transform = `translate(${Math.round(s[0])}px, ${Math.round(s[1])}px) translate(-50%, -50%)`;
});
}
}
+60
View File
@@ -0,0 +1,60 @@
// The Copy switch next to a Move/Rotate gimbal. While it's on, a gimbal drag
// leaves the original where it was and makes a copy; the copy is then
// selected, so the next drag (or typed value + Enter) copies again.
import type { Vec3 } from "../doc/types";
import { icons } from "../ui/icons";
import type { Viewport } from "../view/viewport";
/** Shared by bodies, sketches and images: the switch stays as you left it. */
export const copyMode = { on: false };
export class CopyToggle {
private btn = document.createElement("button");
private hook = () => this.layout();
constructor(
private view: Viewport,
/** Where the gimbal is (world). */
private at: () => Vec3 | null,
private onChange?: (on: boolean) => void,
) {
this.btn.className = "copy-toggle";
this.btn.title = "Copy: drag to make copies (each Enter or release makes one, then keep dragging)";
this.btn.innerHTML = `${icons.copy}<span>Copy</span>`;
// Never let the press reach the viewport (it would start a drag or deselect).
this.btn.addEventListener("pointerdown", (e) => e.stopPropagation());
this.btn.addEventListener("click", (e) => {
e.stopPropagation();
copyMode.on = !copyMode.on;
this.paint();
this.onChange?.(copyMode.on);
});
this.paint();
document.body.append(this.btn);
view.frameHooks.add(this.hook);
view.helpers.add(this);
this.layout();
}
private paint(): void {
this.btn.classList.toggle("on", copyMode.on);
}
private layout(): void {
const w = this.at();
const s = w && this.view.toScreen(w);
this.btn.hidden = !s;
if (s) {
const r = this.view.canvas.getBoundingClientRect();
// Up and to the right of the gimbal, clear of its arrows.
this.btn.style.transform = `translate(${Math.round(r.left + s[0] + 70)}px, ${Math.round(r.top + s[1] - 96)}px)`;
}
}
dispose(): void {
this.view.helpers.delete(this);
this.view.frameHooks.delete(this.hook);
this.btn.remove();
}
}
+86
View File
@@ -0,0 +1,86 @@
// Type a value while holding a drag: digits set the value live, Enter applies
// it and finishes, Esc drops what was typed. "," is accepted as decimal point.
import { evaluate, UNIT_LABEL, units } from "../units";
import type { ToolPointer } from "../view/input";
import type { AppContext } from "./tool";
export interface DragTypingTarget {
kind: "length" | "angle" | "number";
/** Apply a typed value (mm for lengths, degrees for angles). */
apply(v: number): void;
/** Enter: finish with the current value. */
commit(): void;
/** Esc: drop the typed text and go back to following the pointer. */
cancel?(): void;
/** Tab: move to the next dimension (e.g. rectangle width → height). */
next?(): boolean;
/** Show the typed text somewhere else than the pointer label (e.g. a dimension box). */
show?(text: string, invalid: boolean): void;
}
export class DragTyping {
text = "";
private at: { x: number; y: number } = { x: 0, y: 0 };
constructor(private app: AppContext) {}
/** While text is typed, pointer motion shouldn't change the value. */
get active(): boolean {
return this.text.length > 0;
}
/** Remember where the pointer is (the typed value is shown next to it). */
track(p: ToolPointer): void {
this.at = { x: p.x, y: p.y };
if (this.active) this.show();
}
reset(): void {
this.text = "";
}
/** Handle a key during a drag; true if it was used. */
key(e: KeyboardEvent, t: DragTypingTarget): boolean {
if (e.ctrlKey || e.metaKey || e.altKey) return false;
this.display = t.show ?? null;
this.unit = t.kind === "length" ? UNIT_LABEL[units()] : t.kind === "angle" ? "°" : "";
if (e.key === "Enter") {
this.text = "";
this.app.ui.setLabel(0, 0, null);
t.commit();
return true;
}
if (e.key === "Escape") {
if (!this.text) return false;
this.text = "";
this.app.ui.setLabel(0, 0, null);
t.cancel?.();
return true;
}
if (e.key === "Tab") {
if (!t.next?.()) return false;
this.text = "";
this.show();
return true;
}
if (e.key === "Backspace") {
this.text = this.text.slice(0, -1);
} else if (e.key.length === 1 && /[0-9.,+\-*/()a-z"' ]/i.test(e.key)) {
this.text += e.key === "," ? "." : e.key;
} else return false;
const v = this.text ? evaluate(this.text, t.kind) : null;
if (v !== null) t.apply(v);
else if (!this.text) t.cancel?.();
this.show(v === null && !!this.text);
return true;
}
private unit = "";
private display: DragTypingTarget["show"] | null = null;
private show(invalid = false): void {
if (this.display) return this.display(this.text, invalid);
this.app.ui.setLabel(this.at.x, this.at.y, this.text ? `${this.text}▌ ${this.unit}${invalid ? " ?" : ""}` : null);
}
}
+258
View File
@@ -0,0 +1,258 @@
import { getPath, setPath } from "../doc/params";
import type { ExtrudeSource, Feature } from "../doc/types";
import type { FieldKind, PanelItem, ToolItem } from "../ui/ui";
import type { ToolPointer } from "../view/input";
import type { PickHit, PickOptions } from "../view/viewport";
import { hitToSel, type AppContext, type Sel, type Tool } from "./tool";
/** Something the user has to point at (an axis, a path, faces to remove, …). */
export interface Slot {
label: string;
/** What the slot shows: "X axis", "2 faces", "Select…". */
describe(): string;
filled(): boolean;
pick: PickOptions;
/** Store the hit into the draft; return false if it doesn't fit this slot. */
accept(hit: PickHit): boolean;
multi?: boolean;
/** Quick choices shown next to the slot (e.g. X / Y / Z). */
presets?: { label: string; apply(): void }[];
/** Highlights of what the slot currently holds. */
shows?(): Sel[];
/** Show the XY/XZ/YZ planes while this slot is waiting for a pick. */
originPlanes?: boolean;
/** Said when a tap hits something this slot can't take. */
rejectHint?: string;
}
/**
* Base for tools that create or edit one feature: pick slots + numbers +
* live preview + Done/Cancel. Subclasses describe the draft; this does the rest.
*/
export abstract class FeatureOp<F extends Feature> implements Tool {
abstract readonly id: string;
feature: F;
protected slots: Slot[] = [];
protected active = -1;
protected error: string | null = null;
constructor(
protected app: AppContext,
draft: F,
protected existing?: F,
) {
this.feature = existing ? structuredClone(existing) : draft;
}
get editingId(): string {
return this.feature.id;
}
/** One-line instruction for the hint bar. */
protected abstract hint(): string;
/** Numbers / choices / toggles in the panel. */
protected abstract items(): PanelItem[];
/** Is the draft complete enough to preview and commit? */
protected ready(): boolean {
return this.slots.every((s) => s.filled());
}
/** Extra panel buttons. */
protected actions(): ToolItem[] {
return [];
}
enter(): void {
this.app.ui.setTools([{ id: "cancel", label: "Cancel", icon: "close", shortcut: "Esc", run: () => this.app.setTool(null) }]);
this.app.ui.setBottom([]);
this.active = this.slots.findIndex((s) => !s.filled());
this.render();
this.update();
this.app.ui.focusPanel();
}
exit(): void {
this.app.view.setOriginPlanesVisible(false);
this.app.ui.showPanel(null);
this.app.ui.setHint(null);
this.app.ui.setLabel(0, 0, null);
this.app.setHover(null);
this.app.setSelection([]);
}
hover(p: ToolPointer | null): void {
const slot = this.slots[this.active];
if (!p || !slot) return this.app.setHover(null);
const hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, ...slot.pick });
this.lastHover = { x: p.x, y: p.y, hit };
this.app.setHover(hitToSel(hit));
}
/** What hover highlighted: a tap at the same spot takes exactly that. */
private lastHover: { x: number; y: number; hit: PickHit | null } | null = null;
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 ?? {}) });
// Tapping empty space ends the tool: keep the result if it's complete.
if (!hit) {
if (this.ready()) this.done();
else this.app.setTool(null);
return;
}
if (!slot) return;
if (!slot.accept(hit)) {
if (slot.rejectHint) this.app.ui.toast(slot.rejectHint);
return;
}
if (!slot.multi) this.active = this.slots.findIndex((s, i) => i > this.active && !s.filled());
this.render();
if (this.finishWhenPicked && this.ready()) return void this.finishIfOk();
this.update();
}
/** Nothing left to set once the picks are made (e.g. Replace Face): the last pick finishes. */
protected finishWhenPicked = false;
private async finishIfOk(): Promise<void> {
this.onDraftChanged();
const r = await this.app.preview(this.featuresWith());
const err = r?.errors.find((e) => e.featureId === this.feature.id)?.message;
if (err) {
this.error = err;
this.setHint();
this.app.ui.toast(err);
return;
}
this.done();
}
key(e: KeyboardEvent): boolean {
if (e.key === "Enter") this.done();
else if (e.key === "Escape") this.app.setTool(null);
else return false;
return true;
}
/** Rebuild the panel (after slots/choices change). */
protected render(): void {
const slotItems: PanelItem[] = this.slots.flatMap((s, i): PanelItem[] => [
{ type: "slot", label: s.label, value: s.describe(), active: i === this.active, filled: s.filled(), onClick: () => ((this.active = i), this.render()) },
...(s.presets?.length && i === this.active
? [{ type: "choice" as const, options: s.presets.map((p, k) => ({ id: String(k), label: p.label })), value: "", onChange: (k: string) => (s.presets![Number(k)].apply(), this.advance(), this.render(), this.update()) }]
: []),
]);
this.app.ui.showPanel({
title: this.feature.name,
items: [...slotItems, ...this.items()],
actions: this.actions(),
onDone: () => this.done(),
onCancel: () => this.app.setTool(null),
});
this.showSlotHighlights();
this.setHint();
this.app.view.setOriginPlanesVisible(!!this.slots[this.active]?.originPlanes);
}
private advance(): void {
const s = this.slots[this.active];
if (s && !s.multi) this.active = this.slots.findIndex((x, i) => i > this.active && !x.filled());
}
private showSlotHighlights(): void {
this.app.setSelection(this.slots.flatMap((s) => s.shows?.() ?? []));
}
private 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);
}
/** Re-run the preview with the current draft. */
protected update(): void {
this.onDraftChanged();
if (!this.ready()) {
this.app.preview([...this.app.store.features]);
return;
}
this.app.preview(this.featuresWith()).then((r) => {
this.error = r?.errors.find((e) => e.featureId === this.feature.id)?.message ?? null;
this.setHint();
});
}
/** Hook for handles etc. */
protected onDraftChanged(): void {}
/**
* A number field bound to a path in the feature (e.g. "distance",
* "op.translate.2") that can also hold a variable expression.
*/
protected num(label: string, path: string, kind: FieldKind, opts: { min?: number; onInput?: (v: number) => void } = {}): PanelItem {
const f = this.feature as Feature;
return {
type: "number",
label,
value: Number(getPath(f, path) ?? 0),
kind,
min: opts.min,
expr: f.exprs?.[path],
onExpr: (expr) => {
const exprs = { ...(f.exprs ?? {}) };
if (expr) exprs[path] = expr;
else delete exprs[path];
f.exprs = Object.keys(exprs).length ? exprs : undefined;
},
onInput: (v) => {
setPath(f, path, v);
if (opts.onInput) opts.onInput(v);
else this.update();
},
};
}
protected featuresWith(): Feature[] {
const list = [...this.app.store.features];
if (!this.existing) return [...list, this.feature];
list[list.findIndex((f) => f.id === this.feature.id)] = this.feature;
return list;
}
protected done(): void {
if (!this.ready()) {
const missing = this.slots.find((s) => !s.filled());
// Nothing left to pick means nothing changed: just close the tool.
if (!missing) return this.app.setTool(null);
this.app.ui.toast("Finish picking first: " + missing.label);
return;
}
if (this.existing) this.app.store.update(this.feature.id, this.feature);
else {
// A new solid from sketches: the sketches step out of the way (the eye in Items brings them back).
const used = sketchesUsed(this.feature as Feature);
const f = this.feature as Feature;
this.app.store.commit((d) => {
d.features.push(f);
if (used.length) d.hidden = [...new Set([...d.hidden, ...used])];
});
}
this.app.setTool(null);
}
}
/** The sketches an extrude / revolve / sweep / loft was made from. */
function sketchesUsed(f: Feature): string[] {
const of = (s: ExtrudeSource) => (s.kind === "profile" ? [s.sketch] : []);
switch (f.type) {
case "extrude":
case "revolve":
return of(f.source);
case "sweep":
return [...of(f.source), ...(f.path.kind === "sketch" ? [f.path.sketch] : [])];
case "loft":
return f.sections.flatMap(of);
default:
return [];
}
}
+629
View File
@@ -0,0 +1,629 @@
// Freeform: shape a smooth body by pulling its control cage. Tap cage points,
// edges or faces (Shift adds), then drag the gimbal — or type a value while
// dragging. The smooth surface updates live; Done turns it into a body.
import { BufferAttribute, BufferGeometry, DoubleSide, LineBasicMaterial, LineSegments, Mesh, MeshStandardMaterial, Points, Raycaster, Vector2 } from "three";
import type { Feature, FreeformFeature, TransformFeature, Vec3 } from "../doc/types";
import { boundaryEdges, bridgeLoops, cageEdgeKey, cageEdges, deleteFaces, fillLoop, holeLoops, isClosed, previewMesh, primitiveCage, subdivide, type Cage, type CagePrimitive } from "../freeform/cage";
import { add, cross, dot, len, niceStep, norm, scale, sub, xDirFor } from "../geom";
import type { PanelItem } from "../ui/ui";
import { fmtLen } from "../units";
import type { ToolPointer } from "../view/input";
import { dotMaterial } from "../view/viewport";
import { DragTyping } from "./dragTyping";
import { Gimbal, GIMBAL_AXES, type GimbalPart } from "./gimbal";
import { axisDrag } from "./handles";
import type { AppContext, Tool } from "./tool";
type Pick = { kind: "vert"; i: number } | { kind: "edge"; e: [number, number] } | { kind: "face"; f: number };
const SEL = 0xffa31a;
const HOVER = 0xffd27a;
export class FreeformTool implements Tool {
readonly id = "freeform";
private cage: Cage;
private existing?: FreeformFeature;
private picks: Pick[] = [];
private hovered: Pick | null = null;
private gimbal: Gimbal | null = null;
private dragging: { part: GimbalPart; from: ToolPointer; base: Vec3[]; center: Vec3; d: Vec3; ang: number } | null = null;
private typing: DragTyping;
private uniform = 1;
/** Moves applied to the body later in History: the cage is shown (and edited) where the body is. */
private place: Placement = { fwd: (v) => v, inv: (v) => v };
private surfaceSheet = false;
private thickness = 0;
private thickSide: "up" | "down" | "both" = "up";
/** A new shape that spawned inside another body: first moved into place as a whole. */
private placing = false;
// Scene objects.
private surface = new Mesh(new BufferGeometry(), new MeshStandardMaterial({ color: 0xb9c6dc, roughness: 0.5, metalness: 0.05, side: DoubleSide, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1 }));
private lines = new LineSegments(new BufferGeometry(), new LineBasicMaterial({ color: 0x5f8fe8, transparent: true, opacity: 0.85, depthTest: false }));
private dots = new Points(new BufferGeometry(), dotMaterial({ color: 0xffffff, size: 8 }));
private marks = new LineSegments(new BufferGeometry(), new LineBasicMaterial({ color: SEL, depthTest: false, linewidth: 2 }));
private markDots = new Points(new BufferGeometry(), dotMaterial({ color: SEL, size: 12 }));
private hoverMarks = new LineSegments(new BufferGeometry(), new LineBasicMaterial({ color: HOVER, depthTest: false }));
private hoverDots = new Points(new BufferGeometry(), dotMaterial({ color: HOVER, size: 12 }));
constructor(
private app: AppContext,
from: { primitive: CagePrimitive } | { feature: FreeformFeature },
) {
if ("feature" in from) {
this.existing = from.feature;
this.place = placementOf(app.store.features, from.feature.id);
const c = structuredClone(from.feature.cage);
this.cage = { faces: c.faces, verts: c.verts.map(this.place.fwd) };
this.surfaceSheet = !!from.feature.surface;
this.thickness = from.feature.thickness ?? 0;
this.thickSide = from.feature.thickSide ?? "up";
} else {
this.cage = primitiveCage(from.primitive);
this.surfaceSheet = from.primitive === "plane";
}
this.typing = new DragTyping(app);
this.lines.renderOrder = 11;
this.dots.renderOrder = 12;
for (const o of [this.marks, this.markDots, this.hoverMarks, this.hoverDots]) o.renderOrder = 13;
}
get editingId(): string | undefined {
return this.existing?.id;
}
enter(): void {
const view = this.app.view;
view.overlay.add(this.surface, this.lines, this.dots, this.marks, this.markDots, this.hoverMarks, this.hoverDots);
// Editing an existing freeform: hide its finished body while the cage is out.
if (this.existing) view.setHidden(new Set([...this.app.store.doc.hidden, this.existing.id]));
this.app.setSelection([]);
this.app.ui.setTools([{ id: "cancel", label: "Cancel", icon: "close", shortcut: "Esc", run: () => this.cancel() }]);
this.app.ui.setBottom([]);
this.rebuild();
if (!this.existing && this.overlapsBodies()) {
// Grab the whole shape first; point editing starts after it's been moved.
this.placing = true;
this.picks = this.cage.verts.map((_, i) => ({ kind: "vert" as const, i }));
this.drawMarks();
this.placeGimbal();
}
this.panel();
this.hint();
}
/** Does the cage's box overlap any visible body's box? */
private overlapsBodies(): boolean {
const lo = [0, 1, 2].map((k) => Math.min(...this.cage.verts.map((v) => v[k])));
const hi = [0, 1, 2].map((k) => Math.max(...this.cage.verts.map((v) => v[k])));
const hidden = new Set(this.app.store.doc.hidden);
return this.app.view.bodyList.some((b) => {
if (hidden.has(b.id) || !b.positions.length) return false;
for (let k = 0; k < 3; k++) {
let mn = Infinity;
let mx = -Infinity;
for (let i = k; i < b.positions.length; i += 3) {
mn = Math.min(mn, b.positions[i]);
mx = Math.max(mx, b.positions[i]);
}
if (mx < lo[k] || mn > hi[k]) return false;
}
return true;
});
}
exit(): void {
const view = this.app.view;
for (const o of [this.surface, this.lines, this.dots, this.marks, this.markDots, this.hoverMarks, this.hoverDots]) {
view.overlay.remove(o);
o.geometry.dispose();
}
this.gimbal?.dispose();
this.gimbal = null;
view.setHidden(new Set(this.app.store.doc.hidden));
this.app.ui.showPanel(null);
this.app.ui.setHint(null);
this.app.ui.setLabel(0, 0, null);
view.requestRender();
}
private hint(): void {
if (this.placing) return this.app.ui.setHint("It's inside another body: drag the gimbal to move it into place first. Then tap points, edges or faces to shape it.");
this.app.ui.setHint(
this.picks.length
? "Drag the gimbal to move or turn the selection (type a value while dragging). Shift+tap adds. Tap empty space to deselect."
: "Tap cage points, edges or faces to select them (Shift adds). Done turns the shape into a body.",
);
}
private panel(): void {
const n = this.selectedVerts().length;
const items: PanelItem[] = [];
if (n) items.push({ type: "number", label: "Scale", value: 1, kind: "number", min: 0.01, onInput: (v) => this.scaleSelection(v) });
const faces = this.picks.filter((p) => p.kind === "face").length;
if (faces) items.push({ type: "button", label: `Delete face${faces > 1 ? "s" : ""}`, icon: "trash", onClick: () => this.deleteSelectedFaces() });
// Rim edges of holes picked: one hole → Fill, two facing holes → Bridge.
const loops = this.pickedLoops();
if (loops.length === 1) items.push({ type: "button", label: "Fill hole", icon: "fill", onClick: () => this.fillHoles(loops) });
if (loops.length === 2) items.push({ type: "button", label: "Bridge holes", icon: "loft", onClick: () => this.fillHoles(loops) });
// An open shape can be given a thickness to become a solid.
if (!isClosed(this.cage)) {
items.push(
{ type: "number", label: "Thickness", value: this.thickness, kind: "length", min: 0, onInput: (v) => ((this.thickness = Math.max(0, v)), this.panelHint()) },
{ type: "choice", options: [{ id: "up", label: "Up" }, { id: "down", label: "Down" }, { id: "both", label: "Symmetric" }], value: this.thickSide, onChange: (v) => ((this.thickSide = v as typeof this.thickSide), this.panel()) },
);
}
this.uniform = 1;
this.app.ui.showPanel({
title: `Freeform${n ? ` · ${n} point${n > 1 ? "s" : ""}` : ""}`,
items,
actions: [{ id: "all", label: "Select all", icon: "pointer", run: () => ((this.picks = this.cage.verts.map((_, i) => ({ kind: "vert" as const, i }))), this.selectionChanged()) }],
onDone: () => this.done(),
onCancel: () => this.cancel(),
});
}
private panelHint(): void {
if (!isClosed(this.cage)) this.app.ui.setHint(this.thickness > 0 ? `Done makes a solid ${fmtLen(this.thickness)} thick.` : "Open shape: Done makes a surface. Give it a Thickness to make a solid.");
}
/** Holes whose rim edges are all picked (edges, or the points along them). */
private pickedLoops(): number[][] {
const verts = new Set(this.selectedVerts());
const chosen = new Set<string>();
for (const [a, b] of boundaryEdges(this.cage)) if (verts.has(a) && verts.has(b)) chosen.add(cageEdgeKey(a, b));
return chosen.size ? holeLoops(this.cage, chosen) : [];
}
private deleteSelectedFaces(): void {
const faces = this.picks.flatMap((p) => (p.kind === "face" ? [p.f] : []));
if (!faces.length) return;
if (faces.length >= this.cage.faces.length) return this.app.ui.toast("At least one face has to stay");
this.cage = deleteFaces(this.cage, faces);
this.picks = [];
this.rebuild();
this.selectionChanged();
this.panelHint();
}
private fillHoles(loops: number[][]): void {
const next = loops.length === 2 ? bridgeLoops(this.cage, loops[0], loops[1]) : fillLoop(this.cage, loops[0]);
if (!next) return this.app.ui.toast(loops.length === 2 ? "Bridging needs two holes with the same number of edges" : "Fill needs a hole with an even number of edges");
this.cage = next;
this.picks = [];
this.rebuild();
this.selectionChanged();
}
// --------------------------------------------------------------- picking
private selectedVerts(): number[] {
const s = new Set<number>();
for (const p of this.picks) {
if (p.kind === "vert") s.add(p.i);
else if (p.kind === "edge") p.e.forEach((i) => s.add(i));
else this.cage.faces[p.f].forEach((i) => s.add(i));
}
return [...s];
}
/** How far along the pointer's ray the smooth surface is (∞ if missed). */
private surfaceDepth(p: ToolPointer): number {
const view = this.app.view;
const r = view.canvas.getBoundingClientRect();
this.ray.setFromCamera(new Vector2((p.x / r.width) * 2 - 1, -(p.y / r.height) * 2 + 1), view.cam.camera);
return this.ray.intersectObject(this.surface, false)[0]?.distance ?? Infinity;
}
private ray = new Raycaster();
/**
* Nearest cage point, else edge, else the frontmost face under the pointer.
* Points and edges behind the smooth surface (the far side) don't count.
*/
private pickAt(p: ToolPointer): Pick | null {
const view = this.app.view;
const scr = this.cage.verts.map((v) => view.toScreen(v));
const tol = Math.max(10, p.tol * 1.3);
const eye = view.cam.camera.position.toArray() as Vec3;
const wall = this.surfaceDepth(p);
const visible = (q: Vec3) => len(sub(q, eye)) < wall + 1e-6;
let best: { d: number; i: number } | null = null;
scr.forEach((s, i) => {
if (!s || !visible(this.cage.verts[i])) return;
const d = Math.hypot(s[0] - p.x, s[1] - p.y);
if (d < tol && (!best || d < best.d)) best = { d, i };
});
if (best) return { kind: "vert", i: (best as { i: number }).i };
let bestE: { d: number; e: [number, number] } | null = null;
for (const e of cageEdges(this.cage)) {
const a = scr[e[0]];
const b = scr[e[1]];
if (!a || !b) continue;
const { d, t } = segDist(p.x, p.y, a, b);
const at = add(this.cage.verts[e[0]], scale(sub(this.cage.verts[e[1]], this.cage.verts[e[0]]), t));
if (d < p.tol && visible(at) && (!bestE || d < bestE.d)) bestE = { d, e };
}
if (bestE) return { kind: "edge", e: (bestE as { e: [number, number] }).e };
// Faces: inside the projected quad; nearest to the camera wins.
let bestF: { d: number; f: number } | null = null;
this.cage.faces.forEach((f, fi) => {
const q = f.map((i) => scr[i]);
if (q.some((s) => !s) || !inPoly(p.x, p.y, q as [number, number][])) return;
const c = scale(f.reduce((s, i) => add(s, this.cage.verts[i]), [0, 0, 0] as Vec3), 0.25);
const d = len(sub(c, eye));
if (!bestF || d < bestF.d) bestF = { d, f: fi };
});
return bestF ? { kind: "face", f: (bestF as { f: number }).f } : null;
}
hover(p: ToolPointer | null): void {
if (this.dragging) return;
const g = p && this.gimbal?.hit(p);
this.gimbal?.setHot(g ?? null);
this.hovered = p && !g ? this.pickAt(p) : null;
this.app.view.canvas.style.cursor = g ? "grab" : "";
this.drawMarks();
}
tap(p: ToolPointer, count = 1): void {
// Double-tap: finish and select the whole body (e.g. to move or colour it).
if (count >= 2) {
const id = this.done();
if (id) this.app.setSelection([{ kind: "body", body: id }]);
return;
}
// A tap while placing: they'd rather edit right away.
if (this.placing) {
this.placing = false;
this.picks = [];
}
const hit = this.pickAt(p);
if (!hit) {
// Empty space: deselect; with nothing selected, finish.
if (this.picks.length) return ((this.picks = []), this.selectionChanged());
this.done();
return;
}
const key = JSON.stringify(hit);
const i = this.picks.findIndex((x) => JSON.stringify(x) === key);
if (p.shift || p.add) {
if (i >= 0) this.picks.splice(i, 1);
else this.picks.push(hit);
} else this.picks = i >= 0 && this.picks.length === 1 ? [] : [hit];
this.selectionChanged();
}
private selectionChanged(): void {
this.drawMarks();
this.placeGimbal();
this.panel();
this.hint();
}
private centroid(ids: number[]): Vec3 {
return scale(ids.reduce((s, i) => add(s, this.cage.verts[i]), [0, 0, 0] as Vec3), 1 / Math.max(1, ids.length));
}
private placeGimbal(): void {
const ids = this.selectedVerts();
if (!ids.length) {
this.gimbal?.dispose();
this.gimbal = null;
return;
}
this.gimbal ??= new Gimbal(this.app.view);
this.gimbal.setCenter(this.centroid(ids));
}
// ------------------------------------------------------------ dragging
down(p: ToolPointer): boolean {
const part = this.gimbal?.hit(p);
if (!part || !this.gimbal) return false;
// One point turned about itself wouldn't move: it turns about the shape's centre instead.
const ids = this.selectedVerts();
const center = part.kind === "ring" && ids.length === 1 ? this.centroid(this.cage.verts.map((_, i) => i)) : this.gimbal.origin;
this.dragging = { part, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center, d: [0, 0, 0], ang: 0 };
this.gimbal.setHot(part);
return true;
}
drag(p: ToolPointer): void {
const dr = this.dragging;
if (!dr) return;
this.typing.track(p);
if (this.typing.active) return;
const view = this.app.view;
const step = niceStep(view.cam.worldPerPixel(view.height) * 4);
const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step);
const part = dr.part;
if (part.kind === "axis") {
const dir = GIMBAL_AXES[part.i];
const d = snap(axisDrag(view, dr.center, dir, dr.from, p));
this.apply(scale(dir, d), 0);
this.app.ui.setLabel(p.x, p.y, `${fmtLen(d)} · type a value`);
} else if (part.kind === "plane" || part.kind === "center") {
const n: Vec3 = part.kind === "plane" ? GIMBAL_AXES[part.i] : (view.cam.viewDir().toArray() as Vec3);
const plane = { origin: dr.center, normal: n, xDir: xDirFor(n) };
const a = view.rayToPlane(dr.from.x, dr.from.y, plane);
const b = view.rayToPlane(p.x, p.y, plane);
if (!a || !b) return;
const d = sub(b, a);
this.apply([snap(d[0]), snap(d[1]), snap(d[2])], 0);
this.app.ui.setLabel(p.x, p.y, `${fmtLen(len(dr.d))} · type a value`);
} else if (part.kind === "ring") {
const axis = GIMBAL_AXES[part.i];
const c = view.toScreen(dr.center);
if (!c) return;
const ang = (q: { x: number; y: number }) => Math.atan2(q.y - c[1], q.x - c[0]);
const facing = dot(axis, view.cam.viewDir().toArray() as Vec3) < 0 ? 1 : -1;
let deg = ((-(ang(p) - ang(dr.from)) * 180) / Math.PI) * facing;
deg = ((deg + 540) % 360) - 180;
const total = p.shift ? deg : Math.round(deg);
this.apply([0, 0, 0], total);
this.app.ui.setLabel(p.x, p.y, `${total}° · type a value`);
}
}
/** Move the selected points from where the drag began: translate d, then turn `deg` about the gimbal axis. */
private apply(d: Vec3, deg: number): void {
const dr = this.dragging;
if (!dr) return;
dr.d = d;
dr.ang = deg;
const ids = this.selectedVerts();
const axis = dr.part.kind === "ring" ? GIMBAL_AXES[dr.part.i] : null;
const t = (deg * Math.PI) / 180;
for (const i of ids) {
let q = dr.base[i];
if (axis && deg) {
// Rodrigues' rotation about the axis through the centre.
const v = sub(q, dr.center);
const r = add(add(scale(v, Math.cos(t)), scale(cross(axis, v), Math.sin(t))), scale(axis, dot(axis, v) * (1 - Math.cos(t))));
q = add(dr.center, r);
}
this.cage.verts[i] = add(q, d);
}
this.gimbal?.setCenter(this.centroid(ids));
this.rebuild();
}
up(): void {
const moved = !!this.dragging && (len(this.dragging.d) > 0 || this.dragging.ang !== 0);
this.dragging = null;
this.typing.reset();
this.app.ui.setLabel(0, 0, null);
this.gimbal?.setHot(null);
if (this.placing && moved) {
// In place: on to editing points, edges and faces.
this.placing = false;
this.picks = [];
this.selectionChanged();
return;
}
this.placeGimbal();
}
dragKey(e: KeyboardEvent): boolean {
const dr = this.dragging;
if (!dr) return false;
const part = dr.part;
const dragDir = norm(dr.d);
return this.typing.key(e, {
kind: part.kind === "ring" ? "angle" : "length",
apply: (v) => {
if (part.kind === "ring") this.apply([0, 0, 0], v);
else if (part.kind === "axis") this.apply(scale(GIMBAL_AXES[part.i], v), 0);
else if (len(dr.d) > 1e-9) this.apply(scale(dragDir, v), 0);
},
commit: () => this.up(),
cancel: () => this.apply([0, 0, 0], 0),
});
}
/** Panel Scale: grow/shrink the selection about its centre (relative to the last value). */
private scaleSelection(v: number): void {
if (v <= 0) return;
const ids = this.selectedVerts();
const c = this.centroid(ids);
const k = v / this.uniform;
this.uniform = v;
for (const i of ids) this.cage.verts[i] = add(c, scale(sub(this.cage.verts[i], c), k));
this.rebuild();
this.placeGimbal();
}
// --------------------------------------------------------------- drawing
private rebuild(): void {
const m = previewMesh(subdivide(this.cage, 3));
const g = this.surface.geometry;
g.setAttribute("position", new BufferAttribute(m.positions, 3));
g.setAttribute("normal", new BufferAttribute(m.normals, 3));
g.setIndex(new BufferAttribute(m.indices, 1));
g.computeBoundingSphere();
const edges = cageEdges(this.cage).flatMap(([a, b]) => [...this.cage.verts[a], ...this.cage.verts[b]]);
setPositions(this.lines, edges);
setPositions(this.dots, this.cage.verts.flat());
this.drawMarks();
}
private drawMarks(): void {
const seg = (ps: Pick[]) =>
ps.flatMap((p) => {
const V = this.cage.verts;
if (p.kind === "edge") return [...V[p.e[0]], ...V[p.e[1]]];
if (p.kind === "face") {
const f = this.cage.faces[p.f];
return f.flatMap((i, k) => [...V[i], ...V[f[(k + 1) % 4]]]);
}
return [];
});
const pts = (ps: Pick[]) => ps.flatMap((p) => (p.kind === "vert" ? [...this.cage.verts[p.i]] : []));
setPositions(this.marks, seg(this.picks));
setPositions(this.markDots, pts(this.picks));
const h = this.hovered ? [this.hovered] : [];
setPositions(this.hoverMarks, seg(h));
setPositions(this.hoverDots, pts(h));
this.app.view.requestRender();
}
// ------------------------------------------------------------- finishing
key(e: KeyboardEvent): boolean {
if (e.key === "Escape") {
if (this.picks.length) ((this.picks = []), this.selectionChanged());
else this.cancel();
return true;
}
if (e.key === "Enter") return (this.done(), true);
if ((e.key === "Delete" || e.key === "Backspace") && this.picks.some((p) => p.kind === "face")) return (this.deleteSelectedFaces(), true);
if (e.key.toLowerCase() === "a" && (e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.picks = this.cage.verts.map((_, i) => ({ kind: "vert" as const, i }));
this.selectionChanged();
return true;
}
return false;
}
/** Save and close; returns the body id. */
private done(): string | null {
// Stored where it was made: later move steps in History still apply on top.
const cage = { faces: structuredClone(this.cage.faces), verts: this.cage.verts.map(this.place.inv) };
const open = !isClosed(cage);
const extra = { surface: this.surfaceSheet || undefined, thickness: open && this.thickness > 0 ? this.thickness : undefined, thickSide: open && this.thickness > 0 ? this.thickSide : undefined };
let id: string;
if (this.existing) {
id = this.existing.id;
this.app.store.update(id, { cage, ...extra } as Partial<FreeformFeature>);
} else {
const f: FreeformFeature = { ...this.app.store.newIdentity("freeform", isClosed(cage) ? "Freeform" : "Freeform surface"), type: "freeform", cage, ...extra };
this.app.store.add(f);
id = f.id;
}
this.app.setTool(null);
return id;
}
private cancel(): void {
this.app.setTool(null);
}
/** Select the cage element under the pointer (used when a tap on the body opens the tool). */
/**
* Delete the cage faces under picked body geometry (from the select tool):
* a face → its patch; an edge or a point → every patch that touches it.
* The shape opens up, so the Thickness choice shows.
*/
deleteAt(points: Vec3[], kind: "face" | "edge" | "vertex"): void {
const sub3 = subdivide(this.cage, 3);
const n = sub3.n;
const size = Math.max(1e-9, ...[0, 1, 2].map((k) => Math.max(...this.cage.verts.map((v) => v[k])) - Math.min(...this.cage.verts.map((v) => v[k]))));
const dist3 = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
const doomed = new Set<number>();
for (const q of points) {
if (kind === "face") {
let best = -1;
let bd = Infinity;
sub3.grids.forEach((g, f) => {
const d = dist3(sub3.points[g[n >> 1][n >> 1]], q);
if (d < bd) [bd, best] = [d, f];
});
if (best >= 0) doomed.add(best);
continue;
}
// Patches whose rim passes through the edge / point.
const rim = sub3.grids.map((g) => {
let d = Infinity;
for (let i = 0; i <= n; i++)
for (const [a, b] of [[0, i], [n, i], [i, 0], [i, n]]) d = Math.min(d, dist3(sub3.points[g[a][b]], q));
return d;
});
const min = Math.min(...rim);
rim.forEach((d, f) => d < min + size * 0.01 && doomed.add(f));
}
if (!doomed.size) return;
if (doomed.size >= this.cage.faces.length) return this.app.ui.toast("At least one face has to stay");
this.cage = deleteFaces(this.cage, [...doomed]);
this.picks = [];
this.rebuild();
this.selectionChanged();
this.app.ui.toast("The shape is no longer closed: give it a Thickness to make a solid, or Done for a surface.");
this.panelHint();
}
selectAt(p: ToolPointer): void {
const hit = this.pickAt(p);
if (!hit) return;
this.picks = [hit];
this.selectionChanged();
}
}
function setPositions(o: LineSegments | Points, xyz: number[]): void {
const g = o.geometry;
g.setAttribute("position", new BufferAttribute(new Float32Array(xyz), 3));
g.computeBoundingSphere();
}
/** Screen distance from (x, y) to segment a–b, and where along it (0…1). */
function segDist(x: number, y: number, a: [number, number], b: [number, number]): { d: number; t: number } {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const l2 = dx * dx + dy * dy || 1;
const t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / l2));
return { d: Math.hypot(x - (a[0] + dx * t), y - (a[1] + dy * t)), t };
}
function inPoly(x: number, y: number, q: [number, number][]): boolean {
let inside = false;
for (let i = 0, j = q.length - 1; i < q.length; j = i++) {
const [xi, yi] = q[i];
const [xj, yj] = q[j];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
interface Placement {
fwd(v: Vec3): Vec3;
inv(v: Vec3): Vec3;
}
/**
* Where later History steps put this body: moves, scales and mirrors that
* act on it (not copies). `inv` undoes them, to store edits in the cage's own place.
*/
function placementOf(features: readonly Feature[], id: string): Placement {
const i = features.findIndex((f) => f.id === id);
const steps = features
.slice(i + 1)
.filter((f): f is TransformFeature => f.type === "transform" && !f.suppressed && !f.copy && f.bodies.includes(id) && ["move", "scale", "mirror"].includes(f.op.kind));
const turn = (p: Vec3, o: Vec3, axis: Vec3, deg: number): Vec3 => {
const k = norm(axis);
const v = sub(p, o);
const t = (deg * Math.PI) / 180;
return add(o, add(add(scale(v, Math.cos(t)), scale(cross(k, v), Math.sin(t))), scale(k, dot(k, v) * (1 - Math.cos(t)))));
};
const reflect = (p: Vec3, o: Vec3, n: Vec3): Vec3 => {
const k = norm(n);
return sub(p, scale(k, 2 * dot(sub(p, o), k)));
};
const apply = (op: TransformFeature["op"], p: Vec3, back: boolean): Vec3 => {
if (op.kind === "move") {
const r = op.rotate;
if (!back) return add(r && r.angle ? turn(p, r.origin, r.axis, r.angle) : p, op.translate);
const q = sub(p, op.translate);
return r && r.angle ? turn(q, r.origin, r.axis, -r.angle) : q;
}
if (op.kind === "scale") return add(op.center, scale(sub(p, op.center), back ? 1 / op.factor : op.factor));
if (op.kind === "mirror") return reflect(p, op.plane.origin, op.plane.normal);
return p;
};
return {
fwd: (v) => steps.reduce((p, f) => apply(f.op, p, false), v),
inv: (v) => [...steps].reverse().reduce((p, f) => apply(f.op, p, true), v),
};
}
+213
View File
@@ -0,0 +1,213 @@
// Move/rotate gimbal: three axis arrows, three plane squares, three rotation
// arcs and a centre ball. Drawn at constant screen size; hit-tested on screen.
import { BoxGeometry, BufferGeometry, ConeGeometry, DoubleSide, Group, Mesh, MeshBasicMaterial, PlaneGeometry, SphereGeometry, Vector3 } from "three";
import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";
import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js";
import { LineMaterial } from "three/examples/jsm/lines/LineMaterial.js";
import type { Vec3 } from "../doc/types";
import type { ToolPointer } from "../view/input";
import type { Viewport } from "../view/viewport";
export type GimbalPart = { kind: "axis" | "plane" | "ring"; i: 0 | 1 | 2 } | { kind: "center" };
const AXES: Vec3[] = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
const COLORS = [0xe0584f, 0x5fbf5a, 0x4f8ce0];
const SIZE_PX = 85;
const ARC_FROM = 0.25;
const ARC_TO = 1.32;
/** Points of the rotation arc around axis i, in unit gimbal space. */
function arcPoints(axes: Vec3[], i: number, n = 24): Vector3[] {
const u = new Vector3(...axes[(i + 1) % 3]);
const v = new Vector3(...axes[(i + 2) % 3]);
return Array.from({ length: n + 1 }, (_, k) => {
const t = ARC_FROM + ((ARC_TO - ARC_FROM) * k) / n;
return u.clone().multiplyScalar(Math.cos(t) * 1.1).addScaledVector(v, Math.sin(t) * 1.1);
});
}
export interface GimbalOptions {
/** The three axes (default world X, Y, Z). For a sketch: plane x, plane y, normal. */
axes?: Vec3[];
/** Which parts exist (e.g. a sketch gimbal has no out-of-plane arrow). */
parts?: (p: GimbalPart) => boolean;
/** Cube ends instead of arrow heads: the scale gimbal. */
cubes?: boolean;
}
/** Scale gimbal: the three axis handles (cube ends) and the centre (uniform). */
export const SCALE_PARTS = (p: GimbalPart) => p.kind === "axis" || p.kind === "center";
/** Parts of a gimbal that keep things in a plane whose normal is axis 2. */
export const IN_PLANE = (p: GimbalPart) => p.kind === "center" || (p.kind === "axis" && p.i < 2) || (p.kind !== "axis" && p.i === 2);
export class Gimbal {
private group = new Group();
private center = new Vector3();
private parts: { part: GimbalPart; obj: Group | Mesh | LineSegments2; color: number }[] = [];
private hook = () => this.layout();
private hot: GimbalPart | null = null;
readonly axes: Vec3[];
private allow: (p: GimbalPart) => boolean;
constructor(
private view: Viewport,
opts: GimbalOptions = {},
) {
this.axes = opts.axes ?? AXES;
this.allow = opts.parts ?? (() => true);
const AX = this.axes;
AX.forEach((a, i) => {
const dir = new Vector3(...a);
const color = COLORS[i];
// Axis arrow
const arrow = new Group();
const shaft = new LineSegments2(new LineSegmentsGeometry().setPositions([...dir.clone().multiplyScalar(0.18).toArray(), ...dir.clone().multiplyScalar(0.82).toArray()]), view.lineMaterial(color, 3.5));
const head = new Mesh(opts.cubes ? new BoxGeometry(0.15, 0.15, 0.15) : new ConeGeometry(0.07, 0.22, 16), new MeshBasicMaterial({ color, depthTest: false }));
head.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), dir);
head.position.copy(dir).multiplyScalar(0.9);
arrow.add(shaft, head);
this.add({ kind: "axis", i: i as 0 | 1 | 2 }, arrow, color);
// Plane square (moves in the plane perpendicular to this axis)
const u = new Vector3(...AX[(i + 1) % 3]);
const v = new Vector3(...AX[(i + 2) % 3]);
const sq = new Mesh(new PlaneGeometry(0.17, 0.17), new MeshBasicMaterial({ color, transparent: true, opacity: 0.55, side: DoubleSide, depthTest: false }));
sq.position.copy(u.clone().add(v).multiplyScalar(0.33));
sq.quaternion.setFromUnitVectors(new Vector3(0, 0, 1), dir);
this.add({ kind: "plane", i: i as 0 | 1 | 2 }, sq, color);
// Rotation arc
const pts = arcPoints(AX, i);
const seg: number[] = [];
for (let k = 0; k < pts.length - 1; k++) seg.push(...pts[k].toArray(), ...pts[k + 1].toArray());
const arc = new LineSegments2(new LineSegmentsGeometry().setPositions(seg), view.lineMaterial(color, 3));
this.add({ kind: "ring", i: i as 0 | 1 | 2 }, arc, color);
});
const ball = new Mesh(new SphereGeometry(0.075, 16, 12), new MeshBasicMaterial({ color: 0xffffff, depthTest: false }));
this.add({ kind: "center" }, ball, 0xffffff);
// Over everything, selection highlights included (see Handle).
this.group.traverse((o) => {
o.renderOrder = 50;
const m = (o as Mesh).material as MeshBasicMaterial | undefined;
if (m && "transparent" in m) m.transparent = true;
});
view.overlay.add(this.group);
view.frameHooks.add(this.hook);
view.helpers.add(this);
}
private add(part: GimbalPart, obj: Group | Mesh | LineSegments2, color: number): void {
obj.visible = this.allow(part);
this.parts.push({ part, obj, color });
this.group.add(obj);
}
setCenter(c: Vec3): void {
this.center.set(...c);
this.layout();
this.view.requestRender();
}
get origin(): Vec3 {
return this.center.toArray() as Vec3;
}
private scale(): number {
return this.view.cam.worldPerPixel(this.view.height) * SIZE_PX;
}
private layout(): void {
this.group.position.copy(this.center);
this.group.scale.setScalar(this.scale());
}
private screen(local: Vector3): [number, number] | null {
return this.view.toScreen(local.clone().multiplyScalar(this.scale()).add(this.center));
}
/** Which part is under the pointer (centre, planes, arrows, arcs — in that order). */
hit(p: ToolPointer): GimbalPart | null {
const tol = Math.max(10, p.tol * 1.2);
const c = this.screen(new Vector3());
if (c && this.allow({ kind: "center" }) && Math.hypot(c[0] - p.x, c[1] - p.y) < tol) return { kind: "center" };
for (let i = 0; i < 3; i++) {
if (!this.allow({ kind: "plane", i: i as 0 | 1 | 2 })) continue;
const u = new Vector3(...this.axes[(i + 1) % 3]);
const v = new Vector3(...this.axes[(i + 2) % 3]);
const m = u.clone().add(v).multiplyScalar(0.33);
const quad = [m.clone().addScaledVector(u, -0.085).addScaledVector(v, -0.085), m.clone().addScaledVector(u, 0.085).addScaledVector(v, -0.085), m.clone().addScaledVector(u, 0.085).addScaledVector(v, 0.085), m.clone().addScaledVector(u, -0.085).addScaledVector(v, 0.085)]
.map((q) => this.screen(q))
.filter((q): q is [number, number] => !!q);
if (quad.length === 4 && inPoly(p.x, p.y, quad)) return { kind: "plane", i: i as 0 | 1 | 2 };
}
let best: { part: GimbalPart; d: number } | null = null;
for (let i = 0; i < 3; i++) {
const dir = new Vector3(...this.axes[i]);
const a = this.screen(dir.clone().multiplyScalar(0.18));
const b = this.screen(dir.clone().multiplyScalar(1.02));
if (a && b && this.allow({ kind: "axis", i: i as 0 | 1 | 2 })) {
const d = segDist(p.x, p.y, a, b);
if (d < tol && (!best || d < best.d)) best = { part: { kind: "axis", i: i as 0 | 1 | 2 }, d };
}
const pts = this.allow({ kind: "ring", i: i as 0 | 1 | 2 }) ? arcPoints(this.axes, i, 16).map((q) => this.screen(q)) : [];
for (let k = 0; k < pts.length - 1; k++) {
const s0 = pts[k];
const s1 = pts[k + 1];
if (!s0 || !s1) continue;
const d = segDist(p.x, p.y, s0, s1);
if (d < tol && (!best || d < best.d)) best = { part: { kind: "ring", i: i as 0 | 1 | 2 }, d };
}
}
return best?.part ?? null;
}
/** Brighten the part under the pointer / being dragged. */
setHot(part: GimbalPart | null): void {
if (JSON.stringify(part) === JSON.stringify(this.hot)) return;
this.hot = part;
for (const { part: q, obj, color } of this.parts) {
const on = !!part && JSON.stringify(part) === JSON.stringify(q);
obj.traverse((o) => {
const m = (o as Mesh).material as MeshBasicMaterial & { color?: { setHex(n: number): void } };
if (m?.color) m.color.setHex(on ? 0xffd34d : color);
});
}
this.view.requestRender();
}
dispose(): void {
this.view.helpers.delete(this);
this.view.frameHooks.delete(this.hook);
this.view.overlay.remove(this.group);
this.group.traverse((o) => {
const m = o as Mesh;
if (m.geometry instanceof BufferGeometry) m.geometry.dispose();
if (m.material instanceof LineMaterial) this.view.releaseLineMaterial(m.material);
});
this.view.requestRender();
}
}
export const GIMBAL_AXES = AXES;
function segDist(x: number, y: number, a: [number, number], b: [number, number]): number {
const dx = b[0] - a[0];
const dy = b[1] - a[1];
const l2 = dx * dx + dy * dy || 1;
const t = Math.max(0, Math.min(1, ((x - a[0]) * dx + (y - a[1]) * dy) / l2));
return Math.hypot(a[0] + dx * t - x, a[1] + dy * t - y);
}
function inPoly(x: number, y: number, poly: [number, number][]): boolean {
let inside = false;
for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {
const [xi, yi] = poly[i];
const [xj, yj] = poly[j];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside;
}
return inside;
}
+131
View File
@@ -0,0 +1,131 @@
import { ConeGeometry, Group, Mesh, MeshBasicMaterial, SphereGeometry, Vector3 } from "three";
import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js";
import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js";
import type { Vec3 } from "../doc/types";
import type { Viewport } from "../view/viewport";
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;
/**
* A drag handle drawn at constant screen size: an arrow along a direction, or a
* dot. `hit` tests in screen space so it's easy to grab with a finger.
*/
export class Handle {
private group = new Group();
private base = new Vector3();
private dir = new Vector3(0, 0, 1);
// Transparent (at full opacity) so it's drawn in the last pass, over see-through
// selection highlights — three.js draws all opaque things before those.
private mat = new MeshBasicMaterial({ color: COLOR, depthTest: false, transparent: true });
private head: Mesh;
private shaft: LineSegments2 | null = null;
private lineMat;
private onFrame = () => this.layout();
constructor(private view: Viewport, readonly shape: "arrow" | "dot") {
this.lineMat = view.lineMaterial(COLOR, 4);
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.renderOrder = 50;
this.group.add(this.head);
if (shape === "arrow") {
this.shaft = new LineSegments2(new LineSegmentsGeometry(), this.lineMat);
this.shaft.renderOrder = 50;
this.group.add(this.shaft);
}
view.overlay.add(this.group);
view.frameHooks.add(this.onFrame);
view.helpers.add(this);
}
private hot = false;
/** Highlight while the pointer is over it (brighter and a bit bigger). */
setHot(on: boolean): void {
if (on === this.hot) return;
this.hot = on;
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.transparent = true;
this.shaft.material = this.lineMat;
}
this.layout();
this.view.requestRender();
}
set(base: Vec3, dir?: Vec3): void {
this.base.set(...base);
if (dir) this.dir.set(...dir).normalize();
this.layout();
this.view.requestRender();
}
/** Screen position of the grabbable part. */
grabPoint(): [number, number] | null {
return this.view.toScreen(this.tip());
}
hit(p: ToolPointer): boolean {
const s = this.grabPoint();
return !!s && Math.hypot(s[0] - p.x, s[1] - p.y) < Math.max(30, p.tol * 1.8);
}
dispose(): void {
this.view.helpers.delete(this);
this.view.frameHooks.delete(this.onFrame);
this.view.overlay.remove(this.group);
this.head.geometry.dispose();
this.shaft?.geometry.dispose();
this.view.releaseLineMaterial(this.lineMat);
this.view.requestRender();
}
private size(): number {
return this.view.cam.worldPerPixel(this.view.height) * ARROW_PX;
}
private headScale(): number {
return this.size() * (this.hot ? 1.45 : 1);
}
private tip(): Vector3 {
return this.shape === "arrow" ? this.base.clone().addScaledVector(this.dir, this.size()) : this.base.clone();
}
private layout(): void {
const s = this.size();
this.head.scale.setScalar(this.headScale());
if (this.shape === "arrow") {
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()]);
} else {
this.head.position.copy(this.base);
}
}
}
/** Screen-space drag along a world axis → signed world distance. */
export function axisDrag(view: Viewport, origin: Vec3, dir: Vec3, from: ToolPointer, to: ToolPointer): number {
const o = new Vector3(...origin);
const a = view.toScreen(o);
const b = view.toScreen(o.clone().addScaledVector(new Vector3(...dir), 1));
const dx = to.x - from.x;
const dy = to.y - from.y;
if (a && b) {
const vx = b[0] - a[0];
const vy = b[1] - a[1];
const l2 = vx * vx + vy * vy;
// Looking almost straight down the axis: fall back to vertical drag.
if (l2 > 0.25) return (dx * vx + dy * vy) / l2;
}
return -dy * view.cam.worldPerPixel(view.height);
}
+258
View File
@@ -0,0 +1,258 @@
import type { PinDef, Vec3 } from "../doc/types";
import { settings } from "../settings";
import { cross, dist, dot, len, sub } from "../geom";
import type { BodyMesh } from "../kernel/protocol";
import { el } from "../ui/ui";
import { fmtLen, trim, UNIT_MM, UNIT_LABEL, units } from "../units";
import type { ToolPointer } from "../view/input";
import { hitToSel, sameSel, type AppContext, type Sel, type Tool } from "./tool";
export interface MeasureHost extends AppContext {
readonly pins: PinDef[];
setPins(p: PinDef[]): void;
}
interface Row {
name: string;
value: string;
at: Vec3;
a?: Vec3;
b?: Vec3;
}
/**
* Measure: tap faces, edges or bodies; a card lists what can be measured
* about them (and between two of them). Pin any value to keep it visible.
*/
export class MeasureTool implements Tool {
readonly id = "measure";
private items: Sel[] = [];
private card: HTMLElement | null = null;
private deltas = false;
constructor(private app: MeasureHost) {}
enter(): void {
this.app.ui.setTools([{ id: "exit", label: "Exit Measure", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) }]);
this.app.ui.setBottom([]);
this.app.ui.setHint("Select objects to see their measurements. Double-tap for a whole body.");
this.card = el("div", "measure-card");
document.body.append(this.card);
this.render();
}
exit(): void {
this.card?.remove();
this.app.ui.setHint(null);
this.app.setSelection([]);
this.app.setHover(null);
}
hover(p: ToolPointer | null): void {
this.app.setHover(p ? hitToSel(this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false })) : null);
}
tap(p: ToolPointer, count: number): void {
let s = hitToSel(this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, profiles: false, planes: false }));
if (!s) {
// Empty space: first clears, second leaves Measure.
if (!this.items.length) return this.app.setTool(null);
this.items = [];
} else {
if (count >= 2 && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex")) s = { kind: "body", body: s.body };
const i = this.items.findIndex((x) => sameSel(x, s!));
if (i >= 0) this.items.splice(i, 1);
else this.items = [...this.items.slice(-1), s];
}
this.app.setSelection(this.items);
this.render();
}
key(e: KeyboardEvent): boolean {
if (e.key === "Escape") {
if (this.items.length) {
this.items = [];
this.app.setSelection([]);
this.render();
} else this.app.setTool(null);
return true;
}
return false;
}
private render(): void {
if (!this.card) return;
this.card.innerHTML = "";
const rows = this.measurements();
const head = el("label", "measure-toggle");
const box = document.createElement("input");
box.type = "checkbox";
box.checked = this.deltas;
box.addEventListener("change", () => ((this.deltas = box.checked), this.render()));
head.append(box, " Include X, Y, Z deltas");
const show = el("label", "measure-toggle");
const sbox = document.createElement("input");
sbox.type = "checkbox";
sbox.checked = settings.value.showPinned;
sbox.addEventListener("change", () => settings.set("showPinned", sbox.checked));
show.append(sbox, " Show pinned measurements");
this.card.append(head, show);
if (!rows.length) this.card.append(el("div", "measure-empty", "Nothing selected"));
for (const r of rows) {
const row = el("div", "measure-row");
row.append(el("div", "measure-value", r.value), el("div", "measure-name", r.name));
const pin = el("button", "icon-btn", "📌");
pin.title = "Pin to always show";
pin.addEventListener("click", () => (this.app.addPin({ text: r.value, at: r.at, a: r.a, b: r.b }), this.render()));
row.append(pin);
this.card.append(row);
}
if (this.app.pins.length) {
const clear = el("button", "text-btn", `Clear ${this.app.pins.length} pinned`);
clear.addEventListener("click", () => (this.app.setPins([]), this.render()));
this.card.append(clear);
}
}
private measurements(): Row[] {
const out: Row[] = [];
const info = this.items.map((s) => this.describe(s)).filter((x): x is Described => !!x);
for (const d of info) out.push(...d.rows);
if (info.length === 2) {
const [a, b] = info;
const mid = (p: Vec3, q: Vec3): Vec3 => [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2, (p[2] + q[2]) / 2];
out.push({ name: "Distance (centers)", value: fmtLen(dist(a.anchor, b.anchor)), at: mid(a.anchor, b.anchor), a: a.anchor, b: b.anchor });
const m = closestPair(a.points, b.points);
out.push({ name: "Minimum distance", value: fmtLen(m.d), at: mid(m.p, m.q), a: m.p, b: m.q });
if (this.deltas) {
const d = sub(b.anchor, a.anchor);
["X", "Y", "Z"].forEach((n, i) => {
const end = [...a.anchor] as Vec3;
end[i] = b.anchor[i];
out.push({ name: `Δ${n}`, value: fmtLen(Math.abs(d[i])), at: mid(a.anchor, end), a: a.anchor, b: end });
});
}
if (a.dir && b.dir) {
const ang = (Math.acos(Math.min(1, Math.abs(dot(a.dir, b.dir)))) * 180) / Math.PI;
out.push({ name: "Angle", value: `${trim(ang, 2)}°`, at: mid(a.anchor, b.anchor) });
}
}
return out;
}
private describe(s: Sel): Described | null {
if (s.kind !== "face" && s.kind !== "edge" && s.kind !== "body" && s.kind !== "vertex") return null;
const b = this.app.view.body(s.body);
if (!b) return null;
if (s.kind === "vertex") {
const v = this.app.view.vertexOf(s.body, s.vertex);
if (!v) return null;
const u = UNIT_MM[units()];
return { rows: [{ name: "Point (X, Y, Z)", value: v.map((c) => trim(c / u, 3)).join(", "), at: v }], anchor: v, points: [v] };
}
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 }];
return { rows, anchor: f.center, points: pts, dir: f.plane ? f.normal : undefined };
}
if (s.kind === "edge") {
const e = b.edges[s.edge];
const pts = edgePoints(b, s.edge);
const rows: Row[] = [{ name: `Length · ${niceType(e.type)}`, value: fmtLen(e.length), at: e.mid, ...(e.type === "LINE" ? { a: e.start, b: e.end } : {}) }];
if (e.type === "CIRCLE" && pts.length >= 3) {
const r = circumradius(pts[0], pts[Math.floor(pts.length / 3)], pts[Math.floor((2 * pts.length) / 3)]);
if (r) rows.push({ name: "Diameter", value: fmtLen(2 * r), at: e.mid }, { name: "Radius", value: fmtLen(r), at: e.mid });
}
return { rows, anchor: e.mid, points: pts, dir: e.type === "LINE" ? e.dir : undefined };
}
const pts: Vec3[] = [];
for (let i = 0; i < b.positions.length; i += 3) pts.push([b.positions[i], b.positions[i + 1], b.positions[i + 2]]);
const min = [0, 1, 2].map((k) => Math.min(...pts.map((p) => p[k])));
const max = [0, 1, 2].map((k) => Math.max(...pts.map((p) => p[k])));
const center: Vec3 = [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2];
const area = b.faces.reduce((s2, f) => s2 + f.area, 0);
return {
rows: [
{ name: "Size (X × Y × Z)", value: `${trim((max[0] - min[0]) / UNIT_MM[units()], 3)} × ${trim((max[1] - min[1]) / UNIT_MM[units()], 3)} × ${fmtLen(max[2] - min[2])}`, at: center },
{ name: "Surface area", value: fmtArea(area), at: center },
{ name: "Volume", value: fmtVolume(volume(b)), at: center },
],
anchor: center,
points: pts,
};
}
}
interface Described {
rows: Row[];
anchor: Vec3;
points: Vec3[];
dir?: Vec3;
}
function facePoints(b: BodyMesh, face: number): Vec3[] {
const g = b.faceGroups.find((x) => x.face === face);
if (!g) return [];
const out: Vec3[] = [];
for (let i = g.start; i < g.start + g.count; i++) {
const v = b.indices[i] * 3;
out.push([b.positions[v], b.positions[v + 1], b.positions[v + 2]]);
}
return out;
}
function edgePoints(b: BodyMesh, edge: number): Vec3[] {
const g = b.edgeGroups.find((x) => x.edge === edge);
if (!g) return [];
const out: Vec3[] = [];
for (let i = g.start; i < g.start + g.count; i++) out.push([b.edgePositions[i * 3], b.edgePositions[i * 3 + 1], b.edgePositions[i * 3 + 2]]);
return out;
}
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));
for (let i = 0; i < a.length; i += step(a.length)) {
for (let j = 0; j < b.length; j += step(b.length)) {
const d = dist(a[i], b[j]);
if (d < best.d) best = { d, p: a[i], q: b[j] };
}
}
return best;
}
function circumradius(a: Vec3, b: Vec3, c: Vec3): number | null {
const ab = len(sub(b, a));
const bc = len(sub(c, b));
const ca = len(sub(a, c));
const area2 = len(cross(sub(b, a), sub(c, a)));
return area2 > 1e-12 ? (ab * bc * ca) / (2 * area2) : null;
}
/** Signed-tetrahedron volume of the (closed) mesh. */
function volume(b: BodyMesh): number {
let v = 0;
const p = b.positions;
for (let i = 0; i < b.indices.length; i += 3) {
const a = b.indices[i] * 3;
const c = b.indices[i + 1] * 3;
const d = b.indices[i + 2] * 3;
v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6;
}
return Math.abs(v);
}
function fmtArea(mm2: number): string {
const k = UNIT_MM[units()];
return `${trim(mm2 / (k * k), 3)} ${UNIT_LABEL[units()]}²`;
}
function fmtVolume(mm3: number): string {
const k = UNIT_MM[units()];
return `${trim(mm3 / (k * k * k), 3)} ${UNIT_LABEL[units()]}³`;
}
function niceType(t: string): string {
return t.toLowerCase().replace(/_/g, " ").replace("bspline", "free-form");
}
+1542
View File
File diff suppressed because it is too large Load Diff
+85
View File
@@ -0,0 +1,85 @@
// A small floating box beside a pattern's drag arrow: how many copies, and how
// far apart (between neighbours, or the whole run from the first to the last).
import { Vector3 } from "three";
import type { Vec3 } from "../doc/types";
import { el } from "../ui/ui";
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
import type { Viewport } from "../view/viewport";
export interface PatternBoxOptions {
count: number;
spacing: number;
/** "between": spacing is from one copy to the next; "total": from the first to the last. */
measure: "between" | "total";
onChange(v: { count: number; spacing: number; measure: "between" | "total" }): void;
onCommit(): void;
}
export class PatternBox {
private box = el("div", "dim-widget pattern-box");
private count = document.createElement("input");
private dist = document.createElement("input");
private sel = document.createElement("select");
private at = new Vector3();
private hook = () => this.layout();
constructor(
private view: Viewport,
opts: PatternBoxOptions,
) {
for (const [id, label] of [["between", "Between"], ["total", "Total"]]) {
const o = document.createElement("option");
o.value = id;
o.textContent = label;
this.sel.append(o);
}
this.sel.value = opts.measure;
this.count.inputMode = "numeric";
this.count.value = String(opts.count);
this.count.title = "Count (the original included)";
this.dist.inputMode = "decimal";
this.dist.value = trim(toDisplay(opts.spacing), 3);
const changed = () => {
const n = Math.round(Number(this.count.value));
const d = evaluate(this.dist.value, "length");
const ok = Number.isFinite(n) && n >= 2 && d !== null;
this.box.classList.toggle("invalid", !ok);
if (ok) opts.onChange({ count: n, spacing: d!, measure: this.sel.value as "between" | "total" });
};
for (const i of [this.count, this.dist]) {
i.spellcheck = false;
i.addEventListener("input", changed);
i.addEventListener("keydown", (e) => {
e.stopPropagation();
if (e.key === "Enter") opts.onCommit();
if (e.key === "Escape") i.blur();
});
}
this.sel.addEventListener("change", changed);
this.box.append(el("span", "dim-unit", "×"), this.count, this.sel, this.dist, el("span", "dim-unit", UNIT_LABEL[units()]));
this.box.addEventListener("pointerdown", (e) => e.stopPropagation());
document.body.append(this.box);
view.frameHooks.add(this.hook);
view.helpers.add(this);
setTimeout(() => (this.count.focus(), this.count.select()), 0);
}
/** Where the box sits (a world point, e.g. the arrow's tip). */
place(p: Vec3): void {
this.at.set(...p);
this.layout();
}
private layout(): void {
const s = this.view.toScreen(this.at);
this.box.hidden = !s;
if (s) this.box.style.transform = `translate(${Math.round(s[0] + 24)}px, ${Math.round(s[1] - 24)}px) translate(0, -50%)`;
}
dispose(): void {
this.view.helpers.delete(this);
this.view.frameHooks.delete(this.hook);
this.box.remove();
}
}
+158
View File
@@ -0,0 +1,158 @@
import type { PlaneDef, Vec3 } from "../doc/types";
import { add, niceStep, scale } from "../geom";
import { fmtLen } from "../units";
import type { ToolPointer } from "../view/input";
import { DragTyping } from "./dragTyping";
import { axisDrag, Handle } from "./handles";
import { hitToSel, type AppContext, type Tool } from "./tool";
export interface SectionState {
plane: PlaneDef;
offset: number;
flipped: boolean;
}
export interface SectionHost extends AppContext {
section: SectionState | null;
setSection(s: SectionState | null): void;
}
/** The plane the view is cut with (offset and flip applied). */
export function sectionPlane(s: SectionState): PlaneDef {
const n: Vec3 = s.flipped ? scale(s.plane.normal, -1) : s.plane.normal;
return { origin: add(s.plane.origin, scale(s.plane.normal, s.offset)), normal: n, xDir: s.plane.xDir };
}
/** Section view: pick a plane or flat face, then drag the cut along its normal. */
export class SectionTool implements Tool {
readonly id = "section";
private handle: Handle | null = null;
private dragging: { from: ToolPointer; o0: number } | null = null;
constructor(private app: SectionHost) {}
enter(): void {
this.app.ui.setTools([{ id: "exit", label: "Exit Section", icon: "exit", shortcut: "Esc", run: () => this.app.setTool(null) }]);
this.app.ui.setBottom([]);
if (this.app.section) this.showControls();
else this.askForPlane();
}
exit(): void {
this.handle?.dispose();
this.handle = null;
this.app.view.setOriginPlanesVisible(false);
this.app.ui.showPanel(null);
this.app.ui.setHint(null);
this.app.ui.setLabel(0, 0, null);
}
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.");
}
hover(p: ToolPointer | null): void {
if (!p || this.app.section) return this.app.setHover(null);
const hit = this.app.view.pick(p.x, p.y, { edges: false, vertices: false, profiles: false, planes: true, planesFirst: true });
const ok = hit && (hit.kind === "plane" || (hit.kind === "face" && !!this.app.view.body(hit.body)?.faces[hit.face]?.plane));
this.app.setHover(ok ? hitToSel(hit) : null);
}
tap(p: ToolPointer): void {
// With a section set, tapping empty space leaves the tool (the section stays on).
if (this.app.section) {
if (!this.app.view.pick(p.x, p.y, { profiles: false })) this.app.setTool(null);
return;
}
const hit = this.app.view.pick(p.x, p.y, { edges: false, profiles: false, planes: true, planesFirst: true });
if (!hit) return this.app.setTool(null);
let plane: PlaneDef | undefined;
if (hit?.kind === "plane") plane = this.app.view.planeOf(hit.id);
if (hit?.kind === "face") plane = this.app.view.body(hit.body)?.faces[hit.face]?.plane;
if (!plane) return;
this.app.view.setOriginPlanesVisible(false);
// A face is cut slightly inside so the face itself shows the section.
this.app.setSection({ plane, offset: hit?.kind === "face" ? -this.app.view.cam.worldPerPixel(this.app.view.height) : 0, flipped: false });
this.showControls();
}
private showControls(): void {
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.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()) },
],
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 setOffset(v: number): void {
const s = this.app.section;
if (!s) return;
this.app.setSection({ ...s, offset: v });
this.app.ui.updatePanelValues([v]);
this.placeHandle();
}
private placeHandle(): void {
const s = this.app.section;
if (!s || !this.handle) return;
this.handle.set(add(s.plane.origin, scale(s.plane.normal, s.offset)), s.plane.normal);
}
down(p: ToolPointer): boolean {
if (!this.handle?.hit(p) || !this.app.section) return false;
this.dragging = { from: p, o0: this.app.section.offset };
return true;
}
private get typing(): DragTyping {
return (this._typing ??= new DragTyping(this.app));
}
private _typing: DragTyping | null = null;
dragKey(e: KeyboardEvent): boolean {
const dr = this.dragging;
if (!dr) return false;
return this.typing.key(e, {
kind: "length",
apply: (v) => this.setOffset(v),
commit: () => ((this.dragging = null), this.app.setTool(null)),
cancel: () => this.setOffset(dr.o0),
});
}
drag(p: ToolPointer): void {
const s = this.app.section;
if (!this.dragging || !s) return;
this.typing.track(p);
if (this.typing.active) return;
const base = add(s.plane.origin, scale(s.plane.normal, this.dragging.o0));
const raw = this.dragging.o0 + axisDrag(this.app.view, base, s.plane.normal, this.dragging.from, p);
const step = niceStep(this.app.view.cam.worldPerPixel(this.app.view.height) * 4);
this.setOffset(Math.round(raw / step) * step);
this.app.ui.setLabel(p.x, p.y, fmtLen(this.app.section!.offset));
}
up(): void {
this.dragging = null;
this.typing.reset();
this.app.ui.setLabel(0, 0, null);
}
key(e: KeyboardEvent): boolean {
if (e.key === "Escape" || e.key === "Enter") {
this.app.setTool(null);
return true;
}
return false;
}
}
+744
View File
@@ -0,0 +1,744 @@
import { BODY_COLORS } from "../doc/types";
import type { DeleteGeomFeature, FreeformFeature, EdgeRef, ExtrudeSource, FaceRef, ImageFeature, PlaneDef, SketchFeature, Vec3 } from "../doc/types";
import { arrangement } from "../sketch/regions";
import { projectPolyline } from "../sketch/edit";
import type { ToolItem } from "../ui/ui";
import type { ToolPointer } from "../view/input";
import { add, dot, len, planeY, scale, sub } from "../geom";
import { fmtLen } from "../units";
import { DimWidget } from "./annotate";
import { Gimbal, IN_PLANE } from "./gimbal";
import { Handle } from "./handles";
import { CopyToggle, copyMode } from "./copyToggle";
import { FreeformTool } from "./freeform";
import { AxisOp, bodyCenter as centerOf, EdgeOp, ExtrudeOp, ImageOp, LoftOp, MoveFaceOp, PlaneOp, ReplaceFaceOp, ScaleFaceOp, ScaleOp, RevolveOp, ShellOp, SplitOp, SweepOp, TransformOp } from "./ops";
import { SketchTool, type SketchKind } from "./sketch";
import { bodiesOf, edgeRefOf, faceRefOf, hitToSel, oppositeFace, sameSel, sourceFrame, sourcesOf, type AppContext, type Sel, type Tool } from "./tool";
const SOON = "Coming soon";
/**
* The default tool. Tap things to select them; the selection decides which
* tools are listed, and the most likely one gets a handle you can drag right away.
*/
export class SelectTool implements Tool {
readonly id = "select";
private handle: Handle | null = null;
private handleAction: (() => Tool) | null = null;
private gimbal: Gimbal | null = null;
private copyToggle: CopyToggle | null = null;
private dim: DimWidget | null = null;
/** A tool chosen with nothing selected waits for the selection. */
private pending: { label: string; accepts: Sel["kind"][]; run: () => void } | null = null;
constructor(private app: AppContext) {}
enter(): void {
this.refresh();
}
exit(): void {
this.clearHandle();
this.app.ui.setHint(null);
this.app.setHover(null);
}
hover(p: ToolPointer | null): void {
if (!p) return this.app.setHover(null);
const g = this.gimbal?.hit(p) ?? null;
this.gimbal?.setHot(g);
const onHandle = !!this.handle?.hit(p);
this.handle?.setHot(onHandle);
if (g || onHandle) {
this.app.view.canvas.style.cursor = "grab";
return this.app.setHover(null);
}
this.app.view.canvas.style.cursor = "";
const hit = this.pickAt(p);
this.lastHover = { x: p.x, y: p.y, hit };
this.app.setHover(hitToSel(hit));
}
/** What the last hover highlighted, and where: tapping there selects exactly that. */
private lastHover: { x: number; y: number; hit: ReturnType<SelectTool["pickAt"]> } | null = null;
private tapHit(p: ToolPointer) {
const h = this.lastHover;
if (h?.hit && Math.hypot(h.x - p.x, h.y - p.y) < 6) return h.hit;
return this.pickAt(p);
}
/**
* The gimbal and the extrude arrow take over only once the pointer moves
* (dragStart): a click or double-click on top of them still selects what's
* under it — e.g. double-clicking a face seen straight on, where the arrow
* points at you and sits right on the face.
*/
down(): boolean {
return false;
}
dragStart(p: ToolPointer): boolean {
if (this.gimbal?.hit(p)) {
const s = this.app.selection[0];
const img = s?.kind === "image" ? this.app.store.find<ImageFeature>(s.id) : undefined;
// A vertex: its gimbal moves just that corner (the faces around it follow).
const at = s?.kind === "vertex" ? this.app.view.vertexOf(s.body, s.vertex) : undefined;
const op = img
? new ImageOp(this.app, img)
: s?.kind === "vertex" && at
? new MoveFaceOp(this.app, { vertex: { body: s.body, at } })
: new TransformOp(this.app, "move", bodiesOf(this.app.selection), undefined, undefined, s?.kind === "body" && copyMode.on);
this.app.setTool(op);
return op.down(p);
}
if (!this.handle?.hit(p) || !this.handleAction) return false;
const op = this.handleAction();
this.app.setTool(op);
return op.down?.(p) ?? false;
}
/** Sketch curves win near them; a face outline copied into a sketch ("bnd-…") is the body's edge. */
private pickAt(p: ToolPointer) {
const hit = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol, curves: true });
if (hit?.kind !== "curve" && hit?.kind !== "point") return hit;
const under = this.app.view.pick(p.x, p.y, { edgeTolPx: p.tol });
if (hit.entity.startsWith("bnd-")) return under;
// A sketch curve behind a body (seen through it) doesn't win over the body in front.
if (under && (under.kind === "face" || under.kind === "edge" || under.kind === "vertex")) {
const eye = this.app.view.cam.camera.position.toArray() as Vec3;
const far = (q: Vec3) => Math.hypot(q[0] - eye[0], q[1] - eye[1], q[2] - eye[2]);
if (far(under.point) < far(hit.point) - this.app.view.cam.worldPerPixel(this.app.view.height) * 2) return under;
}
return hit;
}
tap(p: ToolPointer, count: number): void {
const hit = this.tapHit(p);
// Tapping a line/curve/point of a finished sketch opens it for editing, with that piece selected.
if ((hit?.kind === "curve" || hit?.kind === "point") && !this.pending) {
const tool = new SketchTool(this.app, { sketchId: hit.sketch });
this.app.setSelection([]);
this.app.setTool(tool);
if (hit.kind === "curve") tool.preselect([hit.entity]);
else tool.preselect([], [{ e: hit.entity, p: hit.p }]);
return;
}
// Where the tap was: Edit Freeform picks the cage element there.
this.lastTap = p;
let s = hitToSel(hit);
const sel = this.app.selection;
if (!s) return this.app.setSelection([]);
// Double tap selects the whole body.
if (count >= 2 && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex")) s = { kind: "body", body: s.body };
// With bodies selected, tapping another body adds it (Union/Subtract need two).
if (sel[0]?.kind === "body" && (s.kind === "face" || s.kind === "edge" || s.kind === "vertex") && (p.add || !sel.some((x) => x.kind === "body" && x.body === (s as { body: string }).body))) {
s = { kind: "body", body: s.body };
}
if (sel.length && sel[0].kind === s.kind) {
const i = sel.findIndex((x) => sameSel(x, s!));
if (i >= 0 && count < 2) this.app.setSelection(sel.filter((_, j) => j !== i));
else if (i < 0) this.app.setSelection(p.add || sel[0].kind !== "vertex" ? [...sel, s] : [s]);
} else {
this.app.setSelection([s]);
}
if (this.pending && this.pending.accepts.includes(s.kind)) {
const run = this.pending.run;
this.pending = null;
run();
}
}
/** Window selection: bodies entirely inside the box. */
box(a: { x: number; y: number }, b: { x: number; y: number }, final: boolean, add: boolean): void {
if (!final) return;
const x0 = Math.min(a.x, b.x);
const x1 = Math.max(a.x, b.x);
const y0 = Math.min(a.y, b.y);
const y1 = Math.max(a.y, b.y);
const inside = this.app.view.bodyList.filter((body) => {
if (this.app.view.isHidden(body.id)) return false;
for (let i = 0; i < body.positions.length; i += 3 * Math.max(1, Math.floor(body.positions.length / 3 / 400))) {
const s = this.app.view.toScreen([body.positions[i], body.positions[i + 1], body.positions[i + 2]]);
if (!s || s[0] < x0 || s[0] > x1 || s[1] < y0 || s[1] > y1) return false;
}
return true;
});
const picked: Sel[] = inside.map((body) => ({ kind: "body", body: body.id }));
const base = add ? this.app.selection.filter((s) => s.kind === "body") : [];
this.app.setSelection([...base, ...picked.filter((s) => !base.some((x) => sameSel(x, s)))]);
}
key(e: KeyboardEvent): boolean {
const k = e.key.toLowerCase();
if (k === "escape" && (this.app.selection.length || this.pending)) {
this.pending = null;
this.app.setSelection([]);
return true;
}
if (e.ctrlKey || e.metaKey) return false;
const want = k === "delete" || k === "backspace" ? "DEL" : k.toUpperCase();
const action = flatten(this.actions()).find((a) => a.shortcut?.toUpperCase() === want && !a.disabled && a.run);
if (action) {
action.run!();
return true;
}
return false;
}
/** Re-derive tools and handle from the current selection. */
refresh(): void {
this.clearHandle();
// Whatever an earlier tool left on screen goes too (no ghost arrows or dots).
this.app.view.clearHelpers([]);
const sel = this.app.selection;
this.app.ui.setTools(sel.length ? this.actions() : this.app.mainTools());
this.app.ui.setBottom(this.app.bottomTools());
this.app.ui.setHint(
this.pending
? `${this.pending.label}: select ${this.pending.accepts.join(" or ")}`
: sel.length === 0
? null
: `${sel.length} ${label(sel[0], sel.length)} selected`,
);
const first = sel[0];
if (!first) return;
// The most likely next step gets a handle.
if (first.kind === "profile") {
const src = sourcesOf(this.app, sel)[0];
if (src) this.showHandle(sourceFrame(this.app, src), "arrow", () => new ExtrudeOp(this.app, src));
} else if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type)) {
// Flat and round faces: drag the arrow to offset (round faces change radius).
const src = sourcesOf(this.app, sel)[0];
if (src) {
this.showHandle(sourceFrame(this.app, src), "arrow", () => new ExtrudeOp(this.app, src));
if (this.app.view.body(first.body)?.faces[first.face]?.plane) this.showFaceDimension(first, src);
}
} else if (first.kind === "face" && sel.length === 2 && sel[1].kind === "face") {
this.showFacesDistance(first, sel[1]);
} else if (first.kind === "body") {
// Body: the Move/Rotate gimbal is ready to drag (with Copy beside it).
this.gimbal = new Gimbal(this.app.view);
this.gimbal.setCenter(centerOf(this.app, bodiesOf(sel)));
const g = this.gimbal;
this.copyToggle = new CopyToggle(this.app.view, () => g.origin);
} else if (first.kind === "vertex" && sel.length === 1) {
const v = this.app.view.vertexOf(first.body, first.vertex);
// A freeform's points are moved in Edit Freeform, so no gimbal here.
if (v && this.app.store.find<FreeformFeature>(first.body)?.type !== "freeform") {
this.gimbal = new Gimbal(this.app.view);
this.gimbal.setCenter(v);
}
} else if (first.kind === "image") {
const img = this.app.store.find<ImageFeature>(first.id);
if (img) {
const pl = img.plane;
this.gimbal = new Gimbal(this.app.view, { axes: [pl.xDir, planeY(pl), pl.normal], parts: IN_PLANE });
this.gimbal.setCenter(pl.origin);
}
} else if (first.kind === "edge") {
const e = this.edgeRefs()[0];
if (e) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", this.edgeRefs()).grabFromEdge());
}
}
/** Called by the app when a top-level tool needs a selection first. */
waitFor(label: string, accepts: Sel["kind"][], run: () => void): void {
this.pending = { label, accepts, run };
this.app.setSelection([]);
}
// --------------------------------------------------------------- menus
private actions(): ToolItem[] {
const sel = this.app.selection;
if (!sel.length) return [];
const head: ToolItem[] = [{ id: "deselect", label: "Deselect All", icon: "deselect", shortcut: "Esc", sub: `${sel.length} ${label(sel[0], sel.length)}`, run: () => this.app.setSelection([]) }];
// A freeform body (or a face/edge/point of one): open its cage, picking the spot that was tapped.
const first = sel[0];
const ff = "body" in first ? this.app.store.find<FreeformFeature>(first.body) : undefined;
if (ff?.type === "freeform") head.push({ id: "editFreeform", label: "Edit Freeform", icon: "freeform", shortcut: "F2", run: () => this.editFreeform(ff) });
switch (sel[0].kind) {
case "profile":
return [...head, ...this.profileActions()];
case "face":
return [...head, ...this.faceActions()];
case "edge":
return [...head, ...this.edgeActions()];
case "body":
return [...head, ...this.bodyActions()];
case "plane":
return [...head, ...this.planeActions()];
case "axis":
return [...head, ...this.axisActions()];
case "vertex": {
const bodies = bodiesOf(sel);
const s = sel[0] as Extract<Sel, { kind: "vertex" }>;
const pivot = this.app.view.vertexOf(s.body, s.vertex);
const at = sel.flatMap((x) => (x.kind === "vertex" && x.body === s.body ? [this.app.view.vertexOf(x.body, x.vertex)!].filter(Boolean) : []));
// A freeform's points move in Edit Freeform (at the top of this list), not here.
const isFreeform = !!ff && ff.type === "freeform";
return [
...head,
...(isFreeform ? [] : [{ id: "moveVertex", label: "Move Vertex", icon: "move" as const, shortcut: "M", active: true, disabled: !pivot, run: () => pivot && this.app.setTool(new MoveFaceOp(this.app, { vertex: { body: s.body, at: pivot } })) }]),
{ id: "move", label: "Move/Rotate Body", icon: "move", run: () => this.app.setTool(new TransformOp(this.app, "move", bodies, undefined, pivot)) },
{ id: "delete", label: "Delete Vertex", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { vertices: at }) },
];
}
case "image": {
const img = this.app.store.find<ImageFeature>((sel[0] as Extract<Sel, { kind: "image" }>).id);
if (!img) return head;
return [
...head,
{ id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", active: true, run: () => this.app.setTool(new ImageOp(this.app, img)) },
{ id: "scale", label: "Scale / Opacity", icon: "scale", shortcut: "S", run: () => this.app.setTool(new ImageOp(this.app, img)) },
{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => (this.app.store.remove(img.id), this.app.setSelection([])) },
];
}
default:
return head;
}
}
private profileActions(): ToolItem[] {
const app = this.app;
const sel = app.selection;
const src = sourcesOf(app, sel)[0] as Extract<ExtrudeSource, { kind: "profile" }> | undefined;
const sketchId = (sel[0] as Extract<Sel, { kind: "profile" }>).sketch;
const plane = app.sketchPlane(sketchId);
const inSketch = (kind: string) => () => this.openSketch(sketchId, kind);
const frame = src ? sourceFrame(app, src) : null;
return [
{ id: "sketch", label: "Sketch", icon: "sketch", run: inSketch("line") },
{ id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", run: inSketch("move") },
{ id: "scale", label: "Scale Sketch", icon: "scale", run: inSketch("scale") },
{ id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: inSketch("patternLinear") },
{ id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: inSketch("patternCircular") },
{ id: "extrude", label: "Extrude", icon: "extrude", shortcut: "E", active: true, run: () => src && app.setTool(new ExtrudeOp(app, src)) },
{ id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => frame && app.setTool(new AxisOp(app, frame.base, frame.normal)) },
{ id: "plane", label: "Plane – Offset", icon: "plane", run: () => plane && app.setTool(new PlaneOp(app, plane, undefined)) },
{ id: "text", label: "Text", icon: "text", run: inSketch("text") },
{ id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: inSketch("rotate") },
{ id: "mirror", label: "Mirror", icon: "mirror", run: inSketch("mirror") },
{ id: "loft", label: "Loft", icon: "loft", run: () => app.setTool(new LoftOp(app, sourcesOf(app, sel).flatMap(splitRegions), sel)) },
{ id: "split", label: "Split Body", icon: "split", disabled: !app.view.bodyList.length || !plane, why: "Needs a body", run: () => this.splitWith(plane!) },
{ id: "revolve", label: "Revolve", icon: "revolve", shortcut: "R", run: () => src && app.setTool(new RevolveOp(app, src)) },
{ id: "sweep", label: "Sweep", icon: "sweep", shortcut: "W", run: () => src && app.setTool(new SweepOp(app, src)) },
{ id: "fill", label: "Fill", icon: "fill", disabled: true, why: SOON },
{ id: "offset", label: "Offset Edge", icon: "offset", shortcut: "O", run: inSketch("offset") },
{ id: "projs", label: "Project as Sketch", icon: "project", disabled: true, why: SOON },
{ id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON },
{ id: "wrap", label: "Wrap & Emboss", icon: "wrap", disabled: true, why: SOON },
{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => this.deleteProfiles() },
];
}
private faceActions(): ToolItem[] {
const app = this.app;
const sel = app.selection;
const s = sel[0] as Extract<Sel, { kind: "face" }>;
const info = app.view.body(s.body)?.faces[s.face];
const flat = !!info?.plane;
const one = sel.length === 1;
const src = sourcesOf(app, sel)[0];
const bodies = bodiesOf(sel);
const faceRefs = sel.flatMap((x) => (x.kind === "face" ? [faceRefOf(app, x)!] : []));
const needFlat = { disabled: !flat || !one, why: "Needs one flat face" };
const ref = faceRefOf(app, s);
return [
{ id: "sketch", label: "Sketch", icon: "sketch", shortcut: "S", ...needFlat, run: () => this.sketchOnFace() },
// Moves just this face; the rest of the body stretches to follow.
{ id: "move", label: "Move/Rotate Face", icon: "move", shortcut: "M", ...needFlat, run: () => ref && info?.plane && app.setTool(new MoveFaceOp(app, { face: ref, plane: info.plane })) },
// Scales just this face, within its plane; the sides tilt to follow.
{ id: "scale", label: "Scale Face", icon: "scale", ...needFlat, run: () => ref && info?.plane && app.setTool(new ScaleFaceOp(app, ref, info.plane)) },
{ id: "align", label: "Align", icon: "align", disabled: true, why: SOON },
{ id: "offsetFace", label: "Offset Face", icon: "offsetFace", shortcut: "E", active: true, disabled: !one || !offsettable(info?.type), why: "Needs one flat or round face", run: () => src && app.setTool(new ExtrudeOp(app, src)) },
{ id: "fillet", label: "Fillet", icon: "fillet", shortcut: "F", run: () => this.edgesOfFaces("fillet") },
{ id: "chamfer", label: "Chamfer", icon: "chamfer", run: () => this.edgesOfFaces("chamfer") },
{ id: "extrude", label: "Extrude", icon: "extrude", ...needFlat, run: () => src && app.setTool(new ExtrudeOp(app, src, undefined, "new")) },
{ id: "shell", label: "Shell", icon: "shell", run: () => app.setTool(new ShellOp(app, s.body, faceRefs)) },
{ id: "axis", label: "Axis – Perp. to Face", icon: "axis", run: () => info && app.setTool(new AxisOp(app, info.center, info.normal)) },
{ id: "plane", label: "Plane – Offset", icon: "plane", ...needFlat, run: () => info?.plane && app.setTool(new PlaneOp(app, info.plane, faceRefOf(app, s)!)) },
{ id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: () => app.setTool(new TransformOp(app, "linear", bodies)) },
{ id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: () => app.setTool(new TransformOp(app, "circular", bodies)) },
{ id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) },
{ id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) },
{ id: "mirror", label: "Mirror", icon: "mirror", run: () => app.setTool(new TransformOp(app, "mirror", bodies)) },
{ id: "loft", label: "Loft", icon: "loft", ...needFlat, run: () => app.setTool(new LoftOp(app, sourcesOf(app, sel).flatMap(splitRegions), sel)) },
{ id: "split", label: "Split Body", icon: "split", disabled: !flat || app.view.bodyList.length < 2, why: "Needs another body to split", run: () => this.splitWith(info!.plane!, s.body) },
{ id: "revolve", label: "Revolve", icon: "revolve", ...needFlat, run: () => src && app.setTool(new RevolveOp(app, src)) },
{ id: "sweep", label: "Sweep", icon: "sweep", ...needFlat, run: () => src && app.setTool(new SweepOp(app, src)) },
{ id: "fill", label: "Fill", icon: "fill", disabled: true, why: SOON },
{
id: "more",
label: "More",
icon: "more",
children: [
{ id: "replace", label: "Replace Face", icon: "replaceFace", ...needFlat, run: () => ref && app.setTool(new ReplaceFaceOp(app, ref)) },
{ id: "offsetEdge", label: "Offset Edge", icon: "offset", ...needFlat, run: () => this.projectFace("offset") },
{ id: "projs", label: "Project as Sketch", icon: "project", ...needFlat, run: () => this.projectFace("select") },
{ id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON },
{ id: "text", label: "Text", icon: "text", ...needFlat, run: () => this.sketchOnFace("text") },
{ id: "moveBody", label: "Move/Rotate Body", icon: "move", run: () => app.setTool(new TransformOp(app, "move", bodies)) },
{ id: "deleteBody", label: "Delete Body", icon: "trash", run: () => this.deleteBodies(bodies) },
],
},
// The neighbours extend to close the gap (fillets, chamfers, holes).
{ id: "delete", label: "Delete Face", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { faces: faceRefs.filter((f) => f.body === s.body) }) },
];
}
private edgeActions(): ToolItem[] {
const app = this.app;
const sel = app.selection;
const s = sel[0] as Extract<Sel, { kind: "edge" }>;
const info = app.view.body(s.body)?.edges[s.edge];
const bodies = bodiesOf(sel);
const straight = info?.type === "LINE";
const ref = this.edgeRefs()[0];
// With variables defined, Fillet/Chamfer open a list: a free size, or one of the variables.
const vars = app.store.doc.variables ?? [];
const sized = (kind: "fillet" | "chamfer"): Partial<ToolItem> =>
vars.length
? {
sub: "Pick a size",
children: [
{ id: `${kind}-free`, label: "Drag / type", icon: kind, run: () => app.setTool(new EdgeOp(app, kind, this.edgeRefs())) },
...vars.map((v) => ({ id: `${kind}-var-${v.name}`, label: `${v.name} = ${v.expr}`, icon: "variable" as const, run: () => app.setTool(new EdgeOp(app, kind, this.edgeRefs(), undefined, v.name)) })),
],
}
: {};
return [
{ id: "fillet", label: "Fillet", icon: "fillet", shortcut: "F", active: true, run: () => app.setTool(new EdgeOp(app, "fillet", this.edgeRefs())), ...sized("fillet") },
{ id: "chamfer", label: "Chamfer", icon: "chamfer", shortcut: "C", run: () => app.setTool(new EdgeOp(app, "chamfer", this.edgeRefs())), ...sized("chamfer") },
// Moves just this edge: the faces on it tilt to follow.
{ id: "move", label: "Move/Rotate Edge", icon: "move", shortcut: "M", disabled: !straight || sel.length !== 1, why: "Needs one straight edge", run: () => ref && app.setTool(new MoveFaceOp(app, { edge: ref })) },
{ id: "moveBody", label: "Move/Rotate Body", icon: "move", run: () => app.setTool(new TransformOp(app, "move", bodies)) },
{ id: "axis", label: "Axis – Along Edge", icon: "axis", disabled: !straight, why: "Needs a straight edge", run: () => info && app.setTool(new AxisOp(app, info.start, info.dir)) },
{ id: "planePerp", label: "Plane – Perp. to Edge", icon: "plane", run: () => info && app.setTool(new PlaneOp(app, { origin: info.mid, normal: info.dir, xDir: perpTo(info.dir) }, undefined)) },
{ id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) },
{ id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) },
{ id: "proje", label: "Project as Edge", icon: "projectEdge", disabled: true, why: SOON },
{ id: "delete", label: "Delete Edge", icon: "trash", shortcut: "Del", run: () => this.deleteGeom(s.body, { edges: this.edgeRefs().filter((e) => e.body === s.body) }) },
];
}
private bodyActions(): ToolItem[] {
const app = this.app;
const bodies = bodiesOf(app.selection);
const multi = bodies.length >= 2;
const boolean = (op: "union" | "subtract" | "intersect") => () => {
app.store.add({ ...app.store.newIdentity("boolean", cap(op)), type: "boolean", op, target: bodies[0], tools: bodies.slice(1) });
app.setSelection([{ kind: "body", body: bodies[0] }]);
};
return [
{ id: "move", label: "Move/Rotate", icon: "move", shortcut: "M", active: true, run: () => app.setTool(new TransformOp(app, "move", bodies)) },
{
id: "scale",
label: "Scale",
icon: "scale",
// Starts the kind used last.
sub: lastScale.xyz ? "X / Y / Z" : "Uniform",
run: () => app.setTool(new ScaleOp(app, lastScale.xyz, bodies)),
children: [
{ id: "scaleUniform", label: "Uniform", icon: "scale", active: !lastScale.xyz, run: () => ((lastScale.xyz = false), app.setTool(new ScaleOp(app, false, bodies))) },
{ id: "scaleXYZ", label: "X / Y / Z", icon: "scale", sub: "freeform bodies", active: lastScale.xyz, run: () => ((lastScale.xyz = true), app.setTool(new ScaleOp(app, true, bodies))) },
],
},
{ id: "translate", label: "Translate", icon: "translate", shortcut: "N", run: () => app.setTool(new TransformOp(app, "translate", bodies)) },
{ id: "patl", label: "Pattern – Linear", icon: "patternLinear", run: () => app.setTool(new TransformOp(app, "linear", bodies)) },
{ id: "patc", label: "Pattern – Circular", icon: "patternCircular", run: () => app.setTool(new TransformOp(app, "circular", bodies)) },
{ id: "rotate", label: "Rotate Around Axis", icon: "rotateAxis", run: () => app.setTool(new TransformOp(app, "rotate", bodies)) },
{ id: "mirror", label: "Mirror", icon: "mirror", run: () => app.setTool(new TransformOp(app, "mirror", bodies)) },
{ id: "union", label: "Union", icon: "union", shortcut: "U", disabled: !multi, why: "Select 2+ bodies", run: boolean("union") },
{ id: "subtract", label: "Subtract", icon: "subtract", disabled: !multi, why: "Select 2+ bodies (first is kept)", run: boolean("subtract") },
{ id: "intersect", label: "Intersect", icon: "intersect", disabled: !multi, why: "Select 2+ bodies", run: boolean("intersect") },
{ id: "split", label: "Split Body", icon: "split", run: () => app.setTool(new SplitOp(app, bodies[0])) },
{ id: "shell", label: "Shell", icon: "shell", run: () => app.setTool(new ShellOp(app, bodies[0], [])) },
{
id: "color",
label: "Color",
icon: "color",
sub: BODY_COLORS.find((c) => c.hex === (app.store.doc.colors ?? {})[bodies[0]])?.name ?? "Grey",
children: BODY_COLORS.map((c, i) => ({
id: `color-${i}`,
label: c.name,
icon: "color",
swatch: c.hex,
active: ((app.store.doc.colors ?? {})[bodies[0]] ?? BODY_COLORS[0].hex) === c.hex,
run: () =>
app.store.commit((d) => {
const colors = { ...(d.colors ?? {}) };
for (const b of bodies) if (i === 0) delete colors[b];
else colors[b] = c.hex;
d.colors = colors;
}),
})),
},
{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => this.deleteBodies(bodies) },
];
}
private planeActions(): ToolItem[] {
const app = this.app;
const s = app.selection[0] as Extract<Sel, { kind: "plane" }>;
const plane = app.view.planeOf(s.id);
const isFeature = !!app.store.find(s.id);
return [
{ id: "sketch", label: "Sketch", icon: "sketch", shortcut: "S", run: () => plane && (app.setSelection([]), app.setTool(new SketchTool(app, { plane }))) },
{ id: "plane", label: "Plane – Offset", icon: "plane", run: () => plane && app.setTool(new PlaneOp(app, plane, undefined)) },
{ id: "split", label: "Split Body", icon: "split", disabled: !app.view.bodyList.length, why: "Needs a body", run: () => plane && this.splitWith(plane) },
{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", disabled: !isFeature, why: "Origin planes can't be deleted", run: () => (app.store.remove(s.id), app.setSelection([])) },
];
}
private axisActions(): ToolItem[] {
const app = this.app;
const s = app.selection[0] as Extract<Sel, { kind: "axis" }>;
return [{ id: "delete", label: "Delete", icon: "trash", shortcut: "Del", run: () => (app.store.remove(s.id), app.setSelection([])) }];
}
// ------------------------------------------------------------- helpers
private showHandle(frame: { base: Vec3; normal: Vec3 }, shape: "arrow" | "dot", action: () => Tool): void {
this.handle = new Handle(this.app.view, shape);
this.handle.set(frame.base, shape === "arrow" ? frame.normal : undefined);
this.handleAction = action;
}
private clearHandle(): void {
this.handle?.dispose();
this.handle = null;
this.handleAction = null;
this.gimbal?.dispose();
this.gimbal = null;
this.copyToggle?.dispose();
this.copyToggle = null;
clearTimeout(this.dimTimer);
this.dim?.dispose();
this.dim = null;
}
/**
* A selected flat face shows its thickness to the opposite face (Total);
* typing a value or switching to Offset starts Offset Face right away.
*/
private showFaceDimension(s: Extract<Sel, { kind: "face" }>, src: ExtrudeSource): void {
const f = this.app.view.body(s.body)!.faces[s.face];
const opp = oppositeFace(this.app, s.body, s.face);
if (!opp) return;
const start = (measure: "total" | "offset", distance: number, typed?: string) =>
this.app.setTool(new ExtrudeOp(this.app, src, undefined, "auto", { measure, distance, typed }));
// Shown a moment later, beside the face — never under the pointer while you double-click for the body.
this.dimTimer = window.setTimeout(() => {
this.dim = new DimWidget(this.app.view, {
value: opp.distance,
// Past the tip of the extrude arrow, which starts at the face.
boxAt: "beyond",
boxGap: 96,
dir: f.normal,
modes: [{ id: "total", label: "Total" }, { id: "offset", label: "Offset" }],
mode: "total",
onMode: (m) => start(m as "total" | "offset", 0),
onInput: (v) => start("total", v - opp.distance, this.dim?.text),
onPin: () => this.app.addPin({ text: fmtLen(opp.distance), a: opp.point, b: f.center, at: scale(add(opp.point, f.center), 0.5) }),
});
this.dim.set(opp.point, f.center);
}, 400);
}
private dimTimer = 0;
/**
* Two faces: their distance as a dimension with a pin. Parallel flat faces:
* the gap between them; otherwise centre to centre.
*/
private showFacesDistance(a: Extract<Sel, { kind: "face" }>, b: Extract<Sel, { kind: "face" }>): void {
const fa = this.app.view.body(a.body)?.faces[a.face];
const fb = this.app.view.body(b.body)?.faces[b.face];
if (!fa || !fb) return;
const n = fa.normal;
const parallel = !!fa.plane && !!fb.plane && Math.abs(dot(n, fb.normal)) > 0.9999;
const p0 = fa.center;
const p1 = parallel ? add(p0, scale(n, dot(sub(fb.center, p0), n))) : fb.center;
const d = len(sub(p1, p0));
this.dim = new DimWidget(this.app.view, {
value: d,
boxAt: "side",
onPin: () => this.app.addPin({ text: fmtLen(d), a: p0, b: p1, at: scale(add(p0, p1), 0.5) }),
});
this.dim.set(p0, p1);
this.app.ui.setHint(`${parallel ? "Distance between the faces" : "Centre to centre"}: ${fmtLen(d)}`);
}
private edgeRefs(): EdgeRef[] {
return this.app.selection.flatMap((s) => (s.kind === "edge" ? [edgeRefOf(this.app, s)!].filter(Boolean) : []));
}
/** Fillet/chamfer every edge lying on the selected flat faces. */
private edgesOfFaces(kind: "fillet" | "chamfer"): void {
const refs: EdgeRef[] = [];
for (const s of this.app.selection) {
if (s.kind !== "face") continue;
const b = this.app.view.body(s.body);
const f = b?.faces[s.face];
if (!b || !f?.plane) continue;
b.edges.forEach((e, i) => {
const on = [e.start, e.end, e.mid].every((p) => Math.abs((p[0] - f.center[0]) * f.normal[0] + (p[1] - f.center[1]) * f.normal[1] + (p[2] - f.center[2]) * f.normal[2]) < 1e-5);
if (on) refs.push(edgeRefOf(this.app, { body: s.body, edge: i })!);
});
}
if (!refs.length) return this.app.ui.toast("Select flat faces, or tap the edges directly");
this.app.setTool(new EdgeOp(this.app, kind, refs));
}
private sketchOnFace(kind?: string): void {
const s = this.app.selection[0] as Extract<Sel, { kind: "face" }>;
const info = this.app.view.body(s.body)?.faces[s.face];
if (!info?.plane) return;
const ref = faceRefOf(this.app, s)!;
this.app.setSelection([]);
const tool = new SketchTool(this.app, { plane: info.plane, attachedTo: ref });
this.app.setTool(tool);
if (kind) tool.setKind(kind as SketchKind);
}
/** Project the face outline into a new sketch on that face. */
private projectFace(then: string): void {
const s = this.app.selection[0] as Extract<Sel, { kind: "face" }>;
const b = this.app.view.body(s.body);
const f = b?.faces[s.face];
if (!b || !f?.plane) return;
const plane = f.plane;
const entities = b.edges.flatMap((e, i) => {
const on = [e.start, e.end, e.mid].every((p) => Math.abs((p[0] - f.center[0]) * f.normal[0] + (p[1] - f.center[1]) * f.normal[1] + (p[2] - f.center[2]) * f.normal[2]) < 1e-5);
if (!on) return [];
const g = b.edgeGroups.find((x) => x.edge === i)!;
const pts: Vec3[] = [];
for (let k = g.start; k < g.start + g.count; k++) if ((k - g.start) % 2 === 0 || k === g.start + g.count - 1) pts.push([b.edgePositions[k * 3], b.edgePositions[k * 3 + 1], b.edgePositions[k * 3 + 2]]);
const ent = projectPolyline(pts, plane, e.type);
return ent ? [ent] : [];
});
const sk: SketchFeature = { ...this.app.store.newIdentity("sketch"), type: "sketch", plane, attachedTo: faceRefOf(this.app, s)!, entities };
this.app.store.add(sk);
this.openSketch(sk.id, then);
}
private openSketch(sketchId: string, kind: string): void {
// Preselect the curves bounding the selected regions for sketch-level edits.
const sk = this.app.store.find<SketchFeature>(sketchId);
const regions = this.app.selection.filter((s): s is Extract<Sel, { kind: "profile" }> => s.kind === "profile" && s.sketch === sketchId).map((s) => s.region);
const ids = new Set<string>();
if (sk) {
const arr = arrangement(this.app.sketchCurves(sketchId));
for (const ri of regions) {
const r = arr.regions[ri];
for (const loop of [r?.outer, ...(r?.holes ?? [])])
for (const ref of loop?.pieces ?? []) {
const src = arr.prims[arr.pieces[ref.piece].prim].src;
if (!src.startsWith("bnd-")) ids.add(src);
}
}
}
this.app.setSelection([]);
const tool = new SketchTool(this.app, { sketchId });
this.app.setTool(tool);
tool.setKind(kind as SketchKind);
if (ids.size && kind !== "line" && kind !== "text") tool.preselect(ids);
}
private splitWith(plane: PlaneDef, exceptBody?: string): void {
const body = this.app.view.bodyList.find((b) => b.id !== exceptBody)?.id;
if (body) this.app.setTool(new SplitOp(this.app, body, undefined, plane));
}
private deleteProfiles(): void {
const sel = this.app.selection.filter((s): s is Extract<Sel, { kind: "profile" }> => s.kind === "profile");
const sk = sel[0] && this.app.store.find<SketchFeature>(sel[0].sketch);
if (!sk) return;
const arr = arrangement(this.app.sketchCurves(sk.id));
// Remove curves that only bound the selected regions (face outline curves aren't the sketch's).
const used = new Map<string, Set<number>>();
arr.regions.forEach((r) => {
for (const loop of [r.outer, ...r.holes]) for (const ref of loop.pieces) {
const src = arr.prims[arr.pieces[ref.piece].prim].src;
used.set(src, (used.get(src) ?? new Set()).add(r.index));
}
});
const chosen = new Set(sel.map((s) => s.region));
const doomed = [...used].filter(([, rs]) => [...rs].every((r) => chosen.has(r))).map(([id]) => id);
this.app.store.update(sk.id, { entities: sk.entities.filter((e) => !doomed.includes(e.id)) });
this.app.setSelection([]);
}
private lastTap: ToolPointer | null = null;
private editFreeform(ff: FreeformFeature): void {
const at = this.lastTap;
const tool = new FreeformTool(this.app, { feature: ff });
this.app.setTool(tool);
if (at) tool.selectAt(at);
}
/** Delete faces/edges/vertices of one body; tells the user when it can't heal. */
private deleteGeom(body: string, what: { faces?: FaceRef[]; edges?: EdgeRef[]; vertices?: Vec3[] }): void {
// A freeform body: the cage loses the faces there, and stays open for a thickness.
const ff = this.app.store.find<FreeformFeature>(body);
if (ff?.type === "freeform") {
const tool = new FreeformTool(this.app, { feature: ff });
this.app.setTool(tool);
if (what.faces?.length) tool.deleteAt(what.faces.map((f) => f.center), "face");
else if (what.edges?.length) tool.deleteAt(what.edges.map((e) => e.mid), "edge");
else if (what.vertices?.length) tool.deleteAt(what.vertices, "vertex");
return;
}
const f: DeleteGeomFeature = { ...this.app.store.newIdentity("deleteGeom"), type: "deleteGeom", body, faces: what.faces ?? [], edges: what.edges ?? [], vertices: what.vertices ?? [] };
this.app.setSelection([]);
this.app.preview([...this.app.store.features, f]).then((r) => {
const err = r?.errors.find((e) => e.featureId === f.id);
if (err) {
this.app.ui.toast(err.message);
this.app.preview([...this.app.store.features]);
} else this.app.store.add(f);
});
}
private deleteBodies(bodies: string[]): void {
this.app.store.add({ ...this.app.store.newIdentity("delete"), type: "delete", bodies });
this.app.setSelection([]);
}
}
/** Loft wants one profile per section. */
function splitRegions(s: ExtrudeSource): ExtrudeSource[] {
return s.kind === "profile" ? s.regions.map((r) => ({ ...s, regions: [r] })) : [s];
}
/** Faces Offset Face can push: flat ones and round (cylindrical) ones. */
function offsettable(type: string | undefined): boolean {
return type === "PLANE" || type === "CYLINDRE";
}
function flatten(items: ToolItem[]): ToolItem[] {
return items.flatMap((i) => [i, ...flatten(i.children ?? [])]);
}
function perpTo(d: Vec3): Vec3 {
const a: Vec3 = Math.abs(d[2]) < 0.9 ? [0, 0, 1] : [1, 0, 0];
const x: Vec3 = [a[1] * d[2] - a[2] * d[1], a[2] * d[0] - a[0] * d[2], a[0] * d[1] - a[1] * d[0]];
const l = Math.hypot(...x) || 1;
return [x[0] / l, x[1] / l, x[2] / l];
}
function label(s: Sel, n: number): string {
const base = { face: "face", edge: "edge", vertex: "vertex", body: "body", profile: "profile", curve: "curve", point: "point", image: "image", plane: "plane", axis: "axis" }[s.kind];
if (base === "vertex") return n === 1 ? "vertex" : "vertices";
return n === 1 ? base : base === "body" ? "bodies" : base === "axis" ? "axes" : `${base}s`;
}
function cap(s: string): string {
return s[0].toUpperCase() + s.slice(1);
}
/** Which Scale was used last (the button starts that one). */
const lastScale = { xyz: false };
+2556
View File
File diff suppressed because it is too large Load Diff
+240
View File
@@ -0,0 +1,240 @@
// Sketch constraint UI: the constraint button column, building constraints from
// the selection, and the badges/dimension labels drawn next to the geometry.
import type { ConstraintType, PlaneDef, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../doc/types";
import { applicable, pointOf, pointsOf, sizeOf } from "../sketch/constraints";
import { arcFrom3 } from "../sketch/curves";
import { uid } from "../sketch/edit";
import { el } from "../ui/ui";
import { fmtLen, trim } from "../units";
import type { Viewport } from "../view/viewport";
import { sketchToWorld } from "../view/viewport";
export const CONSTRAINT_BUTTONS: { type: ConstraintType | "hv"; label: string; glyph: string; key: string }[] = [
{ type: "parallel", label: "Parallel", glyph: "∥", key: "A" },
{ type: "perpendicular", label: "Perpendicular", glyph: "⟂", key: "P" },
{ type: "tangent", label: "Tangent", glyph: "T", key: "T" },
{ type: "coincident", label: "Coincident", glyph: "●", key: "N" },
{ type: "midpoint", label: "Midpoint", glyph: "M", key: "M" },
{ type: "concentric", label: "Concentric", glyph: "◎", key: "C" },
{ type: "hv", label: "Horizontal/Vertical", glyph: "H/V", key: "V" },
{ type: "equal", label: "Equal", glyph: "=", key: "E" },
{ type: "symmetric", label: "Symmetry", glyph: "⇋", key: "S" },
{ type: "fix", label: "Lock", glyph: "🔒", key: "L" },
{ type: "distance", label: "Distance", glyph: "↔", key: "D" },
];
const GLYPH: Partial<Record<ConstraintType, string>> = {
coincident: "●",
horizontal: "H",
vertical: "V",
parallel: "∥",
perpendicular: "⟂",
equal: "=",
tangent: "T",
concentric: "◎",
midpoint: "M",
symmetric: "⇋",
fix: "🔒",
};
/** 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[] {
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] }];
}
return [];
}
if (!applicable(type, pts, curves)) return [];
const ids = curves.map((c) => c.id);
switch (type) {
case "coincident":
return pts.length === 2 ? [{ id: uid(), type, pts }] : [{ id: uid(), type, pts, curves: ids }];
case "midpoint":
case "symmetric":
return [{ id: uid(), type, pts, curves: ids }];
case "distance": {
const v = distanceOf(pts, curves);
return v === null ? [] : [{ id: uid(), type, pts, curves: ids.length ? ids : undefined, value: v }];
}
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 }] : []));
return [...all.map((p) => ({ id: uid(), type, pts: [p] })), ...sizes];
}
default:
return [{ id: uid(), type, curves: ids }];
}
}
/** Current distance between two points, or a point and a line. */
export function distanceOf(pts: PointRef[], curves: SketchEntity[], all: SketchEntity[] = curves): number | null {
const P = (r: PointRef) => {
const e = all.find((x) => x.id === r.e);
return e ? pointOf(e, r.p) : null;
};
if (pts.length === 2 && !curves.length) {
const [a, b] = pts.map(P);
return a && b ? Math.hypot(a[0] - b[0], a[1] - b[1]) : null;
}
const l = curves[0];
const p = pts[0] && P(pts[0]);
if (pts.length === 1 && curves.length === 1 && l.kind === "line" && p) {
const dx = l.b[0] - l.a[0];
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);
}
return null;
}
/**
* Constraints already on the selection for a button: the column shows them
* as on, and tapping the button removes them.
*/
export function existingConstraints(type: ConstraintType | "hv", constraints: SketchConstraint[], pts: PointRef[], curves: SketchEntity[]): SketchConstraint[] {
const ids = new Set(curves.map((e) => e.id));
const ptKeys = new Set(pts.map((p) => `${p.e}:${p.p}`));
const types: string[] = type === "hv" ? ["horizontal", "vertical"] : [type];
// 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) => {
if (!types.includes(c.type)) return false;
const cv = c.curves ?? [];
const cp = c.pts ?? [];
if (!cv.length && !cp.length) return false;
if (type === "fix") return cp.every(ptIn);
// Every curve and point it involves is in the selection.
return cv.every((id) => ids.has(id)) && cp.every(ptIn) && (cv.length + cp.length > 1 || ids.size + pts.length === 1);
});
}
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);
const c: SketchConstraint = { id: i >= 0 ? list[i].id : uid(), type: "dim", curves: [entity], prop, value, ...(expr ? { expr } : {}) };
return i >= 0 ? list.map((x, k) => (k === i ? c : x)) : [...list, c];
}
/** The dimension constraint on an entity's property, if any. */
export function dimOf(list: SketchConstraint[], entity: string, prop: string): SketchConstraint | undefined {
return list.find((c) => c.type === "dim" && c.curves?.[0] === entity && c.curves.length === 1 && c.prop === prop);
}
/** Badges + dimension labels for the constraints of the sketch being edited. */
export class ConstraintGlyphs {
private host = el("div", "cglyphs");
private chips = new Map<string, HTMLElement>();
private hook = () => this.layout();
private items: { c: SketchConstraint; at: Vec2; off: [number, number] }[] = [];
private plane: PlaneDef | null = null;
selected: string | null = null;
constructor(
private view: Viewport,
private onClick: (id: string) => void,
) {
document.body.append(this.host);
view.frameHooks.add(this.hook);
}
set(plane: PlaneDef, entities: SketchEntity[], constraints: SketchConstraint[]): void {
this.plane = plane;
const get = (id: string) => entities.find((e) => e.id === id);
const mid = (e: SketchEntity): Vec2 | null => {
if (e.kind === "line") return [(e.a[0] + e.b[0]) / 2, (e.a[1] + e.b[1]) / 2];
if (e.kind === "arc") return e.m;
if (e.kind === "circle" || e.kind === "ellipse" || e.kind === "rect" || e.kind === "polygon") return e.center;
return e.points[0] ?? null;
};
this.items = [];
// Several badges at one spot are fanned out so they stay readable.
const counts = new Map<string, number>();
for (const c of constraints) {
let at: Vec2 | null = null;
if (c.pts?.length) {
const e = get(c.pts[0].e);
at = e ? pointOf(e, c.pts[0].p) : null;
} else if (c.curves?.length) {
const e = get(c.curves[0]);
at = e ? mid(e) : null;
if (e && c.type === "dim" && (c.prop === "radius" || c.prop === "diameter")) {
const r = e.kind === "circle" ? e.radius : e.kind === "arc" ? (arcFrom3(e.a, e.m, e.b)?.r ?? 0) : e.kind === "polygon" ? e.radius : 0;
const ctr = e.kind === "arc" ? (arcFrom3(e.a, e.m, e.b)?.c ?? at!) : at!;
at = [ctr[0] + r * 0.707, ctr[1] + r * 0.707];
}
if (e && c.type === "dim" && e.kind === "rect" && (c.prop === "w" || c.prop === "h")) {
const cs = Math.cos(e.rotation);
const sn = Math.sin(e.rotation);
const off = c.prop === "w" ? [0, -e.h / 2] : [e.w / 2, 0];
at = [e.center[0] + off[0] * cs - off[1] * sn, e.center[1] + off[0] * sn + off[1] * cs];
}
}
if (!at) continue;
const k = `${at[0].toFixed(4)},${at[1].toFixed(4)}`;
const n = counts.get(k) ?? 0;
counts.set(k, n + 1);
const isDim = c.type === "dim" || c.type === "distance";
this.items.push({ c, at, off: isDim ? [0, -16] : [14 + n * 18, 12] });
}
// Sync chips.
const live = new Set(this.items.map((i) => i.c.id));
for (const [id, chip] of this.chips) if (!live.has(id)) (chip.remove(), this.chips.delete(id));
for (const { c } of this.items) {
let chip = this.chips.get(c.id);
if (!chip) {
chip = el("button", "cglyph");
chip.addEventListener("pointerdown", (e) => e.stopPropagation());
chip.addEventListener("click", (e) => (e.stopPropagation(), this.onClick(c.id)));
this.host.append(chip);
this.chips.set(c.id, chip);
}
chip.className = `cglyph${c.type === "dim" || c.type === "distance" ? " dim" : ""}${c.id === this.selected ? " sel" : ""}${c.expr ? " expr" : ""}`;
chip.textContent = label(c, get);
chip.title = c.type === "dim" ? `${c.prop} dimension${c.expr ? ` = ${c.expr}` : ""} (click to edit)` : `${c.type} (click to select)`;
}
this.layout();
}
/** Show or hide all the badges (the "Show constraints" switch). */
setVisible(on: boolean): void {
this.host.hidden = !on;
}
private layout(): void {
if (!this.plane) return;
for (const it of this.items) {
const chip = this.chips.get(it.c.id);
if (!chip) continue;
const s = this.view.toScreen(sketchToWorld(this.plane, it.at));
chip.hidden = !s;
if (s) chip.style.transform = `translate(${Math.round(s[0] + it.off[0])}px, ${Math.round(s[1] + it.off[1])}px) translate(-50%, -50%)`;
}
}
dispose(): void {
this.view.frameHooks.delete(this.hook);
this.host.remove();
}
}
function label(c: SketchConstraint, get: (id: string) => SketchEntity | undefined): string {
if (c.type === "dim") {
const e = c.curves?.[0] ? get(c.curves[0]) : undefined;
const v = c.value ?? (e && c.prop ? sizeOf(e, c.prop) : 0) ?? 0;
const name = c.expr && /[a-z_]/i.test(c.expr) ? `${c.expr} = ` : "";
if (c.prop === "angle") return `${name}${trim(v, 2)}°`;
if (c.prop === "radius") return `${name}R ${fmtLen(v)}`;
if (c.prop === "diameter") return `${name}⌀ ${fmtLen(v)}`;
return `${name}${fmtLen(v)}`;
}
if (c.type === "distance") return fmtLen(c.value ?? 0);
return GLYPH[c.type] ?? "?";
}
+278
View File
@@ -0,0 +1,278 @@
// Reusable pick slots: axis, plane, direction, path, faces, profiles.
import type { AxisRef, EdgeRef, ExtrudeSource, FaceRef, PathRef, PlaneDef, SketchFeature, Vec3 } from "../doc/types";
import { norm, sub, toWorld } from "../geom";
import { arrangement, regionRef } from "../sketch/regions";
import { Vector3 } from "three";
import type { Slot } from "./featureOp";
import { edgeRefOf, faceRefOf, type AppContext, type Sel } from "./tool";
const WORLD_AXES: { label: string; dir: Vec3 }[] = [
{ label: "X", dir: [1, 0, 0] },
{ label: "Y", dir: [0, 1, 0] },
{ label: "Z", dir: [0, 0, 1] },
];
export function axisSlot(app: AppContext, label: string, get: () => AxisRef | null, set: (a: AxisRef) => void): Slot {
let shown: Sel | null = null;
let name = "";
return {
label,
describe: () => (get() ? name || "Axis" : "Tap a line, edge or axis"),
filled: () => !!get(),
pick: { profiles: false, curves: true, planes: false, axes: true, worldAxes: true },
presets: WORLD_AXES.map((a) => ({ label: a.label, apply: () => ((name = `${a.label} axis`), (shown = null), set({ origin: [0, 0, 0], dir: a.dir })) })),
shows: () => (shown ? [shown] : []),
accept(hit) {
if (hit.kind === "curve") {
const s = app.store.find<SketchFeature>(hit.sketch);
const e = s?.entities.find((x) => x.id === hit.entity);
const plane = app.sketchPlane(hit.sketch);
if (!s || !plane || e?.kind !== "line") return false;
const a = toWorld(plane, e.a);
set({ origin: a, dir: norm(sub(toWorld(plane, e.b), a)), ref: { kind: "sketchLine", sketch: s.id, entity: e.id } });
name = "Sketch line";
} else if (hit.kind === "edge") {
const info = app.view.body(hit.body)?.edges[hit.edge];
if (!info || info.type !== "LINE") return false;
set({ origin: info.start, dir: info.dir });
name = "Edge";
} else if (hit.kind === "axis") {
const ax = app.view.axisOf(hit.id);
if (!ax) return false;
// World axes don't move; construction axes are followed by reference.
const world = ["X", "Y", "Z"].includes(hit.id);
set({ origin: ax.plane.origin, dir: ax.plane.normal, ...(world ? {} : { ref: { kind: "axis" as const, feature: hit.id } }) });
name = ax.name;
} else return false;
shown = { ...hit } as Sel;
delete (shown as { point?: unknown }).point;
return true;
},
};
}
export function planeSlot(app: AppContext, label: string, get: () => PlaneDef | null, set: (p: PlaneDef, face?: FaceRef) => void): Slot {
let shown: Sel | null = null;
let name = "";
return {
label,
describe: () => (get() ? name || "Plane" : "Tap a plane or flat face"),
originPlanes: true,
rejectHint: "Tap a flat face or a plane (or pick XY / XZ / YZ)",
filled: () => !!get(),
pick: { profiles: false, edges: false, planes: true },
presets: ["XY", "XZ", "YZ"].map((id) => ({ label: id, apply: () => ((name = `${id} plane`), (shown = null), set(app.view.planeOf(id)!)) })),
shows: () => (shown ? [shown] : []),
accept(hit) {
if (hit.kind === "plane") {
const p = app.view.planeOf(hit.id);
if (!p) return false;
set(p);
name = ["XY", "XZ", "YZ"].includes(hit.id) ? `${hit.id} plane` : "Plane";
shown = { kind: "plane", id: hit.id };
return true;
}
if (hit.kind === "face") {
const info = app.view.body(hit.body)?.faces[hit.face];
if (!info?.plane) return false;
set(info.plane, faceRefOf(app, hit) ?? undefined);
name = "Face";
shown = { kind: "face", body: hit.body, face: hit.face };
return true;
}
return false;
},
};
}
/** 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;
let name = "";
return {
label,
describe: () => (get() ? name || "Direction" : "Tap an edge, axis or face"),
filled: () => !!get(),
pick: { profiles: false, planes: false, axes: true, worldAxes: true },
presets: WORLD_AXES.map((a) => ({ label: a.label, apply: () => ((name = a.label), (shown = null), set(a.dir)) })),
shows: () => (shown ? [shown] : []),
accept(hit) {
if (hit.kind === "edge") {
const info = app.view.body(hit.body)?.edges[hit.edge];
if (!info) return false;
set(info.dir);
name = "Edge";
shown = { kind: "edge", body: hit.body, edge: hit.edge };
} else if (hit.kind === "face") {
const info = app.view.body(hit.body)?.faces[hit.face];
if (!info) return false;
set(info.normal);
name = "Face normal";
shown = { kind: "face", body: hit.body, face: hit.face };
} else if (hit.kind === "axis") {
const ax = app.view.axisOf(hit.id);
if (!ax) return false;
set(ax.plane.normal);
name = ax.name;
shown = { kind: "axis", id: hit.id };
} else return false;
return true;
},
};
}
/** Sweep path: sketch curves (one sketch) or body edges. */
export function pathSlot(app: AppContext, get: () => PathRef | null, set: (p: PathRef) => void): Slot {
return {
label: "Path",
multi: true,
describe: () => {
const p = get();
if (!p) return "Tap curves or edges";
return p.kind === "sketch" ? `${p.entities.length} curve${p.entities.length > 1 ? "s" : ""}` : `${p.edges.length} edge${p.edges.length > 1 ? "s" : ""}`;
},
filled: () => !!get(),
pick: { profiles: false, curves: true, planes: false, axes: false },
shows: () => {
const p = get();
if (!p) return [];
if (p.kind === "sketch") return p.entities.map((entity) => ({ kind: "curve", sketch: p.sketch, entity }) as Sel);
return [];
},
accept(hit) {
const p = get();
if (hit.kind === "curve") {
if (p?.kind === "sketch" && p.sketch === hit.sketch) {
const has = p.entities.includes(hit.entity);
set({ ...p, entities: has ? p.entities.filter((e) => e !== hit.entity) : [...p.entities, hit.entity] });
} else set({ kind: "sketch", sketch: hit.sketch, entities: [hit.entity] });
return true;
}
if (hit.kind === "edge") {
const ref = edgeRefOf(app, hit);
if (!ref) return false;
const edges: EdgeRef[] = p?.kind === "edges" ? [...p.edges, ref] : [ref];
set({ kind: "edges", edges });
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[] = [];
return {
label,
multi: true,
describe: () => (get().length ? `${get().length} face${get().length > 1 ? "s" : ""}` : optional ? "None (closed)" : "Tap faces"),
filled: () => optional || get().length > 0,
pick: { profiles: false, edges: false, planes: false, axes: false },
shows: () => picked,
accept(hit) {
if (hit.kind !== "face") return false;
const ref = faceRefOf(app, hit);
if (!ref) return false;
const i = picked.findIndex((s) => s.kind === "face" && s.body === hit.body && s.face === hit.face);
if (i >= 0) {
picked.splice(i, 1);
set(get().filter((_, k) => k !== i));
} else {
picked.push({ kind: "face", body: hit.body, face: hit.face });
set([...get(), ref]);
}
return true;
},
};
}
/** Profiles / flat faces for loft sections. */
export function sectionsSlot(app: AppContext, get: () => ExtrudeSource[], set: (s: ExtrudeSource[]) => void, initial: Sel[]): Slot {
const picked: Sel[] = [...initial];
return {
label: "Profiles",
multi: true,
describe: () => `${get().length} picked${get().length < 2 ? " — tap more" : ""}`,
filled: () => get().length >= 2,
pick: { edges: false, planes: false, axes: false },
shows: () => picked,
accept(hit) {
if (hit.kind === "profile") {
const r = arrangement(app.sketchCurves(hit.sketch)).regions[hit.region];
if (!r) return false;
// Tapped again: take it back out.
const i = picked.findIndex((p) => p.kind === "profile" && p.sketch === hit.sketch && p.region === hit.region);
const ref = regionRef(r);
if (i >= 0) {
picked.splice(i, 1);
set(get().filter((s) => !(s.kind === "profile" && s.sketch === hit.sketch && s.regions.length === 1 && Math.hypot(s.regions[0].c[0] - ref.c[0], s.regions[0].c[1] - ref.c[1]) < 1e-6)));
return true;
}
picked.push({ kind: "profile", sketch: hit.sketch, region: hit.region });
set([...get(), { kind: "profile", sketch: hit.sketch, regions: [ref] }]);
return true;
}
if (hit.kind === "face") {
const ref = faceRefOf(app, hit);
if (!ref || !app.view.body(hit.body)?.faces[hit.face]?.plane) return false;
const i = picked.findIndex((p) => p.kind === "face" && p.body === hit.body && p.face === hit.face);
if (i >= 0) {
picked.splice(i, 1);
set(get().filter((s) => !(s.kind === "face" && s.face.body === ref.body && Math.hypot(...(sub3(s.face.center, ref.center) as [number, number, number])) < 1e-6)));
return true;
}
picked.push({ kind: "face", body: hit.body, face: hit.face });
set([...get(), { kind: "face", face: ref }]);
return true;
}
return false;
},
};
}
const sub3 = (a: number[], b: number[]) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
/**
* A point: a corner, a point on an edge (its ends and middle snap), a face
* (its centre snaps), a sketch point or curve, or a plane.
*/
export function pointSlot(app: AppContext, label: string, get: () => Vec3 | null, set: (p: Vec3) => void): Slot {
let shown: Sel | null = null;
return {
label,
describe: () => {
const p = get();
return p ? p.map((v) => Math.round(v * 1000) / 1000).join(", ") : "Tap a corner, edge, face or point";
},
filled: () => !!get(),
pick: { profiles: false, curves: true, planes: true },
shows: () => (shown ? [shown] : []),
accept(hit) {
let at: Vec3 | null = "point" in hit ? hit.point : null;
if (!at) return false;
// Snap to the obvious points when close on screen.
const near = (q: Vec3) => {
const a = app.view.toScreen(new Vector3(...q));
const b = app.view.toScreen(new Vector3(...at!));
return !!a && !!b && Math.hypot(a[0] - b[0], a[1] - b[1]) < 16;
};
if (hit.kind === "vertex") {
at = app.view.vertexOf(hit.body, hit.vertex) ?? at;
shown = { kind: "vertex", body: hit.body, vertex: hit.vertex };
} else if (hit.kind === "edge") {
const e = app.view.body(hit.body)?.edges[hit.edge];
const snap = e && [e.start, e.end, e.mid].find(near);
if (snap) at = snap;
shown = { kind: "edge", body: hit.body, edge: hit.edge };
} else if (hit.kind === "face") {
const f = app.view.body(hit.body)?.faces[hit.face];
if (f?.plane && near(f.center)) at = f.center;
shown = { kind: "face", body: hit.body, face: hit.face };
} else shown = null;
set(at);
return true;
},
};
}
+184
View File
@@ -0,0 +1,184 @@
import type { DocStore } from "../doc/store";
import type { EdgeRef, ExtrudeSource, FaceRef, Feature, PinDef, PlaneDef, SketchEntity, SketchFeature, Vec3 } from "../doc/types";
import type { KernelClient } from "../kernel/client";
import type { RegenResult } from "../kernel/protocol";
import { arrangement, regionRef } from "../sketch/regions";
import type { ToolItem, UI } from "../ui/ui";
import type { PointerHandler } from "../view/input";
import type { Highlight, PickHit, Viewport } from "../view/viewport";
/** Something selected in the viewport. Same shape as a highlight. */
export type Sel = Highlight;
export interface Tool extends PointerHandler {
readonly id: string;
/** Sketch being edited, so the viewport can draw it as active. */
readonly activeSketch?: string;
/** Feature being created/edited (highlighted in History). */
readonly editingId?: string;
enter?(): void;
exit?(): void;
/** Return true when the key was handled. */
key?(e: KeyboardEvent): boolean;
/** Keys typed while a drag is held (type an exact value; Enter finishes). */
dragKey?(e: KeyboardEvent): boolean;
/** Called after every regeneration (committed or preview). */
refresh?(): void;
}
export interface AppContext {
readonly store: DocStore;
readonly kernel: KernelClient;
readonly view: Viewport;
readonly ui: UI;
readonly result: RegenResult | null;
readonly selection: Sel[];
setSelection(sel: Sel[]): void;
setHover(h: Sel | null): void;
/** null returns to the selection tool. */
setTool(tool: Tool | null): void;
/** Show the model as if `features` were the document (live preview). */
preview(features: Feature[]): Promise<RegenResult | null>;
/** Current plane of a sketch (sketches on faces follow the face). */
sketchPlane(id: string): PlaneDef | undefined;
/** A sketch's curves plus the outline of the face it sits on (what regions are made of). */
sketchCurves(id: string): SketchEntity[];
mainTools(): ToolItem[];
bottomTools(): ToolItem[];
/** Pin a measurement in 3D (saved with the project). */
addPin(pin: PinDef): void;
/** Bodies shown alone, or null when nothing is isolated. */
readonly isolated: string[] | null;
isolate(bodies: string[] | null): void;
}
/** Index of the body face matching a stored reference (by centre and normal). */
export function faceIndexOf(app: AppContext, ref: FaceRef): number | null {
const faces = app.view.body(ref.body)?.faces ?? [];
let best: { i: number; d: number } | null = null;
faces.forEach((f, i) => {
const align = f.normal[0] * ref.normal[0] + f.normal[1] * ref.normal[1] + f.normal[2] * ref.normal[2];
if (align < 0.99) return;
const d = Math.hypot(f.center[0] - ref.center[0], f.center[1] - ref.center[1], f.center[2] - ref.center[2]);
if (!best || d < best.d) best = { i, d };
});
return best ? (best as { i: number }).i : null;
}
/**
* The nearest parallel face of the same body facing the other way, behind a
* flat face: "total" thickness for push/pull (like the distance to the bottom).
*/
export function oppositeFace(app: AppContext, body: string, face: number): { distance: number; point: Vec3 } | null {
const b = app.view.body(body);
const f = b?.faces[face];
if (!b || !f?.plane) return null;
let best: number | null = null;
for (const g of b.faces) {
if (!g.plane) continue;
const d = f.normal[0] * g.normal[0] + f.normal[1] * g.normal[1] + f.normal[2] * g.normal[2];
if (d > -0.999) continue;
const t = f.normal[0] * (f.center[0] - g.center[0]) + f.normal[1] * (f.center[1] - g.center[1]) + f.normal[2] * (f.center[2] - g.center[2]);
if (t > 1e-9 && (best === null || t < best)) best = t;
}
if (best === null) return null;
return { distance: best, point: [f.center[0] - f.normal[0] * best, f.center[1] - f.normal[1] * best, f.center[2] - f.normal[2] * best] };
}
export function sameSel(a: Sel, b: Sel): boolean {
return JSON.stringify(a) === JSON.stringify(b);
}
export function hitToSel(h: PickHit | null): Sel | null {
if (!h) return null;
const { point: _p, ...rest } = h;
return rest as Sel;
}
// -------------------------------------------------- selection → references
export function faceRefOf(app: AppContext, s: { body: string; face: number }): FaceRef | null {
const info = app.view.body(s.body)?.faces[s.face];
return info ? { body: s.body, center: info.center, normal: info.normal, area: info.area } : null;
}
export function edgeRefOf(app: AppContext, s: { body: string; edge: number }): EdgeRef | null {
const info = app.view.body(s.body)?.edges[s.edge];
return info ? { body: s.body, mid: info.mid, dir: info.dir, length: info.length } : null;
}
/** A selected profile or flat face as something extrude/revolve/… can use. */
export function sourcesOf(app: AppContext, sel: Sel[]): ExtrudeSource[] {
const out: ExtrudeSource[] = [];
const bySketch = new Map<string, number[]>();
for (const s of sel) {
if (s.kind === "profile") bySketch.set(s.sketch, [...(bySketch.get(s.sketch) ?? []), s.region]);
if (s.kind === "face") {
const f = faceRefOf(app, s);
if (f) out.push({ kind: "face", face: f });
}
}
for (const [sketch, idx] of bySketch) {
if (!app.store.find<SketchFeature>(sketch)) continue;
const regions = arrangement(app.sketchCurves(sketch)).regions;
out.unshift({ kind: "profile", sketch, regions: idx.map((i) => regions[i]).filter(Boolean).map(regionRef) });
}
return out;
}
/**
* A point on a curved face (its centre is off the face — on a cylinder's axis)
* and the normal there: the mesh vertex nearest the centre on the side facing the viewer.
*/
export function faceAnchor(app: AppContext, body: string, face: number): { base: Vec3; normal: Vec3 } | null {
const b = app.view.body(body);
const g = b?.faceGroups.find((x) => x.face === face);
const info = b?.faces[face];
if (!b || !g || !info) return null;
const view = app.view.cam.viewDir().toArray() as Vec3;
let best: { base: Vec3; normal: Vec3; score: number } | null = null;
for (let i = g.start; i < g.start + g.count; i++) {
const v = b.indices[i] * 3;
const p: Vec3 = [b.positions[v], b.positions[v + 1], b.positions[v + 2]];
const n: Vec3 = [b.normals[v], b.normals[v + 1], b.normals[v + 2]];
const facing = n[0] * view[0] + n[1] * view[1] + n[2] * view[2];
const d = Math.hypot(p[0] - info.center[0], p[1] - info.center[1], p[2] - info.center[2]);
const score = d + (facing > 0 ? 1e6 : 0);
if (!best || score < best.score) best = { base: p, normal: n, score };
}
return best && { base: best.base, normal: best.normal };
}
/** Point + normal of a source, for placing handles. */
export function sourceFrame(app: AppContext, src: ExtrudeSource): { base: Vec3; normal: Vec3 } {
if (src.kind === "face") {
const k = faceIndexOf(app, src.face);
const info = k !== null ? app.view.body(src.face.body)?.faces[k] : undefined;
if (k !== null && info && !info.plane) return faceAnchor(app, src.face.body, k) ?? { base: src.face.center, normal: src.face.normal };
return { base: src.face.center, normal: src.face.normal };
}
const plane = app.sketchPlane(src.sketch);
if (!plane) return { base: [0, 0, 0], normal: [0, 0, 1] };
const c = src.regions[0]?.c ?? [0, 0];
const y: Vec3 = [
plane.normal[1] * plane.xDir[2] - plane.normal[2] * plane.xDir[1],
plane.normal[2] * plane.xDir[0] - plane.normal[0] * plane.xDir[2],
plane.normal[0] * plane.xDir[1] - plane.normal[1] * plane.xDir[0],
];
return {
base: [plane.origin[0] + plane.xDir[0] * c[0] + y[0] * c[1], plane.origin[1] + plane.xDir[1] * c[0] + y[1] * c[1], plane.origin[2] + plane.xDir[2] * c[0] + y[2] * c[1]],
normal: plane.normal,
};
}
/** Body that a source "sits on" (joins/cuts default to it). */
export function targetOf(app: AppContext, src: ExtrudeSource): string | undefined {
if (src.kind === "face") return src.face.body;
return app.store.find<SketchFeature>(src.sketch)?.attachedTo?.body;
}
/** Bodies referenced by the selection (faces/edges/vertices count for their body). */
export function bodiesOf(sel: Sel[]): string[] {
const ids = sel.flatMap((s) => (s.kind === "body" || s.kind === "face" || s.kind === "edge" || s.kind === "vertex" ? [s.body] : []));
return [...new Set(ids)];
}
+92
View File
@@ -0,0 +1,92 @@
// Inline SVG icons (24×24, stroke = currentColor). Original artwork.
const svg = (body: string) =>
`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">${body}</svg>`;
export const icons = {
pivot: svg('<circle cx="12" cy="12" r="3"/><path d="M12 2v4M12 18v4M2 12h4M18 12h4"/><path d="M5.5 8.5a7.5 7.5 0 0 1 3-3" />'),
sketch: svg('<path d="M4 20l4-1 11-11-3-3L5 16z"/><path d="M14 7l3 3"/>'),
line: svg('<path d="M5 19L19 5"/><circle cx="5" cy="19" r="1.6"/><circle cx="19" cy="5" r="1.6"/>'),
arc: svg('<path d="M4 18a10 10 0 0 1 16 0"/><circle cx="4" cy="18" r="1.4"/><circle cx="20" cy="18" r="1.4"/>'),
spline: svg('<path d="M3 17c4-10 7 2 10-4s5-6 8-6"/>'),
rect: svg('<rect x="4" y="6" width="16" height="12" rx="0.5"/>'),
circle: svg('<circle cx="12" cy="12" r="7.5"/><circle cx="12" cy="12" r="0.8" fill="currentColor"/>'),
ellipse: svg('<ellipse cx="12" cy="12" rx="9" ry="5.5"/>'),
polygon: svg('<path d="M12 3.5l7.4 4.25v8.5L12 20.5l-7.4-4.25v-8.5z"/>'),
project: svg('<path d="M12 3l7 4v6l-7 4-7-4V7z"/><path d="M5 20h14" stroke-dasharray="2 2"/>'),
offset: svg('<rect x="7" y="7" width="10" height="10" rx="1"/><rect x="3.5" y="3.5" width="17" height="17" rx="3" stroke-dasharray="2.5 2"/>'),
sketchFillet: svg('<path d="M4 20V11a7 7 0 0 1 7-7h9"/>'),
text: svg('<path d="M5 6V4h14v2M12 4v16M9 20h6"/>'),
move: svg('<path d="M12 3v18M3 12h18"/><path d="M9 6l3-3 3 3M9 18l3 3 3-3M6 9l-3 3 3 3M18 9l3 3-3 3"/>'),
scale: svg('<rect x="3" y="11" width="10" height="10"/><path d="M13 11l8-8M15 3h6v6"/>'),
patternLinear: svg('<rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><rect x="14" y="14" width="7" height="7"/>'),
patternCircular: svg('<circle cx="12" cy="5" r="2.2"/><circle cx="19" cy="12" r="2.2"/><circle cx="12" cy="19" r="2.2"/><circle cx="5" cy="12" r="2.2"/><circle cx="12" cy="12" r="0.8" fill="currentColor"/>'),
rotateAxis: svg('<path d="M12 2v20" stroke-dasharray="2 2"/><path d="M5 9a8 4 0 1 0 14 0"/><path d="M17 6l2 3-3 1"/>'),
mirror: svg('<path d="M12 3v18" stroke-dasharray="2 2"/><path d="M9 7L4 17h5zM15 7l5 10h-5z"/>'),
trim: svg('<circle cx="6" cy="7" r="3"/><circle cx="6" cy="17" r="3"/><path d="M8.5 8.5L20 18M8.5 15.5L20 6"/>'),
alignLine: svg('<path d="M4 6h16"/><path d="M6 17h12" stroke-dasharray="2 2"/><path d="M12 15V9"/><path d="M9.5 11.5L12 9l2.5 2.5"/>'),
extend: svg('<path d="M3 12h10"/><path d="M13 12h5" stroke-dasharray="2 2"/><path d="M20 5v14"/>'),
construction: svg('<rect x="4" y="4" width="16" height="16" stroke-dasharray="3 2.5"/>'),
pointer: svg('<path d="M6 3l12 9-5.5 1L15 19l-2.5 1.2-2.6-5.9L6 18z"/>'),
extrude: svg('<path d="M4 16l8 4 8-4-8-4z"/><path d="M12 12V3"/><path d="M9 6l3-3 3 3"/>'),
revolve: svg('<path d="M4 4v16" stroke-dasharray="2 2"/><path d="M8 6h6v12H8"/><path d="M14 9c4 0 6 1.5 6 3s-2 3-6 3"/>'),
sweep: svg('<circle cx="5" cy="17" r="2.5"/><path d="M7 15c4-8 8-10 13-9"/>'),
loft: svg('<rect x="3" y="16" width="10" height="5"/><circle cx="16" cy="6" r="3.5"/><path d="M3 16l9.5-11M13 16l6-8"/>'),
shell: svg('<path d="M4 8v12h16V8"/><path d="M7 8v9h10V8"/>'),
split: svg('<rect x="4" y="5" width="16" height="14"/><path d="M12 2v20" stroke-dasharray="2 2"/>'),
fill: svg('<path d="M4 18L12 4l8 14z" fill="currentColor" fill-opacity=".3"/>'),
wrap: svg('<path d="M4 7c5-3 11-3 16 0v10c-5-3-11-3-16 0z"/><path d="M9 11h6"/>'),
replaceFace: svg('<rect x="4" y="9" width="12" height="11"/><path d="M8 9l4-5h8l-4 5M20 4v11l-4 5"/>'),
projectEdge: svg('<rect x="4" y="12" width="16" height="8"/><path d="M8 4h8l-2 8h-4z" stroke-dasharray="2 2"/>'),
plane: svg('<path d="M3 15l6-6h12l-6 6z"/>'),
axis: svg('<path d="M4 20L20 4" stroke-dasharray="3 2"/><circle cx="12" cy="12" r="1.5" fill="currentColor"/>'),
align: svg('<path d="M4 3v18"/><rect x="7" y="6" width="9" height="4"/><rect x="7" y="14" width="13" height="4"/>'),
translate: svg('<path d="M4 12h16M16 8l4 4-4 4"/>'),
fillet: svg('<path d="M4 20V10a6 6 0 0 1 6-6h10"/><path d="M4 20h16V4" stroke-dasharray="2 2.5"/>'),
chamfer: svg('<path d="M4 20V10l6-6h10"/><path d="M4 20h16V4" stroke-dasharray="2 2.5"/>'),
offsetFace: svg('<path d="M4 14l8 4 8-4M4 10l8 4 8-4-8-4z"/>'),
union: svg('<circle cx="9" cy="12" r="5.5"/><circle cx="15" cy="12" r="5.5"/>'),
subtract: svg('<circle cx="9" cy="12" r="5.5"/><circle cx="15" cy="12" r="5.5" stroke-dasharray="2 2"/>'),
intersect: svg('<circle cx="9" cy="12" r="5.5" stroke-dasharray="2 2"/><circle cx="15" cy="12" r="5.5" stroke-dasharray="2 2"/><path d="M12 7.4a5.5 5.5 0 0 1 0 9.2a5.5 5.5 0 0 1 0-9.2z" fill="currentColor" fill-opacity=".35"/>'),
trash: svg('<path d="M5 7h14"/><path d="M9 7V4h6v3"/><path d="M7 7l1 13h8l1-13"/>'),
undo: svg('<path d="M9 14L4 9l5-5"/><path d="M4 9h10a6 6 0 0 1 0 12h-3"/>'),
redo: svg('<path d="M15 14l5-5-5-5"/><path d="M20 9H10a6 6 0 0 0 0 12h3"/>'),
history: svg('<path d="M3 12a9 9 0 1 0 3-6.7L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l3 2"/>'),
fit: svg('<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>'),
file: svg('<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/>'),
insert: svg('<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M12 8v8M8 12h8"/>'),
variable: svg('<path d="M5 6c3 0 3 12 6 12M11 6c-3 0-3 12-6 12"/><path d="M14 9h6M17 6v6M14 16h6"/>'),
image: svg('<rect x="3" y="5" width="18" height="14" rx="1"/><circle cx="8.5" cy="10" r="1.6"/><path d="M21 16l-5-5-8 8"/>'),
construct: svg('<path d="M3 15l6-6h12l-6 6z"/><path d="M12 3v18" stroke-dasharray="2 2"/>'),
transform: svg('<path d="M12 3l3 3h-2v4h4V8l3 3-3 3v-2h-4v4h2l-3 3-3-3h2v-4H7v2l-3-3 3-3v2h4V6H9z"/>'),
tools: svg('<path d="M14 7l3-3 3 3-3 3M4 20l9-9"/><path d="M5 4l4 4-2 2-4-4z"/>'),
section: svg('<path d="M4 8l8-4 8 4v8l-8 4-8-4z"/><path d="M4 12h16" stroke-dasharray="2 2"/>'),
measure: svg('<path d="M3 17L17 3l4 4L7 21z"/><path d="M7 13l2 2M10 10l2 2M13 7l2 2"/>'),
magnet: svg('<path d="M6 4v8a6 6 0 0 0 12 0V4h-4v8a2 2 0 0 1-4 0V4z"/>'),
ruler: svg('<path d="M4 20V4"/><path d="M4 7h4M4 11h6M4 15h4M4 19h6"/><path d="M14 4h6M17 4v16M14 20h6"/>'),
views: svg('<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z"/><path d="M12 12l8-4.5M12 12v9M12 12L4 7.5"/>'),
display: svg('<path d="M12 3l9 5-9 5-9-5z" fill="currentColor" fill-opacity=".25"/><path d="M3 13l9 5 9-5"/>'),
camera: svg('<path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/>'),
eye: svg('<path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>'),
eyeOff: svg('<path d="M3 3l18 18"/><path d="M10.6 5.1A10 10 0 0 1 12 5c6.4 0 10 7 10 7a17 17 0 0 1-3.2 4"/><path d="M6.6 6.6C3.7 8.4 2 12 2 12s3.6 7 10 7a9.6 9.6 0 0 0 5.4-1.6"/>'),
check: svg('<path d="M5 12.5l4.5 4.5L19 7"/>'),
close: svg('<path d="M6 6l12 12M18 6L6 18"/>'),
exit: svg('<path d="M14 4h5v16h-5"/><path d="M10 8l-4 4 4 4"/><path d="M6 12h10"/>'),
normal: svg('<rect x="5" y="5" width="14" height="14"/><circle cx="12" cy="12" r="2"/>'),
menu: svg('<path d="M4 7h16M4 12h16M4 17h16"/>'),
rename: svg('<path d="M4 20h4l10-10-4-4L4 16z"/><path d="M13 7l4 4"/>'),
pin: svg('<path d="M9 4h6l-1 6 3 3H7l3-3z"/><path d="M12 13v7"/>'),
flip: svg('<path d="M7 4v16M17 4v16"/><path d="M7 8h10l-3-3M17 16H7l3 3"/>'),
deselect: svg('<rect x="4" y="4" width="16" height="16" rx="2" stroke-dasharray="3 2"/><path d="M9 9l6 6M15 9l-6 6"/>'),
more: svg('<circle cx="6" cy="12" r="1.3" fill="currentColor"/><circle cx="12" cy="12" r="1.3" fill="currentColor"/><circle cx="18" cy="12" r="1.3" fill="currentColor"/>'),
splitLine: svg('<path d="M3 15L10 9.5M14 8L21 3"/><path d="M12 4v16" stroke-dasharray="2 2"/><circle cx="12" cy="9" r="1.6" fill="currentColor"/>'),
freeform: svg('<path d="M4 15c2-7 6-9 9-6s5 1 7-3"/><path d="M4 15c3 3 8 4 12 1s4-6 4-10" stroke-dasharray="2 2"/><circle cx="4" cy="15" r="1.4" fill="currentColor"/><circle cx="13" cy="9" r="1.4" fill="currentColor"/><circle cx="20" cy="6" r="1.4" fill="currentColor"/>'),
copy: svg('<rect x="8" y="8" width="12" height="12" rx="1.5"/><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"/>'),
color: svg('<circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor"/>'),
folder: svg('<path d="M3 7a1 1 0 0 1 1-1h5l2 2h9a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1z"/>'),
constraints: svg('<path d="M5 5v14M9 5v14"/><path d="M13 19L19 5"/><circle cx="16" cy="12" r="1.2" fill="currentColor"/>'),
isolate: svg('<circle cx="12" cy="12" r="4"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/>'),
body: svg('<path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z" fill="currentColor" fill-opacity=".2"/>'),
};
export type IconName = keyof typeof icons;
+228
View File
@@ -0,0 +1,228 @@
// Items panel: every body, sketch, plane, axis and image, with visibility
// toggles — plus folders (at the bottom) to group any of them.
import type { DocStore } from "../doc/store";
import type { Feature, ItemFolder } from "../doc/types";
import type { RegenResult } from "../kernel/protocol";
import { icons, type IconName } from "./icons";
import { el } from "./ui";
export interface ItemsHandlers {
selectBody(id: string): void;
editSketch(id: string): void;
selectPlane(id: string): void;
selectImage(id: string): void;
deleteBody(id: string): void;
deleteFeature(id: string): void;
/** Rename a body (custom name) or a feature (its history name). */
rename(id: string, current: string, isBody: boolean): void;
/** Ask for a name (folders). */
askName(title: string, current: string): Promise<string | null>;
isolated(): string[] | null;
}
interface Row {
id: string;
name: string;
icon: IconName;
open(): void;
remove(): void;
extra?: string;
isBody?: boolean;
}
export class ItemsPanel {
private el = document.getElementById("items")!;
private list = document.getElementById("items-list")!;
/** Rows ticked for grouping (Ctrl/Shift+click, or the checkboxes in Select mode). */
private checked = new Set<string>();
private picking = false;
private collapsed = new Set<string>();
private last: RegenResult | null = null;
constructor(
private store: DocStore,
private h: ItemsHandlers,
) {
document.getElementById("items-btn")!.addEventListener("click", () => this.toggle());
document.getElementById("items-close")!.innerHTML = icons.close;
document.getElementById("items-close")!.addEventListener("click", () => this.toggle(false));
const pick = document.getElementById("items-pick")!;
pick.addEventListener("click", () => {
this.picking = !this.picking;
if (!this.picking) this.checked.clear();
pick.classList.toggle("on", this.picking);
this.render(this.last);
});
}
toggle(open?: boolean): void {
const on = this.el.classList.toggle("open", open);
// Phones: one panel at a time (Items or History).
if (on && window.innerWidth <= 720) {
document.getElementById("history")?.classList.remove("open");
document.body.classList.remove("history-open");
}
// The tool column steps aside while Items is open.
document.body.classList.toggle("items-open", on);
// The value panel and tool column re-fit around it.
window.dispatchEvent(new Event("resize"));
}
private get folders(): ItemFolder[] {
return this.store.doc.folders ?? [];
}
private shown = "";
render(result: RegenResult | null): void {
this.last = result;
// Nothing that the list shows changed: keep the rows (rebuilding them under a
// click that's in progress would swallow that click).
const d = this.store.doc;
const sig = JSON.stringify([
d.hidden, d.names, d.folders, this.h.isolated(), [...this.checked], this.picking, [...this.collapsed],
result?.bodies.map((b) => [b.id, b.name]),
d.features.filter((f) => ["sketch", "plane", "axis", "image"].includes(f.type)).map((f) => [f.id, f.name, f.type]),
]);
if (sig === this.shown) return;
this.shown = sig;
this.list.innerHTML = "";
const hidden = new Set(this.store.doc.hidden);
const iso = this.h.isolated();
const inFolder = new Set(this.folders.flatMap((f) => f.items));
const section = (title: string) => this.list.append(el("li", "items-heading", title));
// Everything there is, by kind.
const bodies = result?.bodies ?? [];
const names = this.store.doc.names ?? {};
const feats = this.store.doc.features;
const of = <T extends Feature["type"]>(t: T) => feats.filter((f) => f.type === t);
const rows: Record<string, Row[]> = {
Bodies: bodies.map((b) => ({ id: b.id, name: names[b.id] ?? b.name, icon: "body" as IconName, open: () => this.h.selectBody(b.id), remove: () => this.h.deleteBody(b.id), extra: iso && !iso.includes(b.id) ? " isolated-out" : "", isBody: true })),
Sketches: of("sketch").map((s) => ({ id: s.id, name: s.name, icon: "sketch" as IconName, open: () => this.h.editSketch(s.id), remove: () => this.h.deleteFeature(s.id) })),
"Planes & axes": [...of("plane"), ...of("axis")].map((c) => ({ id: c.id, name: c.name, icon: (c.type === "plane" ? "plane" : "axis") as IconName, open: () => this.h.selectPlane(c.id), remove: () => this.h.deleteFeature(c.id) })),
Images: of("image").map((i) => ({ id: i.id, name: i.name, icon: "image" as IconName, open: () => this.h.selectImage(i.id), remove: () => this.h.deleteFeature(i.id) })),
};
const byId = new Map(Object.values(rows).flat().map((r) => [r.id, r]));
for (const [title, list] of Object.entries(rows)) {
const loose = list.filter((r) => !inFolder.has(r.id));
if (title !== "Bodies" && !loose.length) continue;
section(`${title} (${loose.length})`);
if (!loose.length) this.list.append(el("li", "items-empty", bodies.length ? "All in folders" : "No bodies yet"));
for (const r of loose) this.row(r, hidden, 0);
}
// Folders last, each with what it holds.
if (this.folders.length) section(`Folders (${this.folders.length})`);
for (const f of this.folders) {
const items = f.items.map((id) => byId.get(id)).filter((r): r is Row => !!r);
this.folderRow(f, items, hidden);
if (!this.collapsed.has(f.id)) for (const r of items) this.row(r, hidden, 1);
}
// Grouping bar.
if (this.checked.size) {
const bar = el("li", "items-groupbar");
const make = el("button", "text-btn primary", `New folder (${this.checked.size})`);
make.addEventListener("click", () => void this.makeFolder());
const clear = el("button", "text-btn", "Clear");
clear.addEventListener("click", () => (this.checked.clear(), this.render(this.last)));
bar.append(make, clear);
this.list.append(bar);
} else if (this.picking) {
this.list.append(el("li", "items-empty", "Tick items, then make a folder of them."));
}
}
private row(r: Row, hidden: Set<string>, depth: number): void {
const li = el("li", `items-row${hidden.has(r.id) ? " hidden-item" : ""}${r.extra ?? ""}${this.checked.has(r.id) ? " checked" : ""}${depth ? " in-folder" : ""}`);
if (this.picking) {
const box = document.createElement("input");
box.type = "checkbox";
box.className = "items-check";
box.checked = this.checked.has(r.id);
box.addEventListener("change", () => this.check(r.id, box.checked));
li.append(box);
}
const eye = el("button", "icon-btn");
eye.title = hidden.has(r.id) ? "Show" : "Hide";
eye.innerHTML = icons[hidden.has(r.id) ? "eyeOff" : "eye"];
eye.addEventListener("click", (e) => {
e.stopPropagation();
this.store.commit((d) => (d.hidden = hidden.has(r.id) ? d.hidden.filter((x) => x !== r.id) : [...d.hidden, r.id]));
});
const label = el("button", "items-name");
label.innerHTML = icons[r.icon];
label.append(r.name);
// Ctrl/Cmd/Shift+click ticks the row for grouping; a plain click opens it.
label.addEventListener("click", (e) => (e.ctrlKey || e.metaKey || e.shiftKey || this.picking ? this.check(r.id, !this.checked.has(r.id)) : r.open()));
const ren = el("button", "icon-btn");
ren.title = "Rename";
ren.innerHTML = icons.rename;
ren.addEventListener("click", (e) => (e.stopPropagation(), this.h.rename(r.id, r.name, !!r.isBody)));
const del = el("button", "icon-btn");
del.title = "Delete";
del.innerHTML = icons.trash;
del.addEventListener("click", (e) => (e.stopPropagation(), r.remove()));
li.append(eye, label, ren, del);
this.list.append(li);
}
private folderRow(f: ItemFolder, items: Row[], hidden: Set<string>): void {
const li = el("li", "items-row folder-row");
const allHidden = items.length > 0 && items.every((r) => hidden.has(r.id));
const eye = el("button", "icon-btn");
eye.title = allHidden ? "Show all in folder" : "Hide all in folder";
eye.innerHTML = icons[allHidden ? "eyeOff" : "eye"];
eye.addEventListener("click", () =>
this.store.commit((d) => {
const ids = new Set(items.map((r) => r.id));
d.hidden = allHidden ? d.hidden.filter((x) => !ids.has(x)) : [...new Set([...d.hidden, ...ids])];
}),
);
const label = el("button", "items-name");
label.innerHTML = icons.folder;
label.append(f.name, el("span", "items-count", ` ${items.length}`), el("span", "items-caret", this.collapsed.has(f.id) ? " ▸" : " ▾"));
label.title = "Show / hide its contents";
label.addEventListener("click", () => {
if (this.collapsed.has(f.id)) this.collapsed.delete(f.id);
else this.collapsed.add(f.id);
this.render(this.last);
});
const ren = el("button", "icon-btn");
ren.title = "Rename folder";
ren.innerHTML = icons.rename;
ren.addEventListener("click", async () => {
const name = await this.h.askName("Rename folder", f.name);
if (name) this.store.commit((d) => (d.folders = (d.folders ?? []).map((x) => (x.id === f.id ? { ...x, name } : x))));
});
const del = el("button", "icon-btn");
del.title = "Remove folder (keeps what's in it)";
del.innerHTML = icons.trash;
del.addEventListener("click", () => this.store.commit((d) => (d.folders = (d.folders ?? []).filter((x) => x.id !== f.id))));
li.append(eye, label, ren, del);
this.list.append(li);
}
private check(id: string, on: boolean): void {
if (on) this.checked.add(id);
else this.checked.delete(id);
this.render(this.last);
}
private async makeFolder(): Promise<void> {
const ids = [...this.checked];
const name = await this.h.askName("New folder", `Folder ${this.folders.length + 1}`);
if (!name) return;
this.checked.clear();
this.picking = false;
document.getElementById("items-pick")!.classList.remove("on");
// An item lives in one folder at a time.
this.store.commit((d) => {
const rest = (d.folders ?? []).map((f) => ({ ...f, items: f.items.filter((x) => !ids.includes(x)) }));
d.folders = [...rest, { id: `folder-${Date.now().toString(36)}`, name, items: ids }];
});
}
}
+167
View File
@@ -0,0 +1,167 @@
// Right column popovers: snapping, units & grid, views, display modes, screenshot, history.
import type { SavedView, Units, Vec3 } from "../doc/types";
import type { DocStore } from "../doc/store";
import { settings, type Settings } from "../settings";
import { UNIT_LABEL, units } from "../units";
import type { Viewport } from "../view/viewport";
import type { UI } from "./ui";
import { el } from "./ui";
export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnits: (u: Units) => void): void {
ui.addRight("fit", "fit", "Zoom to fit (F)", () => view.cam.fit(view.bounds()), () => "Fit");
ui.addRight("snap", "magnet", "Snapping", (host) => {
const s = settings.value;
host.append(heading("Snap to"));
const snapRow = (key: keyof Settings["snap"], label: string) =>
toggleRow(label, s.snap[key], (v) => settings.set("snap", { ...settings.value.snap, [key]: v }));
host.append(snapRow("grid", "Grid"), snapRow("guideLines", "Sketch guide lines"), snapRow("guidePoints", "Sketch guide points"), snapRow("points3d", "3D guide points"), snapRow("distantEdges", "Distant edges"));
host.append(heading("Show"));
host.append(toggleRow("Guide points", s.showGuidePoints, (v) => settings.set("showGuidePoints", v)), toggleRow("Snapping hints", s.showSnapHints, (v) => settings.set("showSnapHints", v)));
host.append(el("div", "pop-note", "Hold Shift while drawing to place a point without snapping."));
});
ui.addRight(
"units",
"ruler",
"Units & grid",
(host) => {
host.append(heading("Units"));
const list: [Units, string][] = [
["mm", "Millimeter"],
["cm", "Centimeter"],
["m", "Meter"],
["in", "Inch"],
["ft", "Foot"],
];
for (const [u, label] of list) host.append(choiceRow(label, units() === u, () => (onUnits(u), ui.refreshPopover())));
host.append(heading("Grid"));
const s = settings.value;
host.append(toggleRow(`Lock grid size (${s.gridStep} mm)`, s.gridLocked, (v) => settings.set("gridLocked", v)));
const stepRow = el("label", "pop-row");
stepRow.append(el("span", "", "Locked size (mm)"));
const input = document.createElement("input");
input.className = "pop-input";
input.value = String(s.gridStep);
input.addEventListener("change", () => {
const v = Number(input.value);
if (v > 0) settings.set("gridStep", v);
});
stepRow.append(input);
host.append(stepRow);
host.append(el("div", "pop-note", `Tip: the grid adapts to zoom (now ${fmtStep(view.grid.step)} per square).`));
host.append(heading("Degree format"));
host.append(choiceRow("Decimal (27.15°)", s.degrees === "decimal", () => settings.set("degrees", "decimal")), choiceRow("Fractional (27° 15′)", s.degrees === "fractional", () => settings.set("degrees", "fractional")));
},
() => UNIT_LABEL[units()],
);
ui.addRight("views", "views", "Views", (host) => {
const tabs = el("div", "pop-tabs");
const views = el("button", "", "Views");
const appearance = el("button", "active", "Appearance");
tabs.append(appearance, views);
const body = el("div", "");
host.append(tabs, body);
const showViews = () => {
views.className = "active";
appearance.className = "";
body.innerHTML = "";
const go = (label: string, n: Vec3, x?: Vec3) => choiceRow(label, false, () => view.cam.lookAlong(n, x));
body.append(choiceRow("⌂ Default view", false, () => (view.cam.iso(), view.cam.fit(view.bounds()))));
body.append(go("Top", [0, 0, 1]), go("Bottom", [0, 0, -1]), go("Front", [0, -1, 0]), go("Back", [0, 1, 0], [-1, 0, 0]), go("Right", [1, 0, 0], [0, 1, 0]), go("Left", [-1, 0, 0], [0, -1, 0]));
body.append(heading("Saved views"));
for (const v of store.doc.views) {
const row = choiceRow(v.name, false, () => view.cam.restore(v));
const del = el("button", "icon-btn small", "✕");
del.title = "Delete view";
del.addEventListener("click", (e) => {
e.stopPropagation();
store.commit((d) => (d.views = d.views.filter((x) => x.name !== v.name)));
showViews();
});
row.append(del);
body.append(row);
}
body.append(
choiceRow("+ Save current view", false, () => {
const name = `View ${store.doc.views.length + 1}`;
const sv: SavedView = view.cam.savedView(name);
store.commit((d) => d.views.push(sv));
showViews();
}),
);
};
const showAppearance = () => {
views.className = "";
appearance.className = "active";
body.innerHTML = "";
const s = settings.value;
body.append(
toggleRow("Animate camera", s.animateCamera, (v) => settings.set("animateCamera", v)),
toggleRow("Orthographic", s.ortho, (v) => settings.set("ortho", v)),
toggleRow("Show grid", s.showGrid, (v) => settings.set("showGrid", v)),
toggleRow("Show world axes", s.showAxes, (v) => settings.set("showAxes", v)),
);
};
views.addEventListener("click", showViews);
appearance.addEventListener("click", showAppearance);
showAppearance();
});
ui.addRight("display", "display", "Display modes", (host) => {
const s = settings.value;
host.append(heading("Shaders"));
for (const [id, label] of [["wireframe", "Wireframe"], ["xray", "X-Ray"], ["shaded", "Shaded"]] as const) {
host.append(choiceRow(label, s.shader === id, () => (settings.set("shader", id), ui.refreshPopover())));
}
host.append(heading("Options"));
host.append(toggleRow("Show edges", s.showEdges, (v) => settings.set("showEdges", v)), toggleRow("Show hidden edges", s.showHiddenEdges, (v) => settings.set("showHiddenEdges", v)));
}, () => ({ shaded: "Shaded", wireframe: "Wire", xray: "X-Ray" })[settings.value.shader]);
ui.addRight("shot", "camera", "Screenshot", () => {
void view.screenshot().then((blob) => {
if (!blob) return;
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `${store.doc.name} ${new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-")}.png`;
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
ui.toast("Screenshot saved");
});
});
ui.addRight("history", "history", "History", () => ui.toggleHistory());
// Sketch mode only (CSS shows it under body.sketching): show/hide the constraint column.
const cons = ui.addRight("constraints", "constraints", "Constraints (sketch)", () => settings.set("showConstraints", !settings.value.showConstraints));
cons.classList.add("sketch-only");
const mark = () => cons.classList.toggle("on", settings.value.showConstraints);
settings.onChange(mark);
mark();
settings.onChange(() => ui.refreshRight());
}
function heading(text: string): HTMLElement {
return el("div", "pop-heading", text);
}
function toggleRow(label: string, value: boolean, onChange: (v: boolean) => void): HTMLElement {
const row = el("button", `pop-row toggle-row${value ? " on" : ""}`);
row.append(el("span", "", label), el("span", "switch"));
row.addEventListener("click", () => {
const next = !row.classList.contains("on");
row.classList.toggle("on", next);
onChange(next);
});
return row;
}
function choiceRow(label: string, active: boolean, run: () => void): HTMLElement {
const row = el("button", `pop-row choice-row${active ? " active" : ""}`, label);
row.addEventListener("click", run);
return row;
}
function fmtStep(mm: number): string {
return mm >= 1000 ? `${mm / 1000} m` : mm >= 10 ? `${mm / 10} cm` : `${mm} mm`;
}
+80
View File
@@ -0,0 +1,80 @@
// Orbit centre: a button under the view cube. Tap it, then tap a body, a sketch
// or the ground: from then on the view turns about that point. Zoom to fit
// (or tapping empty space while choosing) goes back to turning about the view's centre.
import { BufferGeometry, Points, Vector3 } from "three";
import type { Viewport } from "../view/viewport";
import { dotMaterial } from "../view/viewport";
import { GROUND } from "../geom";
import { icons } from "./icons";
export class PivotButton {
readonly el = document.createElement("button");
private cursor = document.createElement("div");
private choosing = false;
private marker: Points;
constructor(private view: Viewport, private toast: (text: string) => void) {
this.el.className = "pivot-btn";
this.el.title = "Orbit centre: tap here, then tap where the view should turn around";
this.el.innerHTML = icons.pivot;
this.el.addEventListener("click", () => this.setChoosing(!this.choosing));
this.cursor.className = "pivot-cursor";
this.cursor.innerHTML = icons.pivot;
this.cursor.hidden = true;
document.body.append(this.cursor);
this.marker = new Points(new BufferGeometry().setFromPoints([new Vector3()]), dotMaterial({ color: 0x3d8bff, size: 10 }));
this.marker.renderOrder = 60;
(this.marker.material as { depthTest: boolean }).depthTest = false;
this.marker.visible = false;
view.overlay.add(this.marker);
// While choosing, the next press on the model picks the point (and goes nowhere else).
view.canvas.addEventListener(
"pointerdown",
(e) => {
if (!this.choosing || e.button !== 0) return;
e.stopImmediatePropagation();
e.preventDefault();
const r = view.canvas.getBoundingClientRect();
this.pick(e.clientX - r.left, e.clientY - r.top);
},
true,
);
window.addEventListener("pointermove", (e) => {
if (!this.choosing) return;
this.cursor.style.transform = `translate(${e.clientX + 14}px, ${e.clientY + 14}px)`;
});
window.addEventListener("keydown", (e) => e.key === "Escape" && this.choosing && this.setChoosing(false));
view.frameHooks.add(() => this.layout());
}
private setChoosing(on: boolean): void {
this.choosing = on;
this.el.classList.toggle("on", on || !!this.view.cam.pivot);
this.cursor.hidden = !on;
this.view.canvas.style.cursor = on ? "crosshair" : "";
if (on) this.toast("Tap a point on the model to turn the view around it");
}
private pick(x: number, y: number): void {
const hit = this.view.pick(x, y, { edgeTolPx: 10, curves: true, planes: false, axes: false });
const at = hit?.point ?? this.view.rayToPlane(x, y, GROUND);
if (hit?.point || at) {
this.view.cam.pivot = new Vector3(...(at as [number, number, number]));
} else {
this.view.cam.pivot = null;
}
this.setChoosing(false);
this.view.requestRender();
}
private layout(): void {
const p = this.view.cam.pivot;
this.marker.visible = !!p;
this.el.classList.toggle("on", this.choosing || !!p);
if (p) {
this.marker.position.copy(p);
this.marker.updateMatrixWorld();
}
}
}
+631
View File
@@ -0,0 +1,631 @@
import type { Feature } from "../doc/types";
import type { FeatureError } from "../kernel/protocol";
import { evaluate, toDisplay, trim, UNIT_LABEL, units } from "../units";
import { icons, type IconName } from "./icons";
export interface ToolItem {
id: string;
label: string;
icon: IconName;
/** Small second line, e.g. the current variant ("Diagonal"). */
sub?: string;
shortcut?: string;
active?: boolean;
disabled?: boolean;
/** Reason shown when disabled. */
why?: string;
/** Opens a flyout with variants / sub-tools instead of running. */
children?: ToolItem[];
/** Show a colour circle instead of the icon (colour choices). */
swatch?: string;
run?(): void;
}
export type FieldKind = "length" | "angle" | "number" | "int";
export type PanelItem =
| {
type: "number";
label: string;
value: number;
kind?: FieldKind;
min?: number;
onInput(v: number): void;
/** Expression currently driving the value (shown instead of the number). */
expr?: string;
/** Set when the field may hold an expression: called with it, or null for a plain number. */
onExpr?(expr: string | null): void;
}
| { type: "slot"; label: string; value: string; active: boolean; filled: boolean; onClick(): void }
| { type: "choice"; label?: string; options: { id: string; label: string }[]; value: string; onChange(id: string): void }
| { type: "toggle"; label: string; value: boolean; onChange(v: boolean): void }
| { type: "button"; label: string; icon?: IconName; onClick(): void };
/** Kept for older call sites: a numeric field. */
export interface ValueField {
label: string;
value: number;
unit?: string;
min?: number;
step?: number;
integer?: boolean;
kind?: FieldKind;
onInput(v: number): void;
}
export interface ValuePanel {
title: string;
fields?: ValueField[];
items?: PanelItem[];
onDone?(): void;
onCancel?(): void;
/** Extra buttons shown in the panel (e.g. Delete). */
actions?: ToolItem[];
}
export interface HistoryHandlers {
edit(id: string): void;
/** Pointer over a step (null: left it): show what it works on. */
hover?(id: string | null): void;
toggle(id: string): void;
remove(id: string): void;
}
const $ = <T extends HTMLElement>(sel: string) => document.querySelector(sel) as T;
/** All DOM chrome around the viewport. Deliberately framework-free and small. */
export class UI {
private toolbar = $<HTMLElement>("#toolbar");
private bottomLeft = $<HTMLElement>("#bottom-left");
private flyout = $<HTMLElement>("#flyout");
private hint = $<HTMLElement>("#hint");
private panel = $<HTMLElement>("#panel");
private historyEl = $<HTMLElement>("#history");
private historyList = $<HTMLElement>("#history-list");
private toastEl = $<HTMLElement>("#toast");
private labelEl = $<HTMLElement>("#label");
private status = $<HTMLElement>("#status");
private rightCol = $<HTMLElement>("#right-col");
private popover = $<HTMLElement>("#popover");
readonly pins = $<HTMLElement>("#pins");
private toastTimer = 0;
private panelSpec: ValuePanel | null = null;
private flyoutOwner: string | null = null;
private popoverOwner: string | null = null;
constructor() {
$("#history-close").innerHTML = icons.close;
$("#history-close").addEventListener("click", () => this.toggleHistory(false));
document.addEventListener("pointerdown", (e) => {
const t = e.target as HTMLElement;
if (!t.closest("#flyout, #toolbar, #bottom-left")) this.closeFlyout();
});
if (window.innerWidth >= 1000) this.toggleHistory(true);
window.addEventListener("resize", () => (this.fitToolbar(), this.fitPanel()));
}
toggleHistory(open?: boolean): void {
const on = this.historyEl.classList.toggle("open", open);
// Phones: one panel at a time (History or Items).
if (on && window.innerWidth <= 720) {
document.getElementById("items")?.classList.remove("open");
document.body.classList.remove("items-open");
}
// Everything on the right makes room for the docked History panel.
document.body.classList.toggle("history-open", on);
// Things placed beside the right-hand bar (panel, constraint column) re-fit.
window.dispatchEvent(new Event("resize"));
}
// ------------------------------------------------------------- left column
setTools(items: ToolItem[]): void {
this.closeFlyout();
this.toolItems = items;
renderTools(this.toolbar, items, (item, btn) => this.runAndOpen(item, btn, this.toolbar, () => this.toolItems));
this.fitToolbar();
}
setBottom(items: ToolItem[]): void {
this.bottomItems = items;
renderTools(this.bottomLeft, items, (item, btn) => this.runAndOpen(item, btn, this.bottomLeft, () => this.bottomItems));
this.fitToolbar();
}
private toolItems: ToolItem[] = [];
private bottomItems: ToolItem[] = [];
/**
* A tool with options (Spline: fit / control points…): a click starts it
* straight away with the option used last, and opens the options beside it.
*/
private runAndOpen(item: ToolItem, btn: HTMLElement, host: HTMLElement, items: () => ToolItem[]): void {
if (!item.run || this.flyoutOwner === item.id) return this.openFlyout(item, btn);
const rect = btn.getBoundingClientRect();
item.run();
// Running it may have redrawn the column: open the options on the new button
// (or where the button was, if a tool took the column over).
const fresh = items().find((x) => x.id === item.id) ?? item;
const nb = host.querySelector<HTMLElement>(`[data-tool="${CSS.escape(item.id)}"]`) ?? ({ getBoundingClientRect: () => rect } as HTMLElement);
if (fresh.children?.length) this.openFlyout(fresh, nb);
}
/**
* The tool column is centred on the left edge; keep it clear of the top bar
* and of the buttons at the bottom-left, with a gap like the other panels.
*/
/**
* The value panel is centred at the bottom: keep it between the left tool
* columns and the right column / History, wrapping onto more rows if needed.
*/
fitPanel(): void {
if (window.innerWidth <= 720) return void (this.panel.style.maxWidth = "");
const GAP = 12;
const visible = (e: HTMLElement) => !e.hidden && e.childElementCount > 0 && getComputedStyle(e).display !== "none";
const left = Math.max(0, ...[this.toolbar, this.bottomLeft, document.getElementById("undo-dock")!].filter(visible).map((e) => e.getBoundingClientRect().right));
const rights = [this.rightCol, ...(this.historyEl.classList.contains("open") ? [this.historyEl] : [])].map((e) => e.getBoundingClientRect().left);
const right = window.innerWidth - Math.min(window.innerWidth, ...rights);
const reserve = Math.max(left, right) + GAP;
this.panel.style.maxWidth = `${Math.max(260, window.innerWidth - 2 * reserve)}px`;
}
fitToolbar(): void {
if (window.innerWidth <= 720) return void (this.toolbar.style.maxHeight = "");
const GAP = 14;
// Whatever is stacked at the bottom-left (section/measure buttons, the undo dock).
const stack = [this.bottomLeft, document.getElementById("undo-dock")!].filter((e) => e.childElementCount && getComputedStyle(e).display !== "none");
const below = stack.length ? window.innerHeight - Math.min(...stack.map((e) => e.getBoundingClientRect().top)) + GAP : 0;
const above = 52 + GAP;
this.toolbar.style.maxHeight = `${Math.max(160, window.innerHeight - 2 * Math.max(below, above))}px`;
}
/** Back-compat: the context list now lives in the main column. */
setContext(_items: ToolItem[]): void {}
private openFlyout(item: ToolItem, anchor: HTMLElement): void {
if (this.flyoutOwner === item.id) return this.closeFlyout();
this.flyoutOwner = item.id;
// Measure before re-rendering: a nested anchor lives inside this flyout.
const r = anchor.getBoundingClientRect();
this.flyout.innerHTML = "";
renderTools(this.flyout, item.children ?? [], (child, btn) => this.openFlyout(child, btn), () => this.closeFlyout());
// Colour choices show as a grid of circles.
this.flyout.classList.toggle("swatch-grid", !!item.children?.length && item.children.every((c) => c.swatch));
this.flyout.hidden = false;
const narrow = window.innerWidth <= 720;
if (narrow) {
// Above the bottom strip and the buttons stacked over it (undo, section…).
const stack = [this.bottomLeft, document.getElementById("undo-dock")!].filter((e) => e.childElementCount && getComputedStyle(e).display !== "none").map((e) => e.getBoundingClientRect().top);
const above = Math.min(r.top, ...stack.filter((t) => t < r.top));
this.flyout.style.left = "8px";
this.flyout.style.top = "";
this.flyout.style.bottom = `${window.innerHeight - above + 8}px`;
} else {
this.flyout.style.left = `${r.right + 6}px`;
this.flyout.style.bottom = "";
this.flyout.style.top = `${Math.min(r.top, window.innerHeight - this.flyout.offsetHeight - 12)}px`;
}
}
closeFlyout(): void {
this.flyout.hidden = true;
this.flyoutOwner = null;
}
// ------------------------------------------------------------ right column
addRight(id: string, icon: IconName, title: string, open: (host: HTMLElement) => void, label?: () => string): HTMLButtonElement {
const b = document.createElement("button");
b.className = "right-btn";
b.title = title;
b.innerHTML = icons[icon];
if (label) {
const l = document.createElement("span");
l.className = "right-label";
b.append(l);
b.dataset.dynamic = "1";
(b as HTMLButtonElement & { refresh?: () => void }).refresh = () => (l.textContent = label());
(b as HTMLButtonElement & { refresh?: () => void }).refresh!();
}
b.addEventListener("click", () => {
// Popovers stay open until their button is clicked again.
if (this.popoverOwner === id) return this.closePopover();
this.popoverOwner = id;
this.popoverFill = () => {
this.popover.innerHTML = "";
open(this.popover);
};
this.popoverFill();
if (!this.popover.childElementCount) return this.closePopover();
this.popover.hidden = false;
const r = b.getBoundingClientRect();
this.popover.style.top = `${Math.max(8, Math.min(r.top, window.innerHeight - this.popover.offsetHeight - 8))}px`;
this.rightCol.querySelectorAll(".right-btn").forEach((x) => x.classList.toggle("pop-open", x === b));
// Things placed beside the right column (the constraint column) move over.
window.dispatchEvent(new Event("resize"));
});
this.rightCol.append(b);
return b;
}
refreshRight(): void {
this.rightCol.querySelectorAll<HTMLButtonElement & { refresh?: () => void }>("button").forEach((b) => b.refresh?.());
}
private popoverFill: (() => void) | null = null;
closePopover(): void {
if (this.popover.hidden) return;
this.popover.hidden = true;
this.popoverOwner = null;
this.popoverFill = null;
this.rightCol.querySelectorAll(".pop-open").forEach((x) => x.classList.remove("pop-open"));
window.dispatchEvent(new Event("resize"));
}
/** Re-draw the open popover (after one of its choices changed). */
refreshPopover(): void {
this.popoverFill?.();
}
// ------------------------------------------------------- hint/status/toast
setHint(text: string | null): void {
this.hint.textContent = text ?? "";
this.hint.hidden = !text;
}
/** A small persistent note (e.g. "body not closed"), never blocking. */
setWarning(text: string | null): void {
const w = document.getElementById("warn")!;
w.textContent = text ?? "";
w.hidden = !text;
}
setStatus(text: string | null): void {
this.status.textContent = text ?? "";
this.status.hidden = !text;
}
toast(text: string, kind: "info" | "error" = "info"): void {
this.toastEl.textContent = text;
this.toastEl.className = `show ${kind}`;
clearTimeout(this.toastTimer);
this.toastTimer = window.setTimeout(() => (this.toastEl.className = ""), 3600);
}
/** Floating label next to the pointer, e.g. live dimensions while drawing. */
setLabel(x: number, y: number, text: string | null): void {
if (!text) {
this.labelEl.hidden = true;
return;
}
this.labelEl.hidden = false;
// The value, plus a reminder that it can be typed (or how to apply what's typed).
// Callers mark typeable values with a trailing "· type a value".
const value = text.replace(/\s+· type a value$/, "");
const typeable = value !== text;
const typing = value.includes("▌");
const tip = typing ? "Enter ↵ apply · Esc cancel" : typeable ? "⌨ type a value · Enter ↵" : null;
this.labelEl.replaceChildren(el("span", "label-value", value), ...(tip ? [el("span", "label-tip", tip)] : []));
this.labelEl.classList.toggle("typing", typing);
this.labelEl.style.transform = `translate(${Math.round(x + 18)}px, ${Math.round(y + 14)}px)`;
}
/** Small modal form; resolves with the values, or null if cancelled. */
dialog(title: string, fields: { key: string; label: string; value: string; placeholder?: string }[], note?: string): Promise<Record<string, string> | null> {
return new Promise((resolve) => {
const back = el("div", "dialog-back");
const box = el("form", "dialog");
box.append(el("div", "panel-title", title));
if (note) box.append(el("div", "dialog-note", note));
const inputs = fields.map((f) => {
const l = el("label", "dialog-field");
l.append(el("span", "field-label", f.label));
const i = document.createElement("input");
i.value = f.value;
i.placeholder = f.placeholder ?? "";
i.autocomplete = "off";
i.spellcheck = false;
l.append(i);
box.append(l);
return i;
});
const row = el("div", "panel-buttons");
const close = (v: Record<string, string> | null) => {
back.remove();
resolve(v);
};
row.append(textButton("Cancel", "Esc", () => close(null)));
const ok = textButton("OK", "Enter", () => close(Object.fromEntries(fields.map((f, i) => [f.key, inputs[i].value]))), true);
row.append(ok);
box.append(row);
box.addEventListener("submit", (e) => (e.preventDefault(), ok.click()));
// Enter is OK (left to the browser it would "click" the first button: Cancel).
for (const b of row.querySelectorAll("button")) b.type = "button";
box.addEventListener("keydown", (e) => {
if (e.key === "Escape") close(null);
if (e.key === "Enter") (e.preventDefault(), ok.click());
e.stopPropagation();
});
back.append(box);
document.body.append(back);
inputs[0]?.focus();
});
}
// ------------------------------------------------------------------- panel
get panelOpen(): boolean {
return this.panelSpec !== null;
}
showPanel(spec: ValuePanel | null): void {
this.panelSpec = spec;
this.panel.innerHTML = "";
this.panel.hidden = !spec;
if (!spec) return;
queueMicrotask(() => this.fitPanel());
this.panel.append(el("div", "panel-title", spec.title));
const row = el("div", "panel-fields");
const items: PanelItem[] = [
...(spec.fields ?? []).map(
(f): PanelItem => ({ type: "number", label: f.label, value: f.value, kind: f.kind ?? (f.integer ? "int" : f.unit ? "length" : "number"), min: f.min, onInput: f.onInput }),
),
...(spec.items ?? []),
];
let numberIndex = 0;
for (const it of items) {
if (it.type === "number") row.append(this.numberField(it, numberIndex++, spec));
else if (it.type === "slot") {
const b = el("button", `slot${it.active ? " active" : ""}${it.filled ? " filled" : ""}`);
b.append(el("span", "slot-label", it.label), el("span", "slot-value", it.value));
b.addEventListener("click", it.onClick);
row.append(b);
} else if (it.type === "choice") {
const g = el("div", "choice");
if (it.label) g.append(el("span", "field-label", it.label));
for (const o of it.options) {
const b = el("button", o.id === it.value ? "active" : "", o.label);
b.addEventListener("click", () => it.onChange(o.id));
g.append(b);
}
row.append(g);
} else if (it.type === "toggle") {
const b = el("button", `toggle${it.value ? " on" : ""}`, it.label);
b.addEventListener("click", () => it.onChange(!it.value));
row.append(b);
} else {
const b = el("button", "text-btn");
if (it.icon) b.innerHTML = icons[it.icon];
b.append(it.label);
b.addEventListener("click", it.onClick);
row.append(b);
}
}
this.panel.append(row);
const buttons = el("div", "panel-buttons");
for (const a of spec.actions ?? []) {
const b = toolButton(a, true);
b.addEventListener("click", () => a.run?.());
buttons.append(b);
}
if (spec.onCancel) buttons.append(textButton("Cancel", "Esc", spec.onCancel));
if (spec.onDone) buttons.append(textButton("Done", "Enter", spec.onDone, true));
this.panel.append(buttons);
}
private numberField(f: Extract<PanelItem, { type: "number" }>, index: number, spec: ValuePanel): HTMLElement {
const kind = f.kind ?? "length";
const label = el("label", "field");
label.append(el("span", "field-label", f.label));
const input = document.createElement("input");
input.type = "text";
input.inputMode = "decimal";
input.autocomplete = "off";
input.spellcheck = false;
input.value = f.expr ?? shown(f.value, kind);
input.dataset.index = String(index);
input.dataset.kind = kind;
if (f.expr) input.classList.add("has-expr");
const apply = () => {
const v = evaluate(input.value, kind === "length" ? "length" : kind === "angle" ? "angle" : "number");
const ok = v !== null && (f.min === undefined || v >= f.min);
input.classList.toggle("invalid", !ok);
if (!ok) return;
// Text with a variable name stays an expression (parametric); plain numbers don't.
const isExpr = isExpression(input.value);
input.classList.toggle("has-expr", isExpr);
f.onExpr?.(isExpr ? input.value.trim() : null);
f.onInput(kind === "int" ? Math.round(v!) : v!);
};
input.addEventListener("input", apply);
input.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
apply();
spec.onDone?.();
} else if (e.key === "Escape") {
e.preventDefault();
spec.onCancel?.();
} else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
e.preventDefault();
const v = evaluate(input.value, kind === "length" ? "length" : "number") ?? 0;
const step = kind === "length" ? (e.shiftKey ? 10 : 1) : e.shiftKey ? 10 : 1;
const next = v + (e.key === "ArrowUp" ? step : -step) * (kind === "length" ? unitScale() : 1);
input.value = shown(next, kind);
apply();
}
e.stopPropagation();
});
label.append(input);
const unit = kind === "length" ? UNIT_LABEL[units()] : kind === "angle" ? "°" : "";
if (unit) label.append(el("span", "field-unit", unit));
if (f.onExpr && this.variableFactory) {
const fx = el("button", "fx-btn", "ƒx");
fx.title = "Make this value a named variable";
fx.addEventListener("click", async (e) => {
e.preventDefault();
const name = await this.variableFactory!(input.value);
if (!name) return;
input.value = name;
apply();
});
label.append(fx);
}
return label;
}
/** Creates a variable from a field's current text; returns its name (set by the app). */
variableFactory: ((current: string) => Promise<string | null>) | null = null;
/** Update displayed values without rebuilding (keeps focus while dragging). */
updatePanelValues(values: number[]): void {
this.panel.querySelectorAll<HTMLInputElement>("input[data-index]").forEach((input) => {
const v = values[Number(input.dataset.index)];
if (v !== undefined && document.activeElement !== input) input.value = shown(v, input.dataset.kind as FieldKind);
});
}
focusPanel(): void {
// Only focus with a keyboard; on touch it would pop the on-screen keyboard.
if (matchMedia("(pointer: fine)").matches) this.panel.querySelector<HTMLInputElement>("input")?.select();
}
// ----------------------------------------------------------------- history
renderHistory(features: readonly Feature[], errors: FeatureError[], activeId: string | null, h: HistoryHandlers, warnings: Map<string, string> = new Map()): void {
this.historyList.innerHTML = "";
if (features.length === 0) {
this.historyList.append(el("li", "history-empty", "Nothing yet. Start with Sketch."));
return;
}
for (const f of features) {
const li = el("li", "history-item");
const err = errors.find((e) => e.featureId === f.id);
if (err) li.classList.add("error");
if (f.suppressed) li.classList.add("suppressed");
if (f.id === activeId) li.classList.add("active");
const name = el("button", "history-name", f.name);
name.title = err ? err.message : "Edit";
// A step that works but leaves something to look at (e.g. a body that isn't closed).
const warn = warnings.get(f.id);
if (warn && !err) {
const mark = el("span", "history-warn", "!");
mark.title = warn;
name.prepend(mark);
name.title = warn;
}
name.addEventListener("click", () => h.edit(f.id));
li.addEventListener("pointerenter", () => h.hover?.(f.id));
li.addEventListener("pointerleave", () => h.hover?.(null));
const eye = iconButton(f.suppressed ? "eyeOff" : "eye", f.suppressed ? "Enable" : "Suppress", () => h.toggle(f.id));
const del = iconButton("trash", "Delete", () => h.remove(f.id));
li.append(name, eye, del);
if (err) li.append(el("div", "history-error", err.message));
this.historyList.append(li);
// What was done inside a sketch, step by step.
if (f.type === "sketch" && f.log?.length) {
const steps = f.log;
const shownSteps = steps.length > 12 ? steps.slice(-12) : steps;
const sub = el("li", "history-steps");
if (steps.length > shownSteps.length) sub.append(el("div", "history-step more", `… ${steps.length - shownSteps.length} earlier`));
for (const s of shownSteps) {
const row = el("button", "history-step", `${s.op}${s.n > 1 ? ` ×${s.n}` : ""}`);
row.title = "Open the sketch";
row.addEventListener("click", () => h.edit(f.id));
sub.append(row);
}
this.historyList.append(sub);
}
}
}
}
/** Does the text use a variable (a name that isn't a unit suffix)? */
export function isExpression(text: string): boolean {
return /[a-z_]/i.test(text.replace(/(\d|\))\s*(mm|cm|m|in|ft)\b/gi, "$1"));
}
function unitScale(): number {
return { mm: 1, cm: 10, m: 1000, in: 25.4, ft: 304.8 }[units()];
}
function shown(v: number, kind: FieldKind): string {
if (kind === "length") return trim(toDisplay(v), 4);
if (kind === "int") return String(Math.round(v));
return trim(v, 4);
}
function renderTools(host: HTMLElement, items: ToolItem[], onFlyout: (item: ToolItem, btn: HTMLElement) => void, after?: () => void): void {
host.innerHTML = "";
for (const item of items) {
if (item.id.startsWith("---")) {
host.append(el("div", "tool-sep"));
continue;
}
const b = toolButton(item, true);
b.addEventListener("click", (e) => {
e.stopPropagation();
if (item.disabled) return;
if (item.children?.length) onFlyout(item, b);
else {
item.run?.();
after?.();
}
});
host.append(b);
}
}
function toolButton(item: ToolItem, withLabel: boolean): HTMLButtonElement {
const b = document.createElement("button");
b.className = "tool";
b.dataset.tool = item.id;
b.classList.toggle("active", !!item.active);
b.classList.toggle("has-children", !!item.children?.length);
b.classList.toggle("disabled", !!item.disabled);
b.title = item.disabled && item.why ? item.why : item.shortcut ? `${item.label} (${item.shortcut})` : item.label;
b.innerHTML = item.swatch ? `<span class="swatch" style="background:${item.swatch}"></span>` : icons[item.icon];
if (withLabel) {
const l = el("span", "tool-label");
const top = el("span", "tool-name", item.label);
if (item.shortcut) top.append(el("kbd", "", item.shortcut));
l.append(top);
if (item.sub) l.append(el("span", "tool-sub", item.sub));
b.append(l);
}
return b;
}
function iconButton(icon: IconName, title: string, run: () => void): HTMLButtonElement {
const b = document.createElement("button");
b.className = "icon-btn";
b.title = title;
b.innerHTML = icons[icon];
b.addEventListener("click", (e) => {
e.stopPropagation();
run();
});
return b;
}
function textButton(label: string, kbd: string, run: () => void, primary = false): HTMLButtonElement {
const b = document.createElement("button");
b.className = primary ? "text-btn primary" : "text-btn";
b.append(label);
if (matchMedia("(pointer: fine)").matches) b.append(el("kbd", "", kbd));
b.addEventListener("click", run);
return b;
}
export function el<K extends keyof HTMLElementTagNameMap>(tag: K, cls: string, text?: string): HTMLElementTagNameMap[K] {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text) e.textContent = text;
return e;
}
export function fmt(v: number): string {
return String(Math.round(v * 1000) / 1000);
}
+137
View File
@@ -0,0 +1,137 @@
// Length units and expression evaluation for every numeric field.
// Internally everything is millimetres.
import type { Units, Variable } from "./doc/types";
export const UNIT_MM: Record<Units, number> = { mm: 1, cm: 10, m: 1000, in: 25.4, ft: 304.8 };
export const UNIT_LABEL: Record<Units, string> = { mm: "mm", cm: "cm", m: "m", in: "in", ft: "ft" };
let current: Units = "mm";
let variables: Variable[] = [];
export function setUnits(u: Units): void {
current = u;
}
export function units(): Units {
return current;
}
export function setVariables(v: Variable[]): void {
variables = v;
}
/** mm → display string in the current unit. */
export function fmtLen(mm: number, digits = 3): string {
const v = mm / UNIT_MM[current];
return `${trim(v, digits)} ${UNIT_LABEL[current]}`;
}
/** mm → number in the current unit (for input fields). */
export function toDisplay(mm: number): number {
return mm / UNIT_MM[current];
}
export function trim(v: number, digits = 3): string {
const p = Math.pow(10, digits);
return String(Math.round(v * p) / p);
}
/**
* Parse a field value: numbers, + - * / ^ ( ), unit suffixes (25.4mm, 1in,
* 2 ft), and variable names. Plain numbers are in the current unit.
* Returns millimetres for lengths (kind "length"), the raw value otherwise.
*/
export function evaluate(text: string, kind: "length" | "number" | "angle" = "length"): number | null {
try {
const scaleFor = kind === "length" ? UNIT_MM[current] : 1;
const v = new Parser(text, scaleFor, kind === "length", 0).parse();
return Number.isFinite(v) ? v : null;
} catch {
return null;
}
}
class Parser {
private i = 0;
constructor(
private s: string,
private defaultScale: number,
private lengths: boolean,
private depth: number,
) {}
parse(): number {
const v = this.expr();
this.ws();
if (this.i < this.s.length) throw new Error("Unexpected input");
return v;
}
private ws() {
while (this.s[this.i] === " ") this.i++;
}
private expr(): number {
let v = this.term();
for (;;) {
this.ws();
const c = this.s[this.i];
if (c === "+") (this.i++, (v += this.term()));
else if (c === "-") (this.i++, (v -= this.term()));
else return v;
}
}
private term(): number {
let v = this.factor();
for (;;) {
this.ws();
const c = this.s[this.i];
// Multiplying/dividing two lengths would square units; treat the right side as a plain number.
if (c === "*") (this.i++, (v *= this.factor() / (this.lengths ? this.defaultScale : 1)));
else if (c === "/") (this.i++, (v /= this.factor() / (this.lengths ? this.defaultScale : 1)));
else return v;
}
}
private factor(): number {
this.ws();
const c = this.s[this.i];
if (c === "-") {
this.i++;
return -this.factor();
}
if (c === "(") {
this.i++;
const v = this.expr();
this.ws();
if (this.s[this.i++] !== ")") throw new Error("Missing )");
// Already in mm; a suffix re-interprets the bracketed number in that unit.
return this.unit(v / this.defaultScale);
}
const num = /^\d*\.?\d+(e[-+]?\d+)?/i.exec(this.s.slice(this.i));
if (num) {
this.i += num[0].length;
return this.unit(parseFloat(num[0]));
}
const name = /^[a-z_][a-z0-9_]*/i.exec(this.s.slice(this.i));
if (name) {
this.i += name[0].length;
const variable = variables.find((x) => x.name === name[0]);
if (!variable || this.depth > 8) throw new Error(`Unknown variable ${name[0]}`);
return new Parser(variable.expr, this.defaultScale, this.lengths, this.depth + 1).parse();
}
throw new Error("Expected a number");
}
/** Apply an optional unit suffix; no suffix = current unit. */
private unit(v: number): number {
this.ws();
const m = /^(mm|cm|m|in|ft|"|')(?![a-z])/i.exec(this.s.slice(this.i));
if (m && this.lengths) {
this.i += m[0].length;
const u = m[0] === '"' ? "in" : m[0] === "'" ? "ft" : (m[0].toLowerCase() as Units);
return v * UNIT_MM[u];
}
return v * this.defaultScale;
}
}
+265
View File
@@ -0,0 +1,265 @@
import { Box3, MathUtils, OrthographicCamera, PerspectiveCamera, Quaternion, Vector3, type Camera } from "three";
import type { SavedView, Vec3 } from "../doc/types";
const UP = new Vector3(0, 0, 1);
const FOV = 40;
/**
* Z-up orbit camera: azimuth around Z, elevation above the XY plane.
* Perspective and orthographic share target/distance, so switching is seamless.
*/
export class CameraController {
readonly persp: PerspectiveCamera;
readonly orthoCam: OrthographicCamera;
ortho = false;
target = new Vector3(0, 0, 0);
distance = 300;
azimuth = MathUtils.degToRad(-60);
elevation = MathUtils.degToRad(30);
/** Roll around the view direction (used for face-on views, rotated 90° steps). */
roll = 0;
animate = true;
/** A chosen point to orbit around (else the view turns about its target). Zoom to fit clears it. */
pivot: Vector3 | null = null;
private aspect = 1;
private animation: { from: ViewState; to: ViewState; t0: number } | null = null;
constructor(aspect: number) {
this.persp = new PerspectiveCamera(FOV, aspect, 0.1, 1e7);
this.orthoCam = new OrthographicCamera(-1, 1, 1, -1, -1e7, 1e7);
this.aspect = aspect;
this.update();
}
get camera(): PerspectiveCamera | OrthographicCamera {
return this.ortho ? this.orthoCam : this.persp;
}
setAspect(a: number): void {
this.aspect = a;
this.update();
}
setOrtho(on: boolean): void {
this.ortho = on;
this.update();
}
orbit(dxPx: number, dyPx: number): void {
this.animation = null;
this.roll = 0;
const az0 = this.azimuth;
const el0 = this.elevation;
this.azimuth -= dxPx * 0.006;
this.elevation = MathUtils.clamp(this.elevation + dyPx * 0.006, -Math.PI / 2 + 1e-4, Math.PI / 2 - 1e-4);
if (this.pivot) {
// Turn the target about the pivot the same way the view turned, so the
// pivot stays put on screen: first about Z (azimuth), then about the
// view's sideways axis (elevation).
const right0 = new Vector3(-Math.sin(az0), Math.cos(az0), 0);
const qEl = new Quaternion().setFromAxisAngle(right0, -(this.elevation - el0));
const qAz = new Quaternion().setFromAxisAngle(UP, this.azimuth - az0);
const rel = this.target.clone().sub(this.pivot).applyQuaternion(qEl).applyQuaternion(qAz);
this.target.copy(this.pivot).add(rel);
}
this.update();
}
/** Pan so the scene follows the pointer. */
pan(dxPx: number, dyPx: number, viewportHeight: number): void {
this.animation = null;
const worldPerPx = this.worldPerPixel(viewportHeight);
const right = new Vector3().setFromMatrixColumn(this.camera.matrixWorld, 0);
const up = new Vector3().setFromMatrixColumn(this.camera.matrixWorld, 1);
this.target.addScaledVector(right, -dxPx * worldPerPx).addScaledVector(up, dyPx * worldPerPx);
this.update();
}
/** factor < 1 zooms in. `toward` keeps that world point under the pointer. */
zoom(factor: number, toward?: Vector3): void {
this.animation = null;
// 0.001 mm … 1 000 000 mm scenes.
const newDist = MathUtils.clamp(this.distance * factor, 0.005, 5e6);
// A point far off (the ground at the horizon, a bad hit) would fling the
// target away: zoom straight in instead.
if (toward && (!Number.isFinite(toward.x + toward.y + toward.z) || toward.distanceTo(this.target) > this.distance * 20)) toward = undefined;
if (toward) {
const k = 1 - newDist / this.distance;
if (this.ortho) {
// In ortho, only move sideways (depth doesn't change what's under the cursor).
const view = this.viewDir();
const t = toward.clone().sub(this.target);
t.addScaledVector(view, -t.dot(view));
this.target.addScaledVector(t, k);
} else {
this.target.lerp(toward, k);
}
}
this.distance = newDist;
this.update();
}
worldPerPixel(viewportHeight: number): number {
return (2 * this.distance * Math.tan(MathUtils.degToRad(FOV / 2))) / viewportHeight;
}
/** Unit vector from the camera towards the target. */
viewDir(): Vector3 {
return this.target.clone().sub(this.camera.position).normalize();
}
/**
* Look along -normal at the target. `xDir` (optional) is the world direction
* that should point right on screen, e.g. a sketch plane's x axis.
*/
lookAlong(normal: Vec3, xDir?: Vec3, target?: Vec3): void {
const n = new Vector3(...normal).normalize();
const to = this.state();
if (target) to.target = new Vector3(...target);
to.elevation = MathUtils.clamp(Math.asin(n.z), -Math.PI / 2 + 1e-4, Math.PI / 2 - 1e-4);
to.roll = 0;
const x = new Vector3(...(xDir ?? [1, 0, 0]));
if (Math.abs(n.z) > 0.999) {
// Top/bottom: at the poles the screen's right is (-sin a, cos a, 0).
to.azimuth = Math.atan2(-x.x, x.y);
} else {
to.azimuth = Math.atan2(n.y, n.x);
if (xDir) {
// Tilted planes: roll so xDir points right on screen.
const d = new Vector3(...normal).normalize();
const right = new Vector3().crossVectors(UP, d).normalize();
const up = new Vector3().crossVectors(d, right);
to.roll = Math.atan2(x.dot(up), x.dot(right));
}
}
this.go(to);
}
/** Rotate the view 90° around the view direction (view cube arrows). */
rollBy(rad: number): void {
const to = this.state();
to.roll += rad;
this.go(to);
}
iso(): void {
this.go({ ...this.state(), azimuth: MathUtils.degToRad(-60), elevation: MathUtils.degToRad(30), roll: 0 });
}
fit(box: Box3, animate = true): void {
this.pivot = null;
const finite = (v: Vector3) => Number.isFinite(v.x) && Number.isFinite(v.y) && Number.isFinite(v.z);
if (box.isEmpty() || !finite(box.min) || !finite(box.max)) box = new Box3(new Vector3(-50, -50, 0), new Vector3(50, 50, 20));
const size = box.getSize(new Vector3()).length();
const center = box.getCenter(new Vector3());
// Fit the tighter of the vertical and horizontal fields of view (portrait phones).
const tanV = Math.tan(MathUtils.degToRad(FOV / 2));
const tanH = tanV * this.aspect;
const distance = (Math.max(size, 0.01) / (2 * Math.min(tanV, tanH))) * 1.15;
const to = { ...this.state(), target: center, distance };
if (animate) this.go(to);
else this.applyState(to);
}
savedView(name: string): SavedView {
return { name, target: this.target.toArray() as Vec3, distance: this.distance, azimuth: this.azimuth, elevation: this.elevation, ortho: this.ortho };
}
restore(v: SavedView): void {
this.ortho = v.ortho;
this.go({ target: new Vector3(...v.target), distance: v.distance, azimuth: v.azimuth, elevation: v.elevation, roll: 0 });
}
/** Advance animations; returns true while animating. */
tick(now: number): boolean {
if (!this.animation) return false;
const { from, to, t0 } = this.animation;
const t = Math.min(1, (now - t0) / 380);
const e = t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2;
let dAz = to.azimuth - from.azimuth;
dAz = Math.atan2(Math.sin(dAz), Math.cos(dAz));
let dRoll = to.roll - from.roll;
dRoll = Math.atan2(Math.sin(dRoll), Math.cos(dRoll));
this.applyState(
{
target: from.target.clone().lerp(to.target, e),
distance: MathUtils.lerp(from.distance, to.distance, e),
azimuth: from.azimuth + dAz * e,
elevation: MathUtils.lerp(from.elevation, to.elevation, e),
roll: from.roll + dRoll * e,
},
);
if (t >= 1) this.animation = null;
return true;
}
get animating(): boolean {
return this.animation !== null;
}
private state(): ViewState {
return { target: this.target.clone(), distance: this.distance, azimuth: this.azimuth, elevation: this.elevation, roll: this.roll };
}
private go(to: ViewState): void {
if (!this.animate) {
this.applyState(to);
return;
}
this.animation = { from: this.state(), to, t0: performance.now() };
}
private applyState(s: ViewState): void {
// Never take a broken view (NaN/Infinity would blank everything, grid included).
const ok = [s.target.x, s.target.y, s.target.z, s.distance, s.azimuth, s.elevation, s.roll].every(Number.isFinite) && s.distance > 0;
if (!ok) return;
this.target.copy(s.target);
this.distance = s.distance;
this.azimuth = s.azimuth;
this.elevation = s.elevation;
this.roll = s.roll;
this.update();
}
/** The last view that was valid: restored if something ever corrupts it. */
private good: ViewState | null = null;
update(): void {
const valid = [this.target.x, this.target.y, this.target.z, this.distance, this.azimuth, this.elevation, this.roll].every(Number.isFinite) && this.distance > 0;
if (!valid) {
const g = this.good ?? { target: new Vector3(), distance: 300, azimuth: MathUtils.degToRad(-60), elevation: MathUtils.degToRad(30), roll: 0 };
this.target.copy(g.target);
Object.assign(this, { distance: g.distance, azimuth: g.azimuth, elevation: g.elevation, roll: g.roll });
this.animation = null;
} else this.good = this.state();
const ce = Math.cos(this.elevation);
const dir = new Vector3(ce * Math.cos(this.azimuth), ce * Math.sin(this.azimuth), Math.sin(this.elevation));
for (const cam of [this.persp, this.orthoCam] as Camera[]) {
cam.position.copy(this.target).addScaledVector(dir, this.distance);
cam.up.copy(UP);
// Near the poles, derive "up" from the azimuth so the view doesn't spin.
if (Math.abs(dir.z) > 0.99) cam.up.set(-Math.cos(this.azimuth) * Math.sign(dir.z), -Math.sin(this.azimuth) * Math.sign(dir.z), 0);
cam.lookAt(this.target);
if (this.roll) cam.rotateZ(this.roll);
}
this.persp.aspect = this.aspect;
this.persp.near = Math.max(1e-4, this.distance / 2000);
this.persp.far = this.distance * 2000;
this.persp.updateProjectionMatrix();
const h = this.distance * Math.tan(MathUtils.degToRad(FOV / 2));
Object.assign(this.orthoCam, { left: -h * this.aspect, right: h * this.aspect, top: h, bottom: -h });
this.orthoCam.near = -this.distance * 1000;
this.orthoCam.far = this.distance * 1000;
this.orthoCam.updateProjectionMatrix();
this.persp.updateMatrixWorld();
this.orthoCam.updateMatrixWorld();
}
}
interface ViewState {
target: Vector3;
distance: number;
azimuth: number;
elevation: number;
roll: number;
}
+107
View File
@@ -0,0 +1,107 @@
import { DoubleSide, Matrix4, Mesh, PlaneGeometry, ShaderMaterial, Vector3 } from "three";
import type { PlaneDef } from "../doc/types";
import { planeY } from "../geom";
/**
* Infinite-looking grid that adapts its spacing to the zoom level (powers of
* ten, 0.001 mm … 1 000 000 mm), or stays at a locked step. It lies on the
* ground, or on the active sketch plane while sketching.
*/
export class AdaptiveGrid {
readonly mesh: Mesh;
/** Current minor step in mm (also used for grid snapping). */
step = 1;
locked = false;
lockedStep = 1;
private plane: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
private material: ShaderMaterial;
constructor() {
this.material = new ShaderMaterial({
transparent: true,
depthWrite: false,
side: DoubleSide,
uniforms: {
uStep: { value: 1 },
uFade: { value: 0 },
uCenter: { value: [0, 0] },
uRadius: { value: 100 },
// Quad centre (u, v) on the plane and its size: turns quad coords into plane coords.
uLocal: { value: [0, 0, 1] },
},
vertexShader: /* glsl */ `
uniform vec3 uLocal;
varying vec2 vUv;
void main() {
vUv = uLocal.xy + position.xy * uLocal.z;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}`,
fragmentShader: /* glsl */ `
uniform float uStep;
uniform float uFade;
uniform vec2 uCenter;
uniform float uRadius;
varying vec2 vUv;
float lines(vec2 p, float s) {
vec2 g = abs(fract(p / s - 0.5) - 0.5) / fwidth(p / s);
return 1.0 - min(min(g.x, g.y), 1.0);
}
void main() {
vec2 p = vUv;
float minor = lines(p, uStep) * (1.0 - uFade);
float mid = lines(p, uStep * 10.0);
float major = lines(p, uStep * 100.0);
float a = max(max(minor * 0.22, mid * 0.38), major * 0.55);
float d = length(p - uCenter) / uRadius;
a *= 1.0 - smoothstep(0.55, 1.0, d);
if (a < 0.01) discard;
gl_FragColor = vec4(vec3(0.78), a);
}`,
});
this.mesh = new Mesh(new PlaneGeometry(1, 1), this.material);
this.mesh.renderOrder = -1;
this.mesh.matrixAutoUpdate = false;
this.mesh.frustumCulled = false;
}
setPlane(p: PlaneDef): void {
this.plane = p;
}
/** Recompute spacing and placement for the current view. */
update(worldPerPixel: number, target: Vector3, distance: number, eye?: Vector3): void {
let fade = 0;
if (this.locked) {
this.step = this.lockedStep;
} else {
// Minor lines at least ~10 px apart; fade them in as they get there.
const raw = worldPerPixel * 10;
const exp = Math.log10(raw);
this.step = Math.pow(10, Math.ceil(exp));
fade = 1 - (Math.ceil(exp) - exp);
fade = Math.max(0, Math.min(1, (fade - 0.6) / 0.4));
}
const n = new Vector3(...this.plane.normal);
const x = new Vector3(...this.plane.xDir);
const y = new Vector3(...planeY(this.plane));
const o = new Vector3(...this.plane.origin);
// Centre the quad under the camera target (projected on the plane).
const rel = target.clone().sub(o);
const cu = rel.dot(x);
const cv = rel.dot(y);
// Big enough to reach the horizon from where the camera is (it can sit far
// above the plane while its target is close, after zooming towards a point).
const height = eye ? Math.abs(eye.clone().sub(o).dot(n)) : 0;
const size = Math.max(distance * 6, height * 12, this.step * 400);
// The quad spans local coords [cu ± size/2]; vUv carries plane coordinates.
const m = new Matrix4().makeBasis(x, y, n).setPosition(o);
const local = new Matrix4().makeScale(size, size, 1).setPosition(cu, cv, 0);
this.mesh.matrix.copy(m.multiply(local));
this.mesh.matrixWorldNeedsUpdate = true;
this.material.uniforms.uStep.value = this.step;
this.material.uniforms.uFade.value = fade;
this.material.uniforms.uCenter.value = [cu, cv];
this.material.uniforms.uRadius.value = size / 2;
this.material.uniforms.uLocal.value = [cu, cv, size];
}
}
+285
View File
@@ -0,0 +1,285 @@
// One input model for mouse, touch and pen (see docs/ARCHITECTURE.md §5).
import type { Viewport } from "./viewport";
export interface ToolPointer {
x: number;
y: number;
type: "mouse" | "pen" | "touch";
shift: boolean;
/** Ctrl/Cmd/Shift held at press: add to the selection. */
add?: boolean;
/** Pick tolerance in px; fingers are fat. */
tol: number;
}
export interface PointerHandler {
/** Return true to capture the drag (e.g. grabbed a handle, started drawing). */
down?(p: ToolPointer): boolean;
drag?(p: ToolPointer): void;
up?(p: ToolPointer): void;
tap?(p: ToolPointer, count: number): void;
hover?(p: ToolPointer | null): void;
/** Right-click without dragging (e.g. end a line chain). */
context?(p: ToolPointer): void;
/**
* The pointer moved past the tap slop without `down` capturing it: return
* true to take this as a drag of what was under the press (`from`), so a
* plain tap on the same thing still selects it.
*/
dragStart?(from: ToolPointer): boolean;
/** Box (window) selection with mouse/pen; `final` on release. */
box?(a: { x: number; y: number }, b: { x: number; y: number }, final: boolean, add: boolean): void;
}
const TAP_SLOP = { mouse: 4, pen: 6, touch: 10 };
const DOUBLE_TAP_MS = 350;
interface Tracked {
id: number;
type: ToolPointer["type"];
x0: number;
y0: number;
x: number;
y: number;
button: number;
shift: boolean;
}
export class InputRouter {
handler: PointerHandler = {};
private pointers = new Map<number, Tracked>();
private mode: "idle" | "pending" | "captured" | "orbit" | "pan" | "pinch" | "box" | "ended" | "rpending" = "idle";
/** A tool is holding a drag (keys typed now go to it). */
get dragging(): boolean {
return this.mode === "captured";
}
/** The drag was finished from the keyboard: ignore the rest until release. */
endDrag(): void {
if (this.mode === "captured") this.mode = "ended";
}
private marquee = document.createElement("div");
private modifiers = false;
private penDown = false;
private lastPinch: { d: number; cx: number; cy: number } | null = null;
private lastTap = { t: 0, x: 0, y: 0, count: 0 };
constructor(private view: Viewport) {
const el = view.canvas;
el.style.touchAction = "none";
this.marquee.id = "marquee";
this.marquee.hidden = true;
document.body.append(this.marquee);
el.addEventListener("pointerdown", (e) => this.onDown(e));
el.addEventListener("pointermove", (e) => this.onMove(e));
el.addEventListener("pointerup", (e) => this.onUp(e));
el.addEventListener("pointercancel", (e) => this.onCancel(e));
el.addEventListener("pointerleave", (e) => {
if (e.pointerType !== "touch" && this.mode === "idle") this.handler.hover?.(null);
});
el.addEventListener("contextmenu", (e) => e.preventDefault());
el.addEventListener("wheel", (e) => this.onWheel(e), { passive: false });
// Stop iPad Safari's own gestures (Scribble, magnifier, page zoom) on the canvas.
el.addEventListener("touchstart", (e) => e.preventDefault(), { passive: false });
el.addEventListener("gesturestart", (e) => e.preventDefault());
}
private local(e: PointerEvent | WheelEvent): [number, number] {
const r = this.view.canvas.getBoundingClientRect();
return [e.clientX - r.left, e.clientY - r.top];
}
private tp(t: Tracked): ToolPointer {
return { x: t.x, y: t.y, type: t.type, shift: t.shift, add: this.modifiers, tol: t.type === "touch" ? 18 : 8 };
}
private onDown(e: PointerEvent): void {
const type = e.pointerType as ToolPointer["type"];
// Palm rejection: while the pen touches the screen, ignore fingers.
if (type === "touch" && this.penDown) return;
if (type === "pen") this.penDown = true;
try {
this.view.canvas.setPointerCapture(e.pointerId);
} catch {
// Synthetic/expired pointers can't be captured; tracking still works.
}
const [x, y] = this.local(e);
const t: Tracked = { id: e.pointerId, type, x0: x, y0: y, x, y, button: e.button, shift: e.shiftKey };
this.pointers.set(e.pointerId, t);
if (type === "touch" && this.pointers.size === 2) {
// Second finger: abandon whatever the first finger was doing and pinch.
if (this.mode === "captured") this.handler.up?.(this.tp(t));
this.mode = "pinch";
this.lastPinch = this.pinchState();
return;
}
if (this.pointers.size > 1) return;
// Mouse: right-drag orbits, middle-drag (or shift+right) pans, alt+left orbits (trackpads).
if (type === "mouse" && (e.button === 1 || (e.button === 2 && e.shiftKey))) {
this.mode = "pan";
return;
}
// Right button: a drag orbits, a click is a "context" action (decided on move/up).
if (type === "mouse" && e.button === 2) {
this.mode = "rpending";
return;
}
if (type === "mouse" && e.button === 0 && e.altKey) {
this.mode = "orbit";
return;
}
this.modifiers = e.ctrlKey || e.metaKey || e.shiftKey;
if (this.handler.down?.(this.tp(t))) {
this.mode = "captured";
return;
}
this.mode = "pending";
}
private onMove(e: PointerEvent): void {
const [x, y] = this.local(e);
const t = this.pointers.get(e.pointerId);
if (!t) {
if (e.pointerType !== "touch" && this.mode === "idle") {
// At most one hover pick per frame: mice report far more often than the screen redraws.
this.hoverAt = { x, y, type: e.pointerType as ToolPointer["type"], shift: e.shiftKey, tol: 8 };
this.hoverFrame ||= requestAnimationFrame(() => {
this.hoverFrame = 0;
if (this.hoverAt && this.mode === "idle") this.handler.hover?.(this.hoverAt);
});
}
return;
}
const dx = x - t.x;
const dy = y - t.y;
t.x = x;
t.y = y;
t.shift = e.shiftKey;
switch (this.mode) {
case "rpending":
if (Math.hypot(x - t.x0, y - t.y0) >= TAP_SLOP.mouse) this.mode = "orbit";
return;
case "pending": {
if (Math.hypot(x - t.x0, y - t.y0) < TAP_SLOP[t.type]) return;
if (this.handler.dragStart?.({ ...this.tp(t), x: t.x0, y: t.y0 })) {
this.mode = "captured";
this.handler.drag?.(this.tp(t));
return;
}
// Mouse/pen drag on empty space = box selection; a finger orbits.
this.mode = t.type !== "touch" && this.handler.box ? "box" : "orbit";
return;
}
case "box": {
const a = { x: t.x0, y: t.y0 };
const b = { x, y };
const r = this.view.canvas.getBoundingClientRect();
Object.assign(this.marquee.style, {
left: `${r.left + Math.min(a.x, b.x)}px`,
top: `${r.top + Math.min(a.y, b.y)}px`,
width: `${Math.abs(b.x - a.x)}px`,
height: `${Math.abs(b.y - a.y)}px`,
});
this.marquee.hidden = false;
this.handler.box?.(a, b, false, this.modifiers);
return;
}
case "captured":
this.handler.drag?.(this.tp(t));
return;
case "orbit":
this.view.cam.orbit(dx, dy);
this.view.requestRender();
return;
case "pan":
this.view.cam.pan(dx, dy, this.view.height);
this.view.requestRender();
return;
case "pinch": {
const s = this.pinchState();
if (!s || !this.lastPinch) return;
this.view.cam.pan(s.cx - this.lastPinch.cx, s.cy - this.lastPinch.cy, this.view.height);
if (s.d > 0 && this.lastPinch.d > 0) {
this.view.cam.zoom(this.lastPinch.d / s.d, this.view.worldUnder(s.cx, s.cy));
}
this.lastPinch = s;
this.view.requestRender();
return;
}
}
}
private onUp(e: PointerEvent): void {
const t = this.pointers.get(e.pointerId);
if (e.pointerType === "pen") this.penDown = false;
if (!t) return;
this.pointers.delete(e.pointerId);
if (this.mode === "pinch") {
// Lifting one finger of a pinch must not orbit with the remaining one.
if (this.pointers.size === 0) this.mode = "idle";
else this.lastPinch = null;
return;
}
if (this.pointers.size > 0) return;
const mode = this.mode;
this.mode = "idle";
if (mode === "captured") this.handler.up?.(this.tp(t));
if (mode === "pending") this.emitTap(t);
if (mode === "rpending") this.handler.context?.(this.tp(t));
if (mode === "box") {
this.marquee.hidden = true;
this.handler.box?.({ x: t.x0, y: t.y0 }, { x: t.x, y: t.y }, true, this.modifiers);
}
}
private onCancel(e: PointerEvent): void {
if (e.pointerType === "pen") this.penDown = false;
const t = this.pointers.get(e.pointerId);
this.pointers.delete(e.pointerId);
if (this.pointers.size === 0) {
if (this.mode === "captured" && t) this.handler.up?.(this.tp(t));
this.mode = "idle";
}
}
private hoverAt: ToolPointer | null = null;
private hoverFrame = 0;
private emitTap(t: Tracked): void {
const now = performance.now();
const near = Math.hypot(t.x - this.lastTap.x, t.y - this.lastTap.y) < 20;
const count = now - this.lastTap.t < DOUBLE_TAP_MS && near ? this.lastTap.count + 1 : 1;
this.lastTap = { t: now, x: t.x, y: t.y, count };
this.handler.tap?.(this.tp(t), count);
}
private pinchState(): { d: number; cx: number; cy: number } | null {
const pts = [...this.pointers.values()];
if (pts.length < 2) return null;
const [a, b] = pts;
return { d: Math.hypot(a.x - b.x, a.y - b.y), cx: (a.x + b.x) / 2, cy: (a.y + b.y) / 2 };
}
private onWheel(e: WheelEvent): void {
e.preventDefault();
const [x, y] = this.local(e);
if (e.ctrlKey || !isTrackpadPan(e)) {
// Mouse wheel, or trackpad pinch (reported as ctrl+wheel).
const factor = Math.exp(e.deltaY * (e.ctrlKey ? 0.01 : 0.0015));
this.view.cam.zoom(factor, this.view.worldUnder(x, y));
} else {
this.view.cam.pan(-e.deltaX, -e.deltaY, this.view.height);
}
this.view.requestRender();
}
}
/** Trackpads send pixel deltas with horizontal components; wheels send lines or big steps. */
function isTrackpadPan(e: WheelEvent): boolean {
return e.deltaMode === 0 && e.deltaX !== 0;
}
+232
View File
@@ -0,0 +1,232 @@
import {
AmbientLight,
BoxGeometry,
CanvasTexture,
DirectionalLight,
EdgesGeometry,
Group,
LineBasicMaterial,
LineSegments,
Matrix4,
Mesh,
MeshBasicMaterial,
MeshLambertMaterial,
OrthographicCamera,
PlaneGeometry,
Raycaster,
Scene,
SRGBColorSpace,
Vector2,
Vector3,
WebGLRenderer,
} from "three";
import type { Vec3 } from "../doc/types";
import type { Viewport } from "./viewport";
const PX = 110;
interface FaceDef {
label: string;
n: Vec3;
/** Screen-right and screen-up directions when looking at the face (Z-up world). */
u: Vec3;
up: Vec3;
}
const FACES: FaceDef[] = [
{ label: "TOP", n: [0, 0, 1], u: [1, 0, 0], up: [0, 1, 0] },
{ label: "BOTTOM", n: [0, 0, -1], u: [1, 0, 0], up: [0, -1, 0] },
{ label: "FRONT", n: [0, -1, 0], u: [1, 0, 0], up: [0, 0, 1] },
{ label: "BACK", n: [0, 1, 0], u: [-1, 0, 0], up: [0, 0, 1] },
{ label: "RIGHT", n: [1, 0, 0], u: [0, 1, 0], up: [0, 0, 1] },
{ label: "LEFT", n: [-1, 0, 0], u: [0, -1, 0], up: [0, 0, 1] },
];
/**
* View cube rendered with its own tiny three.js scene, rotated with the main
* camera. Click a face, edge or corner (26 zones) to look from there; drag to orbit.
*/
export class ViewCube {
readonly el: HTMLElement;
private canvas: HTMLCanvasElement;
private renderer: WebGLRenderer;
private scene = new Scene();
private camera = new OrthographicCamera(-1.05, 1.05, 1.05, -1.05, 0.1, 10);
private faces: Mesh[] = [];
private hover = new Mesh(new PlaneGeometry(1, 1), new MeshBasicMaterial({ color: 0x3d8bff, transparent: true, opacity: 0.55, depthTest: false }));
private raycaster = new Raycaster();
private lastKey = "";
private dragged = false;
constructor(private view: Viewport) {
this.el = document.createElement("div");
this.el.id = "viewcube";
this.canvas = document.createElement("canvas");
this.canvas.style.width = this.canvas.style.height = `${PX}px`;
this.el.append(this.canvas);
this.renderer = new WebGLRenderer({ canvas: this.canvas, antialias: true, alpha: true });
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.setSize(PX, PX, false);
const cube = new Group();
for (const f of FACES) {
const mesh = new Mesh(new PlaneGeometry(1, 1), new MeshLambertMaterial({ map: labelTexture(f.label) }));
mesh.matrixAutoUpdate = false;
mesh.matrix.copy(basis(f.u, f.up, f.n).setPosition(new Vector3(...f.n).multiplyScalar(0.5)));
cube.add(mesh);
this.faces.push(mesh);
}
const edges = new LineSegments(new EdgesGeometry(new BoxGeometry(1, 1, 1)), new LineBasicMaterial({ color: 0x8b93a3 }));
cube.add(edges);
// Small world axes at the cube's corner.
for (const [d, c] of [[[1, 0, 0], 0xe0584f], [[0, 1, 0], 0x5fbf5a], [[0, 0, 1], 0x4f8ce0]] as [Vec3, number][]) {
const g = new BoxGeometry(d[0] ? 0.55 : 0.025, d[1] ? 0.55 : 0.025, d[2] ? 0.55 : 0.025);
const m = new Mesh(g, new MeshBasicMaterial({ color: c }));
m.position.set(-0.5 + d[0] * 0.275, -0.5 + d[1] * 0.275, -0.5 + d[2] * 0.275);
cube.add(m);
}
this.hover.visible = false;
this.hover.matrixAutoUpdate = false;
this.hover.renderOrder = 5;
this.scene.add(cube, this.hover, new AmbientLight(0xffffff, 1.6));
const light = new DirectionalLight(0xffffff, 1.2);
light.position.set(0.5, -1, 2);
this.camera.add(light);
this.scene.add(this.camera);
const rollL = button("⟲", "Rotate view 90° left", () => view.cam.rollBy(Math.PI / 2));
const rollR = button("⟳", "Rotate view 90° right", () => view.cam.rollBy(-Math.PI / 2));
rollL.className = "vc-roll left";
rollR.className = "vc-roll right";
this.el.append(rollL, rollR);
this.wire();
view.frameHooks.add(() => this.render());
}
private wire(): void {
let last: { x: number; y: number } | null = null;
this.canvas.addEventListener("pointerdown", (e) => {
last = { x: e.clientX, y: e.clientY };
this.dragged = false;
this.canvas.setPointerCapture(e.pointerId);
});
this.canvas.addEventListener("pointermove", (e) => {
if (last) {
const dx = e.clientX - last.x;
const dy = e.clientY - last.y;
if (Math.abs(dx) + Math.abs(dy) > 1) this.dragged = true;
if (this.dragged) {
this.view.cam.orbit(dx * 2, dy * 2);
this.view.requestRender();
}
last = { x: e.clientX, y: e.clientY };
return;
}
this.setHover(this.zoneAt(e));
});
this.canvas.addEventListener("pointerleave", () => this.setHover(null));
this.canvas.addEventListener("pointerup", (e) => {
last = null;
if (this.dragged) return;
const zone = this.zoneAt(e);
if (!zone) return;
const face = FACES.find((f) => f.n.every((v, i) => v === zone[i]));
const n = new Vector3(...zone).normalize().toArray() as Vec3;
// Faces get an upright view; edges/corners keep the current spin.
this.view.cam.lookAlong(n, face?.u);
this.view.requestRender();
});
}
/** Zone under the pointer as a vector of -1/0/1 per axis (face, edge or corner). */
private zoneAt(e: PointerEvent): Vec3 | null {
const r = this.canvas.getBoundingClientRect();
const ndc = new Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1);
this.raycaster.setFromCamera(ndc, this.camera);
const hit = this.raycaster.intersectObjects(this.faces, false)[0];
if (!hit) return null;
const p = hit.point;
// Matches the texture: outer 0.2 of each face is an edge/corner band.
const z = (v: number) => (v > 0.3 ? 1 : v < -0.3 ? -1 : 0);
return [z(p.x), z(p.y), z(p.z)];
}
private setHover(zone: Vec3 | null): void {
this.hover.visible = !!zone;
this.canvas.style.cursor = zone ? "pointer" : "grab";
if (zone) {
// A small tile at the zone, on the face of the axis with a ±1 that faces us most.
const n = new Vector3(...zone);
const dir = new Vector3(0, 0, 1).applyQuaternion(this.camera.quaternion);
const axes = [0, 1, 2].filter((i) => zone[i] !== 0).sort((a, b) => Math.abs(dir.getComponent(b)) - Math.abs(dir.getComponent(a)));
const k = axes[0];
const f = FACES.find((x) => x.n[k] === zone[k])!;
// Matches zoneAt(): the middle 0.6 of each axis is "face", the outer 0.2 "edge".
const size = [0, 1, 2].map((i) => (zone[i] === 0 ? 0.6 : 0.2));
const center = n.clone().multiplyScalar(0.4);
center.setComponent(k, zone[k] * 0.502);
const u = new Vector3(...f.u);
const up = new Vector3(...f.up);
const su = Math.abs(u.dot(new Vector3(size[0], size[1], size[2])));
const sv = Math.abs(up.dot(new Vector3(size[0], size[1], size[2])));
this.hover.matrix.copy(basis(f.u, f.up, f.n).multiply(new Matrix4().makeScale(su, sv, 1)).setPosition(center));
}
this.lastKey = "";
}
private render(): void {
const main = this.view.camera;
const key = main.quaternion.toArray().map((x) => x.toFixed(4)).join() + this.hover.visible + this.hover.matrix.elements[12];
if (key === this.lastKey) return;
this.lastKey = key;
this.camera.quaternion.copy(main.quaternion);
this.camera.position.set(0, 0, 3).applyQuaternion(main.quaternion);
this.camera.updateMatrixWorld();
this.renderer.render(this.scene, this.camera);
}
}
function basis(u: Vec3, up: Vec3, n: Vec3): Matrix4 {
return new Matrix4().makeBasis(new Vector3(...u), new Vector3(...up), new Vector3(...n));
}
function labelTexture(text: string): CanvasTexture {
const c = document.createElement("canvas");
c.width = c.height = 128;
const g = c.getContext("2d")!;
g.fillStyle = "#4a505c";
g.fillRect(0, 0, 128, 128);
g.strokeStyle = "#6b7383";
g.lineWidth = 6;
g.strokeRect(3, 3, 122, 122);
// Zone borders: the middle is the face view, the outer bands edges (45°), the corners iso views.
g.strokeStyle = "rgba(160, 170, 190, 0.35)";
g.lineWidth = 2;
for (const v of [25.6, 102.4]) {
g.beginPath();
g.moveTo(v, 0);
g.lineTo(v, 128);
g.moveTo(0, v);
g.lineTo(128, v);
g.stroke();
}
g.fillStyle = "#e9ecf1";
g.font = `600 ${text.length > 5 ? 22 : 26}px system-ui, sans-serif`;
g.textAlign = "center";
g.textBaseline = "middle";
g.fillText(text, 64, 66);
const t = new CanvasTexture(c);
t.colorSpace = SRGBColorSpace;
return t;
}
function button(text: string, title: string, run: () => void): HTMLButtonElement {
const b = document.createElement("button");
b.textContent = text;
b.title = title;
b.addEventListener("click", (e) => {
e.stopPropagation();
run();
});
return b;
}
+1109
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
@echo off
rem Starts the supergeometry.app dev server and opens it in Chrome.
title supergeometry.app dev server
cd /d "%~dp0"
rem Node may not be on PATH in older terminals right after installing it.
where npm >nul 2>nul || set "PATH=%PATH%;C:\Program Files\nodejs"
where npm >nul 2>nul || (echo Node.js not found. Install it from https://nodejs.org & pause & exit /b 1)
rem Already running? Just open the browser.
powershell -NoProfile -Command "try { Invoke-WebRequest http://localhost:5173 -UseBasicParsing -TimeoutSec 2 | Out-Null; exit 0 } catch { exit 1 }"
if %errorlevel%==0 (
call :open
exit /b 0
)
if not exist node_modules (
echo Installing dependencies, first run only...
call npm install || (pause & exit /b 1)
)
rem Open Chrome in the background as soon as the server answers.
start "" /b powershell -NoProfile -WindowStyle Hidden -Command "for ($i=0; $i -lt 60; $i++) { try { Invoke-WebRequest http://localhost:5173 -UseBasicParsing -TimeoutSec 2 | Out-Null; break } catch { Start-Sleep 1 } }; try { Start-Process chrome 'http://localhost:5173' } catch { Start-Process 'http://localhost:5173' }"
echo Starting supergeometry.app at http://localhost:5173 (close this window or press Ctrl+C to stop)
call npm run dev -- --port 5173 --strictPort
pause
exit /b
:open
powershell -NoProfile -Command "try { Start-Process chrome 'http://localhost:5173' } catch { Start-Process 'http://localhost:5173' }"
exit /b
+63
View File
@@ -0,0 +1,63 @@
// Run: npx tsx tests/align.test.ts
import assert from "node:assert/strict";
import type { SketchEntity } from "../src/doc/types";
import { alignLine, joinCollinear } from "../src/sketch/edit";
type LineE = Extract<SketchEntity, { kind: "line" }>;
const L = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b });
const close = (p: number[], q: number[]) => assert.ok(Math.hypot(p[0] - q[0], p[1] - q[1]) < 1e-9, `${p} vs ${q}`);
// A rectangle's right side aligns onto a vertical line further right; top and bottom stretch.
const rect = [L("b", [0, 0], [10, 0]), L("r", [10, 0], [10, 5]), L("t", [10, 5], [0, 5]), L("l", [0, 5], [0, 0])];
const target = L("x", [14, -3], [14, 9]);
const out = alignLine([...rect, target], "r", target)!;
const get = (id: string) => out.find((e) => e.id === id) as LineE;
close(get("r").a, [14, 0]);
close(get("r").b, [14, 5]);
close(get("b").b, [14, 0]);
close(get("t").a, [14, 5]);
close(get("l").a, [0, 5]);
console.log("ok align stretches neighbours");
// A free tilted line lands on the target's axis.
const free = alignLine([L("f", [0, 1], [5, 3]), L("y", [0, 0], [10, 0])], "f", L("y", [0, 0], [10, 0]))!;
const f = free[0] as LineE;
close(f.a, [0, 0]);
close(f.b, [5, 0]);
console.log("ok align free line");
const j = joinCollinear([L("1", [0, 0], [4, 0]), L("2", [4, 0], [9, 0]), L("3", [4, 0], [4, 5])], "1")!;
assert.equal(j.removed, "2");
const one = j.entities.find((e) => e.id === "1") as LineE;
close(one.a, [0, 0]);
close(one.b, [9, 0]);
assert.equal(j.entities.length, 2);
assert.equal(joinCollinear([L("1", [0, 0], [4, 0]), L("3", [4, 0], [4, 5])], "1"), null);
console.log("ok join collinear");
// Splines: Extend/Join with lines, chain offsets through them.
{
const { joinEnds, offsetChain, splineEnds } = await import("../src/sketch/edit");
const sp: SketchEntity = { id: "s", kind: "spline", points: [[0, 0], [10, 5], [20, 0], [30, 8]], closed: false, mode: "fit" };
const wall = L("w", [35, -10], [35, 20]);
const j = joinEnds([sp, wall], { id: "s", at: [29, 7] }, { id: "w", at: [35, 15] })!;
const s2 = j.find((e) => e.id === "s")!;
const w2 = j.find((e) => e.id === "w") as LineE;
close(splineEnds(s2)![1], w2.b);
assert.ok(Math.abs(w2.b[0] - 35) < 1e-9);
const down = L("m", [10, -10], [10, -5]);
const j2 = joinEnds([sp, down], { id: "m", at: [10, -5] }, { id: "s", at: [12, 4] })!;
close((j2.find((e) => e.id === "m") as LineE).b, [10, 5]);
const loop = [sp, L("a", [30, 8], [30, -20]), L("b", [30, -20], [0, -20]), L("c", [0, -20], [0, 0])];
const off = offsetChain(loop, "a", 2)!;
assert.equal(off.length, 8);
// The offset outline stays closed: each piece starts where the one before ends.
const made = off.slice(4);
const ends = made.map((e) => (e.kind === "spline" ? splineEnds(e)! : [(e as LineE).a, (e as LineE).b]));
for (let i = 0; i < ends.length; i++) {
const a = ends[i][1];
const nexts = ends.map((x) => x[0]).concat(ends.map((x) => x[1]));
assert.ok(nexts.some((q, k) => k % ends.length !== i && Math.hypot(q[0] - a[0], q[1] - a[1]) < 1e-6), `gap after piece ${i}`);
}
console.log("ok spline join / extend / chain offset");
}
+99
View File
@@ -0,0 +1,99 @@
// Run: npx tsx tests/constraints.test.ts
import assert from "node:assert/strict";
import type { SketchConstraint, SketchEntity } from "../src/doc/types";
import { solve, sizeOf } from "../src/sketch/constraints";
import { angleLines, filletConstraints, filletCorner } from "../src/sketch/edit";
import { arcFrom3 } from "../src/sketch/curves";
const L = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b });
// A slightly crooked quad that constraints should square up.
const quad = [L("l1", [0, 0], [10.3, 0.4]), L("l2", [10.3, 0.4], [10, 5.2]), L("l3", [10, 5.2], [-0.2, 5]), L("l4", [-0.2, 5], [0, 0])];
const coin = (a: string, pa: string, b: string, pb: string): SketchConstraint => ({ id: a + b, type: "coincident", pts: [{ e: a, p: pa }, { e: b, p: pb }] });
const rect: SketchConstraint[] = [
coin("l1", "b", "l2", "a"),
coin("l2", "b", "l3", "a"),
coin("l3", "b", "l4", "a"),
coin("l4", "b", "l1", "a"),
{ id: "h1", type: "horizontal", curves: ["l1"] },
{ id: "h2", type: "horizontal", curves: ["l3"] },
{ id: "v1", type: "vertical", curves: ["l2"] },
{ id: "v2", type: "vertical", curves: ["l4"] },
{ id: "fx", type: "fix", pts: [{ e: "l1", p: "a" }], at: [0, 0] },
];
const checks: [string, () => void][] = [
["rectangle squares up", () => {
const r = solve(quad, rect);
assert.ok(r.ok, `error ${r.error}`);
const [l1, l2] = r.entities as any[];
assert.ok(Math.abs(l1.a[1] - l1.b[1]) < 1e-6 && Math.abs(l2.a[0] - l2.b[0]) < 1e-6);
}],
["width dimension drives the rectangle", () => {
const r = solve(quad, [...rect, { id: "w", type: "dim", curves: ["l1"], prop: "length", value: 25 }, { id: "h", type: "dim", curves: ["l2"], prop: "length", value: 8 }]);
assert.ok(r.ok, `error ${r.error}`);
assert.ok(Math.abs(sizeOf(r.entities[0], "length")! - 25) < 1e-6);
assert.ok(Math.abs(sizeOf(r.entities[1], "length")! - 8) < 1e-6);
}],
["drag a corner keeps it rectangular", () => {
const base = solve(quad, rect).entities;
const r = solve(base, rect, { drag: [{ ref: { e: "l2", p: "b" }, to: [20, 12] }] });
assert.ok(r.ok, `error ${r.error}`);
const l2 = r.entities[1] as any;
assert.ok(Math.abs(l2.b[0] - 20) < 0.05 && Math.abs(l2.b[1] - 12) < 0.05, JSON.stringify(l2.b));
}],
["tangent line to circle", () => {
const es: SketchEntity[] = [{ id: "c", kind: "circle", center: [0, 0], radius: 5 }, L("t", [-10, 6], [10, 7])];
const r = solve(es, [{ id: "tg", type: "tangent", curves: ["t", "c"] }, { id: "h", type: "horizontal", curves: ["t"] }]);
assert.ok(r.ok, `error ${r.error}`);
const t = r.entities[1] as any;
const c = r.entities[0] as any;
// Either may move: the line must sit exactly one radius from the centre.
assert.ok(Math.abs(Math.abs(t.a[1] - c.center[1]) - c.radius) < 1e-5);
}],
["perpendicular + equal", () => {
const es = [L("a", [0, 0], [10, 1]), L("b", [0, 0], [2, 7])];
const r = solve(es, [{ id: "p", type: "perpendicular", curves: ["a", "b"] }, { id: "e", type: "equal", curves: ["a", "b"] }, coin("a", "a", "b", "a")]);
assert.ok(r.ok, `error ${r.error}`);
assert.ok(Math.abs(sizeOf(r.entities[0], "length")! - sizeOf(r.entities[1], "length")!) < 1e-6);
}],
];
checks.push(
["equal: the first picked line keeps its length", () => {
const es = [L("p", [0, 0], [10, 0]), L("q", [0, 5], [20, 5])];
const r = solve(es, [{ id: "e", type: "equal", curves: ["p", "q"] }], { fixed: new Set(["p"]) });
assert.ok(Math.abs(sizeOf(r.entities[0], "length")! - 10) < 1e-6 && Math.abs(sizeOf(r.entities[1], "length")! - 10) < 1e-6);
}],
["fillet on a joined corner stays tangent after solving", () => {
const es = [L("h", [0, 0], [20, 0]), L("v", [20, 0], [20, 20])];
const cs: SketchConstraint[] = [coin("h", "b", "v", "a"), { id: "hh", type: "horizontal", curves: ["h"] }, { id: "vv", type: "vertical", curves: ["v"] }];
const before = new Set(es.map((e) => e.id));
const next = filletCorner(es, [20, 0], 4, 1e-6)!;
const fc = filletConstraints(next, cs, before);
const r = solve(next, fc);
assert.ok(r.ok, "solves");
const arc = r.entities.find((e) => e.kind === "arc") as any;
const c = arcFrom3(arc.a, arc.m, arc.b)!;
assert.ok(Math.abs(c.r - 4) < 1e-6 && Math.abs(c.c[0] - 16) < 1e-6 && Math.abs(c.c[1] - 4) < 1e-6, JSON.stringify(c));
}],
["angle between lines: second turns about its end nearest the first", () => {
const es = [L("p", [0, 0], [20, 0]), L("q", [5, 1], [5, 11])];
const r = angleLines(es, "p", "q", 30)!;
const q = r.entities[1] as any;
assert.deepEqual(q.a, [5, 1]);
const ang = (Math.atan2(q.b[1] - q.a[1], q.b[0] - q.a[0]) * 180) / Math.PI;
assert.ok(Math.abs(Math.abs(ang) - 30) < 1e-9 || Math.abs(Math.abs(ang) - 150) < 1e-9, `angle ${ang}`);
}],
);
let failed = 0;
for (const [name, fn] of checks) {
try {
fn();
console.log("ok ", name);
} catch (e) {
failed++;
console.log("FAIL", name, "—", (e as Error).message);
}
}
process.exit(failed ? 1 : 0);
+125
View File
@@ -0,0 +1,125 @@
// Run: npx tsx tests/edit.test.ts
import assert from "node:assert/strict";
import type { SketchEntity } from "../src/doc/types";
import { connectedChain, extend, filletCorner, filletEnds, joinEnds, offsetChain, splitEntity, mirrorXf, offsetEntity, transformEntity, trim } from "../src/sketch/edit";
import { arrangement } from "../src/sketch/regions";
const kinds = (es: SketchEntity[]) => es.map((e) => e.kind).sort().join(",");
const checks: [string, () => void][] = [
["trim circle crossed by a line → arc remains", () => {
const es: SketchEntity[] = [{ id: "c", kind: "circle", center: [0, 0], radius: 10 }, { id: "l", kind: "line", a: [-20, 0], b: [20, 0] }];
const out = trim(es, "c", [0, 10]);
assert.equal(kinds(out), "arc,line");
assert.equal(arrangement(out).regions.length, 1); // half disc
}],
["trim middle of a line between two crossings", () => {
const es: SketchEntity[] = [{ id: "l", kind: "line", a: [0, 0], b: [30, 0] }, { id: "v1", kind: "line", a: [10, -5], b: [10, 5] }, { id: "v2", kind: "line", a: [20, -5], b: [20, 5] }];
const out = trim(es, "l", [15, 0]);
assert.equal(out.filter((e) => e.kind === "line").length, 4);
}],
["trim one side of a rect", () => {
const es: SketchEntity[] = [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }];
const out = trim(es, "r", [0, 5]);
assert.equal(out.length, 3);
}],
["fillet a rect corner", () => {
const es: SketchEntity[] = [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }];
const out = filletCorner(es, [10, 5], 2, 0.5)!;
assert.equal(kinds(out), "arc,line,line,line,line");
const r = arrangement(out).regions;
assert.equal(r.length, 1);
assert.ok(Math.abs(r[0].area - (200 - (4 - Math.PI)) ) < 0.05, `area ${r[0].area}`);
}],
["offset rect outward", () => {
const o = offsetEntity({ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }, 2)!;
assert.deepEqual([o.kind, (o as any).w, (o as any).h], ["rect", 24, 14]);
}],
["extend a line to a circle", () => {
const es: SketchEntity[] = [{ id: "l", kind: "line", a: [-5, 0], b: [0, 0] }, { id: "c", kind: "circle", center: [20, 0], radius: 5 }];
const out = extend(es, "l", [0, 0])!;
const l = out.find((e) => e.id === "l") as any;
assert.ok(Math.abs(l.b[0] - 15) < 0.05, `x=${l.b[0]}`);
}],
["join two lines into a corner (picked halves)", () => {
const es: SketchEntity[] = [{ id: "h", kind: "line", a: [0, 0], b: [10, 0] }, { id: "v", kind: "line", a: [20, 5], b: [20, 15] }];
const out = joinEnds(es, { id: "h", at: [8, 0] }, { id: "v", at: [20, 7] })!;
const h = out.find((e) => e.id === "h") as any;
const v = out.find((e) => e.id === "v") as any;
assert.deepEqual([h.a, h.b, v.a, v.b].map((p) => p.map((x: number) => Math.round(x * 1e6) / 1e6)), [[0, 0], [20, 0], [20, 0], [20, 15]]);
assert.equal(arrangement(out).regions.length, 0);
}],
["join line to arc: arc follows its circle", () => {
// Quarter arc of radius 10 around the origin, from (10,0) to (0,10); a line below it.
const es: SketchEntity[] = [{ id: "a", kind: "arc", a: [10, 0], m: [7.0710678, 7.0710678], b: [0, 10] }, { id: "l", kind: "line", a: [-20, -5], b: [-12, -5] }];
const out = joinEnds(es, { id: "a", at: [1, 9.9] }, { id: "l", at: [-13, -5] })!;
const a = out.find((e) => e.id === "a") as any;
const l = out.find((e) => e.id === "l") as any;
const meet = [-Math.sqrt(75), -5];
assert.ok(Math.hypot(a.b[0] - meet[0], a.b[1] - meet[1]) < 1e-6 && Math.hypot(l.b[0] - meet[0], l.b[1] - meet[1]) < 1e-6, JSON.stringify([a.b, l.b]));
assert.ok(Math.abs(Math.hypot(...(a.m as [number, number])) - 10) < 1e-6 && a.m[1] > 0, "mid stays on the circle, upper side");
}],
["both halves of one arc close it into a circle", () => {
const es: SketchEntity[] = [{ id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }];
const out = joinEnds(es, { id: "a", at: [9, 3] }, { id: "a", at: [-9, 3] })!;
assert.equal(out[0].kind, "circle");
}],
["split a line at its middle", () => {
const out = splitEntity([{ id: "l", kind: "line", a: [0, 0], b: [10, 0] }], "l", "l2")!;
assert.deepEqual(out.map((e: any) => [e.id, e.a, e.b]), [["l", [0, 0], [5, 0]], ["l2", [5, 0], [10, 0]]]);
}],
["split an arc at a tapped point", () => {
const out = splitEntity([{ id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }], "a", "a2", [7.07, 7.07])! as any[];
assert.ok(Math.hypot(out[0].b[0] - 7.0710678, out[0].b[1] - 7.0710678) < 1e-3 && out[1].a === out[0].b);
assert.ok(Math.abs(Math.hypot(...(out[0].m as [number, number])) - 10) < 1e-9 && out[0].m[1] > 0);
}],
["fillet two separate lines picked by halves", () => {
const es: SketchEntity[] = [{ id: "h", kind: "line", a: [0, 0], b: [10, 0] }, { id: "v", kind: "line", a: [20, 5], b: [20, 15] }];
const out = filletEnds(es, { id: "h", at: [8, 0] }, { id: "v", at: [20, 7] }, 3)!;
assert.equal(kinds(out), "arc,line,line");
const h = out.find((e) => e.id === "h") as any;
assert.ok(Math.abs(h.b[0] - 17) < 1e-6, `h ends at ${h.b}`);
}],
["chain: a square of four lines is found and closed", () => {
const sq: SketchEntity[] = [{ id: "1", kind: "line", a: [0, 0], b: [10, 0] }, { id: "2", kind: "line", a: [10, 10], b: [10, 0] }, { id: "3", kind: "line", a: [10, 10], b: [0, 10] }, { id: "4", kind: "line", a: [0, 10], b: [0, 0] }];
const c = connectedChain(sq, "3")!;
assert.equal(c.links.length, 4);
assert.ok(c.closed);
}],
["offset a closed chain outward stays closed", () => {
const sq: SketchEntity[] = [{ id: "1", kind: "line", a: [0, 0], b: [10, 0] }, { id: "2", kind: "line", a: [10, 10], b: [10, 0] }, { id: "3", kind: "line", a: [10, 10], b: [0, 10] }, { id: "4", kind: "line", a: [0, 10], b: [0, 0] }];
const out = offsetChain(sq, "1", 1)!;
const regions = arrangement(out.slice(4)).regions;
assert.equal(regions.length, 1);
assert.ok(Math.abs(regions[0].area - 144) < 1e-6, `area ${regions[0].area}`);
}],
["offset a rounded chain (line–arc–line) inward", () => {
// U shape closed: bottom line, right arc, top line, left line.
const es: SketchEntity[] = [
{ id: "b", kind: "line", a: [0, 0], b: [10, 0] },
{ id: "r", kind: "arc", a: [10, 0], m: [15, 5], b: [10, 10] },
{ id: "t", kind: "line", a: [10, 10], b: [0, 10] },
{ id: "l", kind: "line", a: [0, 10], b: [0, 0] },
];
const out = offsetChain(es, "t", -1)!;
const regions = arrangement(out.slice(4)).regions;
assert.equal(regions.length, 1);
const expect = 9 * 8 + (Math.PI * 16) / 2; // 9 x 8 box + half disc of radius 4
assert.ok(Math.abs(regions[0].area - expect) < 0.05, `area ${regions[0].area} vs ${expect}`);
}],
["mirror a rect keeps size", () => {
const m = transformEntity({ id: "r", kind: "rect", center: [10, 0], w: 4, h: 2, rotation: 0 }, mirrorXf([0, -1], [0, 1]), true) as any;
assert.ok(Math.abs(m.center[0] + 10) < 1e-9 && Math.abs(m.w - 4) < 1e-9);
}],
];
let failed = 0;
for (const [name, fn] of checks) {
try {
fn();
console.log("ok ", name);
} catch (e) {
failed++;
console.log("FAIL", name, "—", (e as Error).message);
}
}
process.exit(failed ? 1 : 0);
+192
View File
@@ -0,0 +1,192 @@
// Run: npx tsx tests/engine.test.ts — every feature type through the real engine.
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import type { Feature, PlaneDef } from "../src/doc/types";
import { exportBodies, regenerate } from "../src/kernel/engine";
import { arrangement, regionRef } from "../src/sketch/regions";
import { primitiveCage } from "../src/freeform/cage";
setOC(await (opencascade as unknown as () => Promise<any>)());
const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
const XZ: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] };
const sketch = (id: string, plane: PlaneDef, entities: any[]): Feature => ({ id, name: id, type: "sketch", plane, entities });
const regions = (entities: any[]) => arrangement(entities).regions.map(regionRef);
const rect = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 20, rotation: 0 }];
const circle = [{ id: "c", kind: "circle", center: [30, 10], radius: 5 }];
const base: Feature[] = [
sketch("s1", XY, rect),
{ id: "e1", name: "Extrude", type: "extrude", source: { kind: "profile", sketch: "s1", regions: regions(rect) }, distance: 10, mode: "auto" },
];
const tests: [string, Feature[], (r: Awaited<ReturnType<typeof regenerate>>) => string][] = [
["extrude", base, (r) => `${r.bodies.length} body, ${r.bodies[0].faces.length} faces`],
["revolve 360 around Z offset", [sketch("s2", XZ, circle), { id: "rv", name: "Revolve", type: "revolve", source: { kind: "profile", sketch: "s2", regions: regions(circle) }, axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }], (r) => `${r.bodies.length} body, ${r.bodies[0]?.faces.length} faces`],
["sweep circle along line", [
sketch("s3", XY, [{ id: "c", kind: "circle", center: [0, 0], radius: 2 }]),
sketch("s4", XZ, [{ id: "p", kind: "line", a: [0, 0], b: [0, 30] }]),
{ id: "sw", name: "Sweep", type: "sweep", source: { kind: "profile", sketch: "s3", regions: regions([{ id: "c", kind: "circle", center: [0, 0], radius: 2 }]) }, path: { kind: "sketch", sketch: "s4", entities: ["p"] }, mode: "new" },
], (r) => `${r.bodies.length} body, ${r.bodies[0]?.faces.length} faces`],
["loft rect → circle", [
sketch("l1", XY, rect),
sketch("l2", { ...XY, origin: [0, 0, 30] }, [{ id: "c", kind: "circle", center: [0, 0], radius: 8 }]),
{ id: "lo", name: "Loft", type: "loft", sections: [{ kind: "profile", sketch: "l1", regions: regions(rect) }, { kind: "profile", sketch: "l2", regions: regions([{ id: "c", kind: "circle", center: [0, 0], radius: 8 }]) }], ruled: false, mode: "new" },
], (r) => `${r.bodies.length} body, ${r.bodies[0]?.faces.length} faces`],
["shell open top", [...base, { id: "sh", name: "Shell", type: "shell", body: "e1", faces: [{ body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }], thickness: 2 }], (r) => `${r.bodies[0].faces.length} faces`],
["split by plane x=0", [...base, { id: "sp", name: "Split", type: "split", body: "e1", plane: { origin: [0, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] } }], (r) => `${r.bodies.length} bodies`],
["mirror copy", [...base, { id: "mi", name: "Mirror", type: "transform", bodies: ["e1"], copy: true, op: { kind: "mirror", plane: { origin: [30, 0, 0], xDir: [0, 1, 0], normal: [1, 0, 0] } } }], (r) => `${r.bodies.length} bodies`],
["linear pattern x3", [...base, { id: "lp", name: "Pattern", type: "transform", bodies: ["e1"], copy: true, op: { kind: "linear", dir: [0, 1, 0], spacing: 30, count: 3 } }], (r) => `${r.bodies.length} bodies`],
["circular pattern x4", [...base, { id: "cp", name: "Pattern", type: "transform", bodies: ["e1"], copy: true, op: { kind: "circular", axis: { origin: [60, 0, 0], dir: [0, 0, 1] }, count: 4, angle: 360 } }], (r) => `${r.bodies.length} bodies`],
["move + rotate", [...base, { id: "mv", name: "Move", type: "transform", bodies: ["e1"], copy: false, op: { kind: "move", translate: [0, 0, 5], rotate: { origin: [0, 0, 0], axis: [0, 0, 1], angle: 45 } } }], (r) => `${r.bodies.length} body, zmin=${Math.min(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)).toFixed(1)}`],
["scale x2", [...base, { id: "sc", name: "Scale", type: "transform", bodies: ["e1"], copy: false, op: { kind: "scale", center: [0, 0, 0], factor: 2 } }], (r) => `zmax=${Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2)).toFixed(1)}`],
["offset top face of its own body (+5 → 6 faces)", [...base, { id: "of", name: "Offset", type: "extrude", source: { kind: "face", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 } }, distance: 5, mode: "auto", target: "e1" }], (r) => {
const zmax = Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2));
if (r.bodies[0].faces.length !== 6 || Math.abs(zmax - 15) > 1e-6) throw new Error(`${r.bodies[0].faces.length} faces, zmax ${zmax}`);
return `zmax=${zmax}`;
}],
["move face: tilt top 10°", [...base, { id: "mf", name: "Move face", type: "moveFace", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, translate: [0, 0, 0], rotate: { origin: [0, 0, 10], axis: [0, 1, 0], angle: 10 } }], (r) => {
const zmax = Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2));
if (Math.abs(zmax - (10 + 20 * Math.tan(Math.PI / 18))) > 1e-3) throw new Error(`zmax ${zmax}`);
return `zmax=${zmax.toFixed(2)}`;
}],
["move edge up 5 (faces tilt)", [...base, { id: "me", name: "Move edge", type: "moveFace", edge: { body: "e1", mid: [20, 0, 10], dir: [0, 1, 0], length: 20 }, translate: [0, 0, 5] }], (r) => {
const b = r.bodies[0];
const zmax = Math.max(...Array.from(b.positions).filter((_, i) => i % 3 === 2));
if (b.faces.length !== 6 || Math.abs(zmax - 15) > 1e-3) throw new Error(`${b.faces.length} faces, zmax ${zmax}`);
return `zmax=${zmax.toFixed(2)}`;
}],
["move one corner of the box up 5 (only that corner rises)", [...base, { id: "mvv", name: "Move vertex", type: "moveFace", vertex: { body: "e1", at: [20, 10, 10] }, translate: [0, 0, 5] }], (r) => {
const b = r.bodies[0];
const pos = b.positions;
let corner = -Infinity, other = -Infinity;
for (let i = 0; i < pos.length; i += 3) {
if (Math.hypot(pos[i] - 20, pos[i + 1] - 10) < 1e-6) corner = Math.max(corner, pos[i + 2]);
if (Math.hypot(pos[i] + 20, pos[i + 1] + 10) < 1e-6) other = Math.max(other, pos[i + 2]);
}
if (Math.abs(corner - 15) > 1e-6 || Math.abs(other - 10) > 1e-6 || b.openEdges.length) throw new Error(`corner ${corner}, opposite ${other}, open ${b.openEdges.length}`);
return `corner z=${corner.toFixed(2)}, opposite corner z=${other.toFixed(2)}`;
}],
["move one corner along X: only the point moves, its edge neighbours stay", [...base, { id: "mvx", name: "Move vertex", type: "moveFace", vertex: { body: "e1", at: [20, 10, 10] }, translate: [5, 0, 0] }], (r) => {
const b = r.bodies[0];
const pos = b.positions;
const has = (x: number, y: number, z: number) => { for (let i = 0; i < pos.length; i += 3) if (Math.hypot(pos[i] - x, pos[i + 1] - y, pos[i + 2] - z) < 1e-6) return true; return false; };
// The corners next to it along the edges (below it and beside it) haven't moved.
if (!has(25, 10, 10) || !has(20, 10, 0) || !has(20, -10, 10) || has(25, 10, 0) || b.openEdges.length) throw new Error(`moved ${has(25, 10, 10)}, below ${has(20, 10, 0)}, open ${b.openEdges.length}`);
return `${b.faces.length} faces`;
}],
["extrude (auto) through another body cuts a hole in it, no new body", [...base,
sketch("hole", { ...XY, origin: [0, 0, -5] }, [{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]),
{ id: "he", name: "Extrude", type: "extrude", source: { kind: "profile", sketch: "hole", regions: regions([{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]) }, distance: 30, mode: "auto" }], (r) => {
if (r.bodies.length !== 1 || r.bodies[0].faces.length !== 7) throw new Error(`${r.bodies.length} bodies, ${r.bodies[0]?.faces.length} faces`);
return "1 body, 7 faces (hole through)";
}],
["extrude (new) through another body keeps both", [...base,
sketch("hole", { ...XY, origin: [0, 0, -5] }, [{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]),
{ id: "he", name: "Extrude", type: "extrude", source: { kind: "profile", sketch: "hole", regions: regions([{ id: "hc", kind: "circle", center: [5, 0], radius: 3 }]) }, distance: 30, mode: "new" }], (r) => {
if (r.bodies.length !== 2) throw new Error(`${r.bodies.length} bodies`);
return "2 bodies";
}],
["delete fillet edge's face", [...base,
{ id: "fi", name: "Fillet", type: "fillet", edges: [{ body: "e1", mid: [20, 0, 10], dir: [0, 1, 0], length: 20 }], radius: 2 },
{ id: "dg", name: "Delete", type: "deleteGeom", body: "e1", faces: [], edges: [{ body: "e1", mid: [20, 0, 8], dir: [0, 1, 0], length: 20 }], vertices: [] }], (r) => {
if (r.bodies[0].faces.length !== 6) throw new Error(`${r.bodies[0].faces.length} faces`);
return "6 faces";
}],
["freeform sphere → one closed body", [{ id: "ff", name: "Freeform", type: "freeform", cage: primitiveCage("sphere") }], (r) => {
if (r.bodies.length !== 1 || r.bodies[0].openEdges.length) throw new Error(`${r.bodies.length} bodies, ${r.bodies[0]?.openEdges.length} open edges`);
return `${r.bodies[0].faces.length} faces`;
}],
["scale the top face ×0.5 in its plane → tapered (sides tilt)", [...base, { id: "sf", name: "Scale Face", type: "scaleFace", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, u: [1, 0, 0], factors: [0.5, 0.5] }], (r) => {
const b = r.bodies[0];
const top = b.faces.find((f) => f.normal[2] > 0.999)!;
if (Math.abs(top.area - 200) > 1e-3 || b.faces.length !== 6) throw new Error(`top area ${top.area}, ${b.faces.length} faces`);
return `top area ${top.area.toFixed(1)}`;
}],
["replace the top face with a plane 5 higher", [...base, { id: "rf", name: "Replace", type: "replaceFace", face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, plane: { origin: [0, 0, 15], normal: [0, 0, -1], xDir: [1, 0, 0] } }], (r) => {
const zmax = Math.max(...Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 2));
if (Math.abs(zmax - 15) > 1e-6 || r.bodies[0].faces.length !== 6) throw new Error(`zmax ${zmax}`);
return `zmax=${zmax}`;
}],
["freeform: move, then stretch ×2 along X (rebuilt from the cage)", [
{ id: "ffx", name: "Freeform", type: "freeform", cage: primitiveCage("sphere") },
{ id: "mvx", name: "Move", type: "transform", bodies: ["ffx"], copy: false, op: { kind: "move", translate: [100, 0, 0] } },
{ id: "sx", name: "Scale XYZ", type: "transform", bodies: ["ffx"], copy: false, op: { kind: "scaleXYZ", center: [100, 0, 20], factors: [2, 1, 1] } },
], (r) => {
const xs = Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 0);
const ys = Array.from(r.bodies[0].positions).filter((_, i) => i % 3 === 1);
const w = Math.max(...xs) - Math.min(...xs);
const d = Math.max(...ys) - Math.min(...ys);
if (Math.abs(w / d - 2) > 0.02 || Math.abs((Math.max(...xs) + Math.min(...xs)) / 2 - 100) > 0.1) throw new Error(`w ${w} d ${d}`);
return `width ${w.toFixed(1)} vs depth ${d.toFixed(1)}`;
}],
["construction plane offset from face", [...base, { id: "pl", name: "Plane", type: "plane", plane: XY, face: { body: "e1", center: [0, 0, 10], normal: [0, 0, 1], area: 800 }, offset: 5 }], (r) => `plane z=${r.planes[0]?.plane.origin[2]}`],
];
let failed = 0;
for (const [name, features, describe] of tests) {
try {
const r = await regenerate(features);
if (r.errors.length) throw new Error(r.errors.map((e) => `${e.featureId}: ${e.message}`).join("; "));
console.log("ok ", name, "—", describe(r));
} catch (e) {
failed++;
console.log("FAIL", name, "—", e instanceof Error ? e.message : e);
}
}
// A line across the top face splits it into two regions (with the face outline).
{
const top = { body: "e1", center: [0, 0, 10] as [number, number, number], normal: [0, 0, 1] as [number, number, number], area: 800 };
const plane: PlaneDef = { origin: [0, 0, 10], xDir: [1, 0, 0], normal: [0, 0, 1] };
const line = [{ id: "l", kind: "line", a: [5, -15], b: [5, 15] }];
const withSketch: Feature[] = [...base, { id: "sf", name: "sf", type: "sketch", plane, attachedTo: top, entities: line as any }];
const r1 = await regenerate(withSketch);
const curves = [...line, ...(r1.sketchBoundaries.sf ?? [])] as any[];
const regs = arrangement(curves).regions;
const small = regs.sort((a, b) => a.area - b.area)[0];
const r2 = await regenerate([...withSketch, { id: "ex", name: "ex", type: "extrude", source: { kind: "profile", sketch: "sf", regions: [regionRef(small)] }, distance: 5, mode: "auto", target: "e1" }]);
// Top face is 40 × 20 (x −20…20); the line at x = 5 leaves 15 × 20 = 300 and 25 × 20 = 500.
const ok = regs.length === 2 && Math.round(small.area) === 300 && !r2.errors.length && r2.bodies[0].faces.length > 6;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", "line across a face → 2 regions, extrude one:", regs.map((r) => Math.round(r.area)).join("/"), `${r2.bodies[0]?.faces.length} faces`, r2.errors.map((e) => e.message).join());
}
// A plain box edge can't be deleted: a readable error, the body stays.
{
const r = await regenerate([...base, { id: "dg", name: "Delete", type: "deleteGeom", body: "e1", faces: [], edges: [{ body: "e1", mid: [20, 0, 10], dir: [0, 1, 0], length: 20 }], vertices: [] }]);
const ok = r.errors.length === 1 && r.bodies.length === 1 && r.bodies[0].faces.length === 6;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", "delete box edge refused:", r.errors.map((e) => e.message).join());
}
// Shell a freeform (open at its top patch): a closed, hollow body.
{
const feats: Feature[] = [{ id: "ffs", name: "Freeform", type: "freeform", cage: primitiveCage("box") }];
const b0 = (await regenerate(feats)).bodies[0];
const top = b0.faces.reduce((bi, f, i) => (f.center[2] > b0.faces[bi].center[2] ? i : bi), 0);
const f = b0.faces[top];
const r = await regenerate([...feats, { id: "shf", name: "Shell", type: "shell", body: "ffs", faces: [{ body: "ffs", center: f.center, normal: f.normal, area: f.area }], thickness: 2 }]);
const ok = !r.errors.length && r.bodies[0].faces.length > 40 && r.bodies[0].openEdges.length === 0;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", "shell a freeform:", `${b0.faces.length} → ${r.bodies[0].faces.length} faces`, r.errors.map((e) => e.message).join());
}
// XYZ scale of an ordinary body: a clear message, the body stays.
{
const r = await regenerate([...base, { id: "sx2", name: "Scale XYZ", type: "transform", bodies: ["e1"], copy: false, op: { kind: "scaleXYZ", center: [0, 0, 0], factors: [2, 1, 1] } }]);
const ok = r.errors.length === 1 && /freeform/.test(r.errors[0].message) && r.bodies.length === 1;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", "XYZ scale on a regular body explains why not:", r.errors.map((e) => e.message).join());
}
// Closed solids report no open edges.
{
const r = await regenerate(base);
const ok = r.bodies[0].openEdges.length === 0;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", "closed box has no open edges:", r.bodies[0].openEdges.length);
}
const stl = await exportBodies(base, "stl");
console.log("ok export stl", stl.size, "bytes");
process.exit(failed ? 1 : 0);
+90
View File
@@ -0,0 +1,90 @@
// Run: npx tsx tests/faceedit.test.ts — direct face edits on real OpenCascade solids.
import opencascade from "replicad-opencascadejs";
import { basicFaceExtrusion, makeCylinder, makeBox, measureVolume, setOC, Vector, type Shape3D } from "replicad";
import { deleteFace, offsetFace, replaceFacePlane } from "../src/kernel/faceEdit";
import { regionFaces } from "../src/kernel/sketchGeom";
import { arrangement, regionRef } from "../src/sketch/regions";
setOC(await (opencascade as unknown as () => Promise<any>)());
const XY = { origin: [0, 0, 0] as [number, number, number], xDir: [1, 0, 0] as [number, number, number], normal: [0, 0, 1] as [number, number, number] };
const near = (a: number, b: number, tol = 1e-3) => Math.abs(a - b) < tol * Math.max(1, Math.abs(b));
const faceWith = (s: Shape3D, pred: (n: number[], c: number[], t: string) => boolean) =>
s.faces.find((f) => pred(f.normalAt().toTuple(), f.center.toTuple(), f.geomType))!;
const checks: [string, () => string][] = [
["box: offset top +5 keeps a box", () => {
const box = makeBox([0, 0, 0], [20, 10, 10]) as Shape3D;
const r = offsetFace(box, faceWith(box, (n) => n[2] > 0.9), 5);
if (!near(measureVolume(r), 20 * 10 * 15) || r.faces.length !== 6) throw new Error(`vol ${measureVolume(r)} faces ${r.faces.length}`);
return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`;
}],
["D-shape: flat face pushed out extends the round side", () => {
// Half disc (radius 10) extruded; push the flat side outward by 3.
const es: any[] = [{ id: "l", kind: "line", a: [-10, 0], b: [10, 0] }, { id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }];
const f = regionFaces(es, XY, arrangement(es).regions.map(regionRef))[0];
const d = basicFaceExtrusion(f, new Vector([0, 0, 5])) as Shape3D;
const flat = faceWith(d, (n, _c, t) => t === "PLANE" && n[1] < -0.9);
const r = offsetFace(d, flat, 3);
// Extending the arc downward by 3 (not a prism): faces stay 4, and the round face continues the circle.
const round = r.faces.filter((x) => x.geomType === "CYLINDRE");
if (r.faces.length !== 4 || round.length !== 1) throw new Error(`${r.faces.length} faces, ${round.length} round`);
return `${r.faces.length} faces, vol ${measureVolume(r).toFixed(1)}`;
}],
["cylinder radius 5 → 7", () => {
const c = makeCylinder(5, 10) as Shape3D;
const r = offsetFace(c, faceWith(c, (_n, _c, t) => t === "CYLINDRE"), 2);
if (!near(measureVolume(r), Math.PI * 49 * 10, 2e-3)) throw new Error(`vol ${measureVolume(r)}`);
return `vol ${measureVolume(r).toFixed(1)}`;
}],
["hole radius 3 → 2 (offset +1 adds material)", () => {
const plate = (makeBox([-10, -10, 0], [10, 10, 4]) as Shape3D).cut(makeCylinder(3, 4) as Shape3D);
const wall = faceWith(plate, (_n, _c, t) => t === "CYLINDRE");
const r = offsetFace(plate, wall, 1);
if (!near(measureVolume(r), 400 * 4 - Math.PI * 4 * 4, 2e-3)) throw new Error(`vol ${measureVolume(r)}`);
return `vol ${measureVolume(r).toFixed(1)}`;
}],
["delete a fillet face → sharp box", () => {
const box = makeBox([0, 0, 0], [20, 10, 10]) as Shape3D;
const fil = box.fillet(2, (e) => e.inDirection("Y").ofCurveType("LINE").containsPoint([20, 5, 10]));
const ff = faceWith(fil, (_n, _c, t) => t === "CYLINDRE");
const r = deleteFace(fil, ff);
if (!near(measureVolume(r), 2000)) throw new Error(`vol ${measureVolume(r)}, faces ${r.faces.length}`);
return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`;
}],
["delete an inside-corner fillet → sharp L again (no extra block)", () => {
// L-shape: a 20×20×10 block with a 10×10 notch out of one corner, inner edge filleted.
const L = (makeBox([0, 0, 0], [20, 20, 10]) as Shape3D).cut(makeBox([10, 10, -1], [21, 21, 11]) as Shape3D);
const fil = L.fillet(3, (e) => e.inDirection("Z").containsPoint([10, 10, 5]));
const before = measureVolume(L);
const ff = faceWith(fil, (_n, _c, t) => t === "CYLINDRE");
const r = deleteFace(fil, ff);
if (!near(measureVolume(r), before)) throw new Error(`vol ${measureVolume(r)} vs ${before} (filleted ${measureVolume(fil)})`);
return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`;
}],
["delete a hole wall → solid plate", () => {
const plate = (makeBox([-10, -10, 0], [10, 10, 4]) as Shape3D).cut(makeCylinder(3, 4) as Shape3D);
const r = deleteFace(plate, faceWith(plate, (_n, _c, t) => t === "CYLINDRE"));
if (!near(measureVolume(r), 1600)) throw new Error(`vol ${measureVolume(r)}`);
return `vol ${measureVolume(r).toFixed(1)}`;
}],
["tilt the top face 10° about its edge", () => {
const box = makeBox([0, 0, 0], [20, 10, 10]) as Shape3D;
const a = (10 * Math.PI) / 180;
// Plane through the top edge at x=0, tilted down towards +x.
const r = replaceFacePlane(box, faceWith(box, (n) => n[2] > 0.9), { origin: [0, 5, 10], normal: [Math.sin(a), 0, Math.cos(a)], xDir: [1, 0, 0] });
const expect = 20 * 10 * 10 - 0.5 * 20 * (20 * Math.tan(a)) * 10;
if (!near(measureVolume(r), expect, 2e-3)) throw new Error(`vol ${measureVolume(r)} vs ${expect}`);
return `vol ${measureVolume(r).toFixed(1)}, ${r.faces.length} faces`;
}],
];
let failed = 0;
for (const [name, fn] of checks) {
try {
console.log("ok ", name, "—", fn());
} catch (e) {
failed++;
console.log("FAIL", name, "—", e instanceof Error ? e.message : e);
}
}
process.exit(failed ? 1 : 0);
+68
View File
@@ -0,0 +1,68 @@
// Run: npx tsx tests/filletedit.test.ts — moving faces next to big fillets keeps the fillets
// (no tunnels carved through the body by an extended fillet cylinder).
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import type { Feature, PlaneDef } from "../src/doc/types";
import { regenerate } from "../src/kernel/engine";
import type { BodyMesh } from "../src/kernel/protocol";
import { arrangement, regionRef } from "../src/sketch/regions";
setOC(await (opencascade as unknown as () => Promise<any>)());
const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
const rect = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 30, rotation: 0 }];
const R = 8;
const base: Feature[] = [
{ id: "s", name: "s", type: "sketch", plane: XY, entities: rect as any },
{ id: "b", name: "b", type: "extrude", source: { kind: "profile", sketch: "s", regions: arrangement(rect as any).regions.map(regionRef) }, distance: 20, mode: "new" },
// A big fillet along the top back edge.
{ id: "f", name: "f", type: "fillet", edges: [{ body: "b", mid: [0, 15, 20], dir: [1, 0, 0], length: 40 }], radius: R },
];
const corner = R * R * (1 - Math.PI / 4); // material a fillet takes off, per unit length
function volume(b: BodyMesh): number {
const p = b.positions;
const ix = b.indices;
let v = 0;
for (let i = 0; i < ix.length; i += 3) {
const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3];
v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6;
}
return v;
}
let failed = 0;
async function check(name: string, extra: Feature[], expected: number, cylinders = 1): Promise<void> {
const r = await regenerate([...base, ...extra]);
const b = r.bodies[0];
const v = b ? volume(b) : NaN;
const cyl = b ? b.faces.filter((f) => f.type !== "PLANE").length : -1;
const ok = !r.errors.length && (Number.isNaN(expected) ? v > 20000 && v < 30000 : Math.abs(v - expected) < expected * 0.005) && cyl === cylinders && b.openEdges.length === 0;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", name, `vol ${v.toFixed(1)} (want ${expected.toFixed(1)}), round faces ${cyl}`, r.errors.map((e) => e.message).join("; "));
}
const faceRef = async (pick: (f: { center: number[]; normal: number[] }) => boolean) => {
const r = await regenerate(base);
const f = r.bodies[0].faces.find(pick)!;
return { body: "b", center: f.center, normal: f.normal, area: f.area } as any;
};
const offset = (id: string, face: any, d: number): Feature => ({ id, name: id, type: "extrude", source: { kind: "face", face }, distance: d, mode: "auto", target: "b" } as Feature);
await check("filleted box as built", [], 24000 - 40 * corner);
const top = await faceRef((f) => f.normal[2] > 0.99);
await check("top face (fillet runs into it) up 5", [offset("o1", top, 5)], 40 * 30 * 25 - 40 * corner);
await check("top face down 4", [offset("o1", top, -4)], 40 * 30 * 16 - 40 * corner);
const side = await faceRef((f) => f.normal[0] > 0.99);
await check("side face (fillet ends on it) out 5", [offset("o2", side, 5)], 45 * 30 * 20 - 45 * corner);
await check("side face in 6", [offset("o2", side, -6)], 34 * 30 * 20 - 34 * corner);
const back = await faceRef((f) => f.normal[1] > 0.99);
await check("back face (fillet runs into it) out 3", [offset("o3", back, 3)], 40 * 33 * 20 - 40 * corner);
const front = await faceRef((f) => f.normal[1] < -0.99);
await check("front face (no fillet) out 5", [offset("o4", front, 5)], 40 * 35 * 20 - 40 * corner);
// A corner next to the fillet, pulled up: the faces around it tilt, the fillet stays one round face.
await check("front-right-top corner up 4", [{ id: "mv", name: "mv", type: "moveFace", vertex: { body: "b", at: [20, -15, 20] }, translate: [0, 0, 4] } as Feature], NaN);
await check("edge next to it (front top) up 3", [{ id: "me", name: "me", type: "moveFace", edge: { body: "b", mid: [0, -15, 20], dir: [1, 0, 0], length: 40 }, translate: [0, 0, 3] } as Feature], NaN);
process.exit(failed ? 1 : 0);
+124
View File
@@ -0,0 +1,124 @@
// Run: npx tsx tests/freeform.test.ts — cages, subdivision and the cage → solid conversion.
import assert from "node:assert/strict";
import opencascade from "replicad-opencascadejs";
import { measureVolume, setOC, type Shape3D } from "replicad";
import { boundaryEdges, boxCage, bridgeLoops, cageEdgeKey, cageEdges, cylinderCage, deleteFaces, fillLoop, holeLoops, isClosed, planeCage, sphereCage, subdivide } from "../src/freeform/cage";
import { cageToShape } from "../src/kernel/freeform";
import { evalSurface, interpolateGrid } from "../src/freeform/bspline";
setOC(await (opencascade as unknown as () => Promise<any>)());
const checks: [string, () => string][] = [
["cages are closed (box, cylinder, sphere) / open (plane)", () => {
assert.ok(isClosed(boxCage()));
assert.ok(isClosed(cylinderCage()));
assert.ok(isClosed(sphereCage()));
assert.ok(!isClosed(planeCage()));
return `box ${boxCage().verts.length} pts, cylinder ${cylinderCage().faces.length} faces`;
}],
["subdivision: every face becomes a 9×9 grid sharing its borders", () => {
const s = subdivide(boxCage(), 3);
assert.equal(s.n, 8);
assert.equal(s.grids.length, 24);
// Euler characteristic of a closed surface: V − E + F = 2.
const F = s.grids.length * 64;
const E = (F * 4) / 2;
assert.equal(s.points.length - E + F, 2);
return `${s.points.length} points`;
}],
["patch surfaces pass through their grid points", () => {
const s = subdivide(sphereCage(40), 3);
const g = s.grids[5].map((row) => row.map((i) => s.points[i]));
const poles = interpolateGrid(g);
let worst = 0;
for (let i = 0; i <= 8; i++)
for (let j = 0; j <= 8; j++) {
const q = evalSurface(poles, i / 8, j / 8);
worst = Math.max(worst, Math.hypot(q[0] - g[i][j][0], q[1] - g[i][j][1], q[2] - g[i][j][2]));
}
assert.ok(worst < 1e-9, `off by ${worst}`);
return `max error ${worst.toExponential(1)}`;
}],
["sphere cage → near-spherical solid of ~diameter 40", () => {
const solid = cageToShape(sphereCage(40));
const v = measureVolume(solid);
const ideal = (4 / 3) * Math.PI * 20 ** 3;
const bb = solid.boundingBox;
assert.ok(Math.abs(v - ideal) / ideal < 0.12, `volume ${v} vs ${ideal}`);
return `vol ${v.toFixed(0)} (sphere ${ideal.toFixed(0)}), ${solid.faces.length} faces, size ${bb.width.toFixed(1)}`;
}],
["box cage → closed solid", () => {
const solid = cageToShape(boxCage([40, 40, 40], 2));
const v = measureVolume(solid);
assert.ok(v > 20000 && v < 64000, `volume ${v}`);
return `vol ${v.toFixed(0)}, ${solid.faces.length} faces`;
}],
["cylinder cage → closed solid", () => {
const solid = cageToShape(cylinderCage(40, 40));
const v = measureVolume(solid);
assert.ok(v > 20000, `volume ${v}`);
return `vol ${v.toFixed(0)}`;
}],
["moving a cage point bulges the shape", () => {
const c = sphereCage(40);
const top = c.verts.reduce((best, p, i) => (p[2] > c.verts[best][2] ? i : best), 0);
const before = cageToShape(c).boundingBox.depth;
c.verts[top] = [c.verts[top][0], c.verts[top][1], c.verts[top][2] + 20];
const after = cageToShape(c).boundingBox.depth;
assert.ok(after > before + 5, `${before} → ${after}`);
return `height ${before.toFixed(1)} → ${after.toFixed(1)}`;
}],
["plane surface thickened up / down / both → solids of the same volume", () => {
const vols = (["up", "down", "both"] as const).map((side) => {
const s = cageToShape(planeCage([60, 60], 4), 3, { thickness: 2, side });
const bb = s.boundingBox;
return { v: measureVolume(s), zmin: bb.bounds[0][2], zmax: bb.bounds[1][2] };
});
for (const x of vols) assert.ok(Math.abs(x.v - vols[0].v) / vols[0].v < 0.02 && x.v > 1000, JSON.stringify(vols));
assert.ok(vols[0].zmin > -0.01 && vols[1].zmax < 0.01 && vols[2].zmin < -0.9 && vols[2].zmax > 0.9, JSON.stringify(vols));
return vols.map((x) => `${x.v.toFixed(0)} [${x.zmin.toFixed(1)}…${x.zmax.toFixed(1)}]`).join(", ");
}],
["delete a face, then fill the hole again → closed solid", () => {
const box = boxCage([40, 40, 40], 2);
const holed = deleteFaces(box, [0]);
assert.ok(!isClosed(holed));
const rim = new Set(boundaryEdges(holed).map(([a, b]) => cageEdgeKey(a, b)));
const loops = holeLoops(holed, rim);
assert.equal(loops.length, 1);
const filled = fillLoop(holed, loops[0])!;
assert.ok(isClosed(filled));
const v = measureVolume(cageToShape(filled));
assert.ok(v > 0, `volume ${v}`);
return `hole of ${loops[0].length} edges filled, vol ${v.toFixed(0)}`;
}],
["two facing holes bridged → closed (tunnel)", () => {
// Box, 3 per side: remove the middle top and middle bottom quads → a hole through.
const box = boxCage([40, 40, 40], 3);
const holed = deleteFaces(box, [4, 13]);
const loops = holeLoops(holed, new Set(boundaryEdges(holed).map(([a, b]) => cageEdgeKey(a, b))));
assert.equal(loops.length, 2);
const tube = bridgeLoops(holed, loops[0], loops[1])!;
assert.ok(isClosed(tube));
const solid = cageToShape(tube);
const full = measureVolume(cageToShape(box));
// A real hole through: less than the full box, but most of it is still there.
assert.ok(measureVolume(solid) > full * 0.5 && measureVolume(solid) < full * 0.97, `volume ${measureVolume(solid)} vs box ${full}`);
return `${tube.faces.length} faces, vol ${measureVolume(solid).toFixed(0)}`;
}],
["plane cage → open surface (a shell, no volume)", () => {
const sheet = cageToShape(planeCage([60, 60], 4)) as Shape3D;
assert.equal(sheet.faces.length, 16);
return `${sheet.faces.length} faces, ${cageEdges(planeCage()).length} cage edges`;
}],
];
let failed = 0;
for (const [name, fn] of checks) {
try {
console.log("ok ", name, "—", fn());
} catch (e) {
failed++;
console.log("FAIL", name, "—", e instanceof Error ? e.message : e);
}
}
process.exit(failed ? 1 : 0);
+38
View File
@@ -0,0 +1,38 @@
// Run: npx tsx tests/kernel.test.ts — checks sketch regions become valid solids.
import opencascade from "replicad-opencascadejs";
import { basicFaceExtrusion, measureArea, setOC, Vector } from "replicad";
import type { PlaneDef, SketchEntity } from "../src/doc/types";
import { regionFaces } from "../src/kernel/sketchGeom";
import { arrangement, regionRef } from "../src/sketch/regions";
setOC(await (opencascade as unknown as () => Promise<any>)());
const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
const FRONT: PlaneDef = { origin: [0, 0, 5], xDir: [1, 0, 0], normal: [0, -1, 0] };
const cases: [string, SketchEntity[], PlaneDef][] = [
["rect", [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 10, rotation: 0 }], XY],
["ring", [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 20, rotation: 0 }, { id: "c", kind: "circle", center: [0, 0], radius: 5 }], XY],
["circles crossing", [{ id: "a", kind: "circle", center: [0, 0], radius: 10 }, { id: "b", kind: "circle", center: [10, 0], radius: 10 }], FRONT],
["D", [{ id: "l", kind: "line", a: [-10, 0], b: [10, 0] }, { id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }], XY],
["ellipse", [{ id: "e", kind: "ellipse", center: [3, 2], rx: 10, ry: 5, rotation: 0.3 }], XY],
["ellipse cut by line", [{ id: "e", kind: "ellipse", center: [0, 0], rx: 10, ry: 5, rotation: 0 }, { id: "l", kind: "line", a: [0, -10], b: [0, 10] }], XY],
["spline", [{ id: "s", kind: "spline", points: [[0, 0], [10, 0], [12, 8], [0, 10]], closed: true, mode: "fit" }], XY],
["rotated rect + circle overlap", [{ id: "r", kind: "rect", center: [0, 0], w: 20, h: 20, rotation: 0.4 }, { id: "c", kind: "circle", center: [10, 0], radius: 6 }], XY],
];
let failed = 0;
for (const [name, entities, plane] of cases) {
try {
const arr = arrangement(entities);
const faces = regionFaces(entities, plane, arr.regions.map(regionRef));
const out = faces.map((f, i) => {
const s = basicFaceExtrusion(f, new Vector(plane.normal).multiply(5));
return `${measureArea(f).toFixed(2)}/${arr.regions[i].area.toFixed(2)}:${s.faces.length}f`;
});
console.log("ok ", name, out.join(" "));
} catch (e) {
failed++;
console.log("FAIL", name, e instanceof Error ? e.message : e);
}
}
process.exit(failed ? 1 : 0);
+92
View File
@@ -0,0 +1,92 @@
// Run: npx tsx tests/loft.test.ts — lofts in many arrangements, and a spline revolve.
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import type { ExtrudeSource, Feature, PlaneDef } from "../src/doc/types";
import { regenerate } from "../src/kernel/engine";
import type { BodyMesh } from "../src/kernel/protocol";
import { arrangement, regionRef } from "../src/sketch/regions";
setOC(await (opencascade as unknown as () => Promise<any>)());
const plane = (z: number, flip = false): PlaneDef => ({ origin: [0, 0, z], xDir: [1, 0, 0], normal: flip ? [0, 0, -1] : [0, 0, 1] });
const XZ: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] };
const sketch = (id: string, p: PlaneDef, entities: any[]): Feature => ({ id, name: id, type: "sketch", plane: p, entities });
const prof = (id: string, entities: any[]): ExtrudeSource => ({ kind: "profile", sketch: id, regions: arrangement(entities).regions.map(regionRef) });
const loft = (sections: ExtrudeSource[], ruled = false): Feature => ({ id: "lo", name: "Loft", type: "loft", sections, ruled, mode: "new" });
const rect = (w: number, h: number, rot = 0) => [{ id: "r", kind: "rect", center: [0, 0], w, h, rotation: rot }];
const circle = (r: number, c: [number, number] = [0, 0]) => [{ id: "c", kind: "circle", center: c, radius: r }];
const hexagon = [{ id: "h", kind: "polygon", center: [0, 0], radius: 10, sides: 6, angle: 0.3 }];
const blob = [{ id: "s", kind: "spline", points: [[10, 0], [4, 8], [-9, 5], [-7, -6], [3, -9]], closed: true, mode: "fit" }];
function volume(b: BodyMesh): number {
const p = b.positions;
const ix = b.indices;
let v = 0;
for (let i = 0; i < ix.length; i += 3) {
const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3];
v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6;
}
return v;
}
let failed = 0;
async function check(name: string, feats: Feature[], lo: number, hi: number): Promise<void> {
const r = await regenerate(feats);
const b = r.bodies.find((x) => x.id === "lo" || x.id === "rv") ?? r.bodies[r.bodies.length - 1];
const v = b ? volume(b) : NaN;
const ok = !r.errors.length && !!b && b.openEdges.length === 0 && v > lo && v < hi;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", name, `vol=${v.toFixed(0)} (${lo}..${hi}) faces=${b?.faces.length} open=${b?.openEdges.length}`, r.errors.map((e) => e.message).join("; "));
}
// Prism-like bounds: between the smaller and the larger section × height.
await check("rect → circle", [sketch("a", plane(0), rect(40, 20)), sketch("b", plane(30), circle(8)), loft([prof("a", rect(40, 20)), prof("b", circle(8))])], 200 * 30, 800 * 30);
await check("circle → circle, shifted sideways", [sketch("a", plane(0), circle(10)), sketch("b", plane(30), circle(5, [15, 0])), loft([prof("a", circle(10)), prof("b", circle(5, [15, 0]))])], 78 * 30, 315 * 30);
await check("rect → rect turned 45°", [sketch("a", plane(0), rect(20, 20)), sketch("b", plane(30), rect(20, 20, Math.PI / 4)), loft([prof("a", rect(20, 20)), prof("b", rect(20, 20, Math.PI / 4))])], 300 * 30, 400 * 30 + 1);
await check("three sections rect → circle → rect", [sketch("a", plane(0), rect(30, 30)), sketch("b", plane(20), circle(8)), sketch("c", plane(40), rect(30, 30)), loft([prof("a", rect(30, 30)), prof("b", circle(8)), prof("c", rect(30, 30))])], 200 * 40, 900 * 40);
await check("picked top first", [sketch("a", plane(0), rect(40, 20)), sketch("b", plane(30), circle(8)), loft([prof("b", circle(8)), prof("a", rect(40, 20))])], 200 * 30, 800 * 30);
await check("middle picked last (out of order)", [sketch("a", plane(0), rect(30, 30)), sketch("b", plane(20), circle(8)), sketch("c", plane(40), rect(30, 30)), loft([prof("a", rect(30, 30)), prof("c", rect(30, 30)), prof("b", circle(8))])], 200 * 40, 900 * 40);
await check("plane facing down (reversed wire)", [sketch("a", plane(0), rect(40, 20)), sketch("b", plane(30, true), circle(8)), loft([prof("a", rect(40, 20)), prof("b", circle(8))])], 200 * 30, 800 * 30);
await check("hexagon → circle", [sketch("a", plane(0), hexagon), sketch("b", plane(25), circle(6)), loft([prof("a", hexagon), prof("b", circle(6))])], 113 * 25, 260 * 25);
await check("spline blob → circle", [sketch("a", plane(0), blob), sketch("b", plane(25), circle(5)), loft([prof("a", blob), prof("b", circle(5))])], 78 * 25, 400 * 25);
await check("ruled rect → smaller rect", [sketch("a", plane(0), rect(30, 30)), sketch("b", plane(20), rect(10, 10)), loft([prof("a", rect(30, 30)), prof("b", rect(10, 10))], true)], 100 * 20, 900 * 20);
await check("box top face → circle", [
sketch("a", plane(0), rect(30, 30)),
{ id: "e", name: "Extrude", type: "extrude", source: prof("a", rect(30, 30)), distance: 10, mode: "new" },
sketch("b", plane(40), circle(6)),
{ id: "lo", name: "Loft", type: "loft", sections: [{ kind: "face", face: { body: "e", center: [0, 0, 10], normal: [0, 0, 1], area: 900 } }, prof("b", circle(6))], ruled: false, mode: "new" },
], 113 * 30, 900 * 30);
await check("tilted planes (not parallel)", [sketch("a", plane(0), rect(20, 20)), sketch("b", { origin: [0, 0, 30], xDir: [1, 0, 0], normal: [0, Math.sin(0.4), Math.cos(0.4)] }, circle(8)), loft([prof("a", rect(20, 20)), prof("b", circle(8))])], 200 * 25, 400 * 35);
// A vase: spline side + straight bottom, top and axis, turned about Z.
const vase = [
{ id: "sp", kind: "spline", points: [[10, 0], [14, 10], [8, 25], [12, 40]], closed: false, mode: "fit" },
{ id: "t", kind: "line", a: [12, 40], b: [0, 40] },
{ id: "ax", kind: "line", a: [0, 40], b: [0, 0] },
{ id: "bt", kind: "line", a: [0, 0], b: [10, 0] },
];
{
const feats: Feature[] = [sketch("v", XZ, vase), { id: "rv", name: "Revolve", type: "revolve", source: prof("v", vase), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }];
await check("spline vase revolve", feats, Math.PI * 8 * 8 * 40, Math.PI * 14 * 14 * 40);
// The spline side is one smooth face (not a stack of strips from a fitted curve).
const r = await regenerate(feats);
const side = r.bodies[0].faces.filter((f) => f.type !== "PLANE").length;
const ok = side === 1;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", "vase side is one face:", side);
}
// A thread: a small triangle turned 5 times while moving 10 along the axis (pitch 2).
{
const tri = [{ id: "tr", kind: "polyline", closed: true, points: [[10, 0], [11.2, 0.7], [10, 1.4]] }];
const area = (1.2 * 1.4) / 2;
const ideal = area * 2 * Math.PI * 10.4 * 5;
await check("thread: 5 turns, travel 10", [sketch("t", XZ, tri), { id: "rv", name: "Revolve", type: "revolve", source: prof("t", tri), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 1800, travel: 10, mode: "new" } as Feature], ideal * 0.9, ideal * 1.1);
// A spring the other way round (negative travel).
const disc = [{ id: "d", kind: "circle", center: [15, 0], radius: 1 }];
const ideal2 = Math.PI * 2 * Math.PI * 15 * 3;
await check("spring: 3 turns, travel -12", [sketch("t", XZ, disc), { id: "rv", name: "Revolve", type: "revolve", source: prof("t", disc), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 1080, travel: -12, mode: "new" } as Feature], ideal2 * 0.9, ideal2 * 1.1);
}
process.exit(failed ? 1 : 0);
+69
View File
@@ -0,0 +1,69 @@
// Run: npx tsx tests/offsetcurved.test.ts — Offset Face on flat faces bordered by curved
// (sloped) faces: the curved neighbours carry on, it isn't a straight extrude.
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import type { Feature, PlaneDef } from "../src/doc/types";
import { regenerate } from "../src/kernel/engine";
import type { BodyMesh } from "../src/kernel/protocol";
import { arrangement, regionRef } from "../src/sketch/regions";
setOC(await (opencascade as unknown as () => Promise<any>)());
const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
const XZ: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, -1, 0] };
const sketch = (id: string, plane: PlaneDef, entities: any[]): Feature => ({ id, name: id, type: "sketch", plane, entities });
const prof = (id: string, entities: any[]) => ({ kind: "profile" as const, sketch: id, regions: arrangement(entities).regions.map(regionRef) });
function volume(b: BodyMesh): number {
const p = b.positions;
const ix = b.indices;
let v = 0;
for (let i = 0; i < ix.length; i += 3) {
const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3];
v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6;
}
return v;
}
let failed = 0;
async function offsetTop(name: string, feats: Feature[], body: string, d: number, want: (v0: number) => [number, number]): Promise<void> {
const r0 = await regenerate(feats);
const b0 = r0.bodies.find((b) => b.id === body)!;
const top = b0.faces.reduce((bi, f, i) => (f.normal[2] > 0.99 && (b0.faces[bi].normal[2] <= 0.99 || f.center[2] > b0.faces[bi].center[2]) ? i : bi), 0);
const f = b0.faces[top];
const r = await regenerate([...feats, { id: "of", name: "of", type: "extrude", source: { kind: "face", face: { body, center: f.center, normal: f.normal, area: f.area } }, distance: d, mode: "auto", target: body } as Feature]);
const b = r.bodies.find((x) => x.id === body)!;
const v0 = volume(b0);
const v = volume(b);
const zmax = Math.max(...Array.from(b.positions).filter((_, i) => i % 3 === 2));
const [lo, hi] = want(v0);
const ok = !r.errors.length && v > lo && v < hi && b.openEdges.length === 0 && Math.abs(zmax - (f.center[2] + d)) < 1e-3;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", name, `vol ${v0.toFixed(0)} → ${v.toFixed(0)} (${lo.toFixed(0)}..${hi.toFixed(0)}), top z ${zmax.toFixed(2)}`, r.errors.map((e) => e.message).join("; "));
}
// A cone (frustum r 20 → 10 over 20): the top carries on up the cone.
const trap = [{ id: "t", kind: "polyline", closed: true, points: [[0, 0], [20, 0], [10, 20], [0, 20]] }];
const cone: Feature[] = [sketch("c", XZ, trap), { id: "cone", name: "cone", type: "revolve", source: prof("c", trap), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }];
const frustum = (r1: number, r2: number, h: number) => ((Math.PI * h) / 3) * (r1 * r1 + r1 * r2 + r2 * r2);
// Up 5: top radius 7.5 at z 25 (a straight extrude would keep radius 10).
await offsetTop("cone top up 5", cone, "cone", 5, () => [frustum(20, 7.5, 25) * 0.99, frustum(20, 7.5, 25) * 1.01]);
await offsetTop("cone top down 4", cone, "cone", -4, () => [frustum(20, 12, 16) * 0.99, frustum(20, 12, 16) * 1.01]);
// A loft (square → circle): the circle face carries on along the lofted side.
const sq = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 40, rotation: 0 }];
const ci = [{ id: "c", kind: "circle", center: [0, 0], radius: 10 }];
const lofted: Feature[] = [sketch("a", XY, sq), sketch("b", { ...XY, origin: [0, 0, 30] }, ci), { id: "lo", name: "lo", type: "loft", sections: [prof("a", sq), prof("b", ci)], ruled: false, mode: "new" } as Feature];
await offsetTop("loft top up 3", lofted, "lo", 3, (v0) => [v0 + 3 * 100, v0 + 3 * 314]);
// A vase (revolved spline): the rim carries on.
const vase = [
{ id: "sp", kind: "spline", points: [[10, 0], [14, 10], [8, 25], [12, 40]], closed: false, mode: "fit" },
{ id: "t", kind: "line", a: [12, 40], b: [0, 40] },
{ id: "ax", kind: "line", a: [0, 40], b: [0, 0] },
{ id: "bt", kind: "line", a: [0, 0], b: [10, 0] },
];
const vaseF: Feature[] = [sketch("v", XZ, vase), { id: "rv", name: "rv", type: "revolve", source: prof("v", vase), axis: { origin: [0, 0, 0], dir: [0, 0, 1] }, angle: 360, mode: "new" }];
await offsetTop("vase rim up 2", vaseF, "rv", 2, (v0) => [v0 + 2 * Math.PI * 100, v0 + 2 * Math.PI * 196]);
process.exit(failed ? 1 : 0);
+44
View File
@@ -0,0 +1,44 @@
// Run: npx tsx tests/regions.test.ts
import assert from "node:assert/strict";
import type { SketchEntity } from "../src/doc/types";
import { arrangement } from "../src/sketch/regions";
const rect = (id: string, cx: number, cy: number, w: number, h: number): SketchEntity => ({ id, kind: "rect", center: [cx, cy], w, h, rotation: 0 });
const line = (id: string, a: [number, number], b: [number, number]): SketchEntity => ({ id, kind: "line", a, b });
const summary = (es: SketchEntity[]) =>
arrangement(es)
.regions.map((r) => `${r.area.toFixed(2)}${r.holes.length ? `(h${r.holes.length})` : ""}`)
.sort();
const cases: [string, SketchEntity[], string[]][] = [
["single rect", [rect("a", 0, 0, 20, 10)], ["200.00"]],
// Areas are of the display polygons (96 segments per circle), not exact.
["circle in rect → ring + disk", [rect("a", 0, 0, 40, 20), { id: "c", kind: "circle", center: [0, 0], radius: 5 }], ["721.52(h1)", "78.48"]],
["two overlapping rects → 3", [rect("a", 0, 0, 20, 20), rect("b", 10, 10, 20, 20)], ["100.00", "300.00", "300.00"]],
["four lines → square", [line("1", [0, 0], [10, 0]), line("2", [10, 0], [10, 10]), line("3", [10, 10], [0, 10]), line("4", [0, 10], [0, 0])], ["100.00"]],
["line through rect → 2", [rect("a", 0, 0, 20, 10), line("l", [0, -10], [0, 10])], ["100.00", "100.00"]],
["D shape (arc + line)", [line("l", [-10, 0], [10, 0]), { id: "a", kind: "arc", a: [10, 0], m: [0, 10], b: [-10, 0] }], ["156.97"]],
["dangling line ignored", [rect("a", 0, 0, 20, 10), line("l", [10, 0], [30, 0])], ["200.00"]],
["line ending inside splits nothing", [rect("a", 0, 0, 20, 10), line("l", [0, 0], [30, 0])], ["200.00"]],
["ellipse", [{ id: "e", kind: "ellipse", center: [0, 0], rx: 10, ry: 5, rotation: 0.3 }], ["156.97"]],
["construction ignored", [rect("a", 0, 0, 20, 10), { ...line("l", [0, -10], [0, 10]), construction: true }], ["200.00"]],
["closed spline", [{ id: "s", kind: "spline", points: [[0, 0], [10, 0], [10, 10], [0, 10]], closed: true, mode: "fit" }], ["*"]],
["two circles crossing → 3", [{ id: "c1", kind: "circle", center: [0, 0], radius: 10 }, { id: "c2", kind: "circle", center: [10, 0], radius: 10 }], ["*", "*", "*"]],
// Lines drawn over a face's outline (the rect): the doubled edges count once.
["lines on a rect's edges → 2", [rect("f", 0, 0, 20, 10), line("1", [-10, -5], [0, -5]), line("2", [0, -5], [0, 5]), line("3", [0, 5], [-10, 5]), line("4", [-10, 5], [-10, -5])], ["100.00", "100.00"]],
["partly overlapping lines → square", [line("1", [0, 0], [10, 0]), line("1b", [3, 0], [14, 0]), line("2", [10, 0], [10, 10]), line("3", [10, 10], [0, 10]), line("4", [0, 10], [0, 0])], ["100.00"]],
];
let failed = 0;
for (const [name, es, expected] of cases) {
const got = summary(es);
try {
assert.equal(got.length, expected.length);
expected.forEach((e, i) => e === "*" || assert.equal(got[i], e));
console.log("ok ", name, got.join(" "));
} catch {
failed++;
console.log("FAIL", name, "got", got.join(" "), "expected", expected.join(" "));
}
}
process.exit(failed ? 1 : 0);
+63
View File
@@ -0,0 +1,63 @@
// Run: npx tsx tests/shell.test.ts — Shell on shapes with many faces.
import opencascade from "replicad-opencascadejs";
import { setOC } from "replicad";
import type { Feature, PlaneDef } from "../src/doc/types";
import { regenerate } from "../src/kernel/engine";
import type { BodyMesh } from "../src/kernel/protocol";
import { arrangement, regionRef } from "../src/sketch/regions";
setOC(await (opencascade as unknown as () => Promise<any>)());
const XY: PlaneDef = { origin: [0, 0, 0], xDir: [1, 0, 0], normal: [0, 0, 1] };
const sketch = (id: string, entities: any[], p = XY): Feature => ({ id, name: id, type: "sketch", plane: p, entities });
const extrude = (id: string, sk: string, entities: any[], d: number, mode: "new" | "auto" = "new"): Feature => ({ id, name: id, type: "extrude", source: { kind: "profile", sketch: sk, regions: arrangement(entities).regions.map(regionRef) }, distance: d, mode });
function volume(b: BodyMesh): number {
const p = b.positions;
const ix = b.indices;
let v = 0;
for (let i = 0; i < ix.length; i += 3) {
const [a, c, d] = [ix[i] * 3, ix[i + 1] * 3, ix[i + 2] * 3];
v += (p[a] * (p[c + 1] * p[d + 2] - p[c + 2] * p[d + 1]) - p[a + 1] * (p[c] * p[d + 2] - p[c + 2] * p[d]) + p[a + 2] * (p[c] * p[d + 1] - p[c + 1] * p[d])) / 6;
}
return v;
}
let failed = 0;
/** Shell the body's top-most face and check it hollowed (volume went well down) and stayed closed. */
async function check(name: string, feats: Feature[], body: string, t = 1): Promise<void> {
const r0 = await regenerate(feats);
const b0 = r0.bodies.find((b) => b.id === body)!;
// The biggest upward face (the lid you'd open).
const top = b0.faces.reduce((bi, f, i) => (f.normal[2] > 0.99 && (b0.faces[bi].normal[2] <= 0.99 || f.area > b0.faces[bi].area) ? i : bi), 0);
const f = b0.faces[top];
const r = await regenerate([...feats, { id: "sh", name: "Shell", type: "shell", body, faces: [{ body, center: f.center, normal: f.normal, area: f.area }], thickness: t }]);
const b = r.bodies.find((x) => x.id === body);
const v0 = volume(b0);
const v = b ? volume(b) : NaN;
const ok = !r.errors.length && !!b && v < v0 * 0.8 && v > 0 && b.openEdges.length === 0;
if (!ok) failed++;
console.log(ok ? "ok " : "FAIL", name, `${b0.faces.length} faces, vol ${v0.toFixed(0)} → ${v.toFixed(0)}`, r.errors.map((e) => e.message).join("; "));
}
const box = [{ id: "r", kind: "rect", center: [0, 0], w: 40, h: 30, rotation: 0 }];
const base = [sketch("s", box), extrude("b", "s", box, 20)];
const edgesOfBox = (z: number) => [
{ body: "b", mid: [0, -15, z], dir: [1, 0, 0], length: 40 }, { body: "b", mid: [0, 15, z], dir: [1, 0, 0], length: 40 },
{ body: "b", mid: [-20, 0, z], dir: [0, 1, 0], length: 30 }, { body: "b", mid: [20, 0, z], dir: [0, 1, 0], length: 30 },
];
const verticals = [[-20, -15], [20, -15], [20, 15], [-20, 15]].map(([x, y]) => ({ body: "b", mid: [x, y, 10], dir: [0, 0, 1], length: 20 }));
await check("plain box", base, "b");
await check("box, vertical edges rounded", [...base, { id: "f", name: "f", type: "fillet", edges: verticals as any, radius: 4 }], "b");
await check("box, every edge rounded", [...base, { id: "f1", name: "f", type: "fillet", edges: verticals as any, radius: 4 }, { id: "f2", name: "f", type: "fillet", edges: [{ body: "b", mid: [0, -15, 0], dir: [1, 0, 0], length: 32 }] as any, radius: 2 }], "b");
await check("box, bottom edges chamfered", [...base, { id: "c", name: "c", type: "chamfer", edges: edgesOfBox(0) as any, radius: 2 }], "b");
// Many small faces: a box with ribs joined on top, then a 24-sided column.
const ribs = Array.from({ length: 6 }, (_, i) => ({ id: `k${i}`, kind: "rect", center: [-15 + i * 6, 0], w: 2, h: 30, rotation: 0 }));
await check("box with 6 ribs joined", [...base, sketch("s2", ribs, { ...XY, origin: [0, 0, 20] }), { ...extrude("j", "s2", ribs, 5, "auto"), target: "b" } as any], "b");
const poly = [{ id: "p", kind: "polygon", center: [0, 0], radius: 20, sides: 24, angle: 0 }];
await check("24-sided prism", [sketch("s", poly), extrude("b", "s", poly, 20)], "b");
const star = [{ id: "st", kind: "polyline", closed: true, points: Array.from({ length: 20 }, (_, i) => { const a = (i / 20) * Math.PI * 2; const r = i % 2 ? 9 : 20; return [r * Math.cos(a), r * Math.sin(a)]; }) }];
await check("10-point star prism", [sketch("s", star), extrude("b", "s", star, 15)], "b", 0.8);
process.exit(failed ? 1 : 0);
+53
View File
@@ -0,0 +1,53 @@
// Run: npx tsx tests/svg.test.ts — SVG → sketch curves.
import assert from "node:assert/strict";
import { parseSVG } from "../src/io/svg";
import { arrangement } from "../src/sketch/regions";
const near = (a: number, b: number, tol = 1e-6) => Math.abs(a - b) <= tol * Math.max(1, Math.abs(b));
const checks: [string, () => string][] = [
["mm units from width + viewBox; rect / circle become those shapes", () => {
const { entities, size } = parseSVG(`<svg xmlns="http://www.w3.org/2000/svg" width="100mm" height="50mm" viewBox="0 0 200 100">
<rect x="10" y="10" width="80" height="40"/><circle cx="150" cy="50" r="20"/></svg>`);
const kinds = entities.map((e) => e.kind).sort().join(",");
assert.equal(kinds, "circle,rect");
const r = entities.find((e) => e.kind === "rect") as any;
const c = entities.find((e) => e.kind === "circle") as any;
// 200 user units = 100 mm → 0.5 mm each.
assert.ok(near(r.w, 40) && near(r.h, 20) && near(c.radius, 10), JSON.stringify([r, c]));
assert.equal(arrangement(entities).regions.length, 2);
return `size ${size.map((v) => v.toFixed(1)).join(" × ")} mm`;
}],
["path with lines, a cubic, an arc and close → one closed region", () => {
const { entities } = parseSVG(`<svg viewBox="0 0 100 100" width="100mm">
<path d="M10 10 H60 C80 10 90 30 90 50 A40 40 0 0 1 50 90 L10 90 Z"/></svg>`);
const kinds = entities.map((e) => e.kind);
assert.ok(kinds.includes("spline") && kinds.includes("arc") && kinds.includes("line"), kinds.join());
const regions = arrangement(entities).regions;
assert.equal(regions.length, 1);
return `${entities.length} curves, area ${regions[0].area.toFixed(0)} mm²`;
}],
["relative commands, implicit repeats, groups with transforms; y flips up", () => {
const { entities } = parseSVG(`<svg width="100px" height="100px">
<g transform="translate(10,0)"><path d="m0,0 l10,0 0,10 -10,0 z"/></g></svg>`);
assert.equal(entities.length, 4);
// A 10 px square → 2.646 mm; the drawing is centred on the origin.
const xs = entities.flatMap((e: any) => [e.a[0], e.b[0]]);
assert.ok(near(Math.max(...xs) - Math.min(...xs), (10 * 25.4) / 96), String(xs));
assert.equal(arrangement(entities).regions.length, 1);
return "ok";
}],
["text is skipped with a clear message when nothing else is there", () => {
assert.throws(() => parseSVG(`<svg><text x="0" y="10">Hi</text></svg>`), /converted to paths/);
return "ok";
}],
];
let failed = 0;
for (const [name, fn] of checks) {
try {
console.log("ok ", name, "—", fn());
} catch (e) {
failed++;
console.log("FAIL", name, "—", e instanceof Error ? e.message : e);
}
}
process.exit(failed ? 1 : 0);
+16
View File
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"],
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"skipLibCheck": true,
"isolatedModules": true,
"resolveJsonModule": true,
"types": ["vite/client"]
},
"include": ["src"]
}
+13
View File
@@ -0,0 +1,13 @@
import { readFileSync } from "node:fs";
import { defineConfig } from "vite";
const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) as { version: string };
export default defineConfig({
// Relative base so the build works from any static host sub-path (GitHub Pages etc.).
base: "./",
define: { __APP_VERSION__: JSON.stringify(pkg.version) },
worker: { format: "es" },
optimizeDeps: { exclude: ["replicad-opencascadejs"] },
build: { target: "es2022", chunkSizeWarningLimit: 4000 },
});
+11
View File
@@ -0,0 +1,11 @@
// Cloudflare deployment: a static site (no server code). `npm run build`
// writes the app to dist/, and `npx wrangler deploy` publishes that folder.
{
"name": "supergeometry-app",
"compatibility_date": "2026-10-01",
"assets": {
"directory": "./dist",
// Any unknown path opens the app itself.
"not_found_handling": "single-page-application"
}
}