Linked copies and patterns; Fill Pattern in sketches; freeform solids get every body tool; the right column's buttons lit and its windows clear of everything; More reordered with switches; the grid's size live; Draw turns Line on; the line as wide as its buttons (asked for, nine points: "make sure even the buttons on the middle right (fit, shaders, settings) show when something is opened. like the ones on the middle left ... when a window opens from those, to not override anything else (should be dynamic) ... In More, move Help above Feedback, move Update under Install App, and make the two buttons (guide text and offline mode) have a toggle icon ... Rename About supergeometry.app to only About ... the lock grid size should change on the fly when i zoom ... when i click draw, line should be automatically selected (but the window with different line types should open normally) ... if i copy a body, i have the option to link it, but that doesnt do anything ... whatever change i do to any copy of that body or the original, it should also change the other ones exactly the same. we should also have this in patterns ... a new tool in sketch mode named fill pattern ... when i double click a freeform body, i want the edit freeform button there ... a freeform body that is finished should be treated like a regular body ... on desktop, in sketch mode ... the bar should be wider to fit all the buttons without having to scroll on it").
- Linked bodies. A copy (Move/Rotate, Mirror, Scale with Copy on) or a pattern made with Link on, and what it was made from, are a group: a step that changes one of them - an edge rounded, a hole cut, something joined on - changes every other the same way, each where it stands (turned, mirrored). Moving or turning one only moves that one, and it still follows; one deleted leaves the others; a linked copy of a linked copy is of the same group. Both patterns have a Link switch now. (Link only did anything for freeform copies before.) tests/linked.test.ts, 17 checks. - Fill Pattern, a sketch tool under Draw: tap inside a closed shape and it is filled with Lines, Crossed lines, Zigzag or Waves from edge to edge (ending exactly on the shape's edge, stopping at holes), or with Dots, a Honeycomb, Squares or Diamonds kept wholly inside it; Spacing (or the Gap between shapes), Size and Angle set, shown as they change. The strips and cells are shapes of the sketch: extruded or cut, a texture. A filled shape tapped again: its pattern changed or removed. The pattern is kept with the sketch and made again when the sketch's curves change (a rectangle made taller: 9 cells became 43). Too fine a spacing (thousands of curves) is refused in plain words. tests/fillpattern.test.ts, 28 checks. - A freeform solid that is finished is a body like any other: its faces, edges and corners have every tool a body's have (they were held to Move, Mirror, Pattern and Delete Body), its edges their dot, its corners their gimbal and Move Vertex. Only a freeform left as an open surface keeps its own few. Edit Freeform is beside a freeform body double tapped - also after other steps were done on it - and in History. - The right column: Shaded and Settings are lit while their window is open, as the three at the left are while they are on. Their windows (Units & grid and the others too) are placed in the room there is - under the top bar, the view cube, Items and History, over the line, undo / redo and the guide text - on every screen, and scroll inside when longer; on a phone on its side, beside the view cube. (They came down over the line on a phone.) - More: Update under Install app; Guide text and Offline mode each with a switch (they said On / Off in words); Help above Feedback; About. - Units & grid open, not locked: the size said on Lock grid size, in the box and in the note follows the zoom as it changes. - A sketch's Draw opened with no tool on: Line is on and the list stays open - a tap on the grid draws, a tap in the list takes another tool. - The line at the bottom is as wide as what is on it, up to all the room between undo and the right edge (it stopped at 980): a sketch's picked line or shape has all its sizes and buttons in view on a wide screen. In the app: the nine tried - the windows at 390 x 800, 844 x 390, 768 x 1024 and a desk screen (nothing over anything); a rectangle filled with lines, then a honeycomb, then made taller; a circle filled with waves; a freeform box double tapped, a corner, a face and an edge of it picked; a pattern's Link switch; a sketch's line and rectangle picked on a 1577 wide screen (the line 1050 and 1115 wide, nothing to slide). Tests: all 178 test files pass (mouse.test.ts's 30 s limit on a shell was missed once with five running at a time: 39 of 39 run alone). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -196,6 +196,10 @@ is placed with Enter or Done.
|
||||
perpendicular, where two cross) are kept as constraints. Dragging a point onto
|
||||
another joins them.
|
||||
|
||||
**Fill Pattern:** a closed shape filled with lines from edge to edge (straight, crossed, zigzag, waves) or with
|
||||
small shapes (dots, honeycomb, squares, diamonds), its spacing, size and angle set; the strips and cells are
|
||||
shapes to extrude or cut, for textures.
|
||||
|
||||
**Edit tools:** Offset Edge (parallel copy; whole outlines too), Fillet and
|
||||
Chamfer (round or bevel a corner where lines or arcs meet; tap the next corner
|
||||
to go on), Mirror (the selected shapes, across a line or an axis), Trim (cut
|
||||
|
||||
+6
-6
@@ -115,15 +115,15 @@
|
||||
<div id="more-menu" class="menu" hidden>
|
||||
<button id="m-fullscreen">Fullscreen<span class="menu-soon">F11</span></button>
|
||||
<button id="m-install" hidden>Install app <span class="menu-soon">Home screen</span></button>
|
||||
<hr />
|
||||
<button id="m-help">Help</button>
|
||||
<button id="m-hints">Guide text <span class="menu-soon" id="m-hints-state"></span></button>
|
||||
<button id="m-offline">Offline mode <span class="menu-soon" id="m-offline-state"></span></button>
|
||||
<button id="m-tutorial">Tutorial <span class="menu-soon">soon</span></button>
|
||||
<button id="m-update">Update</button>
|
||||
<hr />
|
||||
<button id="m-hints" class="menu-toggle" role="switch">Guide text <span class="menu-soon" id="m-hints-state"></span><span class="switch"></span></button>
|
||||
<button id="m-offline" class="menu-toggle" role="switch">Offline mode <span class="menu-soon" id="m-offline-state"></span><span class="switch"></span></button>
|
||||
<button id="m-tutorial">Tutorial <span class="menu-soon">soon</span></button>
|
||||
<hr />
|
||||
<button id="m-help">Help</button>
|
||||
<button id="m-feedback">Feedback <span class="menu-soon">Bug / Idea</span></button>
|
||||
<button id="m-about">About superGeometry.app</button>
|
||||
<button id="m-about">About</button>
|
||||
<button id="m-donate">Support <span class="menu-soon" id="m-donate-arrow">▸</span></button>
|
||||
<div id="m-donate-list" class="menu-sub" hidden>
|
||||
<button id="m-support-makerworld">MakerWorld - Boost <span class="menu-soon">↗</span></button>
|
||||
|
||||
+10
-3
@@ -1622,8 +1622,14 @@ export class App implements AppContext {
|
||||
const help = new HelpPanel();
|
||||
moreItem("m-help", () => help.toggle());
|
||||
// The guide text (what to tap next): on or off.
|
||||
const hintsState = document.getElementById("m-hints-state")!;
|
||||
const paintHints = () => (hintsState.textContent = settings.value.showHints ? "On" : "Off");
|
||||
// (Each a switch on its row - they said On or Off in words. Asked for: "make the two buttons (guide text and
|
||||
// offline mode) have a toggle icon. I don't like how right now it's only on or off in text".)
|
||||
const switchOf = (id: string, on: boolean) => {
|
||||
const b = document.getElementById(id)!;
|
||||
b.classList.toggle("on", on);
|
||||
b.setAttribute("aria-checked", String(on));
|
||||
};
|
||||
const paintHints = () => switchOf("m-hints", settings.value.showHints);
|
||||
paintHints();
|
||||
moreItem("m-hints", () => {
|
||||
settings.set("showHints", !settings.value.showHints);
|
||||
@@ -1632,7 +1638,8 @@ export class App implements AppContext {
|
||||
});
|
||||
// Offline mode: the app kept on this device, so it works with no connection.
|
||||
const offlineState = document.getElementById("m-offline-state")!;
|
||||
const offline = new Offline((t, k) => this.ui.toast(t, k), (state) => (offlineState.textContent = state));
|
||||
// (Its switch; beside it only how far the download is while it runs.)
|
||||
const offline = new Offline((t, k) => this.ui.toast(t, k), (state) => ((offlineState.textContent = state === "On" || state === "Off" ? "" : state), switchOf("m-offline", settings.value.offline)));
|
||||
this.updates.offline = { get on() { return settings.value.offline; }, download: (fresh) => offline.download(fresh) };
|
||||
moreItem("m-offline", () => void offline.toggle());
|
||||
moreItem("m-tutorial", () => {});
|
||||
|
||||
@@ -182,6 +182,25 @@ export interface SketchFeature extends FeatureBase {
|
||||
|
||||
/** What was done in the sketch, in order (shown under it in History); repeats are counted. */
|
||||
log?: { op: string; n: number; ids?: string[] }[];
|
||||
/**
|
||||
* Fill patterns: closed shapes of the sketch filled with lines or small shapes (see sketch/fill.ts). Each one's
|
||||
* curves are among `entities`, named "fp-<fill id>-<n>", and are made again when the sketch's curves change.
|
||||
*/
|
||||
fills?: SketchFill[];
|
||||
}
|
||||
|
||||
/** A closed shape of a sketch filled with a pattern (Fill Pattern). */
|
||||
export interface SketchFill {
|
||||
id: string;
|
||||
/** A point inside the shape it fills. */
|
||||
at: Vec2;
|
||||
kind: "lines" | "cross" | "zigzag" | "waves" | "dots" | "hex" | "squares" | "diamonds";
|
||||
/** Lines: how far apart. Shapes: the gap between one and the next (mm). */
|
||||
spacing: number;
|
||||
/** The pattern turned by this much (degrees). */
|
||||
angle: number;
|
||||
/** Shapes: how big each is. Zigzag, waves: how big a tooth or a wave is (mm). */
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface ExtrudeFeature extends FeatureBase {
|
||||
|
||||
+106
-2
@@ -103,6 +103,12 @@ interface Ctx {
|
||||
freeforms: Map<string, { feature: Extract<Feature, { type: "freeform" }>; m: Affine }>;
|
||||
/** The paths sweeps ran along (by sweep): an offset of a sweep's end follows its path back. */
|
||||
sweeps: Map<string, Wire>;
|
||||
/**
|
||||
* Bodies linked to one another (a copy or a pattern made with Link on, and what it was made from): which group
|
||||
* each is of, and where it stands in it - the map that takes the group's shape to this body. A step that changes
|
||||
* one of a group changes the others the same way (see `followLinks`).
|
||||
*/
|
||||
links: Map<string, { group: string; m: Affine }>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -118,7 +124,7 @@ interface Reads {
|
||||
written: Set<string>;
|
||||
}
|
||||
let reading: Reads | null = null;
|
||||
const KINDS = ["bodies", "sketches", "planes", "axes", "freeforms", "sweeps"] as const;
|
||||
const KINDS = ["bodies", "sketches", "planes", "axes", "freeforms", "sweeps", "links"] as const;
|
||||
const rawGet = <V>(m: Map<string, V>, k: string): V | undefined => Map.prototype.get.call(m, k) as V | undefined;
|
||||
const rawHas = (m: Map<string, unknown>, k: string): boolean => Map.prototype.has.call(m, k) as boolean;
|
||||
const rawEntries = <V>(m: Map<string, V>): [string, V][] => [...(Map.prototype.entries.call(m) as IterableIterator<[string, V]>)];
|
||||
@@ -190,6 +196,7 @@ function fork(ctx: Ctx): Ctx {
|
||||
axes: new Noted("axes", ctx.axes),
|
||||
freeforms: new Noted("freeforms", ctx.freeforms),
|
||||
sweeps: new Noted("sweeps", ctx.sweeps),
|
||||
links: new Noted("links", ctx.links),
|
||||
};
|
||||
}
|
||||
/** How many steps the last rebuild ran, took as they were (nothing before them changed), or put back (nothing they read changed). */
|
||||
@@ -813,7 +820,7 @@ async function run(features: Feature[], saved = false) {
|
||||
editable = new Set(features.filter((f) => (f.type === "freeform" || f.type === "faceFreeform") && !f.suppressed).map((f) => f.id));
|
||||
const errors: FeatureError[] = [];
|
||||
const notes: FeatureError[] = [];
|
||||
let ctx: Ctx = fork({ bodies: new Map(), sketches: new Map(), planes: new Map(), axes: new Map(), freeforms: new Map(), sweeps: new Map() });
|
||||
let ctx: Ctx = fork({ bodies: new Map(), sketches: new Map(), planes: new Map(), axes: new Map(), freeforms: new Map(), sweeps: new Map(), links: new Map() });
|
||||
switchedOff = new Set(features.filter((f) => f.suppressed).map((f) => f.id));
|
||||
const off = [...switchedOff].sort().join();
|
||||
// The steps as last rebuilt (by step, wherever in the list they are now).
|
||||
@@ -942,6 +949,12 @@ async function run(features: Feature[], saved = false) {
|
||||
const was = ctx.bodies.get(id);
|
||||
if (body !== was) tagBody(body, f.id, was ? [was, ...from] : from, was ? others.filter((o) => o !== was) : others);
|
||||
}
|
||||
// Linked bodies: the others of a changed one's group follow it. (Any change among the links is a change
|
||||
// for this step: it is built again then.)
|
||||
if (f.type !== "transform") {
|
||||
reads.all.add("links");
|
||||
followLinks(f.id, ctx, out);
|
||||
}
|
||||
if (editNotes.length) entry.note = [...new Set(editNotes)].join(" ");
|
||||
// Anything but a move/scale changing a freeform body makes it an ordinary body.
|
||||
if (f.type !== "freeform" && f.type !== "transform") for (const id of [...out.freeforms.keys()]) if (out.bodies.get(id) !== ctx.bodies.get(id)) out.freeforms.delete(id);
|
||||
@@ -2067,6 +2080,78 @@ async function apply(f: Feature, ctx: Ctx): Promise<void> {
|
||||
type Affine = number[];
|
||||
const AFFINE_ID: Affine = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0];
|
||||
const applyAffine = (m: Affine, p: Vec3): Vec3 => [0, 1, 2].map((r) => m[r * 4] * p[0] + m[r * 4 + 1] * p[1] + m[r * 4 + 2] * p[2] + m[r * 4 + 3]) as Vec3;
|
||||
/** The map that undoes m (null: it squashes something flat, and has none). */
|
||||
function affineInverse(m: Affine): Affine | null {
|
||||
const [a, b, c, , d, e, f, , g, h, i] = m;
|
||||
const det = a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g);
|
||||
if (!(Math.abs(det) > 1e-12)) return null;
|
||||
const r = [(e * i - f * h) / det, (c * h - b * i) / det, (b * f - c * e) / det, (f * g - d * i) / det, (a * i - c * g) / det, (c * d - a * f) / det, (d * h - e * g) / det, (b * g - a * h) / det, (a * e - b * d) / det];
|
||||
const t = [m[3], m[7], m[11]];
|
||||
return [0, 1, 2].flatMap((k) => [r[k * 3], r[k * 3 + 1], r[k * 3 + 2], -(r[k * 3] * t[0] + r[k * 3 + 1] * t[1] + r[k * 3 + 2] * t[2])]);
|
||||
}
|
||||
const affineDet = (m: Affine): number => m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8]) + m[2] * (m[4] * m[9] - m[5] * m[8]);
|
||||
/** A move, turn, mirroring or even scaling (not a stretch): the only maps a shape is put through as it is. */
|
||||
function affineIsSimilar(m: Affine): boolean {
|
||||
const cols = [0, 1, 2].map((c) => [m[c], m[4 + c], m[8 + c]] as Vec3);
|
||||
const L = len(cols[0]);
|
||||
if (!(L > 1e-9)) return false;
|
||||
return cols.every((c) => Math.abs(len(c) - L) < 1e-9 * L) && Math.abs(dot(cols[0], cols[1])) < 1e-9 * L * L && Math.abs(dot(cols[0], cols[2])) < 1e-9 * L * L && Math.abs(dot(cols[1], cols[2])) < 1e-9 * L * L;
|
||||
}
|
||||
/** A shape put through a move, turn, mirroring or even scaling: a new shape, the one given left as it is. */
|
||||
function shapeThrough(s: Shape3D, m: Affine): Shape3D {
|
||||
const oc = getOC();
|
||||
const t = new oc.gp_Trsf();
|
||||
t.SetValues(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11]);
|
||||
const mk = new oc.BRepBuilderAPI_Transform(s.wrapped, t, true, false);
|
||||
try {
|
||||
return cast(mk.Shape()) as Shape3D;
|
||||
} finally {
|
||||
mk.delete();
|
||||
t.delete();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Linked bodies follow each other: a step that changed one body of a group (rounded an edge of it, cut a hole in
|
||||
* it, joined something to it...) leaves every other body of the group changed the same way - the changed body's
|
||||
* new shape, put where the other stands. (Asked for: "if it's linked, whatever change I do to any copy of that
|
||||
* body or the original, it should also change the other ones exactly the same. We should also have this in
|
||||
* patterns".) Moving or turning one of them is its own business: that only changes where it stands. One deleted,
|
||||
* or used up by a join, leaves the group; the others stay.
|
||||
*/
|
||||
function followLinks(step: string, before: Ctx, out: Ctx): void {
|
||||
const links = rawEntries(before.links);
|
||||
if (!links.length) return;
|
||||
const done = new Set<string>();
|
||||
for (const [id, lk] of links) {
|
||||
const now = rawGet(out.bodies, id);
|
||||
if (!now) {
|
||||
Map.prototype.delete.call(out.links, id);
|
||||
continue;
|
||||
}
|
||||
if (now === rawGet(before.bodies, id) || done.has(lk.group)) continue;
|
||||
done.add(lk.group);
|
||||
const back = affineInverse(lk.m);
|
||||
if (!back) continue;
|
||||
for (const [other, ol] of links) {
|
||||
if (other === id || ol.group !== lk.group) continue;
|
||||
const was = rawGet(out.bodies, other);
|
||||
// (Gone, or changed by this very step itself - a join of two of the group: left as the step left it.)
|
||||
if (!was || was !== rawGet(before.bodies, other)) continue;
|
||||
const rel = affineThen(back, ol.m);
|
||||
const s = shapeThrough(now, rel);
|
||||
const det = affineDet(rel);
|
||||
movedFrom.set(s, { from: new WeakRef(now), m: rel, flip: det < 0 });
|
||||
movedTags(now, s, step, rel);
|
||||
const v = volumes.get(now);
|
||||
if (v !== undefined) volumes.set(s, v * Math.abs(det));
|
||||
out.bodies.set(other, s);
|
||||
// (No longer the freeform it was: its shape is the changed body's now.)
|
||||
out.freeforms.delete(other);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** First m, then n. */
|
||||
function affineThen(m: Affine, n: Affine): Affine {
|
||||
const out: number[] = [];
|
||||
@@ -4179,6 +4264,25 @@ function transform(f: Extract<Feature, { type: "transform" }>, ctx: Ctx): void {
|
||||
movedTags(body, s, f.id, m);
|
||||
});
|
||||
const isPattern = op.kind === "linear" || op.kind === "circular";
|
||||
// Linked: the copies and what they were made from are a group (one already of a group: its copies join it);
|
||||
// each stands where its move put it. A linked body moved, turned, mirrored or scaled evenly stands somewhere
|
||||
// else in its group; stretched, it is no longer the others' shape, and leaves it.
|
||||
const placed = (k: number): Affine | null => {
|
||||
const m = rigid(k) ?? (isPattern ? null : opAffine(op));
|
||||
return m && affineIsSimilar(m) ? m : null;
|
||||
};
|
||||
const mine = ctx.links.get(id);
|
||||
if (isPattern || f.copy) {
|
||||
if (f.link && results.every((_, k) => placed(k))) {
|
||||
const at = mine ?? { group: `${f.id}:${id}`, m: AFFINE_ID };
|
||||
if (!mine) ctx.links.set(id, at);
|
||||
results.forEach((_, k) => ctx.links.set(`${f.id}:${id}:${k}`, { group: at.group, m: affineThen(at.m, placed(k)!) }));
|
||||
}
|
||||
} else if (mine) {
|
||||
const m = placed(0);
|
||||
if (m) ctx.links.set(id, { group: mine.group, m: affineThen(mine.m, m) });
|
||||
else ctx.links.delete(id);
|
||||
}
|
||||
// A freeform stays rebuildable through moves, scales and mirrors (copies too).
|
||||
const ff = ctx.freeforms.get(id);
|
||||
const step = ff && !isPattern ? opAffine(op) : null;
|
||||
|
||||
+2
-2
@@ -170,7 +170,7 @@ export function explodeJoined(
|
||||
}
|
||||
|
||||
/** Parameters where other entities cross primitive `p`. */
|
||||
function crossings(p: Prim, others: Prim[]): number[] {
|
||||
export function crossings(p: Prim, others: Prim[]): number[] {
|
||||
const ts: number[] = [];
|
||||
const n = Math.max(primSegments(p), 1) * 4;
|
||||
const A = Array.from({ length: n + 1 }, (_, i) => evalPrim(p, i / n));
|
||||
@@ -311,7 +311,7 @@ export function trim(entities: SketchEntity[], id: string, at: Vec2): SketchEnti
|
||||
}
|
||||
|
||||
/** Entity for part [t0, t1] of a primitive (t may exceed 1 for closed curves). */
|
||||
function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity {
|
||||
export function pieceEntity(p: Prim, t0: number, t1: number, construction?: boolean): SketchEntity {
|
||||
const at = (t: number) => evalPrim(p, isClosedPrim(p) && p.t !== "spline" ? t : Math.min(1, t > 1 ? t - 1 : t));
|
||||
if (p.t === "line") return { id: uid(), kind: "line", a: at(t0), b: at(t1), construction };
|
||||
if (p.t === "circle") return { id: uid(), kind: "arc", a: at(t0), m: at((t0 + t1) / 2), b: at(t1), construction };
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
// Fill Pattern: a closed shape of a sketch filled with a pattern of curves - lines from edge to edge (straight,
|
||||
// crossed, zigzag, waves) or small shapes inside it (dots, a honeycomb, squares, diamonds). The pattern's curves
|
||||
// are curves of the sketch like any other, so the strips and cells they make can be extruded or cut: a texture on
|
||||
// a model. (Asked for: "a new tool in sketch mode named fill pattern ... different line patterns that you can only
|
||||
// put in closed shapes that go from edges to edges ... very useful when I want different textures on my models.
|
||||
// Also I should be able to change the space between lines, or distance between shapes".)
|
||||
|
||||
import type { SketchEntity, SketchFill, Vec2 } from "../doc/types";
|
||||
import { arcFrom3, entityCorners, entityPrims, evalPrim, pointInPoly, type Prim } from "./curves";
|
||||
import { crossings, pieceEntity } from "./edit";
|
||||
import { arrangement, type Region } from "./regions";
|
||||
|
||||
/** The patterns, in the order they are offered. `lines`: whether it runs edge to edge (else: shapes inside). */
|
||||
export const FILL_KINDS: { id: SketchFill["kind"]; label: string; lines: boolean; sized: boolean }[] = [
|
||||
{ id: "lines", label: "Lines", lines: true, sized: false },
|
||||
{ id: "cross", label: "Crossed lines", lines: true, sized: false },
|
||||
{ id: "zigzag", label: "Zigzag", lines: true, sized: true },
|
||||
{ id: "waves", label: "Waves", lines: true, sized: true },
|
||||
{ id: "dots", label: "Dots", lines: false, sized: true },
|
||||
{ id: "hex", label: "Honeycomb", lines: false, sized: true },
|
||||
{ id: "squares", label: "Squares", lines: false, sized: true },
|
||||
{ id: "diamonds", label: "Diamonds", lines: false, sized: true },
|
||||
];
|
||||
|
||||
/** A fill's curves are named for it: "fp-<fill>-<n>". */
|
||||
export const FILL_PREFIX = "fp-";
|
||||
export const fillOf = (entityId: string): string | null => (entityId.startsWith(FILL_PREFIX) ? entityId.slice(FILL_PREFIX.length, entityId.lastIndexOf("-")) : null);
|
||||
/** The sketch's own curves: all but the ones fills made. */
|
||||
export const withoutFills = (entities: SketchEntity[]): SketchEntity[] => entities.filter((e) => !e.id.startsWith(FILL_PREFIX));
|
||||
|
||||
/** No more curves than this in one fill (a spacing typed a hundred times too small). */
|
||||
export const FILL_MOST = 2500;
|
||||
|
||||
const inRegion = (r: Region, q: Vec2): boolean => pointInPoly(q, r.outer.poly) && !r.holes.some((h) => pointInPoly(q, h.poly));
|
||||
|
||||
/** The closed shape a point is in (the smallest, where shapes are one in another): null on none. */
|
||||
export function fillRegion(entities: SketchEntity[], at: Vec2): Region | null {
|
||||
const regions = arrangement(withoutFills(entities)).regions.filter((r) => inRegion(r, at));
|
||||
return regions.sort((a, b) => a.area - b.area)[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The curves of one fill, for the sketch as it is (its own curves; other fills' are left out). Null: no closed
|
||||
* shape there. `tooMany`: the spacing gives more curves than a sketch should hold - none made.
|
||||
*/
|
||||
export function fillCurves(entities: SketchEntity[], fill: SketchFill): { curves: SketchEntity[]; tooMany?: boolean } | null {
|
||||
const own = withoutFills(entities);
|
||||
const region = fillRegion(own, fill.at);
|
||||
if (!region) return null;
|
||||
const around = new Set(region.curves);
|
||||
const edge: Prim[] = own.filter((e) => around.has(e.id) && !e.construction).flatMap(entityPrims);
|
||||
const kind = FILL_KINDS.find((k) => k.id === fill.kind) ?? FILL_KINDS[0];
|
||||
const out: SketchEntity[] = [];
|
||||
const name = () => `${FILL_PREFIX}${fill.id}-${out.length}`;
|
||||
const th = (fill.angle * Math.PI) / 180;
|
||||
const d: Vec2 = [Math.cos(th), Math.sin(th)];
|
||||
const n: Vec2 = [-d[1], d[0]];
|
||||
// The shape's reach along the pattern's own two ways, and its middle there.
|
||||
const along = region.outer.poly.map((p) => p[0] * d[0] + p[1] * d[1]);
|
||||
const across = region.outer.poly.map((p) => p[0] * n[0] + p[1] * n[1]);
|
||||
const [a0, a1, c0, c1] = [Math.min(...along), Math.max(...along), Math.min(...across), Math.max(...across)];
|
||||
const mid: Vec2 = [(a0 + a1) / 2, (c0 + c1) / 2];
|
||||
const at = (u: number, v: number): Vec2 => [d[0] * u + n[0] * v, d[1] * u + n[1] * v];
|
||||
const reach = Math.hypot(a1 - a0, c1 - c0);
|
||||
const step = Math.max(1e-6, Math.abs(fill.spacing));
|
||||
const size = Math.max(1e-6, Math.abs(fill.size));
|
||||
|
||||
/** The parts of a curve that are inside the shape, each from edge to edge. */
|
||||
const clipped = (p: Prim): boolean => {
|
||||
const ts = [0, ...crossings(p, edge), 1].filter((t, i, all) => i === 0 || t - all[i - 1] > 1e-7);
|
||||
for (let i = 0; i + 1 < ts.length; i++) {
|
||||
if (!inRegion(region, evalPrim(p, (ts[i] + ts[i + 1]) / 2))) continue;
|
||||
if (out.length >= FILL_MOST) return false;
|
||||
out.push({ ...pieceEntity(p, ts[i], ts[i + 1]), id: name() } as SketchEntity);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
if (kind.lines) {
|
||||
// Rows `step` apart, the middle one through the shape's middle; cross: the same again, square to them.
|
||||
for (const turn of fill.kind === "cross" ? [0, 1] : [0]) {
|
||||
const [u0, u1, v0, v1, um, vm] = turn ? [c0, c1, -a1, -a0, mid[1], -mid[0]] : [a0, a1, c0, c1, mid[0], mid[1]];
|
||||
const P = (u: number, v: number): Vec2 => (turn ? at(-v, u) : at(u, v));
|
||||
const pad = reach * 0.01 + 1e-3;
|
||||
const rows = Math.ceil((v1 - v0) / step / 2) + 1;
|
||||
if (rows * 2 > FILL_MOST) return { curves: [], tooMany: true };
|
||||
for (let k = -rows; k <= rows; k++) {
|
||||
const v = vm + k * step;
|
||||
// (Zigzag and waves swing `size` either side of their row.)
|
||||
const swing = fill.kind === "zigzag" || fill.kind === "waves" ? size / 2 : 0;
|
||||
if (v + swing <= v0 || v - swing >= v1) continue;
|
||||
if (fill.kind === "lines" || fill.kind === "cross") {
|
||||
if (!clipped({ t: "line", a: P(u0 - pad, v), b: P(u1 + pad, v), src: "" })) return { curves: [], tooMany: true };
|
||||
continue;
|
||||
}
|
||||
// A tooth or a wave every `size` along the row, up then down, starting a whole number of them from the middle.
|
||||
const first = um - Math.ceil((um - u0 + pad) / size) * size;
|
||||
const teeth = Math.ceil((u1 + pad - first) / size);
|
||||
if (teeth * rows > FILL_MOST * 4) return { curves: [], tooMany: true };
|
||||
for (let j = 0; j < teeth; j++) {
|
||||
const up = (Math.round((first - um) / size) + j) % 2 === 0 ? 1 : -1;
|
||||
const [x0, x1] = [first + j * size, first + (j + 1) * size];
|
||||
let prim: Prim;
|
||||
if (fill.kind === "zigzag") prim = { t: "line", a: P(x0, v - (up * size) / 2), b: P(x1, v + (up * size) / 2), src: "" };
|
||||
else {
|
||||
const arc = arcFrom3(P(x0, v), P((x0 + x1) / 2, v + up * size * 0.3), P(x1, v));
|
||||
if (!arc) continue;
|
||||
prim = { t: "circle", c: arc.c, r: arc.r, a0: arc.a0, sweep: arc.sweep, src: "" };
|
||||
}
|
||||
if (!clipped(prim)) return { curves: [], tooMany: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
return { curves: out };
|
||||
}
|
||||
|
||||
// Shapes: `size` across, `step` between one and the next, in rows - every other row half a step along for dots,
|
||||
// the honeycomb and diamonds. Only those wholly inside the shape.
|
||||
const pitch = size + step;
|
||||
const stagger = fill.kind !== "squares";
|
||||
const rowGap = fill.kind === "squares" ? pitch : fill.kind === "diamonds" ? pitch / 2 : (pitch * Math.sqrt(3)) / 2;
|
||||
const rows = Math.ceil((c1 - c0) / rowGap / 2) + 1;
|
||||
const cols = Math.ceil((a1 - a0) / pitch / 2) + 1;
|
||||
if ((2 * rows + 1) * (2 * cols + 1) > FILL_MOST * 6) return { curves: [], tooMany: true };
|
||||
for (let r = -rows; r <= rows; r++) {
|
||||
for (let c = -cols; c <= cols; c++) {
|
||||
const u = mid[0] + c * pitch + (stagger && r % 2 !== 0 ? pitch / 2 : 0);
|
||||
const v = mid[1] + r * rowGap;
|
||||
const centre = at(u, v);
|
||||
let e: SketchEntity;
|
||||
let rim: Vec2[];
|
||||
if (fill.kind === "dots") {
|
||||
e = { id: "", kind: "circle", center: centre, radius: size / 2 } as SketchEntity;
|
||||
rim = Array.from({ length: 16 }, (_, i) => [centre[0] + (size / 2) * Math.cos((i * Math.PI) / 8), centre[1] + (size / 2) * Math.sin((i * Math.PI) / 8)] as Vec2);
|
||||
} else {
|
||||
// (Honeycomb: `size` across its flats, a flat towards its neighbours in the row. Squares: `size` a side.
|
||||
// Diamonds: `size` from point to point.)
|
||||
const [sides, radius, turn] = fill.kind === "hex" ? [6, size / Math.sqrt(3), th] : fill.kind === "squares" ? [4, size / Math.SQRT2, th + Math.PI / 4] : [4, size / 2, th];
|
||||
const poly = { id: "", kind: "polygon" as const, center: centre, radius, sides, angle: turn };
|
||||
e = poly as SketchEntity;
|
||||
const corners = entityCorners(poly as Extract<SketchEntity, { kind: "polygon" }>);
|
||||
rim = corners.flatMap((p, i) => {
|
||||
const q = corners[(i + 1) % corners.length];
|
||||
return [p, [(p[0] + q[0]) / 2, (p[1] + q[1]) / 2] as Vec2];
|
||||
});
|
||||
}
|
||||
if (!rim.every((p) => inRegion(region, p))) continue;
|
||||
// (All its points inside, and its outline crossing nothing: not across a thin neck of the shape.)
|
||||
if (entityPrims(e).some((p) => crossings(p, edge).length)) continue;
|
||||
if (out.length >= FILL_MOST) return { curves: [], tooMany: true };
|
||||
out.push({ ...e, id: name() });
|
||||
}
|
||||
}
|
||||
return { curves: out };
|
||||
}
|
||||
|
||||
/**
|
||||
* The sketch's curves with every fill's made again for the shapes as they are now (a shape changed size: its
|
||||
* pattern follows). A fill whose shape is gone keeps the curves it had; curves of a fill that is no more go.
|
||||
*/
|
||||
export function refill(entities: SketchEntity[], fills: SketchFill[] | undefined): SketchEntity[] {
|
||||
const own = withoutFills(entities);
|
||||
if (!fills?.length) return own.length === entities.length ? entities : own;
|
||||
const made: SketchEntity[] = [];
|
||||
for (const f of fills) {
|
||||
const got = fillCurves(own, f);
|
||||
if (got && !got.tooMany) made.push(...got.curves);
|
||||
else made.push(...entities.filter((e) => fillOf(e.id) === f.id));
|
||||
}
|
||||
return [...own, ...made];
|
||||
}
|
||||
+29
-2
@@ -725,10 +725,17 @@ body.panel-open .tool.active::before,
|
||||
.right-btn:hover {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
.right-btn.on {
|
||||
.right-btn.on,
|
||||
.right-btn.pop-open {
|
||||
background: var(--accent-soft);
|
||||
color: #b9d4ff;
|
||||
}
|
||||
/* (Lit while its window is open, as the three at the left edge are while they are on - asked for: "make sure even
|
||||
the buttons on the middle right (fit, shaders, settings) show when something is opened. like the ones on the
|
||||
middle left".) */
|
||||
.right-btn.pop-open .right-label {
|
||||
color: #b9d4ff;
|
||||
}
|
||||
/* Buttons that only make sense while sketching. */
|
||||
.right-btn.sketch-only {
|
||||
display: none;
|
||||
@@ -5926,7 +5933,11 @@ body.sentence-ui #panel:not(:has(.text-input)) {
|
||||
bottom: calc(10px + var(--safe-b));
|
||||
width: fit-content;
|
||||
min-width: min(260px, 100%);
|
||||
max-width: 980px;
|
||||
/* (As wide as what is on it, up to all the room between undo and the right edge's column: it stopped at 980 and
|
||||
ran under its own end on a wide screen - a sketch's line picked, its sizes and constraints on the line. Asked
|
||||
for: "the bar should be wider to fit all the buttons without having to scroll on it. It's more than enough
|
||||
space on desktop".) */
|
||||
max-width: none;
|
||||
z-index: 12;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -7221,3 +7232,19 @@ body.sentence-ui #undo-dock .dock-btn {
|
||||
bottom: calc(8px + var(--safe-b));
|
||||
}
|
||||
}
|
||||
|
||||
/* A switch on a row of the More list (Guide text, Offline mode), at the row's right end - they said On or Off in
|
||||
words (asked for: "make the two buttons (guide text and offline mode) have a toggle icon"). */
|
||||
.menu .menu-toggle {
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
.menu .menu-toggle .menu-soon {
|
||||
margin-left: auto;
|
||||
}
|
||||
.menu-toggle.on .switch {
|
||||
background: var(--accent);
|
||||
}
|
||||
.menu-toggle.on .switch::after {
|
||||
left: 17px;
|
||||
}
|
||||
|
||||
@@ -1691,6 +1691,8 @@ export class TransformOp extends FeatureOp<TransformFeature> {
|
||||
this.slots = [axisSlot(app, "Axis", () => this.axis, (a) => ((this.axis = a), this.applyAxis()))];
|
||||
this.center = o.kind === "move" && o.rotate ? o.rotate.origin : center;
|
||||
if (copy && !existing && linkMode.on) this.feature.link = true;
|
||||
// (A new pattern: linked if Link was left on the last time.)
|
||||
if ((kind === "linear" || kind === "circular") && !existing && linkMode.on) this.feature.link = true;
|
||||
if (kind === "move") {
|
||||
this.gimbal = new Gimbal(app.view);
|
||||
const g = this.gimbal;
|
||||
@@ -1811,6 +1813,20 @@ export class TransformOp extends FeatureOp<TransformFeature> {
|
||||
},
|
||||
};
|
||||
const copy: PanelItem[] = this.feature.copy && !this.existing ? [copyToggle, link] : [copyToggle];
|
||||
// A pattern's Link: its copies and what they were made from change together afterwards - a hole cut in one is
|
||||
// cut in all (asked for: "we should also have this in patterns"). Off, each is a body of its own.
|
||||
const patternLink: PanelItem = {
|
||||
type: "toggle",
|
||||
label: "Link",
|
||||
value: !!this.feature.link,
|
||||
onChange: (v) => {
|
||||
linkMode.on = v;
|
||||
if (v) this.feature.link = true;
|
||||
else delete this.feature.link;
|
||||
this.render();
|
||||
up();
|
||||
},
|
||||
};
|
||||
// ΔX ΔY ΔZ: when changing a step opened from History, and on touch screens
|
||||
// (with a mouse, moving is dragging or typing while dragging - the numbers
|
||||
// are clutter there; a finger has no keyboard mid-drag, so exact moves need them).
|
||||
@@ -1846,11 +1862,13 @@ export class TransformOp extends FeatureOp<TransformFeature> {
|
||||
return [
|
||||
this.num("Count", "op.count", "int", { min: 2 }),
|
||||
this.num("Spacing", "op.spacing", "length"),
|
||||
patternLink,
|
||||
];
|
||||
case "circular":
|
||||
return [
|
||||
this.num("Count", "op.count", "int", { min: 2 }),
|
||||
this.num("Angle", "op.angle", "angle"),
|
||||
patternLink,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,9 @@ export const QUICK = {
|
||||
// chamfer". Its dot is on the edge to drag as well.)
|
||||
edge: ["fillet", "chamfer", "move", "thread", "connect"],
|
||||
vertex: ["moveVertex", "delete"],
|
||||
body: ["fillet", "mirror"],
|
||||
// (A body that is, or began as, a freeform: Edit Freeform first - asked for: "when I double click a freeform body,
|
||||
// I want the edit freeform button there".)
|
||||
body: ["editFreeform", "fillet", "mirror"],
|
||||
profile: ["extrude", "revolve"],
|
||||
plane: ["sketch", "plane"],
|
||||
axis: ["delete"],
|
||||
|
||||
+29
-14
@@ -478,14 +478,14 @@ export class SelectTool implements Tool {
|
||||
// left); edges: the fillet radius. The tool armed on tap takes the value.
|
||||
if (!e.ctrlKey && !e.metaKey && !e.altKey && /^[0-9.]$/.test(e.key) && sel.length) {
|
||||
const first = sel[0];
|
||||
if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.freeformOf(first.body)) {
|
||||
if (first.kind === "face" && sel.length === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.sheetFreeform(first.body)) {
|
||||
const src = sourcesOf(this.app, sel)[0];
|
||||
if (src) {
|
||||
this.app.setTool(new ExtrudeOp(this.app, src, undefined, "auto", { typed: e.key }));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (first.kind === "edge" && sel.every((x) => x.kind === "edge") && !this.freeformOf(first.body)) {
|
||||
if (first.kind === "edge" && sel.every((x) => x.kind === "edge") && !this.sheetFreeform(first.body)) {
|
||||
const refs = this.edgeRefs();
|
||||
if (refs.length) {
|
||||
this.app.setTool(new EdgeOp(this.app, "fillet", refs.map((r) => ({ ...r })), undefined, undefined, e.key));
|
||||
@@ -554,8 +554,8 @@ export class SelectTool implements Tool {
|
||||
this.copyToggle = new CopyToggle(this.app.view, () => g.origin);
|
||||
} else if (first.kind === "vertex" && sel.length === 1) {
|
||||
const v = this.app.view.vertexOf(first.body, first.vertex);
|
||||
// A freeform's points are moved in Edit Freeform, so no gimbal here.
|
||||
if (v && !this.freeformOf(first.body)) {
|
||||
// (A freeform left as an open surface: its points are moved in Edit Freeform, so no gimbal here.)
|
||||
if (v && !this.sheetFreeform(first.body)) {
|
||||
this.gimbal = new Gimbal(this.app.view);
|
||||
this.gimbal.setCenter(v);
|
||||
}
|
||||
@@ -582,7 +582,7 @@ export class SelectTool implements Tool {
|
||||
// ready to drag, and a number typed is the radius. Moving a straight
|
||||
// edge (its faces tilt to follow) is Move/Rotate Edge (M) in the list.
|
||||
// (A freeform's edges get neither: its shape comes from the cage.)
|
||||
if (e && !this.freeformOf(first.body)) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", [e, ...all.slice(0, -1)]).grabFromEdge());
|
||||
if (e && !this.sheetFreeform(first.body)) this.showHandle({ base: e.mid, normal: e.dir }, "dot", () => new EdgeOp(this.app, "fillet", [e, ...all.slice(0, -1)]).grabFromEdge());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -599,13 +599,13 @@ export class SelectTool implements Tool {
|
||||
const or = this.quick ? `or ${tap} a button beside it` : "or pick a tool";
|
||||
const direct = settings.value.direct;
|
||||
if (direct && first.kind === "profile") return `Drag the shape (or its arrow) to pull it into 3D, ${or}.`;
|
||||
if (direct && first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.freeformOf(first.body)) return `Drag the face (or its arrow) to push or pull it, ${or}.`;
|
||||
if (direct && first.kind === "edge" && !this.freeformOf(first.body)) return `Drag ${n > 1 ? "an edge" : "the edge"} (or its dot) to round ${n > 1 ? "them" : "it"}, ${or}.`;
|
||||
if (direct && first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.sheetFreeform(first.body)) return `Drag the face (or its arrow) to push or pull it, ${or}.`;
|
||||
if (direct && first.kind === "edge" && !this.sheetFreeform(first.body)) return `Drag ${n > 1 ? "an edge" : "the edge"} (or its dot) to round ${n > 1 ? "them" : "it"}, ${or}.`;
|
||||
if (direct && first.kind === "body") return `Drag it to slide it over the floor, or its arrows and arcs to move and turn it, ${or}.`;
|
||||
if (first.kind === "profile") return `Drag the arrow to extrude, ${or}.`;
|
||||
if (first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.freeformOf(first.body)) return `Drag the arrow to move the face, ${or}.`;
|
||||
if (first.kind === "face" && n === 1 && offsettable(this.app.view.body(first.body)?.faces[first.face]?.type) && !this.sheetFreeform(first.body)) return `Drag the arrow to move the face, ${or}.`;
|
||||
if (first.kind === "face" && n === 2 && sel[1].kind === "face") return "The distance between the faces is shown. Pick a tool for them.";
|
||||
if (first.kind === "edge" && !this.freeformOf(first.body)) return `Drag the dot to round ${n > 1 ? "the edges" : "the edge"}, ${or}.`;
|
||||
if (first.kind === "edge" && !this.sheetFreeform(first.body)) return `Drag the dot to round ${n > 1 ? "the edges" : "the edge"}, ${or}.`;
|
||||
if (first.kind === "body") return `Drag the arrows or arcs to move it, ${or}.`;
|
||||
return this.quick ? `${cap(tap)} a button beside it, or pick a tool on the line at the bottom.` : `Pick a tool for ${n > 1 ? "them" : "it"}, or ${tap} another to add it (${tap} a picked one to let it go).`;
|
||||
}
|
||||
@@ -705,9 +705,9 @@ export class SelectTool implements Tool {
|
||||
}
|
||||
head.push({ id: "thicken", label: "Thickness…", icon: "shell", run: () => this.app.setTool(new FreeformTool(this.app, { feature: own() })) });
|
||||
}
|
||||
// A face, edge or point of a freeform: its shape comes from the cage -
|
||||
// fillet, chamfer, offset face… don't apply (they were listed all the same).
|
||||
if (ff?.type === "freeform" && (first.kind === "face" || first.kind === "edge" || first.kind === "vertex")) {
|
||||
// A face, edge or point of a freeform left as an open surface: its shape comes from the cage - fillet, chamfer,
|
||||
// offset face... don't apply. (A finished freeform solid has every tool a body has: it was held to these few.)
|
||||
if (ff?.type === "freeform" && this.sheetFreeform(ffBody) && (first.kind === "face" || first.kind === "edge" || first.kind === "vertex")) {
|
||||
const bodies = bodiesOf(sel);
|
||||
const app = this.app;
|
||||
return [
|
||||
@@ -738,7 +738,7 @@ export class SelectTool implements Tool {
|
||||
const pivot = this.app.view.vertexOf(s.body, s.vertex);
|
||||
const at = sel.flatMap((x) => (x.kind === "vertex" && x.body === s.body ? [this.app.view.vertexOf(x.body, x.vertex)!].filter(Boolean) : []));
|
||||
// A freeform's points move in Edit Freeform (at the top of this list), not here.
|
||||
const isFreeform = !!ff && ff.type === "freeform";
|
||||
const isFreeform = this.sheetFreeform(s.body);
|
||||
return [
|
||||
...head,
|
||||
...(isFreeform ? [] : [{ id: "moveVertex", label: "Move Vertex", icon: "point" as const, shortcut: "M", active: true, disabled: !pivot, run: () => pivot && this.app.setTool(new MoveFaceOp(this.app, { vertex: { body: s.body, at: pivot } })) }]),
|
||||
@@ -1433,6 +1433,21 @@ export class SelectTool implements Tool {
|
||||
this.app.ui.toast("Connected - Thickness… makes it a solid");
|
||||
}
|
||||
|
||||
/**
|
||||
* A freeform that is still an open surface (faces deleted from it, or made as a surface): the one kind of freeform
|
||||
* body that isn't worked on like any other - no arrow to push its faces, no dot to round its edges, its points
|
||||
* moved in Edit Freeform. A finished freeform solid is a body like any other: every body tool is its too (asked
|
||||
* for: "a freeform body that is finished (not in freeform edit mode) should be treated like a regular body ... I
|
||||
* want to have access to normal body tools, to polish it even further"). Edit Freeform is still there for it -
|
||||
* beside the body when it is double tapped, and in History.
|
||||
*/
|
||||
private sheetFreeform(body: string): boolean {
|
||||
const live = freeformBodies(this.app.store.features).get(body)?.feature;
|
||||
if (!live) return false;
|
||||
const now = editedStep<FreeformFeature>(this.app.store.features, live.id) ?? live;
|
||||
return !isClosed(now.cage);
|
||||
}
|
||||
|
||||
/** The freeform a body is made from (its own, or the one a copy was made of). */
|
||||
private freeformOf(body: string): FreeformFeature | undefined {
|
||||
const f = this.app.store.find<FreeformFeature>(body);
|
||||
@@ -1470,7 +1485,7 @@ export class SelectTool implements Tool {
|
||||
/** Delete faces/edges/vertices of one body; tells the user when it can't heal. */
|
||||
private deleteGeom(body: string, what: { faces?: FaceRef[]; edges?: EdgeRef[]; vertices?: Vec3[] }): void {
|
||||
// A freeform body: the cage loses the faces there, and stays open for a thickness.
|
||||
const ff = this.freeformOf(body) && this.ownFreeform(body);
|
||||
const ff = this.sheetFreeform(body) ? this.ownFreeform(body) : undefined;
|
||||
if (ff) {
|
||||
const tool = new FreeformTool(this.app, { feature: ff });
|
||||
this.app.setTool(tool);
|
||||
|
||||
+5791
-5716
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -110,7 +110,7 @@ export function showAbout(): void {
|
||||
const back = el("div", "dialog-back");
|
||||
const box = el("div", "dialog about");
|
||||
const head = el("div", "library-head");
|
||||
head.append(el("div", "panel-title", "About superGeometry.app"));
|
||||
head.append(el("div", "panel-title", "About"));
|
||||
const closeBtn = el("button", "icon-btn library-close");
|
||||
closeBtn.type = "button";
|
||||
closeBtn.title = "Close";
|
||||
|
||||
@@ -56,6 +56,7 @@ const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [
|
||||
{ icon: "offsetFace", name: "Face", text: "Drag the face itself, or its arrow, to push/pull it (its neighbours follow; on a touch screen press and hold a face, then pull, in one touch), Move/Rotate it (every way, and turned about its normal), Scale it, Replace it with another face's plane, sketch on it, or delete it (the neighbours close up as if it was never there - fillets too)." },
|
||||
{ icon: "moveEdge", name: "Edge", text: "Fillet is ready: drag the edge itself or its dot outward to round, inward to bevel, or type the radius. Fillet can be Variable (a start and an end radius; Flip ends swaps them), sized by Chord width (straight across the round) instead of radius, Smooth (G2: the bend eases in from the faces, no line in reflections - straight edges between flat faces, and round edges of cylinders), and given a Corner setback (where three rounded edges meet they stop short and one smooth patch joins them). A round too big for a face beside it cuts on through that face's far edge, still exactly round. Chamfer can use two distances (Flip sides swaps them). Move/Rotate Edge (M) tilts the faces round a straight edge." },
|
||||
{ icon: "move", name: "Body", text: "Drag the body itself to slide it over the floor. The gimbal moves (arrows), slides (squares) and turns (rings) it; drag the dot in its middle to move the point it turns about - it snaps to corners, edges and faces. With Copy on, a drag makes a copy; the panel stays when you let go so you can type exact values. A copy is its own body; switch Link on to keep a freeform copy shaped like its original. A body of a pattern: Whole Pattern picks the rest." },
|
||||
{ icon: "link", name: "Link (copies and patterns)", text: "With Copy on in Move/Rotate, Mirror or Scale - and in both Patterns - switch Link on: the copies and what they were made from then change together. Round an edge or cut a hole in any one of them and all the others get it too, each where it stands. Moving or turning one only moves that one; deleting one leaves the others. Off, each copy is a body of its own." },
|
||||
{ icon: "copy", name: "Sketch → Copy to Plane", text: "Tap a sketch region, then Copy to Plane: drag the blue arrow to a parallel plane (or red/green to slide it), or type the distance. Turn Copy off to move the sketch instead." },
|
||||
{ icon: "color", name: "Colour / Transparency", text: "Pick a colour for the selected bodies (or Custom… for any colour), and how see-through they are (Solid, 75%, 50%, 25%)." },
|
||||
],
|
||||
@@ -75,6 +76,7 @@ const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [
|
||||
{ icon: "spline", name: "Spline > Draw (freehand)", text: "Press and drag to draw, like a pencil (on touch: one finger draws, two move the view). When you let go the stroke is cleaned up into a few pieces: straight parts become lines, round parts arcs, the rest smooth curves through as few points as keep them within a couple of pixels of what you drew; sharp corners stay corners. End where you began to close it (a round loop becomes a circle), then extrude it like any shape. Starting or ending on a point joins it there." },
|
||||
{ icon: "project", name: "Project", text: "Copy body edges or curves of other sketches into this sketch (a round edge comes in as an arc, or seen at a slant as part of an ellipse - two ends, like the edge). Or the other way: tap lines of this sketch, then a plane or flat face parallel to it - they're copied onto it as a new sketch." },
|
||||
{ icon: "offset", name: "Offset Edge", text: "A parallel copy of a curve (or a whole outline) at a distance - or of a body's edge: tap the edge, and choose Edge (that one) or Chain (the whole outline of its face). What is offset stays lit; drag the double arrow on the new curve, or type, to set how far. Tap empty space to finish." },
|
||||
{ icon: "hatch", name: "Fill Pattern", text: "Fills a closed shape with a pattern: under Draw, then tap inside the shape. Lines, Crossed lines, Zigzag and Waves run from edge to edge; Dots, Honeycomb, Squares and Diamonds are small shapes kept inside it. Set the Spacing (or the Gap between shapes), the Size and the Angle, then Apply. The strips and cells are shapes of their own: exit the sketch and extrude or cut them for a texture. Tap a filled shape again to change its pattern or remove it; when the shape changes size, its pattern follows." },
|
||||
{ icon: "sketchFillet", name: "Fillet / Chamfer", text: "Round or bevel a corner: tap the corner itself (of a line chain, rectangle or polygon), or two lines or arcs that meet; tap the next corner to go on." },
|
||||
{ icon: "trim", name: "Trim / Join", text: "Cut away the piece of a curve between crossings (tap, or swipe across several) - or join two lines on the same axis." },
|
||||
{ icon: "mirror", name: "Mirror, Move/Rotate, Pattern", text: "Mirror the selected shapes across a line or an axis; Move/Rotate with its gimbal (turns about the selection's own centre); Rotate About turns the whole selection rigidly about a point you tap - an end, a midpoint or another shape's centre - so its own centre swings round that point (the dotted arc shows the path); Pattern in a row or round a centre." },
|
||||
|
||||
@@ -57,6 +57,8 @@ export const icons = {
|
||||
shell: svg('<path d="M4 8v12h16V8"/><path d="M7 8v9h10V8"/>'),
|
||||
split: svg('<rect x="4" y="5" width="16" height="14"/><path d="M12 2v20" stroke-dasharray="2 2"/>'),
|
||||
fill: svg('<path d="M4 18L12 4l8 14z" fill="currentColor" fill-opacity=".3"/>'),
|
||||
// Fill Pattern: a closed shape with lines across it, edge to edge.
|
||||
hatch: svg('<rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 12l8-8M4 20L20 4M12 20l8-8"/>'),
|
||||
wrap: svg('<path d="M4 7c5-3 11-3 16 0v10c-5-3-11-3-16 0z"/><path d="M9 11h6"/>'),
|
||||
replaceFace: svg('<rect x="4" y="9" width="12" height="11"/><path d="M8 9l4-5h8l-4 5M20 4v11l-4 5"/>'),
|
||||
projectEdge: svg('<rect x="4" y="12" width="16" height="8"/><path d="M8 4h8l-2 8h-4z" stroke-dasharray="2 2"/>'),
|
||||
|
||||
+27
-9
@@ -49,25 +49,43 @@ export function setupRightColumn(ui: UI, view: Viewport, store: DocStore, onUnit
|
||||
const s = settings.value;
|
||||
// Switched on, it keeps the squares as they are right now, at this zoom (asked for: "I want the lock grid size
|
||||
// toggle to adjust to whatever the zoom level is so I can just click toggle on").
|
||||
host.append(
|
||||
toggleRow(s.gridLocked ? `Lock grid size (${fmtStep(s.gridStep)})` : `Lock grid size (now ${fmtStep(view.grid.step)})`, s.gridLocked, (v) => {
|
||||
if (v) settings.set("gridStep", +view.grid.step.toPrecision(6));
|
||||
settings.set("gridLocked", v);
|
||||
ui.refreshPopover();
|
||||
}),
|
||||
);
|
||||
const lockRow = toggleRow(s.gridLocked ? `Lock grid size (${fmtStep(s.gridStep)})` : `Lock grid size (now ${fmtStep(view.grid.step)})`, s.gridLocked, (v) => {
|
||||
if (v) settings.set("gridStep", +view.grid.step.toPrecision(6));
|
||||
settings.set("gridLocked", v);
|
||||
ui.refreshPopover();
|
||||
});
|
||||
host.append(lockRow);
|
||||
const stepRow = el("label", "pop-row");
|
||||
stepRow.append(el("span", "", "Locked size (mm)"));
|
||||
const input = textField("pop-input");
|
||||
input.inputMode = "decimal";
|
||||
input.value = String(s.gridStep);
|
||||
// (Not locked: the squares' size right now - what locking would keep.)
|
||||
input.value = String(s.gridLocked ? s.gridStep : +view.grid.step.toPrecision(6));
|
||||
input.addEventListener("change", () => {
|
||||
const v = Number(input.value);
|
||||
if (v > 0) settings.set("gridStep", v);
|
||||
});
|
||||
stepRow.append(input);
|
||||
host.append(stepRow);
|
||||
host.append(el("div", "pop-note", s.gridLocked ? "The squares stay this size at any zoom, and a sketch snaps to them. Switch the lock off for a grid that follows the zoom." : `The grid follows the zoom (now ${fmtStep(view.grid.step)} a square), and a sketch snaps to the squares shown. Lock it to keep them as they are now.`));
|
||||
const gridNote = el("div", "pop-note", s.gridLocked ? "The squares stay this size at any zoom, and a sketch snaps to them. Switch the lock off for a grid that follows the zoom." : `The grid follows the zoom (now ${fmtStep(view.grid.step)} a square), and a sketch snaps to the squares shown. Lock it to keep them as they are now.`);
|
||||
host.append(gridNote);
|
||||
// Not locked, the size follows the zoom while this is open: the row, the box and the note say the squares'
|
||||
// size as it is now (asked for: "the lock grid size should change on the fly when I zoom so I can see what
|
||||
// size grid it is in that moment"). They said the size it was when the window opened.
|
||||
if (!s.gridLocked) {
|
||||
let shown = view.grid.step;
|
||||
const follow = () => {
|
||||
// (Closed, or drawn again: this one is done.)
|
||||
if (!lockRow.isConnected || lockRow.closest("[hidden]")) return void view.frameHooks.delete(follow);
|
||||
const now = view.grid.step;
|
||||
if (now === shown) return;
|
||||
shown = now;
|
||||
(lockRow.firstElementChild as HTMLElement).textContent = `Lock grid size (now ${fmtStep(now)})`;
|
||||
if (document.activeElement !== input) input.value = String(+now.toPrecision(6));
|
||||
gridNote.textContent = `The grid follows the zoom (now ${fmtStep(now)} a square), and a sketch snaps to the squares shown. Lock it to keep them as they are now.`;
|
||||
};
|
||||
view.frameHooks.add(follow);
|
||||
}
|
||||
host.append(heading("Degree format"));
|
||||
host.append(choiceRow("Decimal (27.15°)", s.degrees === "decimal", () => (settings.set("degrees", "decimal"), ui.refreshPopover())), choiceRow("Fractional (27° 15′)", s.degrees === "fractional", () => (settings.set("degrees", "fractional"), ui.refreshPopover())));
|
||||
}),
|
||||
|
||||
+30
-6
@@ -82,6 +82,8 @@ interface Word {
|
||||
quiet?: boolean;
|
||||
kbd?: string;
|
||||
run?: () => void;
|
||||
/** Done as its list is opened (a sketch's Draw: Line is on, to draw at once). */
|
||||
opens?: () => void;
|
||||
/** What it opens: a tool's kinds, a choice's other options. */
|
||||
kids?: Word[];
|
||||
/** A number: typed, or dragged sideways. */
|
||||
@@ -159,7 +161,7 @@ const SK_ONCE = new Set(["trim", "split"]);
|
||||
const GROUPS = ["create", "combine", "modify", "construct", "transform", "freeform", "sketch"];
|
||||
/** A sketch's groups (as its wheel has them): what each holds, most used first; anything else is under More. */
|
||||
const SK_GROUPS: { id: string; label: string; icon: IconName; tools: string[] }[] = [
|
||||
{ id: "draw", label: "Draw", icon: "line", tools: ["line", "rect", "circle", "arc", "spline", "polygon", "ellipse", "text", "project"] },
|
||||
{ id: "draw", label: "Draw", icon: "line", tools: ["line", "rect", "circle", "arc", "spline", "polygon", "ellipse", "text", "project", "fill"] },
|
||||
{ id: "modify", label: "Modify", icon: "trim", tools: ["trim", "fillet", "offset", "extend", "split", "align"] },
|
||||
{ id: "transform", label: "Transform", icon: "transform", tools: ["move", "mirror", "rotate", "pattern", "scale"] },
|
||||
];
|
||||
@@ -355,8 +357,9 @@ export class Sentence {
|
||||
const [l, r] = to.split("|");
|
||||
this.root.style.left = to ? `${l}px` : "";
|
||||
this.root.style.right = to ? `${r}px` : "";
|
||||
// (No wider than that room: past it the line slides.)
|
||||
this.root.style.maxWidth = to ? `${Math.max(200, Math.min(980, innerWidth - Number(l) - Number(r)))}px` : "";
|
||||
// (No wider than that room: past it the line slides. All of that room, though: it stopped at 980 on a wide
|
||||
// screen, and a sketch's picked line had to be slid to reach its last buttons.)
|
||||
this.root.style.maxWidth = to ? `${Math.max(200, innerWidth - Number(l) - Number(r))}px` : "";
|
||||
this.threadSig = "";
|
||||
}
|
||||
|
||||
@@ -545,7 +548,15 @@ export class Sentence {
|
||||
const its = g.tools.map((id) => tools.find((it) => it.id === id)).filter((it): it is ToolItem => !!it && offered(it));
|
||||
for (const it of its) placed.add(it);
|
||||
const w = its.map(retapped);
|
||||
words.push(this.group(g.id, g.label, g.icon, w, "Pick a line or a shape of the sketch first."));
|
||||
const word = this.group(g.id, g.label, g.icon, w, "Pick a line or a shape of the sketch first.");
|
||||
// Draw opened with no tool on: Line is on, its list open as ever - a tap on the grid draws at once, a tap
|
||||
// in the list takes another (asked for: "when I click draw, line should be automatically selected (but
|
||||
// the window with different line types should open normally) so I can start drawing right away").
|
||||
if (g.id === "draw" && !drawing && picked === 0) {
|
||||
const line = w.find((x) => x.key.endsWith("line") || x.label === "Line");
|
||||
if (line?.run) word.opens = line.run;
|
||||
}
|
||||
words.push(word);
|
||||
if (w.length) groups.push({ cap: g.label, words: w });
|
||||
}
|
||||
// (Delete: a tap - the curves picked, else the tool that deletes what is tapped; unless their window has it already.)
|
||||
@@ -659,6 +670,9 @@ export class Sentence {
|
||||
|
||||
// ------------------------------------------------------------------ drawing
|
||||
|
||||
/** A list kept open through the next change of sentence (opening it started a tool). */
|
||||
private stays = "";
|
||||
|
||||
private render(): void {
|
||||
const b = (this.built = this.build());
|
||||
const fresh = b.about !== this.about;
|
||||
@@ -668,10 +682,11 @@ export class Sentence {
|
||||
else if (!b.about.startsWith("tool:")) this.lastPick = "";
|
||||
const lead: Word[] = b.about.startsWith("tool:") && this.lastPick ? [{ key: "s-was", kind: "subject", label: this.lastPick, quiet: true }] : [];
|
||||
// (Another sentence: whatever was open belonged to the last one.)
|
||||
if (fresh && this.open) {
|
||||
if (fresh && this.open && !(this.open.kind === "kids" && this.open.key === this.stays)) {
|
||||
this.typing?.end(false);
|
||||
this.open = null;
|
||||
}
|
||||
if (fresh) this.stays = "";
|
||||
// (Nothing picked: no subject - the groups say it all.)
|
||||
const about = [...lead, ...(b.subject.key === "s-make" ? [] : [b.subject]), ...(b.more ? [b.more] : []), ...(b.also ?? []), ...(b.title ? [b.title] : [])];
|
||||
this.fill(this.tag, about, fresh);
|
||||
@@ -917,7 +932,16 @@ export class Sentence {
|
||||
if (w.off) return void (buzz(), this.host.ui.toast(w.off));
|
||||
if (w.value) return void this.toggle({ kind: "type", key: w.key });
|
||||
// A tool with kinds starts as it was used last; while it is the one in use, a tap shows its kinds.
|
||||
if (w.kids?.length && (!w.first || w.on)) return void this.toggle({ kind: "kids", key: w.key });
|
||||
if (w.kids?.length && (!w.first || w.on)) {
|
||||
const opening = !(this.open?.kind === "kids" && this.open.key === w.key);
|
||||
this.toggle({ kind: "kids", key: w.key });
|
||||
if (opening && w.opens) {
|
||||
// (What it does makes another sentence - Line is on: this list stays open through that.)
|
||||
this.stays = w.key;
|
||||
w.opens();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!w.run) return;
|
||||
buzz();
|
||||
const stays = w.kind === "toggle" || w.kind === "slot" || d.closest(".sn-sheet") === null;
|
||||
|
||||
+78
-13
@@ -558,19 +558,8 @@ export class UI {
|
||||
this.popoverFill();
|
||||
if (!this.popover.childElementCount) return this.closePopover();
|
||||
this.popover.hidden = false;
|
||||
const r = b.getBoundingClientRect();
|
||||
if (place) {
|
||||
// Opened from the view cube: under the cube, its right edge lined up with the button.
|
||||
// (Clear of the right-hand column below it.)
|
||||
const col = this.rightCol.getBoundingClientRect();
|
||||
this.popover.style.right = `${Math.max(window.innerWidth - r.right, col.width ? window.innerWidth - col.left + 8 : 8)}px`;
|
||||
this.popover.style.top = `${Math.min(r.bottom + 6, window.innerHeight - this.popover.offsetHeight - 8)}px`;
|
||||
} else {
|
||||
this.popover.style.right = "";
|
||||
// Phones: below the top bar, like History.
|
||||
const topMin = window.innerWidth <= 720 || window.innerHeight <= 500 ? 52 : 8;
|
||||
this.popover.style.top = `${Math.max(topMin, Math.min(r.top, window.innerHeight - this.popover.offsetHeight - 8))}px`;
|
||||
}
|
||||
this.popoverAt = { button: b, cube: !!place };
|
||||
this.placePopover();
|
||||
document.querySelectorAll(".pop-open").forEach((x) => x.classList.remove("pop-open"));
|
||||
b.classList.add("pop-open");
|
||||
// Things placed beside the right column (the constraint column) move over.
|
||||
@@ -585,6 +574,80 @@ export class UI {
|
||||
}
|
||||
|
||||
private popoverFill: (() => void) | null = null;
|
||||
/** The button the open window came from (and whether that is the view cube's). */
|
||||
private popoverAt: { button: HTMLElement; cube: boolean } | null = null;
|
||||
private popoverWatch: ResizeObserver | null = null;
|
||||
|
||||
/**
|
||||
* Where the window opened from the right column (Shaded, Settings, Views...) stands: beside its button, and in
|
||||
* the room there is - under the top bar and whatever else is above it there (the view cube, History, Items),
|
||||
* over the line at the bottom, undo / redo and the guide text. Longer than that room, it scrolls inside. Worked
|
||||
* out from where those are now, on every screen (asked for: "when a window opens from those, to not override
|
||||
* anything else (should be dynamic)"): it stood by fixed sizes, and on a phone came down over the line.
|
||||
*/
|
||||
private placePopover(): void {
|
||||
const at = this.popoverAt;
|
||||
const pop = this.popover;
|
||||
if (!at || pop.hidden) return;
|
||||
const W = window.innerWidth;
|
||||
const H = window.innerHeight;
|
||||
const r = at.button.getBoundingClientRect();
|
||||
const col = this.rightCol.getBoundingClientRect();
|
||||
pop.style.maxHeight = "";
|
||||
// Sideways: beside the column (the stylesheet's place), or under the cube with its right edge at the button.
|
||||
pop.style.right = at.cube ? `${Math.max(W - r.right, col.width ? W - col.left + 8 : 8)}px` : "";
|
||||
let box = pop.getBoundingClientRect();
|
||||
const seen = (sel: string): DOMRect | null => {
|
||||
const e = document.querySelector<HTMLElement>(sel);
|
||||
if (!e || e === at.button || e.contains(at.button)) return null;
|
||||
const cs = getComputedStyle(e);
|
||||
if (cs.display === "none" || cs.visibility === "hidden") return null;
|
||||
const q = e.getBoundingClientRect();
|
||||
return q.width && q.height && q.right > box.left + 2 && q.left < box.right - 2 ? q : null;
|
||||
};
|
||||
// (What stands above it gives way to nothing; what stands below neither: the window takes what is between.)
|
||||
let top = 8;
|
||||
let bottom = H - 8;
|
||||
const between = () => {
|
||||
top = 8;
|
||||
bottom = H - 8;
|
||||
for (const sel of ["#topbar", "#viewcube-host", "#history.open", "#items.open", "#hint", ".sn-line", "#undo-dock", "#numpad"]) {
|
||||
const q = seen(sel);
|
||||
if (!q) continue;
|
||||
// (Above the middle: over it. Below: under it. One down the whole edge - a long History - is beside it.)
|
||||
if (q.bottom < H * 0.55) top = Math.max(top, q.bottom + 6);
|
||||
else if (q.top > H * 0.45) bottom = Math.min(bottom, q.top - 6);
|
||||
}
|
||||
};
|
||||
between();
|
||||
// Hardly any room under the view cube (a phone on its side): beside the cube, not a slit under it.
|
||||
const cube = !at.cube && bottom - top < 170 ? seen("#viewcube-host") : null;
|
||||
if (cube && cube.left - 8 >= box.width) {
|
||||
pop.style.right = `${Math.round(W - cube.left + 6)}px`;
|
||||
box = pop.getBoundingClientRect();
|
||||
between();
|
||||
}
|
||||
const room = Math.max(120, bottom - top);
|
||||
pop.style.maxHeight = `${room}px`;
|
||||
const h = Math.min(pop.offsetHeight, room);
|
||||
const want = at.cube ? r.bottom + 6 : r.top;
|
||||
pop.style.top = `${Math.round(Math.max(top, Math.min(want, bottom - h)))}px`;
|
||||
// Its size or the line's changes (a choice inside it, a list opened from the line): placed again.
|
||||
if (!this.popoverWatch) {
|
||||
let queued = false;
|
||||
const again = () => {
|
||||
if (queued) return;
|
||||
queued = true;
|
||||
requestAnimationFrame(() => ((queued = false), this.placePopover()));
|
||||
};
|
||||
this.popoverWatch = new ResizeObserver(again);
|
||||
for (const sel of [".sn-line", "#history", "#items", "#hint"]) {
|
||||
const e = document.querySelector(sel);
|
||||
if (e) this.popoverWatch.observe(e);
|
||||
}
|
||||
window.addEventListener("resize", again);
|
||||
}
|
||||
}
|
||||
|
||||
/** The right column's lists and switches, by id (Settings opens the ones that have no button of their own). */
|
||||
private rightEntries = new Map<string, { open: (host: HTMLElement) => void; label?: () => string }>();
|
||||
@@ -602,6 +665,7 @@ export class UI {
|
||||
this.popover.style.maxHeight = "";
|
||||
this.popover.hidden = true;
|
||||
this.popoverFill = null;
|
||||
this.popoverAt = null;
|
||||
document.querySelectorAll(".pop-open").forEach((x) => x.classList.remove("pop-open"));
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
}
|
||||
@@ -609,6 +673,7 @@ export class UI {
|
||||
/** Re-draw the open popover (after one of its choices changed). */
|
||||
refreshPopover(): void {
|
||||
this.popoverFill?.();
|
||||
this.placePopover();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------- hint/status/toast
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
// Run: npx tsx tests/fillpattern.test.ts
|
||||
// Fill Pattern: a closed shape of a sketch filled with lines from edge to edge, or with small shapes inside it.
|
||||
// The lines end exactly on the shape's edge (so the strips between them are closed shapes to extrude), stay out of
|
||||
// holes, follow the shape when it changes - and the engine builds solids from what they make.
|
||||
import { after, bodies, check, done, health, near, sketch, volume, XY, circle, rect } from "./kit";
|
||||
import { FILL_KINDS, FILL_MOST, fillCurves, fillOf, fillRegion, refill, withoutFills } from "../src/sketch/fill";
|
||||
import { arrangement, regionRef } from "../src/sketch/regions";
|
||||
import { entityCorners, entityPrims, evalPrim } from "../src/sketch/curves";
|
||||
import type { Feature, SketchEntity, SketchFill, Vec2 } from "../src/doc/types";
|
||||
import type { Shape3D } from "replicad";
|
||||
|
||||
const R = [rect("r", 0, 0, 40, 20)];
|
||||
const fill = (kind: SketchFill["kind"], extra: Partial<SketchFill> = {}): SketchFill => ({ id: "f1", at: [20, 10], kind, spacing: 5, angle: 0, size: 4, ...extra });
|
||||
const ends = (e: SketchEntity): Vec2[] => entityPrims(e).flatMap((p) => [evalPrim(p, 0), evalPrim(p, 1)]);
|
||||
const onRect = (p: Vec2, w = 40, h = 20) => (Math.abs(p[0]) < 1e-7 || Math.abs(p[0] - w) < 1e-7 || Math.abs(p[1]) < 1e-7 || Math.abs(p[1] - h) < 1e-7) && p[0] > -1e-7 && p[0] < w + 1e-7 && p[1] > -1e-7 && p[1] < h + 1e-7;
|
||||
const inRect = (p: Vec2, w = 40, h = 20) => p[0] > -1e-7 && p[0] < w + 1e-7 && p[1] > -1e-7 && p[1] < h + 1e-7;
|
||||
|
||||
check("a point in the rectangle is in a closed shape; one outside is in none", !!fillRegion(R, [20, 10]) && !fillRegion(R, [50, 10]));
|
||||
|
||||
// ---- lines
|
||||
{
|
||||
const got = fillCurves(R, fill("lines"))!;
|
||||
const ys = got.curves.map((e) => (e as { a: Vec2 }).a[1]).sort((a, b) => a - b);
|
||||
check("lines 5 apart in a 40 x 20 rectangle: three, at 5, 10 and 15, each from edge to edge", got.curves.length === 3 && ys.join() === "5,10,15" && got.curves.every((e) => e.kind === "line" && ends(e).every((p) => onRect(p))), JSON.stringify(got.curves.map((e) => ends(e))));
|
||||
check(" named for their fill", got.curves.every((e) => fillOf(e.id) === "f1"));
|
||||
const arr = arrangement([...R, ...got.curves]);
|
||||
check(" the rectangle is four strips now, 200 mm² each", arr.regions.length === 4 && arr.regions.every((r) => near(r.area, 200, 1e-6)), arr.regions.map((r) => r.area.toFixed(2)).join());
|
||||
const wide = fillCurves(R, fill("lines", { spacing: 2 }))!;
|
||||
check(" 2 apart: nine", wide.curves.length === 9);
|
||||
const slant = fillCurves(R, fill("lines", { angle: 45 }))!;
|
||||
check(" at 45 degrees: every end on the rectangle's edge, each line at 45", slant.curves.length > 5 && slant.curves.every((e) => ends(e).every((p) => onRect(p)) && near(Math.abs(((e as { b: Vec2 }).b[1] - (e as { a: Vec2 }).a[1]) / ((e as { b: Vec2 }).b[0] - (e as { a: Vec2 }).a[0])), 1, 1e-9)), `${slant.curves.length} lines`);
|
||||
}
|
||||
// ---- crossed lines
|
||||
{
|
||||
const got = fillCurves(R, fill("cross"))!;
|
||||
const arr = arrangement([...R, ...got.curves]);
|
||||
check("crossed lines 5 apart: three one way, seven the other, 32 squares of 25 mm²", got.curves.length === 10 && arr.regions.length === 32 && arr.regions.every((r) => near(r.area, 25, 1e-6)), `${got.curves.length} lines, ${arr.regions.length} regions`);
|
||||
}
|
||||
// ---- in a circle: the ends on the circle exactly
|
||||
{
|
||||
const C = [circle("c", 0, 0, 10)];
|
||||
const got = fillCurves(C, fill("lines", { at: [0, 0], spacing: 3, angle: 30 }))!;
|
||||
const worst = Math.max(...got.curves.flatMap((e) => ends(e).map((p) => Math.abs(Math.hypot(p[0], p[1]) - 10))));
|
||||
check("lines in a circle: every end on the circle (to a millionth of a mm)", got.curves.length === 7 && worst < 1e-6, `${got.curves.length} lines, worst ${worst.toExponential(1)}`);
|
||||
check(" and the circle is eight closed pieces", arrangement([...C, ...got.curves]).regions.length === 8);
|
||||
}
|
||||
// ---- a shape with a hole: the lines stop at the hole
|
||||
{
|
||||
const H = [...R, circle("h", 20, 10, 4)];
|
||||
const got = fillCurves(H, fill("lines", { at: [5, 10] }))!;
|
||||
const mid = got.curves.filter((e) => near((e as { a: Vec2 }).a[1], 10, 1e-9));
|
||||
check("a rectangle with a round hole: the middle line is two, stopping at the hole (x 16 and 24)", got.curves.length === 4 && mid.length === 2 && mid.flatMap(ends).map((p) => +p[0].toFixed(6)).sort((a, b) => a - b).join() === "0,16,24,40", JSON.stringify(mid.map(ends)));
|
||||
check(" a point in the hole fills the hole, not the plate", fillRegion(H, [20, 10])!.area < 60);
|
||||
}
|
||||
// ---- zigzag and waves: edge to edge, and closed strips between rows
|
||||
for (const kind of ["zigzag", "waves"] as const) {
|
||||
const got = fillCurves(R, fill(kind, { spacing: 6, size: 4 }))!;
|
||||
const all = got.curves.flatMap(ends);
|
||||
const arr = arrangement([...R, ...got.curves]);
|
||||
check(`${kind}: every piece inside, its loose ends on the edge, the rectangle in closed strips`, got.curves.length > 20 && all.every((p) => inRect(p)) && all.filter((p) => onRect(p)).length >= 6 && arr.regions.length >= 4 && near(arr.regions.reduce((s, r) => s + r.area, 0), 800, 1e-3), `${got.curves.length} pieces, ${arr.regions.length} regions, ${arr.regions.reduce((s, r) => s + r.area, 0).toFixed(3)} mm²`);
|
||||
}
|
||||
// ---- shapes: all wholly inside, the gap as asked
|
||||
{
|
||||
const dots = fillCurves(R, fill("dots", { size: 4, spacing: 2 }))!;
|
||||
const cs = dots.curves.map((e) => (e as { center: Vec2 }).center);
|
||||
let least = Infinity;
|
||||
for (let i = 0; i < cs.length; i++) for (let j = i + 1; j < cs.length; j++) least = Math.min(least, Math.hypot(cs[i][0] - cs[j][0], cs[i][1] - cs[j][1]));
|
||||
check("dots 4 across, 2 between: all inside the rectangle, none nearer another than 2", dots.curves.length >= 15 && dots.curves.every((e) => e.kind === "circle" && cs.every((c) => c[0] >= 2 - 1e-9 && c[0] <= 38 + 1e-9 && c[1] >= 2 - 1e-9 && c[1] <= 18 + 1e-9)) && near(least, 6, 1e-9), `${dots.curves.length} dots, nearest centres ${least.toFixed(4)}`);
|
||||
for (const kind of ["hex", "squares", "diamonds"] as const) {
|
||||
const got = fillCurves(R, fill(kind, { size: 4, spacing: 1.5 }))!;
|
||||
const corners = got.curves.flatMap((e) => entityCorners(e as Extract<SketchEntity, { kind: "polygon" }>));
|
||||
const arr = arrangement([...R, ...got.curves]);
|
||||
check(`${kind}: all inside, each a closed shape of its own (${got.curves.length})`, got.curves.length >= 8 && corners.every((p) => inRect(p)) && arr.regions.length === got.curves.length + 1, `${arr.regions.length} regions`);
|
||||
}
|
||||
const sq = fillCurves(R, fill("squares", { size: 4, spacing: 1 }))!;
|
||||
const first = entityCorners(sq.curves[0] as Extract<SketchEntity, { kind: "polygon" }>);
|
||||
check(" squares 4 a side", near(Math.hypot(first[1][0] - first[0][0], first[1][1] - first[0][1]), 4, 1e-9));
|
||||
const hx = fillCurves(R, fill("hex", { size: 4, spacing: 1 }))!;
|
||||
const hc = entityCorners(hx.curves[0] as Extract<SketchEntity, { kind: "polygon" }>);
|
||||
check(" a honeycomb cell 4 across its flats", near(Math.hypot(hc[0][0] - hc[2][0], hc[0][1] - hc[2][1]), 4, 1e-9), Math.hypot(hc[0][0] - hc[2][0], hc[0][1] - hc[2][1]).toFixed(4));
|
||||
}
|
||||
// ---- far too many: none made, and said
|
||||
{
|
||||
const got = fillCurves(R, fill("lines", { spacing: 0.001 }))!;
|
||||
check("lines a thousandth apart: none made (too many)", !!got.tooMany && !got.curves.length);
|
||||
const most = fillCurves(R, fill("dots", { size: 0.05, spacing: 0.05 }))!;
|
||||
check("dots a twentieth across: none made (too many)", !!most.tooMany && most.curves.length <= FILL_MOST);
|
||||
}
|
||||
// ---- the shape changes: the pattern follows
|
||||
{
|
||||
const f = fill("lines");
|
||||
const before = refill(R, [f]);
|
||||
const bigger = refill([rect("r", 0, 0, 60, 30), ...before.filter((e) => e.id !== "r")], [f]);
|
||||
const lines = bigger.filter((e) => fillOf(e.id) === "f1");
|
||||
check("the rectangle made 60 x 30: five lines now, each 60 long", withoutFills(bigger).length === 1 && lines.length === 5 && lines.every((e) => ends(e).every((p) => onRect(p, 60, 30))), `${lines.length} lines`);
|
||||
check("the fill taken away: its lines go", refill(bigger, []).length === 1);
|
||||
const gone = refill(before.filter((e) => e.id !== "r"), [f]);
|
||||
check("the shape itself deleted: the lines it had stay as they were", gone.length === 3);
|
||||
check("every kind is offered once", new Set(FILL_KINDS.map((k) => k.id)).size === 8);
|
||||
}
|
||||
// ---- the engine: the strips are shapes to extrude
|
||||
{
|
||||
const f = fill("lines");
|
||||
const ents = refill(R, [f]);
|
||||
const sk = { ...sketch("S", XY(), ents), fills: [f] } as Feature;
|
||||
const regions = arrangement(ents).regions.map(regionRef);
|
||||
const every = { id: "E", name: "E", type: "extrude", source: { kind: "profile", sketch: "S", regions }, distance: 3, mode: "new" } as unknown as Feature;
|
||||
const r = await after([sk, every]);
|
||||
const vol = [...bodies().values()].reduce((s, b) => s + volume(b as Shape3D), 0);
|
||||
check("all four strips extruded 3: 2400 mm³, sound", !r.errors.length && near(vol, 2400, 1e-3) && [...bodies().values()].every((b) => health(b as Shape3D).healthy), `${vol.toFixed(2)} ${r.errors.join("; ")}`);
|
||||
const two = { ...every, source: { kind: "profile", sketch: "S", regions: regions.filter((_, i) => i % 2 === 0) } } as unknown as Feature;
|
||||
const r2 = await after([sk, two]);
|
||||
const v2 = [...bodies().values()].reduce((s, b) => s + volume(b as Shape3D), 0);
|
||||
check("every other strip: two ribs, 1200 mm³", !r2.errors.length && near(v2, 1200, 1e-3), `${v2.toFixed(2)} ${r2.errors.join("; ")}`);
|
||||
const hexes = refill(R, [fill("hex", { size: 4, spacing: 1.5 })]);
|
||||
const cells = arrangement(hexes).regions.filter((x) => x.area < 100).map(regionRef);
|
||||
const r3 = await after([{ ...sketch("S", XY(), hexes) } as Feature, { ...every, source: { kind: "profile", sketch: "S", regions: cells } } as unknown as Feature]);
|
||||
const v3 = [...bodies().values()].reduce((s, b) => s + volume(b as Shape3D), 0);
|
||||
const cell = (Math.sqrt(3) / 2) * 16;
|
||||
check("a honeycomb's cells extruded 3: each cell's area times 3", !r3.errors.length && near(v3, cells.length * cell * 3, 1e-2), `${cells.length} cells, ${v3.toFixed(2)} for ${(cells.length * cell * 3).toFixed(2)} ${r3.errors.join("; ")}`);
|
||||
}
|
||||
done();
|
||||
@@ -0,0 +1,100 @@
|
||||
// Run: npx tsx tests/linked.test.ts
|
||||
// Linked copies and linked patterns: a change made to any one of them (the original or a copy) is made to all the
|
||||
// others the same way, each where it stands. Moving one only moves that one. Not linked: each is its own.
|
||||
import { after, block, bodies, check, cylinder, done, health, near, volume } from "./kit";
|
||||
import type { Feature, Vec3 } from "../src/doc/types";
|
||||
import type { Shape3D } from "replicad";
|
||||
|
||||
const B = (id: string) => bodies().get(id) as Shape3D | undefined;
|
||||
const box = (id: string) => {
|
||||
const [lo, hi] = B(id)!.boundingBox.bounds;
|
||||
return [...lo, ...hi].map((v) => Math.round(v * 1000) / 1000);
|
||||
};
|
||||
const sound = () => [...bodies().values()].every((b) => health(b as Shape3D).healthy);
|
||||
const move = (id: string, body: string, translate: Vec3, extra: Record<string, unknown> = {}): Feature => ({ id, name: id, type: "transform", bodies: [body], copy: true, link: true, op: { kind: "move", translate }, ...extra }) as unknown as Feature;
|
||||
const cut = (id: string, target: string, tool: string): Feature => ({ id, name: id, type: "boolean", op: "subtract", target, tools: [tool] }) as unknown as Feature;
|
||||
|
||||
// A 20 x 10 x 5 block (1000), and a peg to cut holes with: radius 2 through it (pi * 4 * 5 = 62.83).
|
||||
const A = block("A", 20, 10, 5);
|
||||
const hole = Math.PI * 4 * 5;
|
||||
const peg = (id: string, x: number, y: number) => cylinder(id, 2, 9, x, y, -2);
|
||||
|
||||
// ---- a linked copy: a hole in the original is in the copy too
|
||||
{
|
||||
const r = await after([...A, move("C", "A", [50, 0, 0]), ...peg("P", 5, 5), cut("cut", "A", "P")]);
|
||||
check("a hole cut in the original: the linked copy has it too", !r.errors.length && near(volume(B("A")), 1000 - hole, 1e-3) && near(volume(B("C:A:0")), 1000 - hole, 1e-3) && sound(), `${volume(B("A")).toFixed(2)} ${volume(B("C:A:0")).toFixed(2)} ${r.errors.join("; ")}`);
|
||||
check(" the copy still where it was put", box("C:A:0").join() === [50, 0, 0, 70, 10, 5].join(), box("C:A:0").join());
|
||||
}
|
||||
// ---- the other way: a hole in the copy is in the original
|
||||
{
|
||||
const r = await after([...A, move("C", "A", [50, 0, 0]), ...peg("P", 65, 5), cut("cut", "C:A:0", "P")]);
|
||||
check("a hole cut in the copy: the original has it too", !r.errors.length && near(volume(B("A")), 1000 - hole, 1e-3) && near(volume(B("C:A:0")), 1000 - hole, 1e-3) && sound(), `${volume(B("A")).toFixed(2)} ${volume(B("C:A:0")).toFixed(2)} ${r.errors.join("; ")}`);
|
||||
// Where: 15 along the copy from its own corner, so 15 along the original.
|
||||
const probe = await after([...A, move("C", "A", [50, 0, 0]), ...peg("P", 65, 5), cut("cut", "C:A:0", "P"), ...peg("Q", 15, 5), cut("again", "A", "Q")]);
|
||||
check(" and in the same place on it (a peg put there cuts nothing more)", !probe.errors.length || /nothing|didn't|missed/i.test(probe.errors.join()), `${volume(B("A")).toFixed(2)}`);
|
||||
check(" (the original's volume after that second cut: as before it)", near(volume(B("A")), 1000 - hole, 1e-2), volume(B("A")).toFixed(2));
|
||||
}
|
||||
// ---- not linked: each its own
|
||||
{
|
||||
const r = await after([...A, move("C", "A", [50, 0, 0], { link: undefined }), ...peg("P", 5, 5), cut("cut", "A", "P")]);
|
||||
check("a copy that is not linked stays as it was", !r.errors.length && near(volume(B("A")), 1000 - hole, 1e-3) && near(volume(B("C:A:0")), 1000, 1e-3), `${volume(B("A")).toFixed(2)} ${volume(B("C:A:0")).toFixed(2)}`);
|
||||
}
|
||||
// ---- a copy turned: the change turns with it
|
||||
{
|
||||
const turned: Feature = { id: "R", name: "R", type: "transform", bodies: ["A"], copy: true, link: true, op: { kind: "move", translate: [0, 40, 0], rotate: { origin: [0, 0, 0], axis: [0, 0, 1], angle: 90 } } } as unknown as Feature;
|
||||
// A notch off the original's far end (x 16 to 20): on the copy, turned a quarter, that is its far end in y.
|
||||
const notch = block("N", 4, 10, 5, [16, 0, 0]);
|
||||
const r = await after([...A, turned, ...notch, cut("cut", "A", "N")]);
|
||||
check("a copy turned a quarter: the end cut off the original is cut off its own end", !r.errors.length && near(volume(B("R:A:0")), 800, 1e-3) && box("R:A:0").join() === [-10, 40, 0, 0, 56, 5].join() && sound(), `${volume(B("R:A:0")).toFixed(2)} ${box("R:A:0").join()} ${r.errors.join("; ")}`);
|
||||
}
|
||||
// ---- a mirrored copy: the change is mirrored
|
||||
{
|
||||
const mir: Feature = { id: "M", name: "M", type: "transform", bodies: ["A"], copy: true, link: true, op: { kind: "mirror", plane: { origin: [-5, 0, 0], normal: [1, 0, 0], xDir: [0, 1, 0] } } } as unknown as Feature;
|
||||
const notch = block("N", 4, 10, 5, [16, 0, 0]);
|
||||
const r = await after([...A, mir, ...notch, cut("cut", "A", "N")]);
|
||||
// The original now 0..16; mirrored about x = -5: -26..-10.
|
||||
check("a mirrored copy: the far end cut off the original is cut off its far end, mirrored", !r.errors.length && near(volume(B("M:A:0")), 800, 1e-3) && box("M:A:0").join() === [-26, 0, 0, -10, 10, 5].join() && sound() && volume(B("M:A:0")) > 0, `${volume(B("M:A:0")).toFixed(2)} ${box("M:A:0").join()} ${r.errors.join("; ")}`);
|
||||
}
|
||||
// ---- a linked pattern: one changed, all changed
|
||||
{
|
||||
const pat: Feature = { id: "L", name: "L", type: "transform", bodies: ["A"], copy: false, link: true, op: { kind: "linear", dir: [0, 1, 0], spacing: 20, count: 4 } } as unknown as Feature;
|
||||
const r = await after([...A, pat, ...peg("P", 5, 45), cut("cut", "L:A:1", "P")]);
|
||||
const ids = ["A", "L:A:0", "L:A:1", "L:A:2"];
|
||||
check("a linked pattern of four, a hole cut in the third: all four have it", !r.errors.length && ids.every((id) => near(volume(B(id)), 1000 - hole, 1e-3)) && sound(), ids.map((id) => volume(B(id)).toFixed(1)).join(" ") + " " + r.errors.join("; "));
|
||||
check(" each where the pattern put it", ids.map((id) => box(id)[1]).join() === "0,20,40,60", ids.map((id) => box(id)[1]).join());
|
||||
const plain = await after([...A, { ...pat, link: undefined } as Feature, ...peg("P", 5, 45), cut("cut", "L:A:1", "P")]);
|
||||
check(" not linked: only the one cut", !plain.errors.length && near(volume(B("L:A:1")), 1000 - hole, 1e-3) && ["A", "L:A:0", "L:A:2"].every((id) => near(volume(B(id)), 1000, 1e-3)));
|
||||
const ring: Feature = { id: "O", name: "O", type: "transform", bodies: ["A"], copy: false, link: true, op: { kind: "circular", axis: { origin: [-30, 0, 0], dir: [0, 0, 1] }, count: 5, angle: 360 } } as unknown as Feature;
|
||||
const rr = await after([...A, ring, ...peg("P", 5, 5), cut("cut", "A", "P")]);
|
||||
const all = ["A", "O:A:0", "O:A:1", "O:A:2", "O:A:3"];
|
||||
check("a linked pattern round an axis, a hole cut in the first: all five have it", !rr.errors.length && all.every((id) => near(volume(B(id)), 1000 - hole, 1e-3)) && sound(), all.map((id) => volume(B(id)).toFixed(1)).join(" ") + " " + rr.errors.join("; "));
|
||||
}
|
||||
// ---- one of them moved afterwards: only it moves, and it still follows
|
||||
{
|
||||
const shift: Feature = { id: "S", name: "S", type: "transform", bodies: ["C:A:0"], copy: false, op: { kind: "move", translate: [0, 0, 30] } } as unknown as Feature;
|
||||
const r = await after([...A, move("C", "A", [50, 0, 0]), shift, ...peg("P", 5, 5), cut("cut", "A", "P")]);
|
||||
check("a linked copy moved later: only it moved, and it still follows", !r.errors.length && box("A").join() === [0, 0, 0, 20, 10, 5].join() && box("C:A:0").join() === [50, 0, 30, 70, 10, 35].join() && near(volume(B("C:A:0")), 1000 - hole, 1e-3), `${box("C:A:0").join()} ${volume(B("C:A:0")).toFixed(2)}`);
|
||||
}
|
||||
// ---- a copy of a copy is of the same group
|
||||
{
|
||||
const r = await after([...A, move("C", "A", [50, 0, 0]), move("D", "C:A:0", [0, 30, 0]), ...peg("P", 55, 35), cut("cut", "D:C:A:0:0", "P")]);
|
||||
check("a linked copy of a linked copy, cut: the copy and the original follow", !r.errors.length && ["A", "C:A:0", "D:C:A:0:0"].every((id) => near(volume(B(id)), 1000 - hole, 1e-3)), ["A", "C:A:0", "D:C:A:0:0"].map((id) => volume(B(id)).toFixed(1)).join(" ") + " " + r.errors.join("; "));
|
||||
}
|
||||
// ---- one deleted: the others stay, and still follow each other
|
||||
{
|
||||
const del: Feature = { id: "X", name: "X", type: "delete", bodies: ["C:A:0"] } as unknown as Feature;
|
||||
const r = await after([...A, move("C", "A", [50, 0, 0]), move("D", "A", [0, 30, 0]), del, ...peg("P", 5, 5), cut("cut", "A", "P")]);
|
||||
check("one of three deleted: gone, the other two still follow", !r.errors.length && !B("C:A:0") && near(volume(B("A")), 1000 - hole, 1e-3) && near(volume(B("D:A:0")), 1000 - hole, 1e-3));
|
||||
}
|
||||
// ---- changed again and built again: the same (what is kept from the last build is right)
|
||||
{
|
||||
const steps = (x: number) => [...A, move("C", "A", [50, 0, 0]), ...peg("P", x, 5), cut("cut", "A", "P")];
|
||||
await after(steps(5));
|
||||
const first = box("C:A:0").join();
|
||||
const r = await after(steps(21.5));
|
||||
// The peg half off the end: a half hole (half of 62.83, about) - the copy's too.
|
||||
check("the hole moved half off the end and built again: the copy has that", !r.errors.length && near(volume(B("C:A:0")), volume(B("A")), 1e-6) && volume(B("A")) > 1000 - hole + 1 && box("C:A:0").join() === first, `${volume(B("A")).toFixed(2)} ${volume(B("C:A:0")).toFixed(2)}`);
|
||||
const back = await after(steps(5));
|
||||
check("and back", !back.errors.length && near(volume(B("C:A:0")), 1000 - hole, 1e-3));
|
||||
}
|
||||
done();
|
||||
Reference in New Issue
Block a user