feat: improve modeling, exports, and hosted deployment

This commit is contained in:
Formsmith746
2026-08-23 10:20:57 +03:00
parent 4f3859f215
commit 95b029e274
19 changed files with 1643 additions and 126 deletions
+135 -12
View File
@@ -1,4 +1,8 @@
import { timingSafeEqual } from "node:crypto";
import { execFile, spawn } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { promisify } from "node:util";
import { NextResponse } from "next/server";
import { appUpdateIsAvailable, OFFICIAL_UPDATE_GUIDE_URL, type AppUpdateStatus } from "@/lib/appUpdates";
import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
@@ -8,8 +12,11 @@ export const dynamic = "force-dynamic";
export const revalidate = false;
const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json";
const OFFICIAL_REPO_URL = "https://github.com/Formsmith746/SketchForge-3D.git";
const UPDATE_CACHE_MS = 5 * 60 * 1000;
const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000;
const execFileAsync = promisify(execFile);
const VERSION_PATTERN = /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
let cachedLatest: { version: string; expiresAt: number } | null = null;
let nextTriggerAt = 0;
@@ -29,12 +36,56 @@ function sameOriginRequest(request: Request) {
}
}
function loopbackRequest(request: Request) {
try {
const hostname = new URL(request.url).hostname.toLowerCase();
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1" || hostname === "[::1]";
} catch {
return false;
}
}
function safeEqual(left: string, right: string) {
const leftBytes = Buffer.from(left);
const rightBytes = Buffer.from(right);
return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);
}
function findParentRoot(requireGit: boolean) {
let current = path.resolve(process.cwd());
for (let depth = 0; depth < 7; depth += 1) {
const hasPackage = existsSync(path.join(current, "package.json"));
const hasGit = existsSync(path.join(current, ".git"));
if (hasPackage && (!requireGit || hasGit)) return current;
const parent = path.dirname(current);
if (parent === current) break;
current = parent;
}
return null;
}
function packageVersion(root: string | null) {
if (!root) return null;
try {
const payload = JSON.parse(readFileSync(path.join(root, "package.json"), "utf8")) as { version?: unknown };
const version = typeof payload.version === "string" ? payload.version.trim() : "";
return VERSION_PATTERN.test(version) ? version : null;
} catch {
return null;
}
}
function currentAppVersion() {
const configured = process.env.SKETCHFORGE_APP_VERSION?.trim();
if (configured && VERSION_PATTERN.test(configured)) return configured;
return packageVersion(findParentRoot(false)) || SKF_CREATED_WITH_VERSION;
}
function localRepoForRequest(request: Request) {
if (!loopbackRequest(request)) return null;
return findParentRoot(true);
}
function updateTriggerUrl() {
const configured = process.env.SKETCHFORGE_UPDATE_TRIGGER_URL?.trim();
if (!configured) return null;
@@ -59,7 +110,7 @@ async function latestOfficialVersion(force = false) {
if (!response.ok) throw new Error(`Update server returned ${response.status}`);
const payload = await response.json() as { version?: unknown };
const version = typeof payload.version === "string" ? payload.version.trim() : "";
if (!/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
if (!VERSION_PATTERN.test(version)) {
throw new Error("Update server returned an invalid version");
}
cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS };
@@ -73,41 +124,113 @@ function updateGuideUrl() {
return process.env.SKETCHFORGE_UPDATE_GUIDE_URL?.trim() || OFFICIAL_UPDATE_GUIDE_URL;
}
async function statusResponse(force = false): Promise<AppUpdateStatus> {
async function statusResponse(request: Request, force = false): Promise<AppUpdateStatus> {
const trigger = updateTriggerUrl();
const adminKeyConfigured = Boolean(process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim());
const localRepo = localRepoForRequest(request);
const currentVersion = currentAppVersion();
try {
const latestVersion = await latestOfficialVersion(force);
return {
currentVersion: SKF_CREATED_WITH_VERSION,
currentVersion,
latestVersion,
updateAvailable: appUpdateIsAvailable(SKF_CREATED_WITH_VERSION, latestVersion),
updateAvailable: appUpdateIsAvailable(currentVersion, latestVersion),
checkedAt: new Date().toISOString(),
updateUrl: updateGuideUrl(),
installationReady: Boolean(trigger && adminKeyConfigured),
requiresUpdateKey: Boolean(trigger && adminKeyConfigured),
installationReady: Boolean(localRepo || (trigger && adminKeyConfigured)),
requiresUpdateKey: localRepo ? false : Boolean(trigger && adminKeyConfigured),
updateMode: localRepo ? "local" : "server",
};
} catch (error) {
return {
currentVersion: SKF_CREATED_WITH_VERSION,
currentVersion,
latestVersion: null,
updateAvailable: false,
checkedAt: new Date().toISOString(),
updateUrl: updateGuideUrl(),
installationReady: Boolean(trigger && adminKeyConfigured),
requiresUpdateKey: Boolean(trigger && adminKeyConfigured),
installationReady: Boolean(localRepo || (trigger && adminKeyConfigured)),
requiresUpdateKey: localRepo ? false : Boolean(trigger && adminKeyConfigured),
updateMode: localRepo ? "local" : "server",
checkError: error instanceof Error ? error.message : "Could not check for updates",
};
}
}
async function runLocalUpdate(repoRoot: string, expectedVersion: string) {
const gitOptions = { cwd: repoRoot, timeout: 120_000, maxBuffer: 2 * 1024 * 1024 };
const { stdout: dirtyOutput } = await execFileAsync("git", ["status", "--porcelain", "--untracked-files=no"], gitOptions);
if (dirtyOutput.trim()) {
throw new Error("Local SketchForge has uncommitted code changes. Commit or stash them before updating so the updater does not overwrite your work.");
}
await execFileAsync("git", ["fetch", "--no-tags", OFFICIAL_REPO_URL, "main"], gitOptions);
await execFileAsync("git", ["merge", "--ff-only", "FETCH_HEAD"], gitOptions);
const installedVersion = packageVersion(repoRoot);
if (installedVersion && appUpdateIsAvailable(installedVersion, expectedVersion)) {
throw new Error(`The local checkout updated to ${installedVersion}, but ${expectedVersion} was expected.`);
}
const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
await execFileAsync(npmCommand, ["install", "--no-audit", "--no-fund"], {
cwd: repoRoot,
timeout: 5 * 60 * 1000,
maxBuffer: 4 * 1024 * 1024,
windowsHide: true,
});
const restartScript = path.join(repoRoot, "scripts", "restart-local-dev.mjs");
if (existsSync(restartScript)) {
const child = spawn(process.execPath, [restartScript, String(process.pid), repoRoot], {
cwd: repoRoot,
detached: true,
stdio: "ignore",
windowsHide: true,
});
child.unref();
}
return installedVersion || expectedVersion;
}
export async function GET(request: Request) {
const force = new URL(request.url).searchParams.get("force") === "1";
return NextResponse.json(await statusResponse(force), { headers: { "Cache-Control": "no-store" } });
return NextResponse.json(await statusResponse(request, force), { headers: { "Cache-Control": "no-store" } });
}
export async function POST(request: Request) {
if (!sameOriginRequest(request)) return NextResponse.json({ error: "Updates only accept same-origin requests" }, { status: 403 });
const localRepo = localRepoForRequest(request);
if (localRepo) {
if (Date.now() < nextTriggerAt) {
return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 });
}
const status = await statusResponse(request, true);
if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 });
if (!status.updateAvailable || !status.latestVersion) {
return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 });
}
nextTriggerAt = Date.now() + UPDATE_TRIGGER_COOLDOWN_MS;
try {
const installedVersion = await runLocalUpdate(localRepo, status.latestVersion);
return NextResponse.json(
{
accepted: true,
currentVersion: installedVersion,
latestVersion: status.latestVersion,
updateMode: "local",
restartRequired: true,
},
{ status: 202, headers: { "Cache-Control": "no-store" } },
);
} catch (error) {
nextTriggerAt = 0;
return NextResponse.json({ error: error instanceof Error ? error.message : "Could not update local SketchForge" }, { status: 409 });
}
}
const trigger = updateTriggerUrl();
const adminKey = process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim() || "";
if (!trigger || !adminKey) {
@@ -125,7 +248,7 @@ export async function POST(request: Request) {
return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 });
}
const status = await statusResponse(true);
const status = await statusResponse(request, true);
if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 });
if (!status.updateAvailable || !status.latestVersion) {
return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 });
@@ -154,7 +277,7 @@ export async function POST(request: Request) {
});
if (!response.ok) throw new Error(`Update service returned ${response.status}`);
return NextResponse.json(
{ accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion },
{ accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion, updateMode: "server" },
{ status: 202, headers: { "Cache-Control": "no-store" } },
);
} catch (error) {
+15 -18
View File
@@ -5,7 +5,6 @@ import { NextResponse } from "next/server";
export const revalidate = false;
const THUMBNAIL_DIR = path.join(process.cwd(), ".codex", "project-thumbnails");
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
const PNG_DATA_URL_PREFIX = "data:image/png;base64,";
const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024;
const MAX_THUMBNAIL_REQUEST_BYTES = Math.ceil((MAX_THUMBNAIL_BYTES * 4) / 3) + PNG_DATA_URL_PREFIX.length + 2048;
@@ -23,26 +22,24 @@ function thumbnailPath(projectId: string) {
return path.join(THUMBNAIL_DIR, `${safeId}.png`);
}
function isLocalSameOriginRequest(request: Request) {
const requestUrl = new URL(request.url);
if (!LOCAL_HOSTS.has(requestUrl.hostname)) {
return false;
}
function isSameOriginRequest(request: Request) {
const origin = request.headers.get("origin");
if (origin) {
try {
const originUrl = new URL(origin);
if (!LOCAL_HOSTS.has(originUrl.hostname) || originUrl.port !== requestUrl.port || originUrl.protocol !== requestUrl.protocol) {
return false;
}
const requestUrl = new URL(request.url);
const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
const host = forwardedHost || request.headers.get("host") || requestUrl.host;
const protocol = (forwardedProtocol || requestUrl.protocol.replace(/:$/, "")).toLowerCase();
if (protocol !== "http" && protocol !== "https") return false;
if (new URL(origin).origin !== new URL(`${protocol}://${host}`).origin) return false;
} catch {
return false;
}
}
const fetchSite = request.headers.get("sec-fetch-site");
return !fetchSite || fetchSite === "same-origin" || fetchSite === "same-site" || fetchSite === "none";
return !fetchSite || fetchSite === "same-origin" || fetchSite === "none";
}
function decodedBase64ByteLength(value: string) {
@@ -54,8 +51,8 @@ function decodedBase64ByteLength(value: string) {
}
export async function GET(request: Request) {
if (!isLocalSameOriginRequest(request)) {
return new NextResponse("Project thumbnails are only available from this localhost app", { status: 403 });
if (!isSameOriginRequest(request)) {
return new NextResponse("Project thumbnails require a same-origin request", { status: 403 });
}
const projectId = new URL(request.url).searchParams.get("projectId") ?? "";
@@ -78,8 +75,8 @@ export async function GET(request: Request) {
}
export async function POST(request: Request) {
if (!isLocalSameOriginRequest(request)) {
return NextResponse.json({ error: "Project thumbnails are only available from this localhost app" }, { status: 403 });
if (!isSameOriginRequest(request)) {
return NextResponse.json({ error: "Project thumbnails require a same-origin request" }, { status: 403 });
}
const contentLength = Number(request.headers.get("content-length"));
@@ -124,8 +121,8 @@ export async function POST(request: Request) {
}
export async function DELETE(request: Request) {
if (!isLocalSameOriginRequest(request)) {
return NextResponse.json({ error: "Project thumbnails are only available from this localhost app" }, { status: 403 });
if (!isSameOriginRequest(request)) {
return NextResponse.json({ error: "Project thumbnails require a same-origin request" }, { status: 403 });
}
const projectId = new URL(request.url).searchParams.get("projectId") ?? "";
+81
View File
@@ -3459,6 +3459,87 @@ button {
vector-effect: non-scaling-stroke;
}
.sketch-primitive-preview {
fill: rgba(0, 159, 227, 0.12);
stroke: rgba(0, 117, 184, 0.92);
stroke-width: 1.5;
stroke-dasharray: 5 3;
vector-effect: non-scaling-stroke;
}
.sketch-primitive-center {
fill: #ffffff;
stroke: rgba(0, 117, 184, 0.95);
stroke-width: 1.5;
vector-effect: non-scaling-stroke;
}
.sketch-profile-hit-targets path {
fill: transparent;
stroke: transparent;
stroke-width: 10;
vector-effect: non-scaling-stroke;
cursor: move;
}
.sketch-primitive-source {
cursor: grab;
}
.sketch-primitive-source:active {
cursor: grabbing;
}
.sketch-geometry-selection-box {
fill: rgba(0, 117, 184, 0.025);
stroke: rgba(0, 117, 184, 0.82);
stroke-width: 1;
stroke-dasharray: 4 3;
vector-effect: non-scaling-stroke;
cursor: move;
}
.sketch-geometry-resize-handle {
fill: #ffffff;
stroke: rgba(0, 117, 184, 0.95);
stroke-width: 1.5;
vector-effect: non-scaling-stroke;
}
.sketch-geometry-resize-handle.handle-nw,
.sketch-geometry-resize-handle.handle-se {
cursor: nwse-resize;
}
.sketch-geometry-resize-handle.handle-ne,
.sketch-geometry-resize-handle.handle-sw {
cursor: nesw-resize;
}
.sketch-geometry-resize-handle.handle-n,
.sketch-geometry-resize-handle.handle-s {
cursor: ns-resize;
}
.sketch-geometry-resize-handle.handle-e,
.sketch-geometry-resize-handle.handle-w {
cursor: ew-resize;
}
.sketch-geometry-dimension rect {
fill: rgba(255, 255, 255, 0.98);
stroke: rgba(0, 117, 184, 0.8);
stroke-width: 1;
vector-effect: non-scaling-stroke;
filter: drop-shadow(0 1px 2px rgba(25, 55, 76, 0.14));
}
.sketch-geometry-dimension text {
fill: #173b5a;
font-weight: 750;
text-anchor: middle;
}
.sketch-plate-background {
fill: #ddf8ff;
stroke: none;
+40 -6
View File
@@ -802,8 +802,14 @@ export default function Home() {
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ dataUrl: snapshot.image, projectId: snapshot.projectId }),
})
.then((response) => (response.ok ? response.json() : null))
.then((payload: { version?: number } | null) => {
.then(async (response) => {
if (!response.ok) {
const payload = await response.json().catch(() => null) as { error?: string } | null;
throw new Error(payload?.error ?? "Could not save project thumbnail");
}
return response.json() as Promise<{ version?: number }>;
})
.then((payload) => {
const nextVersion = payload?.version ?? Date.now();
const thumbnailUrl = `/api/project-thumbnail?projectId=${encodeURIComponent(snapshot.projectId)}&v=${nextVersion}`;
setProjects((current) =>
@@ -1529,6 +1535,7 @@ function Dashboard({
updateUrl: "",
installationReady: true,
requiresUpdateKey: false,
updateMode: "desktop",
};
setUpdateStatus(payload);
if (result.updateAvailable && result.latestVersion) {
@@ -1597,6 +1604,7 @@ function Dashboard({
updateUrl: "",
installationReady: true,
requiresUpdateKey: false,
updateMode: "desktop",
});
setUpdateMessage("SketchForge is already up to date.");
} else {
@@ -1627,13 +1635,35 @@ function Dashboard({
method: "POST",
headers: { "x-sketchforge-update-key": updateKey.trim() },
});
const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string };
const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string; updateMode?: "local" | "server"; restartRequired?: boolean };
if (!response.ok || !payload.accepted) throw new Error(payload.error || "Could not start the update");
if (updateStatus.latestVersion) {
window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion);
}
setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts.");
setUpdateKey("");
if (payload.updateMode === "local" || updateStatus.updateMode === "local") {
const expectedVersion = updateStatus.latestVersion;
setUpdateMessage("Update installed. Restarting local SketchForge…");
await new Promise((resolve) => window.setTimeout(resolve, 1800));
for (let attempt = 0; attempt < 60; attempt += 1) {
try {
const statusResponse = await fetch("/api/app-update?force=1", { cache: "no-store" });
if (statusResponse.ok) {
const statusPayload = await statusResponse.json() as AppUpdateStatus;
if (!expectedVersion || statusPayload.currentVersion === expectedVersion || !statusPayload.updateAvailable) {
window.location.reload();
return;
}
}
} catch {
// The local dev server is expected to be briefly unavailable while it restarts.
}
await new Promise((resolve) => window.setTimeout(resolve, 500));
}
setUpdateMessage("Update installed. Reload this page once local SketchForge finishes restarting.");
} else {
setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts.");
}
} catch (error) {
setUpdateMessage(error instanceof Error ? error.message : "Could not start the update");
} finally {
@@ -1964,7 +1994,11 @@ function Dashboard({
<div className="dashboard-update-copy">
<p>Do you want to update from version {updateStatus.currentVersion}?</p>
<div className="dashboard-update-safety">
Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent <code>/data/projects</code> volume.
{updateStatus.updateMode === "local" ? (
<>Your browser projects are kept. The updater only replaces the local SketchForge application files.</>
) : (
<>Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent <code>/data/projects</code> volume.</>
)}
</div>
{!updateStatus.installationReady ? (
<div className="dashboard-update-note">One-click installation is not configured on this server. Continue to the safe update guide.</div>
@@ -2024,7 +2058,7 @@ function Dashboard({
</label>
<div className="dashboard-version-row">
<span>SketchForge version</span>
<strong>{desktopAppVersion ?? SKF_CREATED_WITH_VERSION}</strong>
<strong>{desktopAppVersion ?? updateStatus?.currentVersion ?? SKF_CREATED_WITH_VERSION}</strong>
</div>
<section className="dashboard-update-settings" aria-label="Software updates">
<div>
+177 -23
View File
@@ -1,6 +1,6 @@
"use client";
import { Check, CloudUpload, Download, Eye, FolderOpen, X } from "lucide-react";
import { Check, Circle as CircleIcon, CloudUpload, Download, Eye, FolderOpen, Hexagon as HexagonIcon, Square as SquareIcon, Triangle as TriangleIcon, X } from "lucide-react";
import type manifoldModule from "manifold-3d";
import type { ManifoldToplevel } from "manifold-3d";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -48,7 +48,7 @@ import {
ToolbarVectorExportIcon,
} from "./icons";
import { WorkplaneViewport } from "./WorkplaneViewport";
import { SketchWorkspace, type SketchMeasurement, type SketchSelection, type SketchTool } from "./SketchWorkspace";
import { SketchWorkspace, type SketchMeasurement, type SketchPrimitive, type SketchSelection, type SketchTool } from "./SketchWorkspace";
import { EdgeModifierPanel } from "./workplane/EdgeModifierPanel";
import {
canonicalizeShape,
@@ -64,6 +64,8 @@ import {
resizedImportedMeshPositions,
serializeShapesForSync,
shapeDepth,
shapeHasTaper,
shapeTaperScaleAt,
shapeWidth,
withHoleMode,
workplaneShapesEqual,
@@ -89,6 +91,7 @@ import { exportMeshesToObj } from "@/lib/objExport";
import { importedShapeFromObj } from "@/lib/objImport";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
import { addLineIntersectionPoints, splitSketchSegment } from "@/lib/sketchPointRefinement";
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
@@ -1387,6 +1390,15 @@ function shapeFromCadMesh(
mirrorY: undefined,
mirrorZ: undefined,
radius: undefined,
// The CAD result is already generated from the final tapered surface. Do
// not carry the parametric taper fields onto this baked mesh or the viewport
// and subsequent mesh exports will apply the deformation a second time.
taperTopWidth: undefined,
taperTopDepth: undefined,
taperBottomWidth: undefined,
taperBottomDepth: undefined,
taperTopScale: undefined,
taperBottomScale: undefined,
importedMesh: {
positions: flattenedPositions,
normals: flattenedNormals.length === flattenedPositions.length ? flattenedNormals : undefined,
@@ -1618,6 +1630,11 @@ function groupedShapeWithComponentEdgeTreatment(
) {
if (
!base.groupedShapes?.length ||
// A tapered group is sent to CAD as one baked final mesh because the parent
// deformation cannot be represented by its untapered child primitives.
// Keep the treated result flattened instead of rebuilding a nested group
// that would reintroduce the old pre-taper children.
shapeHasTaper(base) ||
!hasOneToOneCadComponentMapping(sourceParts.length, session.componentPreviews.map((component) => component.owner))
) {
return null;
@@ -1758,6 +1775,18 @@ async function restoreEdgeTreatmentInShape(shape: WorkplaneShape, path: number[]
function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
const centerY = shape.height / 2;
const tapered = shapeHasTaper(shape);
let minLocalY = 0;
let maxLocalY = 1;
if (tapered && mesh.vertices.length) {
minLocalY = Number.POSITIVE_INFINITY;
maxLocalY = Number.NEGATIVE_INFINITY;
mesh.vertices.forEach((vertex) => {
minLocalY = Math.min(minLocalY, vertex[1]);
maxLocalY = Math.max(maxLocalY, vertex[1]);
});
}
const taperHeight = Math.max(1e-6, maxLocalY - minLocalY);
const matrix = new THREE.Matrix4().makeRotationFromEuler(
new THREE.Euler(
THREE.MathUtils.degToRad(shape.rotationX ?? 0),
@@ -1773,7 +1802,10 @@ function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
return {
...mesh,
vertices: mesh.vertices.map(([x, y, z]) => {
const vertex = new THREE.Vector3(x * mirrorX, (y - centerY) * mirrorY, z * mirrorZ).applyMatrix4(matrix);
const normalizedHeight = (y - minLocalY) / taperHeight;
const widthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "width") : 1;
const depthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "depth") : 1;
const vertex = new THREE.Vector3(x * widthScale * mirrorX, (y - centerY) * mirrorY, z * depthScale * mirrorZ).applyMatrix4(matrix);
return [vertex.x + shape.x, vertex.y + (shape.elevation ?? 0) + centerY, vertex.z + shape.z] as Vec3;
}),
faces: reversedWinding ? mesh.faces.map(([a, b, c]) => [a, c, b] as [number, number, number]) : mesh.faces,
@@ -2334,6 +2366,10 @@ function shapeHasTransformToBake(shape: WorkplaneShape) {
}
function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimitivePart | null {
// Taper is a non-affine deformation, so an analytic primitive or stored BREP
// cannot represent the final visible surface. Send the baked mesh to the CAD
// worker instead so edge selection/treatment matches the viewport exactly.
if (shapeHasTaper(shape)) return null;
return cadModifierPrimitiveForBakedShape(shape)
?? (shapeHasTransformToBake(shape) ? cadModifierPrimitiveForAnalyticBox(shape) : null);
}
@@ -2404,6 +2440,12 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
mirrorX: undefined,
mirrorY: undefined,
mirrorZ: undefined,
taperTopWidth: undefined,
taperTopDepth: undefined,
taperBottomWidth: undefined,
taperBottomDepth: undefined,
taperTopScale: undefined,
taperBottomScale: undefined,
importedMesh: {
positions,
baseWidth: rawWidth,
@@ -6204,7 +6246,7 @@ export function SketchForgeEditor({
const commitSketchProfile = useCallback(
(next: SketchProfile, message?: string) => {
const snapshot = cloneSketchProfile(next);
const snapshot = cloneSketchProfile(addLineIntersectionPoints(next, createLocalId));
const current = sketchHistoryRef.current;
const currentIndex = Math.min(sketchHistoryIndexRef.current, Math.max(0, current.length - 1));
const trimmed = current.slice(0, currentIndex + 1);
@@ -6341,6 +6383,10 @@ export function SketchForgeEditor({
line: "Line: click points to draw straight segments",
bezier: "Bézier: click and drag points to pull curve handles",
smooth: "Smooth curve: click points to build a flowing path",
rectangle: "Rectangle: drag across the sketch to create a closed rectangle",
circle: "Circle: drag a bounding box to create a closed circle",
triangle: "Triangle: drag a bounding box to create a closed triangle",
hexagon: "Hexagon: drag a bounding box to create a closed hexagon",
select: "Select: edit sketch geometry or place and scale reference images",
refine: "Refine: click a segment to add a point, or a point to remove it",
erase: "Erase: click a point or segment to remove it",
@@ -6434,6 +6480,90 @@ export function SketchForgeEditor({
[commitSketchProfile, connectSketchPoint, measureSketchPoint, sketchActivePointId, sketchProfile, sketchTool],
);
const addSketchPrimitive = useCallback(
(primitive: SketchPrimitive, center: { x: number; z: number } = { x: 0, z: 0 }) => {
const cx = center.x;
const cz = center.z;
const width = 20;
const depth = 20;
const radius = width / 2;
const minX = cx - width / 2;
const maxX = cx + width / 2;
const minZ = cz - depth / 2;
const maxZ = cz + depth / 2;
let points: SketchPoint[] = [];
let segments: SketchSegment[] = [];
if (primitive === "circle") {
const kappa = 0.5522847498307936;
const right: SketchPoint = {
id: createLocalId("sketch-point"), x: cx + radius, z: cz, mode: "smooth",
handleIn: { x: cx + radius, z: cz - kappa * radius },
handleOut: { x: cx + radius, z: cz + kappa * radius },
};
const bottom: SketchPoint = {
id: createLocalId("sketch-point"), x: cx, z: cz + radius, mode: "smooth",
handleIn: { x: cx + kappa * radius, z: cz + radius },
handleOut: { x: cx - kappa * radius, z: cz + radius },
};
const left: SketchPoint = {
id: createLocalId("sketch-point"), x: cx - radius, z: cz, mode: "smooth",
handleIn: { x: cx - radius, z: cz + kappa * radius },
handleOut: { x: cx - radius, z: cz - kappa * radius },
};
const top: SketchPoint = {
id: createLocalId("sketch-point"), x: cx, z: cz - radius, mode: "smooth",
handleIn: { x: cx - kappa * radius, z: cz - radius },
handleOut: { x: cx + kappa * radius, z: cz - radius },
};
points = [right, bottom, left, top];
segments = points.map((point, index) => ({
id: createLocalId("sketch-segment"),
startId: point.id,
endId: points[(index + 1) % points.length]!.id,
kind: "bezier",
}));
} else {
const vertices: Array<{ x: number; z: number }> = primitive === "rectangle"
? [
{ x: minX, z: minZ },
{ x: maxX, z: minZ },
{ x: maxX, z: maxZ },
{ x: minX, z: maxZ },
]
: primitive === "triangle"
? [
{ x: cx, z: minZ },
{ x: maxX, z: maxZ },
{ x: minX, z: maxZ },
]
: Array.from({ length: 6 }, (_, index) => {
const angle = -Math.PI / 2 + index * Math.PI / 3;
return { x: cx + Math.cos(angle) * width / 2, z: cz + Math.sin(angle) * depth / 2 };
});
points = vertices.map((vertex) => ({ id: createLocalId("sketch-point"), ...vertex, mode: "corner" }));
segments = points.map((point, index) => ({
id: createLocalId("sketch-segment"),
startId: point.id,
endId: points[(index + 1) % points.length]!.id,
kind: "line",
}));
}
const next: SketchProfile = {
...sketchProfile,
points: [...sketchProfile.points, ...points],
segments: [...sketchProfile.segments, ...segments],
};
const label = primitive[0]!.toUpperCase() + primitive.slice(1);
commitSketchProfile(next, `${label} added to sketch`);
setSketchActivePointId(null);
setSketchSelection({ kind: "multiple", pointIds: points.map((point) => point.id), segmentIds: segments.map((segment) => segment.id), imageIds: [] });
setSketchTool("select");
},
[commitSketchProfile, sketchProfile],
);
const pressSketchPoint = useCallback(
(id: string) => {
const point = sketchProfile.points.find((entry) => entry.id === id);
@@ -6584,6 +6714,15 @@ export function SketchForgeEditor({
commitSketchProfile(next, "Sketch point moved");
}, [commitSketchProfile, sketchProfile]);
const transformSketchPoints = useCallback((points: SketchPoint[], message = "Sketch geometry transformed") => {
if (!points.length) return;
const byId = new Map(points.map((point) => [point.id, point]));
commitSketchProfile({
...sketchProfile,
points: sketchProfile.points.map((point) => byId.get(point.id) ?? point),
}, message);
}, [commitSketchProfile, sketchProfile]);
const moveSketchHandle = useCallback((id: string, handle: "in" | "out", position: { x: number; z: number }) => {
const next = cloneSketchProfile(sketchProfile);
const point = next.points.find((entry) => entry.id === id);
@@ -6616,21 +6755,11 @@ export function SketchForgeEditor({
commitSketchProfile(next, mode === "corner" ? "Made corner" : mode === "smooth" ? "Made smooth" : "Curve handles split");
}, [commitSketchProfile, sketchProfile]);
const insertSketchPoint = useCallback((segmentId: string, position: { x: number; z: number }) => {
const segment = sketchProfile.segments.find((entry) => entry.id === segmentId);
if (!segment) return;
const point: SketchPoint = { id: createLocalId("sketch-point"), ...position, mode: segment.kind === "line" ? "corner" : "smooth" };
let next: SketchProfile = {
...sketchProfile,
points: [...sketchProfile.points, point],
segments: sketchProfile.segments.flatMap((entry) => entry.id === segmentId ? [
{ ...entry, id: createLocalId("sketch-segment"), endId: point.id },
{ ...entry, id: createLocalId("sketch-segment"), startId: point.id },
] : [entry]),
};
if (segment.kind === "smooth") next = withSmoothSketchHandles(next);
commitSketchProfile(next, "Point added to path");
setSketchSelection({ kind: "point", id: point.id });
const insertSketchPoint = useCallback((segmentId: string, _position: { x: number; z: number }, amount: number) => {
const result = splitSketchSegment(sketchProfile, segmentId, amount, createLocalId);
if (!result.pointId) return;
if (result.inserted) commitSketchProfile(result.profile, "Point added to path");
setSketchSelection({ kind: "point", id: result.pointId });
setSketchTool("select");
}, [commitSketchProfile, sketchProfile]);
@@ -7149,7 +7278,7 @@ export function SketchForgeEditor({
invalidateCadModifierSession();
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment && !shapeHasTaper(selectedShape)
? restoreGroupedChildren(selectedShape)
: [selectedShape]).flatMap(cadModifierSourceParts);
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => {
@@ -7159,6 +7288,7 @@ export function SketchForgeEditor({
Math.abs(shapeDepth(shape) - (frame?.depth ?? shapeDepth(shape))) > 1e-6 ||
Math.abs(shape.height - (frame?.height ?? shape.height)) > 1e-6
);
if (shapeHasTaper(shape)) return { shape, mesh: meshForShape(shape) };
const primitive = cadModifierPrimitiveForShape(shape);
if (primitive) return { shape, primitive };
return shape.cadBrep && frame && !preserveNeedsRetessellation
@@ -7224,7 +7354,7 @@ export function SketchForgeEditor({
}
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape);
const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length);
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment && !shapeHasTaper(shape)
? restoreGroupedChildren(shape)
: [shape]).flatMap(cadModifierSourceParts);
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => {
@@ -7234,6 +7364,7 @@ export function SketchForgeEditor({
Math.abs(shapeDepth(partShape) - (frame?.depth ?? shapeDepth(partShape))) > 1e-6 ||
Math.abs(partShape.height - (frame?.height ?? partShape.height)) > 1e-6
);
if (shapeHasTaper(partShape)) return { shape: partShape, mesh: meshForShape(partShape) };
const primitive = cadModifierPrimitiveForShape(partShape);
if (primitive) return { shape: partShape, primitive };
return partShape.cadBrep && frame && !preserveNeedsRetessellation
@@ -8359,7 +8490,8 @@ export function SketchForgeEditor({
}
const meshes = exportable.map(meshForShape);
if (format === "stl") {
void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl")
const blob = new Blob([exportMeshesToStl(meshes)], { type: "model/stl" });
void downloadBlobFile(projectExportFileName(exportName, "stl"), blob)
.then((result) => finishNotice("STL", result))
.catch((error: unknown) => failNotice("STL", error));
return;
@@ -8821,7 +8953,7 @@ export function SketchForgeEditor({
return;
}
if (!shortcut && !event.altKey && key === "r" && hasSelection) {
if (!shortcut && !event.altKey && (event.code === "KeyR" || key === "r") && hasSelection) {
event.preventDefault();
rotateSelected45();
return;
@@ -8931,6 +9063,7 @@ export function SketchForgeEditor({
onStartSketch={(operation) => beginSketch(operation)}
onEditSketch={beginSketchEdit}
onSketchTool={setActiveSketchTool}
onSketchPrimitive={(primitive) => addSketchPrimitive(primitive, { x: 0, z: 0 })}
onSketchImage={() => {
if (sketchTool !== "select") {
setNotice("Choose Select before adding a sketch image");
@@ -8985,6 +9118,7 @@ export function SketchForgeEditor({
initialSnap={snapGrid}
initialWorkspace={workspaceSettings}
onPlanePoint={addSketchPlanePoint}
onAddPrimitive={addSketchPrimitive}
onPointPress={pressSketchPoint}
onSelectSegment={(id) => {
setSketchSelection({ kind: "segment", id });
@@ -9006,6 +9140,7 @@ export function SketchForgeEditor({
onDeletePoint={deleteSketchPoint}
onDeleteSegment={deleteSketchSegment}
onMovePoint={moveSketchPoint}
onTransformPoints={transformSketchPoints}
onMoveHandle={moveSketchHandle}
onInsertPoint={insertSketchPoint}
onSetPointMode={setSketchPointMode}
@@ -9227,6 +9362,7 @@ function SecondaryToolbar({
onStartSketch,
onEditSketch,
onSketchTool,
onSketchPrimitive,
onSketchImage,
onSketchUndo,
onSketchRedo,
@@ -9278,6 +9414,7 @@ function SecondaryToolbar({
onStartSketch: (operation: SketchOperation) => void;
onEditSketch: () => void;
onSketchTool: (tool: SketchTool) => void;
onSketchPrimitive: (primitive: SketchPrimitive) => void;
onSketchImage: () => void;
onSketchUndo: () => void;
onSketchRedo: () => void;
@@ -9647,6 +9784,23 @@ function SecondaryToolbar({
</button>
</div>
</div>
<div className="toolbar-section sketch-shapes-section">
<div className="toolbar-section-label">Shapes</div>
<div className="toolbar-section-tools">
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Rectangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("rectangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "rectangle"); }}>
<SquareIcon size={25} strokeWidth={1.8} />
</button>
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Circle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("circle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "circle"); }}>
<CircleIcon size={25} strokeWidth={1.8} />
</button>
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Triangle" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("triangle")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "triangle"); }}>
<TriangleIcon size={25} strokeWidth={1.8} />
</button>
<button className="toolbar-icon sketch-tool-icon sketch-primitive-source" type="button" draggable aria-label="Hexagon" title="Click to add at sketch origin, or drag onto the sketch" onClick={() => onSketchPrimitive("hexagon")} onDragStart={(event) => { event.dataTransfer.effectAllowed = "copy"; event.dataTransfer.setData("application/x-sketchforge-sketch-primitive", "hexagon"); }}>
<HexagonIcon size={25} strokeWidth={1.8} />
</button>
</div>
</div>
<div className="toolbar-section sketch-edit-section">
<div className="toolbar-section-label">Select</div>
<div className="toolbar-section-tools">
+259 -8
View File
@@ -6,11 +6,13 @@ import { SnapGridControl } from "@/components/workplane/ShapeInspector";
import { SketchRevolvePreview } from "@/components/SketchRevolvePreview";
import { parseMeasurementInput } from "@/lib/measurementUnits";
import { WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
import { closestPointOnSketchSegment, type SketchSegmentPlacement } from "@/lib/sketchPointRefinement";
import { mirrorSign, resizedImportedMeshPositions } from "@/lib/workplaneShapes";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
import type { GridSize, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export type SketchTool = "line" | "bezier" | "smooth" | "select" | "refine" | "erase" | "measure";
export type SketchPrimitive = "rectangle" | "circle" | "triangle" | "hexagon";
export type SketchTool = "line" | "bezier" | "smooth" | SketchPrimitive | "select" | "refine" | "erase" | "measure";
export type SketchSelection =
| { kind: "point"; id: string }
| { kind: "segment"; id: string }
@@ -32,6 +34,7 @@ type SketchWorkspaceProps = {
initialSnap?: GridSize;
initialWorkspace?: WorkplaneWorkspaceSettings;
onPlanePoint: (point: { x: number; z: number }, handles?: { handleIn: { x: number; z: number }; handleOut: { x: number; z: number } }) => void;
onAddPrimitive: (primitive: SketchPrimitive, center: { x: number; z: number }) => void;
onPointPress: (id: string) => void;
onSelectSegment: (id: string) => void;
onSelectMany: (pointIds: string[], segmentIds: string[], imageIds: string[]) => void;
@@ -41,8 +44,9 @@ type SketchWorkspaceProps = {
onDeletePoint: (id: string) => void;
onDeleteSegment: (id: string) => void;
onMovePoint: (id: string, point: { x: number; z: number }) => void;
onTransformPoints: (points: SketchPoint[], message?: string) => void;
onMoveHandle: (id: string, handle: "in" | "out", point: { x: number; z: number }) => void;
onInsertPoint: (segmentId: string, point: { x: number; z: number }) => void;
onInsertPoint: (segmentId: string, point: { x: number; z: number }, amount: number) => void;
onSetPointMode: (id: string, mode: "corner" | "smooth" | "split") => void;
onClearMeasurement: () => void;
};
@@ -53,6 +57,8 @@ type SketchReferenceFootprint = { fillD: string | null; outlineD: string | null
type PointerAction =
| { kind: "bezier"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
| { kind: "move-point"; pointerId: number; pointId: string; current: { x: number; z: number } }
| { kind: "move-selection"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number }; startPoints: SketchPoint[] }
| { kind: "resize-selection"; pointerId: number; handle: ResizeHandle; current: { x: number; z: number }; startPoints: SketchPoint[]; bounds: SelectionBounds }
| { kind: "move-handle"; pointerId: number; pointId: string; handle: "in" | "out"; current: { x: number; z: number } }
| { kind: "pan"; pointerId: number; clientX: number; clientY: number }
| { kind: "marquee"; pointerId: number; origin: { x: number; z: number }; current: { x: number; z: number } }
@@ -60,6 +66,7 @@ type PointerAction =
| { kind: "resize-image"; pointerId: number; imageId: string; handle: ResizeHandle; current: { x: number; z: number }; start: SketchImage };
type ResizeHandle = "nw" | "n" | "ne" | "e" | "se" | "s" | "sw" | "w";
type SelectionBounds = { minX: number; maxX: number; minZ: number; maxZ: number; width: number; depth: number; cx: number; cz: number };
function snapStep(size: GridSize) {
if (size === "Off") return 0;
@@ -126,6 +133,62 @@ function resizeSketchImage(start: SketchImage, handle: ResizeHandle, point: { x:
};
}
function boundsForSketchPoints(points: SketchPoint[]): SelectionBounds | null {
if (points.length < 2) return null;
const xs = points.map((point) => point.x);
const zs = points.map((point) => point.z);
const minX = Math.min(...xs);
const maxX = Math.max(...xs);
const minZ = Math.min(...zs);
const maxZ = Math.max(...zs);
return {
minX,
maxX,
minZ,
maxZ,
width: maxX - minX,
depth: maxZ - minZ,
cx: (minX + maxX) / 2,
cz: (minZ + maxZ) / 2,
};
}
function translateSketchPoints(points: SketchPoint[], dx: number, dz: number) {
return points.map((point) => ({
...point,
x: point.x + dx,
z: point.z + dz,
handleIn: point.handleIn ? { x: point.handleIn.x + dx, z: point.handleIn.z + dz } : undefined,
handleOut: point.handleOut ? { x: point.handleOut.x + dx, z: point.handleOut.z + dz } : undefined,
}));
}
function resizeSketchPoints(points: SketchPoint[], bounds: SelectionBounds, handle: ResizeHandle, current: { x: number; z: number }) {
const minimum = 0.5;
let minX = bounds.minX;
let maxX = bounds.maxX;
let minZ = bounds.minZ;
let maxZ = bounds.maxZ;
if (handle.includes("w")) minX = Math.min(current.x, bounds.maxX - minimum);
if (handle.includes("e")) maxX = Math.max(current.x, bounds.minX + minimum);
if (handle.includes("n")) minZ = Math.min(current.z, bounds.maxZ - minimum);
if (handle.includes("s")) maxZ = Math.max(current.z, bounds.minZ + minimum);
const width = Math.max(minimum, bounds.width);
const depth = Math.max(minimum, bounds.depth);
const scaleX = (maxX - minX) / width;
const scaleZ = (maxZ - minZ) / depth;
const map = (value: { x: number; z: number }) => ({
x: minX + (value.x - bounds.minX) * scaleX,
z: minZ + (value.z - bounds.minZ) * scaleZ,
});
return points.map((point) => ({
...point,
...map(point),
handleIn: point.handleIn ? map(point.handleIn) : undefined,
handleOut: point.handleOut ? map(point.handleOut) : undefined,
}));
}
function formatDimension(value: number, accuracy: 1 | 2 | 3) {
const threshold = 0.5 * 10 ** -accuracy;
return (Math.abs(value) < threshold ? 0 : value).toFixed(accuracy);
@@ -414,6 +477,7 @@ export function SketchWorkspace({
initialSnap,
initialWorkspace,
onPlanePoint,
onAddPrimitive,
onPointPress,
onSelectSegment,
onSelectMany,
@@ -423,6 +487,7 @@ export function SketchWorkspace({
onDeletePoint,
onDeleteSegment,
onMovePoint,
onTransformPoints,
onMoveHandle,
onInsertPoint,
onSetPointMode,
@@ -434,6 +499,7 @@ export function SketchWorkspace({
const [zoom, setZoom] = useState(1);
const [pan, setPan] = useState({ x: 0, z: 0 });
const [hover, setHover] = useState<{ x: number; z: number } | null>(null);
const [refinePreview, setRefinePreview] = useState<{ segmentId: string; placement: SketchSegmentPlacement } | null>(null);
const [pointerAction, setPointerAction] = useState<PointerAction | null>(null);
const [svgSize, setSvgSize] = useState({ width: 0, height: 0 });
const svgRef = useRef<SVGSVGElement | null>(null);
@@ -447,6 +513,20 @@ export function SketchWorkspace({
return fittedScale > 0 ? 1 / fittedScale : Math.max(width, depth) / 720;
}, [depth, svgSize.height, svgSize.width, width]);
const displayProfile = useMemo(() => {
if (pointerAction?.kind === "move-selection") {
const moved = translateSketchPoints(
pointerAction.startPoints,
pointerAction.current.x - pointerAction.origin.x,
pointerAction.current.z - pointerAction.origin.z,
);
const movedById = new Map(moved.map((point) => [point.id, point]));
return { ...profile, points: profile.points.map((point) => movedById.get(point.id) ?? point) };
}
if (pointerAction?.kind === "resize-selection") {
const resized = resizeSketchPoints(pointerAction.startPoints, pointerAction.bounds, pointerAction.handle, pointerAction.current);
const resizedById = new Map(resized.map((point) => [point.id, point]));
return { ...profile, points: profile.points.map((point) => resizedById.get(point.id) ?? point) };
}
if (pointerAction?.kind === "move-point") {
const source = profile.points.find((point) => point.id === pointerAction.pointId);
if (!source) return profile;
@@ -498,6 +578,10 @@ export function SketchWorkspace({
const activePoint = activePointId ? pointById.get(activePointId) ?? null : null;
const selectedPoint = selected?.kind === "point" ? pointById.get(selected.id) ?? null : null;
const selectedImage = selected?.kind === "image" ? displayImages.find((image) => image.id === selected.id) ?? null : null;
const selectedGeometryPoints = selected?.kind === "multiple"
? selected.pointIds.map((id) => pointById.get(id)).filter((point): point is SketchPoint => Boolean(point))
: [];
const selectedGeometryBounds = boundsForSketchPoints(selectedGeometryPoints);
const isPointSelected = (id: string) => selected?.kind === "point" ? selected.id === id : selected?.kind === "multiple" ? selected.pointIds.includes(id) : false;
const isSegmentSelected = (id: string) => selected?.kind === "segment" ? selected.id === id : selected?.kind === "multiple" ? selected.segmentIds.includes(id) : false;
const gridStep = clamp(workspace.gridBlockSize, 1, 200);
@@ -529,6 +613,10 @@ export function SketchWorkspace({
};
};
useEffect(() => {
if (tool !== "refine") setRefinePreview(null);
}, [tool]);
useEffect(() => {
const svg = svgRef.current;
if (!svg) return;
@@ -619,6 +707,13 @@ export function SketchWorkspace({
handleIn: { x: action.origin.x - dx, z: action.origin.z - dz },
handleOut: { x: action.origin.x + dx, z: action.origin.z + dz },
});
} else if (action.kind === "move-selection") {
onTransformPoints(
translateSketchPoints(action.startPoints, action.current.x - action.origin.x, action.current.z - action.origin.z),
"Sketch shape moved",
);
} else if (action.kind === "resize-selection") {
onTransformPoints(resizeSketchPoints(action.startPoints, action.bounds, action.handle, action.current), "Sketch shape resized");
} else if (action.kind === "move-point") {
onMovePoint(action.pointId, action.current);
} else if (action.kind === "move-handle") {
@@ -673,6 +768,16 @@ export function SketchWorkspace({
{ id: "sw", x: selectedImageBounds.minX, z: selectedImageBounds.maxZ },
{ id: "w", x: selectedImageBounds.minX, z: selectedImage.z },
] : [];
const selectionResizeHandles: Array<{ id: ResizeHandle; x: number; z: number }> = selectedGeometryBounds ? [
{ id: "nw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.minZ },
{ id: "n", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.minZ },
{ id: "ne", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.minZ },
{ id: "e", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.cz },
{ id: "se", x: selectedGeometryBounds.maxX, z: selectedGeometryBounds.maxZ },
{ id: "s", x: selectedGeometryBounds.cx, z: selectedGeometryBounds.maxZ },
{ id: "sw", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.maxZ },
{ id: "w", x: selectedGeometryBounds.minX, z: selectedGeometryBounds.cz },
] : [];
const referenceFootprints = useMemo(
() => new Map(referenceShapes.map((shape) => [shape.id, importedMeshFootprint(shape)])),
[referenceShapes],
@@ -697,8 +802,23 @@ export function SketchWorkspace({
onPointerMove={handlePointerMove}
onPointerUp={finishPointerAction}
onPointerCancel={() => setPointerAction(null)}
onPointerLeave={() => !pointerAction && setHover(null)}
onPointerLeave={() => {
if (!pointerAction) setHover(null);
setRefinePreview(null);
}}
onWheel={handleWheel}
onDragOver={(event) => {
if (!event.dataTransfer.types.includes("application/x-sketchforge-sketch-primitive")) return;
event.preventDefault();
event.dataTransfer.dropEffect = "copy";
}}
onDrop={(event) => {
const primitive = event.dataTransfer.getData("application/x-sketchforge-sketch-primitive") as SketchPrimitive;
if (!["rectangle", "circle", "triangle", "hexagon"].includes(primitive)) return;
event.preventDefault();
const point = pointFromEvent(event);
if (point) onAddPrimitive(primitive, point);
}}
>
<rect className="sketch-plate-background" x={-workspace.width / 2} y={-workspace.depth / 2} width={workspace.width} height={workspace.depth} />
{workspace.showGrid ? (
@@ -783,6 +903,29 @@ export function SketchWorkspace({
<g className="sketch-profile-fills" pointerEvents="none">
{paths.some((path) => path.closed) ? <path d={paths.filter((path) => path.closed).map(pathData).join(" ")} /> : null}
</g>
<g className="sketch-profile-hit-targets" pointerEvents={tool === "select" ? "auto" : "none"}>
{paths.filter((path) => path.closed).map((path) => (
<path
key={`hit-${path.id}`}
data-sketch-entity="closed-profile"
d={pathData(path)}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0 || tool !== "select") return;
const point = pointFromEvent(event);
if (!point) return;
const pointIds = path.points.map((entry) => entry.id);
const segmentIds = path.steps.map((step) => step.segment.id);
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
onSelectMany(pointIds, segmentIds, []);
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
}}
/>
))}
</g>
<g className="sketch-segments">
{displayProfile.segments.map((segment) => (
<path
@@ -790,20 +933,59 @@ export function SketchWorkspace({
className={isSegmentSelected(segment.id) ? "selected" : ""}
key={segment.id}
d={segmentData(segment, pointById)}
onPointerMove={(event) => {
if (tool !== "refine") return;
const target = pointFromEvent(event);
const start = pointById.get(segment.startId);
const end = pointById.get(segment.endId);
if (!target || !start || !end) return;
setRefinePreview({ segmentId: segment.id, placement: closestPointOnSketchSegment(segment, start, end, target) });
}}
onPointerLeave={() => {
if (tool === "refine") setRefinePreview((current) => current?.segmentId === segment.id ? null : current);
}}
onPointerDown={(event) => {
const point = pointFromEvent(event);
event.preventDefault();
event.stopPropagation();
if (event.button === 1) beginPan(event);
else if (tool === "erase") onDeleteSegment(segment.id);
else if (event.button === 0 && tool === "refine" && point) onInsertPoint(segment.id, point);
else if (event.button === 0) onSelectSegment(segment.id);
else if (event.button === 0 && tool === "refine" && point) {
const start = pointById.get(segment.startId);
const end = pointById.get(segment.endId);
if (start && end) {
const placement = closestPointOnSketchSegment(segment, start, end, point);
onInsertPoint(segment.id, placement.point, placement.amount);
}
}
else if (event.button === 0 && tool === "select" && point) {
const closedPath = paths.find((path) => path.closed && path.steps.some((step) => step.segment.id === segment.id));
if (!closedPath) {
onSelectSegment(segment.id);
return;
}
const pointIds = closedPath.points.map((entry) => entry.id);
const segmentIds = closedPath.steps.map((step) => step.segment.id);
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
onSelectMany(pointIds, segmentIds, []);
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
} else if (event.button === 0) onSelectSegment(segment.id);
}}
/>
))}
</g>
{tool === "refine" && refinePreview ? (
<circle
className="sketch-cursor-point"
cx={refinePreview.placement.point.x}
cy={refinePreview.placement.point.z}
r={hoverPointRadius}
opacity={0.72}
pointerEvents="none"
/>
) : null}
<g className="sketch-segment-dimensions" pointerEvents="none">
{displayProfile.segments.map((segment) => {
{selected?.kind === "multiple" ? null : displayProfile.segments.map((segment) => {
const dimension = segmentDimension(segment, pointById);
if (!dimension) return null;
const label = formatDimension(dimension.length, workspace.accuracy);
@@ -816,6 +998,66 @@ export function SketchWorkspace({
);
})}
</g>
{selectedGeometryBounds && tool === "select" ? (() => {
const widthLabel = formatDimension(selectedGeometryBounds.width, workspace.accuracy);
const depthLabel = formatDimension(selectedGeometryBounds.depth, workspace.accuracy);
const widthPill = dimensionPillSize(widthLabel, screenUnit, 18);
const depthPill = dimensionPillSize(depthLabel, screenUnit, 18);
return (
<g className="sketch-geometry-selection">
<rect
data-sketch-entity="selection-box"
className="sketch-geometry-selection-box"
x={selectedGeometryBounds.minX}
y={selectedGeometryBounds.minZ}
width={selectedGeometryBounds.width}
height={selectedGeometryBounds.depth}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0 || selected?.kind !== "multiple") return;
const point = pointFromEvent(event);
if (!point) return;
const startPoints = selected.pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: point, current: point, startPoints });
}}
/>
<g className="sketch-geometry-dimension" pointerEvents="none" transform={`translate(${selectedGeometryBounds.cx} ${selectedGeometryBounds.minZ - labelOffset})`}>
<rect x={-widthPill.width / 2} y={-widthPill.height / 2} width={widthPill.width} height={widthPill.height} rx={widthPill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{widthLabel}</text>
</g>
<g className="sketch-geometry-dimension" pointerEvents="none" transform={`translate(${selectedGeometryBounds.maxX + 34 * screenUnit} ${selectedGeometryBounds.cz})`}>
<rect x={-depthPill.width / 2} y={-depthPill.height / 2} width={depthPill.width} height={depthPill.height} rx={depthPill.radius} />
<text y={5 * screenUnit} fontSize={13 * screenUnit}>{depthLabel}</text>
</g>
{selectionResizeHandles.map((handle) => (
<rect
key={`selection-handle-${handle.id}`}
data-sketch-entity="selection-handle"
className={`sketch-geometry-resize-handle handle-${handle.id}`}
x={handle.x - handleSize / 2}
y={handle.z - handleSize / 2}
width={handleSize}
height={handleSize}
rx={handleRadius}
onPointerDown={(event) => {
if (event.button === 1) {
beginPan(event);
return;
}
if (event.button !== 0 || selected?.kind !== "multiple") return;
const startPoints = selected.pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
const bounds = boundsForSketchPoints(startPoints);
if (!bounds) return;
beginEntityDrag(event, { kind: "resize-selection", pointerId: event.pointerId, handle: handle.id, current: { x: handle.x, z: handle.z }, startPoints, bounds });
}}
/>
))}
</g>
);
})() : null}
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? <line className="sketch-preview-line" x1={activePoint.x} y1={activePoint.z} x2={hover.x} y2={hover.z} pointerEvents="none" /> : null}
{activePoint && hover && ["line", "bezier", "smooth"].includes(tool) ? (
<g className="sketch-segment-dimensions preview" pointerEvents="none" transform={`translate(${(activePoint.x + hover.x) / 2} ${(activePoint.z + hover.z) / 2 - labelOffset})`}>
@@ -888,8 +1130,17 @@ export function SketchWorkspace({
} else if (tool === "erase" || tool === "refine") {
onDeletePoint(point.id);
} else if (event.button === 0 && tool === "select") {
onPointPress(point.id);
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
const closedPath = paths.find((path) => path.closed && path.points.some((entry) => entry.id === point.id));
if (closedPath) {
const pointIds = closedPath.points.map((entry) => entry.id);
const segmentIds = closedPath.steps.map((step) => step.segment.id);
const startPoints = pointIds.map((id) => profile.points.find((entry) => entry.id === id)).filter((entry): entry is SketchPoint => Boolean(entry)).map((entry) => ({ ...entry, handleIn: entry.handleIn ? { ...entry.handleIn } : undefined, handleOut: entry.handleOut ? { ...entry.handleOut } : undefined }));
onSelectMany(pointIds, segmentIds, []);
beginEntityDrag(event, { kind: "move-selection", pointerId: event.pointerId, origin: { x: point.x, z: point.z }, current: { x: point.x, z: point.z }, startPoints });
} else {
onPointPress(point.id);
beginEntityDrag(event, { kind: "move-point", pointerId: event.pointerId, pointId: point.id, current: { x: point.x, z: point.z } });
}
} else if (event.button === 0) {
onPointPress(point.id);
}
+225 -30
View File
@@ -44,7 +44,7 @@ import {
import { regularPolygonFootprintScale } from "@/lib/regularPolygonFootprint";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
import { interiorWorkplaneGridCoordinates, workplaneThemePalette, WORKPLANE_LINE_ELEVATION, WORKPLANE_MAJOR_GRID_INTERVAL } from "@/lib/workplaneGrid";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, preservesEdgeTreatmentSize, proportionalResizeScale, resizedImportedCoordinates, resizedImportedMeshPositions, resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeTaperScaleAt, shapeWidth } from "@/lib/workplaneShapes";
import { sphereTessellation } from "@/lib/sphereTessellation";
import type { SketchForgeMcpViewFace } from "@/lib/sketchforgeMcpProtocol";
import {
@@ -214,6 +214,15 @@ type WorkplaneViewportProps = {
type WorkspaceSettings = WorkplaneWorkspaceSettings;
type ViewCubeFace = "top" | "bottom" | "front" | "back" | "right" | "left";
const VIEW_FACE_SHORTCUTS: Readonly<Record<string, ViewCubeFace>> = {
"1": "front",
"2": "back",
"3": "left",
"4": "right",
"5": "top",
"6": "bottom",
};
function readSavedWorkspaceDefault(key: string | null) {
if (!key || typeof window === "undefined") {
return null;
@@ -816,6 +825,12 @@ function rulerShapeTopologyKey(shape: WorkplaneShape): string {
segments: shape.segments,
topRadius: shape.topRadius,
baseRadius: shape.baseRadius,
taperTopWidth: shape.taperTopWidth,
taperTopDepth: shape.taperTopDepth,
taperBottomWidth: shape.taperBottomWidth,
taperBottomDepth: shape.taperBottomDepth,
taperTopScale: shape.taperTopScale,
taperBottomScale: shape.taperBottomScale,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
@@ -872,12 +887,16 @@ function shapeMaterialSignature(shape: WorkplaneShape): string {
}
function shapeGeometrySignature(shape: WorkplaneShape): string {
const taper = shape.kind === "gear" || !shapeHasTaper(shape)
? null
: { ...shapeTaperDimensions(shape), baseWidth: shapeWidth(shape), baseDepth: shapeDepth(shape) };
if (shape.groupedShapes?.length && !shape.importedMesh) {
return JSON.stringify({
kind: "group",
width: shapeWidth(shape),
depth: shapeDepth(shape),
height: shape.height,
taper,
children: shape.groupedShapes.map((child) => [
child.id,
child.hidden,
@@ -894,6 +913,7 @@ function shapeGeometrySignature(shape: WorkplaneShape): string {
return JSON.stringify({
kind: "mesh",
mesh: shapeResourceId(shape.importedMesh),
taper,
preserve: preservesEdgeTreatmentSize(shape)
? [shapeWidth(shape), shapeDepth(shape), shape.height, shape.edgeTreatments]
: false,
@@ -901,16 +921,16 @@ function shapeGeometrySignature(shape: WorkplaneShape): string {
}
if (shape.kind === "box" && !(shape.radius && shape.radius > 0)) {
return JSON.stringify({ kind: "box" });
return JSON.stringify({ kind: "box", taper });
}
if (shape.kind === "cylinder") {
return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments });
return JSON.stringify({ kind: "cylinder", sides: shape.sides, segments: shape.segments, taper });
}
if (shape.kind === "sphere") {
return JSON.stringify({ kind: "sphere", steps: shape.steps });
return JSON.stringify({ kind: "sphere", steps: shape.steps, taper });
}
if (shape.kind === "polygon") {
return JSON.stringify({ kind: "polygon" });
return JSON.stringify({ kind: "polygon", taper });
}
return JSON.stringify({
@@ -926,6 +946,12 @@ function shapeGeometrySignature(shape: WorkplaneShape): string {
segments: shape.segments,
topRadius: shape.topRadius,
baseRadius: shape.baseRadius,
taperTopWidth: shape.taperTopWidth,
taperTopDepth: shape.taperTopDepth,
taperBottomWidth: shape.taperBottomWidth,
taperBottomDepth: shape.taperBottomDepth,
taperTopScale: shape.taperTopScale,
taperBottomScale: shape.taperBottomScale,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
@@ -1442,10 +1468,11 @@ function shapeCenter(shape: WorkplaneShape) {
}
function shapeLocalExtents(shape: WorkplaneShape) {
const footprint = shapeOverallFootprintDimensions(shape);
return {
x: shapeWidth(shape) / 2,
x: footprint.width / 2,
y: shape.height / 2,
z: shapeDepth(shape) / 2,
z: footprint.depth / 2,
};
}
@@ -1490,13 +1517,28 @@ function importedShapeProjectionBounds(
const min = new THREE.Vector3(Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
const max = new THREE.Vector3(Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
const point = new THREE.Vector3();
const tapered = shapeHasTaper(shape);
let taperMinY = Number.POSITIVE_INFINITY;
let taperMaxY = Number.NEGATIVE_INFINITY;
if (tapered) {
for (let index = 1; index < positions.length; index += 3) {
const localY = positions[index] * scaleY;
taperMinY = Math.min(taperMinY, localY);
taperMaxY = Math.max(taperMaxY, localY);
}
}
const taperHeight = Math.max(1e-6, taperMaxY - taperMinY);
for (let index = 0; index + 2 < positions.length; index += 3) {
const localY = positions[index + 1] * scaleY;
const normalizedHeight = tapered ? (localY - taperMinY) / taperHeight : 0;
const widthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "width") : 1;
const depthScale = tapered ? shapeTaperScaleAt(shape, normalizedHeight, "depth") : 1;
point
.set(
positions[index] * scaleX,
positions[index + 1] * scaleY - shape.height / 2,
positions[index + 2] * scaleZ,
positions[index] * scaleX * widthScale,
localY - shape.height / 2,
positions[index + 2] * scaleZ * depthScale,
)
.applyQuaternion(quaternion)
.add(center);
@@ -1713,6 +1755,27 @@ function resizedShapePatchFromFrame(shape: WorkplaneShape, center: THREE.Vector3
return patch;
}
function scaledHorizontalShapePatch(shape: WorkplaneShape, scaleX: number, scaleZ: number): Partial<WorkplaneShape> {
const width = Math.max(MIN_SHAPE_SIZE, shapeWidth(shape) * scaleX);
const depth = Math.max(MIN_SHAPE_SIZE, shapeDepth(shape) * scaleZ);
const patch: Partial<WorkplaneShape> = {
width,
depth,
size: resizedShapeSize(width, depth),
};
if (shape.kind === "cone") {
patch.baseRadius = width / 2;
}
if (shapeHasTaper(shape)) {
const taper = shapeTaperDimensions(shape);
patch.taperTopWidth = Math.max(MIN_SHAPE_SIZE, taper.topWidth * scaleX);
patch.taperBottomWidth = Math.max(MIN_SHAPE_SIZE, taper.bottomWidth * scaleX);
patch.taperTopDepth = Math.max(MIN_SHAPE_SIZE, taper.topDepth * scaleZ);
patch.taperBottomDepth = Math.max(MIN_SHAPE_SIZE, taper.bottomDepth * scaleZ);
}
return patch;
}
function shapeScreenBounds(state: ThreeState, shape: WorkplaneShape) {
const frame = selectionFrameForShapes([shape], [shape.id]);
if (!frame) {
@@ -1895,12 +1958,16 @@ function patchWithResizeAnchor(
return patchWithPreservedWorldBottom(shape, patch);
}
const width = Math.max(MIN_SHAPE_SIZE, patch.width ?? shapeWidth(shape));
const depth = Math.max(MIN_SHAPE_SIZE, patch.depth ?? shapeDepth(shape));
const draftShape = { ...shape, ...patch };
const draftFrame = selectionFrameForShapes([draftShape], [shape.id]);
const width = Math.max(MIN_SHAPE_SIZE, draftFrame?.width ?? patch.width ?? shapeWidth(shape));
const depth = Math.max(MIN_SHAPE_SIZE, draftFrame?.depth ?? patch.depth ?? shapeDepth(shape));
const center = resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, width, depth);
return patchWithPreservedWorldBottom(shape, {
...patch,
...resizedShapePatchFromFrame(shape, center, width, depth),
x: cleanNearZero(center.x, 0.0005),
z: cleanNearZero(center.z, 0.0005),
elevation: cleanNearZero(center.y - shape.height / 2, 0.0005),
});
}
@@ -1945,6 +2012,17 @@ function resizeShapeFromFrameHandle(
const nextCenter = altKey
? frame.center.clone()
: resizeCenterFromAnchor(frame, transform.scaleAnchorPoint ?? resizeAnchorPointForFrame(frame, signs), signs, nextWidth, nextDepth);
if (shapeHasTaper(shape)) {
const scaleX = nextWidth / Math.max(MIN_SHAPE_SIZE, width);
const scaleZ = nextDepth / Math.max(MIN_SHAPE_SIZE, depth);
const scaled = scaledHorizontalShapePatch(shape, scaleX, scaleZ);
return {
...scaled,
x: cleanNearZero(nextCenter.x, 0.0005),
z: cleanNearZero(nextCenter.z, 0.0005),
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
};
}
return resizedShapePatchFromFrame(shape, nextCenter, nextWidth, nextDepth);
}
@@ -2176,13 +2254,13 @@ function resizeSelectionFromHandle(
.add(frame.zAxis.clone().multiplyScalar(localCenter.z * nextZ.scale));
const width = snapDimension(shapeWidth(item.startShape) * nextX.scale, step, MIN_SHAPE_SIZE, 260);
const depth = snapDimension(shapeDepth(item.startShape) * nextZ.scale, step, MIN_SHAPE_SIZE, 260);
const actualScaleX = width / Math.max(MIN_SHAPE_SIZE, shapeWidth(item.startShape));
const actualScaleZ = depth / Math.max(MIN_SHAPE_SIZE, shapeDepth(item.startShape));
const patch = {
...scaledHorizontalShapePatch(item.startShape, actualScaleX, actualScaleZ),
x: nextItemCenter.x,
z: nextItemCenter.z,
elevation: cleanNearZero(nextItemCenter.y - item.startShape.height / 2, 0.0005),
width,
depth,
size: resizedShapeSize(width, depth),
} satisfies Partial<WorkplaneShape>;
return {
id: item.id,
@@ -3722,13 +3800,45 @@ export function WorkplaneViewport({
if (Number.isFinite(value) && value > 0) {
const nextValue = Math.max(MIN_SHAPE_SIZE, value);
if (edit.axis === "width") {
const patch: Partial<WorkplaneShape> = { width: nextValue, size: resizedShapeSize(nextValue, shapeDepth(shape)) };
if (shape.kind === "cone") {
patch.baseRadius = nextValue / 2;
const frame = selectionFrameForShapes([shape], [shape.id]);
if (shapeHasTaper(shape) && frame) {
const scaleX = nextValue / Math.max(MIN_SHAPE_SIZE, frame.width);
const anchor = lastResizeAnchorRef.current;
const signs = anchor?.shapeId === shape.id ? resizeSignsForDimension(anchor.signs, "width") : { x: 0, z: 0 };
const nextCenter = signs.x
? resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, nextValue, frame.depth)
: frame.center.clone();
onUpdateShape(id, {
...scaledHorizontalShapePatch(shape, scaleX, 1),
x: cleanNearZero(nextCenter.x, 0.0005),
z: cleanNearZero(nextCenter.z, 0.0005),
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
});
} else {
const patch: Partial<WorkplaneShape> = { width: nextValue, size: resizedShapeSize(nextValue, shapeDepth(shape)) };
if (shape.kind === "cone") {
patch.baseRadius = nextValue / 2;
}
onUpdateShape(id, patchWithResizeAnchor(shape, patch, edit.axis, lastResizeAnchorRef.current));
}
onUpdateShape(id, patchWithResizeAnchor(shape, patch, edit.axis, lastResizeAnchorRef.current));
} else if (edit.axis === "depth") {
onUpdateShape(id, patchWithResizeAnchor(shape, { depth: nextValue, size: resizedShapeSize(shapeWidth(shape), nextValue) }, edit.axis, lastResizeAnchorRef.current));
const frame = selectionFrameForShapes([shape], [shape.id]);
if (shapeHasTaper(shape) && frame) {
const scaleZ = nextValue / Math.max(MIN_SHAPE_SIZE, frame.depth);
const anchor = lastResizeAnchorRef.current;
const signs = anchor?.shapeId === shape.id ? resizeSignsForDimension(anchor.signs, "depth") : { x: 0, z: 0 };
const nextCenter = signs.z
? resizeCenterFromAnchor(frame, resizeAnchorPointForFrame(frame, signs), signs, frame.width, nextValue)
: frame.center.clone();
onUpdateShape(id, {
...scaledHorizontalShapePatch(shape, 1, scaleZ),
x: cleanNearZero(nextCenter.x, 0.0005),
z: cleanNearZero(nextCenter.z, 0.0005),
elevation: cleanNearZero(nextCenter.y - shape.height / 2, 0.0005),
});
} else {
onUpdateShape(id, patchWithResizeAnchor(shape, { depth: nextValue, size: resizedShapeSize(shapeWidth(shape), nextValue) }, edit.axis, lastResizeAnchorRef.current));
}
} else {
onUpdateShape(id, patchWithResizeAnchor(shape, { height: nextValue }, edit.axis, lastResizeAnchorRef.current));
}
@@ -4740,6 +4850,9 @@ export function WorkplaneViewport({
}
const key = event.key.toLowerCase();
const shortcutView = !event.ctrlKey && !event.metaKey && !event.altKey
? VIEW_FACE_SHORTCUTS[event.key]
: undefined;
if (event.key === "Escape" && workplaneModeRef.current) {
event.preventDefault();
onWorkplaneModeChange(false);
@@ -4752,6 +4865,9 @@ export function WorkplaneViewport({
setRulerMoveMode(false);
rulerPointDragRef.current = null;
setRulerToolsOpen(false);
} else if (shortcutView) {
event.preventDefault();
setViewCubeFace(shortcutView);
} else if (key === "w") {
event.preventDefault();
if (!event.shiftKey || !setPlacementWorkplaneAtSelection()) {
@@ -4774,18 +4890,18 @@ export function WorkplaneViewport({
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, togglePlacementWorkplane, toggleProjection, zoomCamera]);
}, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, setViewCubeFace, togglePlacementWorkplane, toggleProjection, zoomCamera]);
return (
<main className={`workplane-stage ${challengeTutorial ? `key-tag-tutorial-active ${challengeTutorialCollapsed ? "key-tag-tutorial-collapsed" : ""}` : ""}`}>
<div className="view-cube" aria-label="View orientation cube" onPointerDown={(event) => event.stopPropagation()}>
<div className="view-cube-inner" ref={viewCubeRef}>
<button type="button" className="cube-face cube-top" aria-label="Bottom view" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
<button type="button" className="cube-face cube-bottom" aria-label="Top view" onClick={() => setViewCubeFace("top")}>TOP</button>
<button type="button" className="cube-face cube-front" aria-label="Front view" onClick={() => setViewCubeFace("front")}>FRONT</button>
<button type="button" className="cube-face cube-back" aria-label="Back view" onClick={() => setViewCubeFace("back")}>BACK</button>
<button type="button" className="cube-face cube-right" aria-label="Right view" onClick={() => setViewCubeFace("right")}>RIGHT</button>
<button type="button" className="cube-face cube-left" aria-label="Left view" onClick={() => setViewCubeFace("left")}>LEFT</button>
<button type="button" className="cube-face cube-top" aria-label="Bottom view" aria-keyshortcuts="6" title="Bottom view (6)" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
<button type="button" className="cube-face cube-bottom" aria-label="Top view" aria-keyshortcuts="5" title="Top view (5)" onClick={() => setViewCubeFace("top")}>TOP</button>
<button type="button" className="cube-face cube-front" aria-label="Front view" aria-keyshortcuts="1" title="Front view (1)" onClick={() => setViewCubeFace("front")}>FRONT</button>
<button type="button" className="cube-face cube-back" aria-label="Back view" aria-keyshortcuts="2" title="Back view (2)" onClick={() => setViewCubeFace("back")}>BACK</button>
<button type="button" className="cube-face cube-right" aria-label="Right view" aria-keyshortcuts="4" title="Right view (4)" onClick={() => setViewCubeFace("right")}>RIGHT</button>
<button type="button" className="cube-face cube-left" aria-label="Left view" aria-keyshortcuts="3" title="Left view (3)" onClick={() => setViewCubeFace("left")}>LEFT</button>
</div>
</div>
@@ -7088,6 +7204,7 @@ function createShapeObject(
);
content.position.y = -shape.height / 2;
group.add(content);
applyGroupedContentTaper(content, shape, contentBox);
group.traverse((child) => {
child.userData.shapeId = shape.id;
});
@@ -7259,6 +7376,83 @@ function createImagePlateMaterials(shape: WorkplaneShape, sideMaterial: THREE.Me
];
}
function taperGeometryForShape(geometry: THREE.BufferGeometry, shape: WorkplaneShape) {
if (!shapeHasTaper(shape)) return geometry;
const tapered = geometry.userData.cached ? geometry.clone() : geometry;
if (tapered !== geometry) {
tapered.userData = {};
}
tapered.computeBoundingBox();
const box = tapered.boundingBox;
const position = tapered.getAttribute("position");
if (!box || !position) return tapered;
const height = Math.max(1e-6, box.max.y - box.min.y);
const centerX = (box.min.x + box.max.x) / 2;
const centerZ = (box.min.z + box.max.z) / 2;
for (let index = 0; index < position.count; index += 1) {
const y = position.getY(index);
const normalizedHeight = (y - box.min.y) / height;
const widthScale = shapeTaperScaleAt(shape, normalizedHeight, "width");
const depthScale = shapeTaperScaleAt(shape, normalizedHeight, "depth");
position.setXYZ(
index,
centerX + (position.getX(index) - centerX) * widthScale,
y,
centerZ + (position.getZ(index) - centerZ) * depthScale,
);
}
position.needsUpdate = true;
tapered.computeVertexNormals();
tapered.computeBoundingBox();
tapered.computeBoundingSphere();
return tapered;
}
function applyGroupedContentTaper(content: THREE.Group, shape: WorkplaneShape, baseBounds: THREE.Box3) {
if (!shapeHasTaper(shape)) return;
const height = Math.max(1e-6, baseBounds.max.y - baseBounds.min.y);
const centerX = (baseBounds.min.x + baseBounds.max.x) / 2;
const centerZ = (baseBounds.min.z + baseBounds.max.z) / 2;
content.updateMatrixWorld(true);
const contentWorldInverse = content.matrixWorld.clone().invert();
content.traverse((object) => {
if (!(object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.LineSegments)) return;
if (!(object.geometry instanceof THREE.BufferGeometry)) return;
const sourcePosition = object.geometry.getAttribute("position");
if (!sourcePosition) return;
object.updateMatrixWorld(true);
const localToContent = new THREE.Matrix4().multiplyMatrices(contentWorldInverse, object.matrixWorld);
const contentToLocal = localToContent.clone().invert();
if (object instanceof THREE.Mesh) {
releaseSharedShapeGeometry(object);
}
const nextGeometry = object.geometry.clone();
nextGeometry.userData = {};
const position = nextGeometry.getAttribute("position");
const point = new THREE.Vector3();
for (let index = 0; index < position.count; index += 1) {
point.fromBufferAttribute(position, index).applyMatrix4(localToContent);
const normalizedHeight = (point.y - baseBounds.min.y) / height;
const widthScale = shapeTaperScaleAt(shape, normalizedHeight, "width");
const depthScale = shapeTaperScaleAt(shape, normalizedHeight, "depth");
point.x = centerX + (point.x - centerX) * widthScale;
point.z = centerZ + (point.z - centerZ) * depthScale;
point.applyMatrix4(contentToLocal);
position.setXYZ(index, point.x, point.y, point.z);
}
position.needsUpdate = true;
if (object instanceof THREE.Mesh) {
nextGeometry.computeVertexNormals();
}
nextGeometry.computeBoundingBox();
nextGeometry.computeBoundingSphere();
object.geometry = nextGeometry;
if (object instanceof THREE.Mesh && content.userData.acceleratedPicking !== false) {
enableAcceleratedMeshPicking(object, nextGeometry, Boolean(shape.importedMesh));
}
});
}
function addMesh(
group: THREE.Group,
geometry: THREE.BufferGeometry,
@@ -7268,7 +7462,8 @@ function addMesh(
rotation?: THREE.Euler,
scale?: THREE.Vector3,
) {
const prepared = geometry.userData.cached ? geometry : putGeometryOnBase(geometry);
const based = geometry.userData.cached ? geometry : putGeometryOnBase(geometry);
const prepared = taperGeometryForShape(based, shape);
const mesh = new THREE.Mesh(prepared, material);
mesh.userData.shapeSurface = true;
retainSharedShapeGeometry(mesh, prepared);
@@ -7375,7 +7570,7 @@ function getPreservedImportedMeshGeometry(shape: WorkplaneShape) {
}
function getEdgesGeometry(shape: WorkplaneShape, geometry: THREE.BufferGeometry, threshold: number) {
const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape)
const importedCache = shape.importedMesh && !preservesEdgeTreatmentSize(shape) && !shapeHasTaper(shape)
? getImportedMeshCache(shape.importedMesh).edges
: null;
let cache = importedCache ?? sharedEdgesGeometryCache.get(geometry);
@@ -22,7 +22,7 @@ import {
gearToothPitch,
} from "@/lib/gearGeometry";
import { displayStepFromMillimeters, displayToMillimeters, formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, parseMeasurementInput } from "@/lib/measurementUnits";
import { resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
import { resizedShapeSize, shapeDepth, shapeHasTaper, shapeOverallFootprintDimensions, shapeTaperDimensions, shapeWidth } from "@/lib/workplaneShapes";
import { normalizeSketchRevolveSettings } from "@/lib/sketchRevolve";
import type { GearType, GridSize, MeasurementAccuracy, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
@@ -104,18 +104,52 @@ function formatPropertyNumber(value: number, accuracy: MeasurementAccuracy, step
}
function propertyUsesLengthUnit(label: string) {
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole"].includes(label);
return ["Radius", "Length", "Width", "Height", "Bevel", "Top Radius", "Base Radius", "Thickness", "Tooth Size", "Tooth Width", "Center Hole", "Top Length", "Top Width", "Bottom Length", "Bottom Width"].includes(label);
}
function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdate): ShapePropertyConfig[] {
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) }, { resizeAxis: "width" });
const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) }, { resizeAxis: "depth" });
const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) }, { resizeAxis: "width" });
const baseWidth = shapeWidth(shape);
const baseDepth = shapeDepth(shape);
const footprint = shapeOverallFootprintDimensions(shape);
const width = footprint.width;
const depth = footprint.depth;
const taper = shapeTaperDimensions(shape);
const widthPatch = (value: number): Partial<WorkplaneShape> => {
if (!shapeHasTaper(shape)) {
return { width: value, size: resizedShapeSize(value, baseDepth) };
}
const scale = value / Math.max(MIN_SHAPE_SIZE, width);
const nextBaseWidth = Math.max(MIN_SHAPE_SIZE, baseWidth * scale);
return {
width: nextBaseWidth,
size: resizedShapeSize(nextBaseWidth, baseDepth),
taperTopWidth: Math.max(MIN_SHAPE_SIZE, taper.topWidth * scale),
taperBottomWidth: Math.max(MIN_SHAPE_SIZE, taper.bottomWidth * scale),
};
};
const depthPatch = (value: number): Partial<WorkplaneShape> => {
if (!shapeHasTaper(shape)) {
return { depth: value, size: resizedShapeSize(baseWidth, value) };
}
const scale = value / Math.max(MIN_SHAPE_SIZE, depth);
const nextBaseDepth = Math.max(MIN_SHAPE_SIZE, baseDepth * scale);
return {
depth: nextBaseDepth,
size: resizedShapeSize(baseWidth, nextBaseDepth),
taperTopDepth: Math.max(MIN_SHAPE_SIZE, taper.topDepth * scale),
taperBottomDepth: Math.max(MIN_SHAPE_SIZE, taper.bottomDepth * scale),
};
};
const setWidth = (value: number) => onUpdate(widthPatch(value), { resizeAxis: "width" });
const setDepth = (value: number) => onUpdate(depthPatch(value), { resizeAxis: "depth" });
const setConeWidth = (value: number) => {
const patch = widthPatch(value);
patch.baseRadius = Math.max(MIN_SHAPE_SIZE, (patch.width ?? baseWidth) / 2);
onUpdate(patch, { resizeAxis: "width" });
};
const setBaseRadius = (value: number) => {
const diameter = value * 2;
onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, depth) }, { resizeAxis: "width" });
onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, baseDepth) }, { resizeAxis: "width" });
};
const setHeight = (height: number) => onUpdate({ height }, { resizeAxis: "height" });
@@ -171,7 +205,7 @@ function getShapeProperties(shape: WorkplaneShape, onUpdate: ShapeInspectorUpdat
if (shape.kind === "cone") {
return [
{ label: "Top Radius", value: shape.topRadius ?? 0, min: 0, max: 40, onChange: (topRadius) => onUpdate({ topRadius }) },
{ label: "Base Radius", value: shape.baseRadius ?? width / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius },
{ label: "Base Radius", value: shape.baseRadius ?? baseWidth / 2, min: MIN_SHAPE_SIZE, max: 80, onChange: setBaseRadius },
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setConeWidth },
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: setHeight },
@@ -356,9 +390,41 @@ export function ShapeInspector({
const gearHelixProperties = shape.kind === "gear"
? properties.filter((property) => ["Helix Angle", "Quality"].includes(property.label))
: [];
const taper = shapeTaperDimensions(shape);
const taperProperties: ShapePropertyConfig[] = shape.kind === "gear" ? [] : [
{
label: "Top Length",
value: taper.topDepth,
min: MIN_SHAPE_SIZE,
max: 480,
onChange: (taperTopDepth) => onUpdate({ taperTopDepth, taperTopWidth: taper.topWidth, taperTopScale: undefined }),
},
{
label: "Top Width",
value: taper.topWidth,
min: MIN_SHAPE_SIZE,
max: 480,
onChange: (taperTopWidth) => onUpdate({ taperTopWidth, taperTopDepth: taper.topDepth, taperTopScale: undefined }),
},
{
label: "Bottom Length",
value: taper.bottomDepth,
min: MIN_SHAPE_SIZE,
max: 480,
onChange: (taperBottomDepth) => onUpdate({ taperBottomDepth, taperBottomWidth: taper.bottomWidth, taperBottomScale: undefined }),
},
{
label: "Bottom Width",
value: taper.bottomWidth,
min: MIN_SHAPE_SIZE,
max: 480,
onChange: (taperBottomWidth) => onUpdate({ taperBottomWidth, taperBottomDepth: taper.bottomDepth, taperBottomScale: undefined }),
},
];
const isSketchRevolve = shape.sketchOperation === "revolve" || Boolean(shape.sketchRevolve);
const inspectorRef = useRef<HTMLElement>(null);
const [propertiesOpen, setPropertiesOpen] = useState(true);
const [taperOpen, setTaperOpen] = useState(false);
const [gearTeethOpen, setGearTeethOpen] = useState(true);
const [gearHelixOpen, setGearHelixOpen] = useState(true);
const [colorOpen, setColorOpen] = useState(false);
@@ -513,6 +579,25 @@ export function ShapeInspector({
</div>
) : null}
</div>
{shape.kind !== "gear" ? (
<div className={`property-card ${taperOpen ? "" : "collapsed"}`}>
<button
className="property-card-header"
type="button"
aria-expanded={taperOpen}
aria-controls={`taper-${shape.id}`}
onClick={() => setTaperOpen((open) => !open)}
>
<span>Taper</span>
<ChevronUp className={taperOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
</button>
{taperOpen ? (
<div className="property-list" id={`taper-${shape.id}`}>
<ShapePropertyRows properties={taperProperties} workspace={workspace} disabled={locked} onInteractionActiveChange={onInteractionActiveChange} />
</div>
) : null}
</div>
) : null}
{shape.kind === "gear" ? (
<div className={`property-card ${gearTeethOpen ? "" : "collapsed"}`}>
<button
@@ -631,7 +716,7 @@ function RangeProperty({
onChange,
onInteractionActiveChange,
}: RangePropertyConfig & { workspace: WorkplaneWorkspaceSettings; disabled?: boolean; onInteractionActiveChange?: (active: boolean) => void }) {
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height";
const allowsAboveSliderMax = label === "Length" || label === "Width" || label === "Height" || label.endsWith(" Length") || label.endsWith(" Width");
const isLength = propertyUsesLengthUnit(label);
const accuracy = workspace.accuracy;
const actualValue = Math.max(min, Number.isFinite(value) ? value : min);
@@ -644,11 +729,6 @@ function RangeProperty({
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState(formatPropertyNumber(controlValue, accuracy, controlStep));
const unit = isLength ? lengthDisplayUnit(workspace).label : null;
useEffect(() => {
if (!editing) {
setDraft(formatPropertyNumber(controlValue, accuracy, controlStep));
}
}, [accuracy, controlStep, controlValue, editing]);
const toModelValue = (nextValue: number) => isLength ? displayToMillimeters(nextValue, workspace) : nextValue;
const commitDraft = () => {
const next = parseMeasurementInput(draft);
+1
View File
@@ -8,6 +8,7 @@ export type AppUpdateStatus = {
updateUrl: string;
installationReady: boolean;
requiresUpdateKey: boolean;
updateMode?: "local" | "server" | "desktop";
checkError?: string;
};
+6
View File
@@ -47,6 +47,12 @@ export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape,
segments: shape.segments,
topRadius: shape.topRadius,
baseRadius: shape.baseRadius,
taperTopWidth: shape.taperTopWidth,
taperTopDepth: shape.taperTopDepth,
taperBottomWidth: shape.taperBottomWidth,
taperBottomDepth: shape.taperBottomDepth,
taperTopScale: shape.taperTopScale,
taperBottomScale: shape.taperBottomScale,
teeth: shape.teeth,
toothSize: shape.toothSize,
toothWidth: shape.toothWidth,
+257
View File
@@ -0,0 +1,257 @@
import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge";
export type SketchSegmentPlacement = {
point: { x: number; z: number };
amount: number;
};
type IdFactory = (prefix: string) => string;
type SplitResult = {
profile: SketchProfile;
pointId: string;
inserted: boolean;
};
const ENDPOINT_EPSILON = 1e-7;
const POINT_EPSILON = 1e-6;
function clamp01(value: number) {
return Math.min(1, Math.max(0, value));
}
function lerpPoint(a: { x: number; z: number }, b: { x: number; z: number }, amount: number) {
return {
x: a.x + (b.x - a.x) * amount,
z: a.z + (b.z - a.z) * amount,
};
}
function cubicPoint(
start: { x: number; z: number },
first: { x: number; z: number },
second: { x: number; z: number },
end: { x: number; z: number },
amount: number,
) {
const inverse = 1 - amount;
return {
x: inverse ** 3 * start.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * end.x,
z: inverse ** 3 * start.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * end.z,
};
}
function distanceSquared(a: { x: number; z: number }, b: { x: number; z: number }) {
const dx = a.x - b.x;
const dz = a.z - b.z;
return dx * dx + dz * dz;
}
function isStraightSegment(segment: SketchSegment) {
return !segment.kind || segment.kind === "line";
}
export function closestPointOnSketchSegment(
segment: SketchSegment,
start: SketchPoint,
end: SketchPoint,
target: { x: number; z: number },
): SketchSegmentPlacement {
const first = start.handleOut;
const second = end.handleIn;
if (isStraightSegment(segment) || !first || !second) {
const dx = end.x - start.x;
const dz = end.z - start.z;
const lengthSquared = dx * dx + dz * dz;
const amount = lengthSquared > ENDPOINT_EPSILON
? clamp01(((target.x - start.x) * dx + (target.z - start.z) * dz) / lengthSquared)
: 0;
return { point: lerpPoint(start, end, amount), amount };
}
const samples = 64;
let bestIndex = 0;
let bestDistance = Number.POSITIVE_INFINITY;
for (let index = 0; index <= samples; index += 1) {
const amount = index / samples;
const point = cubicPoint(start, first, second, end, amount);
const distance = distanceSquared(point, target);
if (distance < bestDistance) {
bestDistance = distance;
bestIndex = index;
}
}
let left = Math.max(0, (bestIndex - 1) / samples);
let right = Math.min(1, (bestIndex + 1) / samples);
for (let iteration = 0; iteration < 22; iteration += 1) {
const third = (right - left) / 3;
const firstAmount = left + third;
const secondAmount = right - third;
const firstDistance = distanceSquared(cubicPoint(start, first, second, end, firstAmount), target);
const secondDistance = distanceSquared(cubicPoint(start, first, second, end, secondAmount), target);
if (firstDistance <= secondDistance) right = secondAmount;
else left = firstAmount;
}
const amount = clamp01((left + right) / 2);
return { point: cubicPoint(start, first, second, end, amount), amount };
}
export function splitSketchSegment(
profile: SketchProfile,
segmentId: string,
amountValue: number,
createId: IdFactory,
): SplitResult {
const segment = profile.segments.find((entry) => entry.id === segmentId);
if (!segment) return { profile, pointId: "", inserted: false };
const start = profile.points.find((entry) => entry.id === segment.startId);
const end = profile.points.find((entry) => entry.id === segment.endId);
if (!start || !end) return { profile, pointId: "", inserted: false };
const amount = clamp01(amountValue);
if (amount <= ENDPOINT_EPSILON) return { profile, pointId: start.id, inserted: false };
if (amount >= 1 - ENDPOINT_EPSILON) return { profile, pointId: end.id, inserted: false };
const first = start.handleOut;
const second = end.handleIn;
const newPointId = createId("sketch-point");
let point: SketchPoint;
let nextPoints = profile.points;
if (!isStraightSegment(segment) && first && second) {
const a = lerpPoint(start, first, amount);
const b = lerpPoint(first, second, amount);
const c = lerpPoint(second, end, amount);
const d = lerpPoint(a, b, amount);
const e = lerpPoint(b, c, amount);
const position = lerpPoint(d, e, amount);
point = {
id: newPointId,
...position,
handleIn: d,
handleOut: e,
mode: "smooth",
};
nextPoints = profile.points.map((entry) => {
if (entry.id === start.id) return { ...entry, handleOut: a };
if (entry.id === end.id) return { ...entry, handleIn: c };
return entry;
});
} else {
point = { id: newPointId, ...lerpPoint(start, end, amount), mode: "corner" };
}
const secondSegmentId = createId("sketch-segment");
return {
profile: {
...profile,
points: [...nextPoints, point],
segments: profile.segments.flatMap((entry) => entry.id === segmentId ? [
{ ...entry, endId: point.id },
{ ...entry, id: secondSegmentId, startId: point.id },
] : [entry]),
},
pointId: point.id,
inserted: true,
};
}
type SegmentSplit = { amount: number; pointId: string };
function cross(ax: number, az: number, bx: number, bz: number) {
return ax * bz - az * bx;
}
export function addLineIntersectionPoints(profile: SketchProfile, createId: IdFactory) {
const pointById = new Map(profile.points.map((point) => [point.id, point]));
const lines = profile.segments.filter((segment) => isStraightSegment(segment) && pointById.has(segment.startId) && pointById.has(segment.endId));
const splits = new Map<string, SegmentSplit[]>();
const addedPoints: SketchPoint[] = [];
const pointNear = (position: { x: number; z: number }) => {
for (const point of [...profile.points, ...addedPoints]) {
if (Math.hypot(point.x - position.x, point.z - position.z) <= POINT_EPSILON) return point;
}
return null;
};
const addSplit = (segment: SketchSegment, amount: number, pointId: string) => {
if (amount <= ENDPOINT_EPSILON || amount >= 1 - ENDPOINT_EPSILON) return;
const current = splits.get(segment.id) ?? [];
if (!current.some((entry) => entry.pointId === pointId || Math.abs(entry.amount - amount) <= ENDPOINT_EPSILON)) {
current.push({ amount, pointId });
splits.set(segment.id, current);
}
};
for (let firstIndex = 0; firstIndex < lines.length; firstIndex += 1) {
const firstSegment = lines[firstIndex];
const a = pointById.get(firstSegment.startId)!;
const b = pointById.get(firstSegment.endId)!;
const rx = b.x - a.x;
const rz = b.z - a.z;
for (let secondIndex = firstIndex + 1; secondIndex < lines.length; secondIndex += 1) {
const secondSegment = lines[secondIndex];
if (
firstSegment.startId === secondSegment.startId ||
firstSegment.startId === secondSegment.endId ||
firstSegment.endId === secondSegment.startId ||
firstSegment.endId === secondSegment.endId
) continue;
const c = pointById.get(secondSegment.startId)!;
const d = pointById.get(secondSegment.endId)!;
const sx = d.x - c.x;
const sz = d.z - c.z;
const denominator = cross(rx, rz, sx, sz);
const denominatorTolerance = ENDPOINT_EPSILON * Math.max(1, Math.hypot(rx, rz) * Math.hypot(sx, sz));
if (Math.abs(denominator) <= denominatorTolerance) continue;
const qpx = c.x - a.x;
const qpz = c.z - a.z;
const firstAmount = cross(qpx, qpz, sx, sz) / denominator;
const secondAmount = cross(qpx, qpz, rx, rz) / denominator;
if (
firstAmount < -ENDPOINT_EPSILON || firstAmount > 1 + ENDPOINT_EPSILON ||
secondAmount < -ENDPOINT_EPSILON || secondAmount > 1 + ENDPOINT_EPSILON
) continue;
const clampedFirst = clamp01(firstAmount);
const clampedSecond = clamp01(secondAmount);
const position = lerpPoint(a, b, clampedFirst);
const firstEndpoint = clampedFirst <= ENDPOINT_EPSILON ? a : clampedFirst >= 1 - ENDPOINT_EPSILON ? b : null;
const secondEndpoint = clampedSecond <= ENDPOINT_EPSILON ? c : clampedSecond >= 1 - ENDPOINT_EPSILON ? d : null;
if (firstEndpoint && secondEndpoint) continue;
let intersectionPoint = firstEndpoint ?? secondEndpoint ?? pointNear(position);
if (!intersectionPoint) {
intersectionPoint = { id: createId("sketch-point"), ...position, mode: "corner" };
addedPoints.push(intersectionPoint);
}
addSplit(firstSegment, clampedFirst, intersectionPoint.id);
addSplit(secondSegment, clampedSecond, intersectionPoint.id);
}
}
if (!splits.size) return profile;
const segments = profile.segments.flatMap((segment) => {
const segmentSplits = splits.get(segment.id);
if (!segmentSplits?.length) return [segment];
const ordered = [...segmentSplits].sort((left, right) => left.amount - right.amount);
const pointIds = [segment.startId, ...ordered.map((entry) => entry.pointId), segment.endId];
return pointIds.slice(0, -1).map((startId, index) => ({
...segment,
id: index === 0 ? segment.id : createId("sketch-segment"),
startId,
endId: pointIds[index + 1],
}));
});
return {
...profile,
points: [...profile.points, ...addedPoints],
segments,
};
}
+35 -11
View File
@@ -5,6 +5,11 @@ export type StlExportMesh = {
faces: readonly (readonly [number, number, number])[];
};
const STL_HEADER_BYTES = 80;
const STL_TRIANGLE_COUNT_BYTES = 4;
const STL_TRIANGLE_BYTES = 50;
const STL_PREFIX_BYTES = STL_HEADER_BYTES + STL_TRIANGLE_COUNT_BYTES;
function normalFor(a: MeshPoint, b: MeshPoint, c: MeshPoint): [number, number, number] {
const ux = b[0] - a[0];
const uy = b[1] - a[1];
@@ -19,23 +24,42 @@ function normalFor(a: MeshPoint, b: MeshPoint, c: MeshPoint): [number, number, n
return [nx / length, ny / length, nz / length];
}
export function exportMeshesToStl(meshes: readonly StlExportMesh[]) {
const lines = ["solid sketchforge_design"];
function writePoint(view: DataView, offset: number, point: MeshPoint) {
view.setFloat32(offset, point[0], true);
view.setFloat32(offset + 4, point[1], true);
view.setFloat32(offset + 8, point[2], true);
return offset + 12;
}
export function exportMeshesToStl(meshes: readonly StlExportMesh[]): ArrayBuffer {
const triangleCount = meshes.reduce((count, mesh) => count + mesh.faces.length, 0);
if (triangleCount > 0xffff_ffff) {
throw new Error("STL export exceeds the binary format's triangle limit");
}
const buffer = new ArrayBuffer(STL_PREFIX_BYTES + triangleCount * STL_TRIANGLE_BYTES);
const bytes = new Uint8Array(buffer);
const header = new TextEncoder().encode("Binary STL (Z-up coordinates)");
bytes.set(header.subarray(0, STL_HEADER_BYTES));
const view = new DataView(buffer);
view.setUint32(STL_HEADER_BYTES, triangleCount, true);
let offset = STL_PREFIX_BYTES;
meshes.forEach((mesh) => {
mesh.faces.forEach(([ai, bi, ci]) => {
const a = sketchForgeToZUp(mesh.vertices[ai]);
const b = sketchForgeToZUp(mesh.vertices[bi]);
const c = sketchForgeToZUp(mesh.vertices[ci]);
const n = normalFor(a, b, c);
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
lines.push(" outer loop");
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
lines.push(" endloop");
lines.push(" endfacet");
offset = writePoint(view, offset, n);
offset = writePoint(view, offset, a);
offset = writePoint(view, offset, b);
offset = writePoint(view, offset, c);
view.setUint16(offset, 0, true);
offset += 2;
});
});
lines.push("endsolid sketchforge_design");
return lines.join("\n");
return buffer;
}
+56
View File
@@ -38,6 +38,56 @@ export function shapeDepth(shape: WorkplaneShape) {
return shape.depth ?? shape.size;
}
export function normalizeTaperScale(value?: number) {
if (!Number.isFinite(value)) return 1;
return Math.min(3, Math.max(0.05, value as number));
}
function positiveTaperDimension(value: number | undefined, fallback: number) {
if (!Number.isFinite(value)) return fallback;
return Math.max(0.01, value as number);
}
export function shapeTaperDimensions(shape: WorkplaneShape) {
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
return {
topWidth: positiveTaperDimension(shape.taperTopWidth, width * normalizeTaperScale(shape.taperTopScale)),
topDepth: positiveTaperDimension(shape.taperTopDepth, depth * normalizeTaperScale(shape.taperTopScale)),
bottomWidth: positiveTaperDimension(shape.taperBottomWidth, width * normalizeTaperScale(shape.taperBottomScale)),
bottomDepth: positiveTaperDimension(shape.taperBottomDepth, depth * normalizeTaperScale(shape.taperBottomScale)),
};
}
export function shapeHasTaper(shape: WorkplaneShape) {
if (shape.kind === "gear") return false;
const width = shapeWidth(shape);
const depth = shapeDepth(shape);
const taper = shapeTaperDimensions(shape);
return Math.abs(taper.topWidth - width) > 1e-6 || Math.abs(taper.topDepth - depth) > 1e-6 || Math.abs(taper.bottomWidth - width) > 1e-6 || Math.abs(taper.bottomDepth - depth) > 1e-6;
}
export function shapeOverallFootprintDimensions(shape: WorkplaneShape) {
if (!shapeHasTaper(shape)) {
return { width: shapeWidth(shape), depth: shapeDepth(shape) };
}
const taper = shapeTaperDimensions(shape);
return {
width: Math.max(taper.topWidth, taper.bottomWidth),
depth: Math.max(taper.topDepth, taper.bottomDepth),
};
}
export function shapeTaperScaleAt(shape: WorkplaneShape, normalizedHeight: number, axis: "width" | "depth" = "width") {
if (shape.kind === "gear") return 1;
const taper = shapeTaperDimensions(shape);
const base = axis === "width" ? shapeWidth(shape) : shapeDepth(shape);
const bottom = axis === "width" ? taper.bottomWidth : taper.bottomDepth;
const top = axis === "width" ? taper.topWidth : taper.topDepth;
const t = Math.min(1, Math.max(0, Number.isFinite(normalizedHeight) ? normalizedHeight : 0));
return (bottom + (top - bottom) * t) / Math.max(0.01, base);
}
export function meshYawDegrees(shape: WorkplaneShape) {
const isRoundPrimitive = !shape.importedMesh && (shape.kind === "cylinder" || shape.kind === "cone");
const isCircular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < 0.0005;
@@ -199,6 +249,12 @@ export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
a.segments === b.segments &&
a.topRadius === b.topRadius &&
a.baseRadius === b.baseRadius &&
a.taperTopWidth === b.taperTopWidth &&
a.taperTopDepth === b.taperTopDepth &&
a.taperBottomWidth === b.taperBottomWidth &&
a.taperBottomDepth === b.taperBottomDepth &&
a.taperTopScale === b.taperTopScale &&
a.taperBottomScale === b.taperBottomScale &&
a.teeth === b.teeth &&
a.toothSize === b.toothSize &&
a.toothWidth === b.toothWidth &&
+7
View File
@@ -197,6 +197,13 @@ export type WorkplaneShape = {
segments?: number;
topRadius?: number;
baseRadius?: number;
taperTopWidth?: number;
taperTopDepth?: number;
taperBottomWidth?: number;
taperBottomDepth?: number;
/** Legacy local-dev taper fields kept for compatibility with in-progress projects. */
taperTopScale?: number;
taperBottomScale?: number;
teeth?: number;
toothSize?: number;
toothWidth?: number;
+31
View File
@@ -0,0 +1,31 @@
import { spawn } from "node:child_process";
const parentPid = Number.parseInt(process.argv[2] || "", 10);
const repoRoot = process.argv[3] || process.cwd();
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Give the update API response time to reach the browser before stopping Next.
await sleep(1200);
if (Number.isFinite(parentPid) && parentPid > 0) {
try {
process.kill(parentPid, "SIGTERM");
} catch {
// The dev server may already have stopped on its own.
}
}
await sleep(1200);
const options = {
cwd: repoRoot,
detached: true,
stdio: "ignore",
windowsHide: true,
};
const child = process.platform === "win32"
? spawn("cmd.exe", ["/d", "/s", "/c", "npm run dev"], options)
: spawn("npm", ["run", "dev"], options);
child.unref();
+52
View File
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { GET, POST } from "@/app/api/project-thumbnail/route";
function missingThumbnailRequest(url: string, headers?: HeadersInit) {
return new Request(`${url}/api/project-thumbnail?projectId=missing-thumbnail`, { headers });
}
describe("project thumbnail request origins", () => {
it("allows same-origin requests on a public HTTPS host", async () => {
const response = await GET(missingThumbnailRequest("https://projects.example.test", {
Origin: "https://projects.example.test",
"Sec-Fetch-Site": "same-origin",
}));
expect(response.status).toBe(404);
});
it("uses forwarded host and protocol behind a TLS reverse proxy", async () => {
const response = await GET(missingThumbnailRequest("http://localhost:3000", {
Origin: "https://projects.example.test",
"Sec-Fetch-Site": "same-origin",
"X-Forwarded-Host": "projects.example.test",
"X-Forwarded-Proto": "https",
}));
expect(response.status).toBe(404);
});
it("rejects a different origin", async () => {
const response = await GET(missingThumbnailRequest("https://projects.example.test", {
Origin: "https://other.example.test",
"Sec-Fetch-Site": "cross-site",
}));
expect(response.status).toBe(403);
});
it("allows same-origin uploads to proceed to request validation", async () => {
const response = await POST(new Request("https://projects.example.test/api/project-thumbnail", {
method: "POST",
headers: {
"Content-Type": "application/json",
Origin: "https://projects.example.test",
"Sec-Fetch-Site": "same-origin",
},
body: JSON.stringify({}),
}));
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({ error: "Invalid thumbnail request" });
});
});
+99
View File
@@ -0,0 +1,99 @@
import { describe, expect, it } from "vitest";
import { addLineIntersectionPoints, closestPointOnSketchSegment, splitSketchSegment } from "@/lib/sketchPointRefinement";
import type { SketchProfile } from "@/types/sketchforge";
function idFactory() {
let value = 0;
return (prefix: string) => `${prefix}-${++value}`;
}
describe("sketch point refinement", () => {
it("projects the refine preview onto the exact line position", () => {
const start = { id: "a", x: 0, z: 0 };
const end = { id: "b", x: 10, z: 0 };
const placement = closestPointOnSketchSegment(
{ id: "line", startId: "a", endId: "b", kind: "line" },
start,
end,
{ x: 3, z: 4 },
);
expect(placement.amount).toBeCloseTo(0.3, 8);
expect(placement.point).toEqual({ x: 3, z: 0 });
});
it("splits a bezier without moving the curve at the inserted point", () => {
const profile: SketchProfile = {
points: [
{ id: "a", x: 0, z: 0, handleOut: { x: 0, z: 10 }, mode: "smooth" },
{ id: "b", x: 10, z: 0, handleIn: { x: 10, z: 10 }, mode: "smooth" },
],
segments: [{ id: "curve", startId: "a", endId: "b", kind: "bezier" }],
};
const result = splitSketchSegment(profile, "curve", 0.5, idFactory());
expect(result.inserted).toBe(true);
const inserted = result.profile.points.find((point) => point.id === result.pointId);
expect(inserted?.x).toBeCloseTo(5, 8);
expect(inserted?.z).toBeCloseTo(7.5, 8);
expect(inserted?.handleIn).toEqual({ x: 2.5, z: 7.5 });
expect(inserted?.handleOut).toEqual({ x: 7.5, z: 7.5 });
expect(result.profile.segments).toHaveLength(2);
expect(result.profile.segments[0].endId).toBe(result.pointId);
expect(result.profile.segments[1].startId).toBe(result.pointId);
});
it("adds one shared point and splits both crossing lines", () => {
const profile: SketchProfile = {
points: [
{ id: "a", x: 0, z: 0 },
{ id: "b", x: 10, z: 10 },
{ id: "c", x: 0, z: 10 },
{ id: "d", x: 10, z: 0 },
],
segments: [
{ id: "first", startId: "a", endId: "b", kind: "line" },
{ id: "second", startId: "c", endId: "d", kind: "line" },
],
};
const next = addLineIntersectionPoints(profile, idFactory());
const intersection = next.points.find((point) => Math.abs(point.x - 5) < 1e-8 && Math.abs(point.z - 5) < 1e-8);
expect(intersection).toBeTruthy();
expect(next.points).toHaveLength(5);
expect(next.segments).toHaveLength(4);
expect(next.segments.filter((segment) => segment.startId === intersection?.id || segment.endId === intersection?.id)).toHaveLength(4);
});
it("reuses an existing endpoint when it lands on the middle of another line", () => {
const profile: SketchProfile = {
points: [
{ id: "a", x: 0, z: 0 },
{ id: "b", x: 10, z: 0 },
{ id: "touch", x: 5, z: 0 },
{ id: "d", x: 5, z: 6 },
],
segments: [
{ id: "horizontal", startId: "a", endId: "b", kind: "line" },
{ id: "vertical", startId: "touch", endId: "d", kind: "line" },
],
};
const next = addLineIntersectionPoints(profile, idFactory());
expect(next.points).toHaveLength(4);
expect(next.segments).toHaveLength(3);
expect(next.segments.filter((segment) => segment.startId === "touch" || segment.endId === "touch")).toHaveLength(3);
});
it("does not invent points for collinear overlap", () => {
const profile: SketchProfile = {
points: [
{ id: "a", x: 0, z: 0 },
{ id: "b", x: 10, z: 0 },
{ id: "c", x: 5, z: 0 },
{ id: "d", x: 15, z: 0 },
],
segments: [
{ id: "first", startId: "a", endId: "b", kind: "line" },
{ id: "second", startId: "c", endId: "d", kind: "line" },
],
};
expect(addLineIntersectionPoints(profile, idFactory())).toBe(profile);
});
});
+42 -3
View File
@@ -1,13 +1,52 @@
import { describe, expect, it } from "vitest";
import { exportMeshesToStl } from "@/lib/stlExport";
describe("STL export orientation", () => {
it("writes editor Y-up coordinates as slicer Z-up coordinates", () => {
function readPoint(view: DataView, offset: number) {
return [
view.getFloat32(offset, true),
view.getFloat32(offset + 4, true),
view.getFloat32(offset + 8, true),
];
}
describe("binary STL export", () => {
it("uses the fixed binary STL record size and triangle count", () => {
const stl = exportMeshesToStl([
{
vertices: [[0, 0, 0], [1, 0, 0], [0, 1, 0]],
faces: [[0, 1, 2]],
},
{
vertices: [[0, 0, 0], [0, 1, 0], [0, 0, 1]],
faces: [[0, 1, 2]],
},
]);
const view = new DataView(stl);
expect(stl.byteLength).toBe(84 + 2 * 50);
expect(view.getUint32(80, true)).toBe(2);
});
it("writes editor Y-up coordinates as slicer Z-up float32 values", () => {
const stl = exportMeshesToStl([{
vertices: [[0, 0, 0], [10, 0, 0], [0, 20, 5]],
faces: [[0, 1, 2]],
}]);
const view = new DataView(stl);
expect(stl).toContain("vertex 0 -5 20");
expect(readPoint(view, 84 + 12 + 2 * 12)).toEqual([0, -5, 20]);
});
it("writes a unit facet normal and clears the attribute byte count", () => {
const stl = exportMeshesToStl([{
vertices: [[0, 0, 0], [10, 0, 0], [0, 20, 5]],
faces: [[0, 1, 2]],
}]);
const view = new DataView(stl);
const normal = readPoint(view, 84);
expect(Math.hypot(...normal)).toBeCloseTo(1);
expect(normal).toEqual([0, expect.closeTo(-0.9701425), expect.closeTo(-0.2425356)]);
expect(view.getUint16(84 + 48, true)).toBe(0);
});
});
+30
View File
@@ -17,6 +17,10 @@ import {
resizedShapeSize,
serializeShapesForSync,
shapeDepth,
shapeHasTaper,
shapeOverallFootprintDimensions,
shapeTaperDimensions,
shapeTaperScaleAt,
shapeWidth,
withHoleMode,
workplaneShapesEqual,
@@ -78,6 +82,32 @@ describe("workplane shape helpers", () => {
expect(proportionalResizeScale(50, 100, 25, 80)).toBe(0.5);
});
it("interpolates actual top and bottom taper dimensions while excluding gears", () => {
const tapered = shape({
taperBottomWidth: 10,
taperBottomDepth: 5,
taperTopWidth: 30,
taperTopDepth: 40,
});
expect(shapeTaperDimensions(tapered)).toEqual({ topWidth: 30, topDepth: 40, bottomWidth: 10, bottomDepth: 5 });
expect(shapeOverallFootprintDimensions(tapered)).toEqual({ width: 30, depth: 40 });
expect(shapeHasTaper(tapered)).toBe(true);
expect(shapeTaperScaleAt(tapered, 0, "width")).toBe(0.5);
expect(shapeTaperScaleAt(tapered, 0.5, "width")).toBe(1);
expect(shapeTaperScaleAt(tapered, 1, "width")).toBe(1.5);
expect(shapeTaperScaleAt(tapered, 0, "depth")).toBe(0.25);
expect(shapeTaperScaleAt(tapered, 0.5, "depth")).toBe(1.125);
expect(shapeTaperScaleAt(tapered, 1, "depth")).toBe(2);
const legacy = shape({ taperBottomScale: 0.5, taperTopScale: 1.5 });
expect(shapeTaperDimensions(legacy)).toEqual({ topWidth: 30, topDepth: 30, bottomWidth: 10, bottomDepth: 10 });
const gear = shape({ kind: "gear", taperBottomWidth: 10, taperTopWidth: 30 });
expect(shapeHasTaper(gear)).toBe(false);
expect(shapeTaperScaleAt(gear, 0.5, "width")).toBe(1);
expect(shapeTaperScaleAt(gear, 0.5, "depth")).toBe(1);
});
it("canonicalizes mirror flags and nested group rotations", () => {
const canonical = canonicalizeShape(
shape({