Git Komut Rehberi & Terminal Asistanı
Sıfırdan Yeni Bir Depo Başlatın:
Mevcut Bir Git Deposu veya Klasörü Gönderin:
Hataları Geri Alma, İptal & Temizlik:
Son commit'i geri al (yapılan değişiklikleri korur):
git reset --soft HEAD~1
Yapılan yerel değişiklikleri iptal et (çalışma ağacını temizler):
git restore .
Takip edilmeyen gereksiz dosyaları sil:
git clean -fd
Değişiklikleri geçici sakla ve geri getir (stash):
git stash git stash pop
Dal (Branch) ve Sürüm Etiketleri:
Yeni dal aç ve geçiş yap:
git checkout -b yeni-ozellik git push -u origin yeni-ozellik
Sürüm etiketi (tag) oluştur ve gönder:
git tag -a v1.0.0 -m "Sürüm 1.0.0" git push origin --tags
Add workspace editor tools
This commit is contained in:
@@ -0,0 +1,29 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
checks:
|
||||
name: Typecheck and unit tests
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Typecheck
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Unit tests
|
||||
run: npm test
|
||||
@@ -15,7 +15,6 @@
|
||||
</table>
|
||||
|
||||
<p>
|
||||
<a href="https://sketchforge-3d.vercel.app"><img alt="Live demo" src="https://img.shields.io/badge/live%20demo-open-000000"></a>
|
||||
<a href="LICENSE"><img alt="MIT license" src="https://img.shields.io/badge/license-MIT-16a34a"></a>
|
||||
<a href="https://github.com/Formsmith746/SketchForge-3D/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/Formsmith746/SketchForge-3D?style=social"></a>
|
||||
<img alt="Local first" src="https://img.shields.io/badge/local--first-no%20account-0ea5e9">
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const isStaticExport = process.env.STATIC_EXPORT === "true";
|
||||
const extraAllowedDevOrigins = (process.env.SKETCHFORGE_ALLOWED_DEV_ORIGINS ?? "")
|
||||
.split(",")
|
||||
.map((origin) => origin.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
devIndicators: false,
|
||||
allowedDevOrigins: ["localhost", "127.0.0.1", "192.168.2.5"],
|
||||
allowedDevOrigins: ["localhost", "127.0.0.1", ...extraAllowedDevOrigins],
|
||||
env: {
|
||||
NEXT_PUBLIC_STATIC_EXPORT: isStaticExport ? "true" : "false",
|
||||
},
|
||||
images: {
|
||||
unoptimized: true
|
||||
},
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 110 B |
Binary file not shown.
|
Before Width: | Height: | Size: 110 B |
Binary file not shown.
|
Before Width: | Height: | Size: 109 B |
@@ -2,7 +2,12 @@ import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const localHosts = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
||||
export const revalidate = false;
|
||||
|
||||
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
|
||||
const PNG_DATA_URL_PREFIX = "data:image/png;base64,";
|
||||
const MAX_SCREENSHOT_BYTES = 25 * 1024 * 1024;
|
||||
const MAX_SCREENSHOT_REQUEST_BYTES = Math.ceil((MAX_SCREENSHOT_BYTES * 4) / 3) + PNG_DATA_URL_PREFIX.length + 2048;
|
||||
|
||||
function sanitizeFileName(value: unknown) {
|
||||
const fallback = `codex-screenshot-${Date.now()}.png`;
|
||||
@@ -13,22 +18,71 @@ function sanitizeFileName(value: unknown) {
|
||||
return cleaned.endsWith(".png") ? cleaned : `${cleaned || fallback}.png`;
|
||||
}
|
||||
|
||||
function isLocalSameOriginRequest(request: Request) {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (!LOCAL_HOSTS.has(requestUrl.hostname)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const origin = request.headers.get("origin");
|
||||
if (origin) {
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const fetchSite = request.headers.get("sec-fetch-site");
|
||||
return !fetchSite || fetchSite === "same-origin" || fetchSite === "none";
|
||||
}
|
||||
|
||||
function decodedBase64ByteLength(value: string) {
|
||||
if (value.length % 4 === 1 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {
|
||||
return null;
|
||||
}
|
||||
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((value.length * 3) / 4) - padding;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
if (process.env.NODE_ENV === "production") {
|
||||
return NextResponse.json({ error: "Codex screenshot capture is only available in local development." }, { status: 404 });
|
||||
}
|
||||
|
||||
const host = request.headers.get("host")?.split(":")[0] ?? "";
|
||||
if (!localHosts.has(host)) {
|
||||
if (!isLocalSameOriginRequest(request)) {
|
||||
return NextResponse.json({ error: "Codex screenshot capture only accepts local requests." }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = (await request.json()) as { dataUrl?: unknown; name?: unknown };
|
||||
if (typeof body.dataUrl !== "string" || !body.dataUrl.startsWith("data:image/png;base64,")) {
|
||||
const contentLength = Number(request.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_SCREENSHOT_REQUEST_BYTES) {
|
||||
return NextResponse.json({ error: "Screenshot image is too large." }, { status: 413 });
|
||||
}
|
||||
|
||||
let body: { dataUrl?: unknown; name?: unknown };
|
||||
try {
|
||||
body = (await request.json()) as { dataUrl?: unknown; name?: unknown };
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid screenshot request." }, { status: 400 });
|
||||
}
|
||||
|
||||
if (typeof body.dataUrl !== "string" || !body.dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
|
||||
return NextResponse.json({ error: "Expected a PNG data URL." }, { status: 400 });
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(body.dataUrl.slice("data:image/png;base64,".length), "base64");
|
||||
const encodedImage = body.dataUrl.slice(PNG_DATA_URL_PREFIX.length);
|
||||
const decodedBytes = decodedBase64ByteLength(encodedImage);
|
||||
if (decodedBytes === null) {
|
||||
return NextResponse.json({ error: "Expected a PNG data URL." }, { status: 400 });
|
||||
}
|
||||
if (decodedBytes > MAX_SCREENSHOT_BYTES) {
|
||||
return NextResponse.json({ error: "Screenshot image is too large." }, { status: 413 });
|
||||
}
|
||||
|
||||
const bytes = Buffer.from(encodedImage, "base64");
|
||||
const directory = path.join(process.cwd(), ".codex", "screenshots");
|
||||
await mkdir(directory, { recursive: true });
|
||||
|
||||
|
||||
@@ -2,26 +2,65 @@ import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export const revalidate = false;
|
||||
|
||||
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);
|
||||
const MAX_LOCAL_DOWNLOAD_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
function safeFileName(filename: string) {
|
||||
const base = path.basename(filename).replace(/[<>:"/\\|?*\u0000-\u001f]/g, "_").trim();
|
||||
return base || "download.txt";
|
||||
}
|
||||
|
||||
function isLocalSameOriginRequest(request: Request) {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (!LOCAL_HOSTS.has(requestUrl.hostname)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const origin = request.headers.get("origin");
|
||||
if (origin) {
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const fetchSite = request.headers.get("sec-fetch-site");
|
||||
return !fetchSite || fetchSite === "same-origin" || fetchSite === "none";
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
if (!isLocalSameOriginRequest(request)) {
|
||||
return NextResponse.json({ error: "Local folder downloads are only available from this localhost app" }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = (await request.json()) as { content?: unknown; filename?: unknown; folder?: unknown };
|
||||
if (typeof body.content !== "string" || typeof body.filename !== "string" || typeof body.folder !== "string") {
|
||||
return NextResponse.json({ error: "Invalid download request" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (Buffer.byteLength(body.content, "utf8") > MAX_LOCAL_DOWNLOAD_BYTES) {
|
||||
return NextResponse.json({ error: "File is too large for local folder download" }, { status: 413 });
|
||||
}
|
||||
|
||||
const trimmedFolder = body.folder.trim();
|
||||
if (!trimmedFolder) {
|
||||
return NextResponse.json({ error: "Choose a folder first" }, { status: 400 });
|
||||
}
|
||||
|
||||
const targetDirectory = path.isAbsolute(trimmedFolder) ? trimmedFolder : path.join(process.cwd(), trimmedFolder);
|
||||
const targetDirectory = path.resolve(path.isAbsolute(trimmedFolder) ? trimmedFolder : path.join(process.cwd(), trimmedFolder));
|
||||
await fs.mkdir(targetDirectory, { recursive: true });
|
||||
const targetPath = path.join(targetDirectory, safeFileName(body.filename));
|
||||
const targetPath = path.resolve(targetDirectory, safeFileName(body.filename));
|
||||
const relativeTarget = path.relative(targetDirectory, targetPath);
|
||||
if (relativeTarget.startsWith("..") || path.isAbsolute(relativeTarget)) {
|
||||
return NextResponse.json({ error: "Invalid file path" }, { status: 400 });
|
||||
}
|
||||
await fs.writeFile(targetPath, body.content, "utf8");
|
||||
|
||||
return NextResponse.json({ path: targetPath });
|
||||
|
||||
@@ -2,7 +2,13 @@ import { promises as fs } from "fs";
|
||||
import path from "path";
|
||||
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;
|
||||
|
||||
function safeProjectId(projectId: string) {
|
||||
const clean = projectId.replace(/[^a-zA-Z0-9_-]/g, "");
|
||||
@@ -17,7 +23,41 @@ 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;
|
||||
}
|
||||
|
||||
const origin = request.headers.get("origin");
|
||||
if (origin) {
|
||||
try {
|
||||
const originUrl = new URL(origin);
|
||||
if (originUrl.origin !== requestUrl.origin || !LOCAL_HOSTS.has(originUrl.hostname)) {
|
||||
return false;
|
||||
}
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const fetchSite = request.headers.get("sec-fetch-site");
|
||||
return !fetchSite || fetchSite === "same-origin" || fetchSite === "none";
|
||||
}
|
||||
|
||||
function decodedBase64ByteLength(value: string) {
|
||||
if (value.length % 4 === 1 || !/^[A-Za-z0-9+/]+={0,2}$/.test(value)) {
|
||||
return null;
|
||||
}
|
||||
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
||||
return Math.floor((value.length * 3) / 4) - padding;
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
if (!isLocalSameOriginRequest(request)) {
|
||||
return new NextResponse("Project thumbnails are only available from this localhost app", { status: 403 });
|
||||
}
|
||||
|
||||
const projectId = new URL(request.url).searchParams.get("projectId") ?? "";
|
||||
const filePath = thumbnailPath(projectId);
|
||||
if (!filePath) {
|
||||
@@ -38,6 +78,15 @@ 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 });
|
||||
}
|
||||
|
||||
const contentLength = Number(request.headers.get("content-length"));
|
||||
if (Number.isFinite(contentLength) && contentLength > MAX_THUMBNAIL_REQUEST_BYTES) {
|
||||
return NextResponse.json({ error: "Thumbnail image is too large" }, { status: 413 });
|
||||
}
|
||||
|
||||
let body: { dataUrl?: unknown; projectId?: unknown };
|
||||
try {
|
||||
body = (await request.json()) as { dataUrl?: unknown; projectId?: unknown };
|
||||
@@ -51,14 +100,22 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
const filePath = thumbnailPath(body.projectId);
|
||||
const match = body.dataUrl.match(/^data:image\/png;base64,(.+)$/);
|
||||
if (!filePath || !match) {
|
||||
if (!filePath || !body.dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
|
||||
return NextResponse.json({ error: "Invalid thumbnail image" }, { status: 400 });
|
||||
}
|
||||
|
||||
const encodedImage = body.dataUrl.slice(PNG_DATA_URL_PREFIX.length);
|
||||
const decodedBytes = decodedBase64ByteLength(encodedImage);
|
||||
if (decodedBytes === null) {
|
||||
return NextResponse.json({ error: "Invalid thumbnail image" }, { status: 400 });
|
||||
}
|
||||
if (decodedBytes > MAX_THUMBNAIL_BYTES) {
|
||||
return NextResponse.json({ error: "Thumbnail image is too large" }, { status: 413 });
|
||||
}
|
||||
|
||||
await fs.mkdir(THUMBNAIL_DIR, { recursive: true });
|
||||
await fs.rm(filePath, { force: true });
|
||||
await fs.writeFile(filePath, Buffer.from(match[1], "base64"));
|
||||
await fs.writeFile(filePath, Buffer.from(encodedImage, "base64"));
|
||||
|
||||
return NextResponse.json({ version: Date.now() });
|
||||
} catch (error) {
|
||||
@@ -67,6 +124,10 @@ 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 });
|
||||
}
|
||||
|
||||
const projectId = new URL(request.url).searchParams.get("projectId") ?? "";
|
||||
const filePath = thumbnailPath(projectId);
|
||||
if (!filePath) {
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
--nav-text: #31465d;
|
||||
--workplane: #9adcf0;
|
||||
--workplane-soft: rgba(154, 220, 240, 0.28);
|
||||
--star: #ffd543;
|
||||
--shadow: 0 2px 6px rgba(35, 55, 75, 0.12);
|
||||
--font-ui: "Avenir Next", Avenir, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
@@ -1367,40 +1366,6 @@ button {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.ai-build-body {
|
||||
width: 430px;
|
||||
}
|
||||
|
||||
.top-action-panel:has(.ai-build-body) {
|
||||
width: 456px;
|
||||
}
|
||||
|
||||
.ai-build-body label {
|
||||
display: grid;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.ai-build-body label span {
|
||||
color: #40586d;
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.ai-build-body textarea {
|
||||
min-height: 104px;
|
||||
resize: vertical;
|
||||
padding: 9px;
|
||||
color: #18364f;
|
||||
background: #f8fbfd;
|
||||
border: 1px solid #d6e2ea;
|
||||
border-radius: 3px;
|
||||
font: 12px/1.45 Consolas, "Courier New", monospace;
|
||||
}
|
||||
|
||||
.ai-build-body label:first-child textarea {
|
||||
min-height: 154px;
|
||||
}
|
||||
|
||||
.hidden-file-input {
|
||||
display: none;
|
||||
}
|
||||
@@ -3109,15 +3074,6 @@ button {
|
||||
text-shadow: 2px 2px 0 color-mix(in srgb, var(--shape-color), black 35%);
|
||||
}
|
||||
|
||||
.kind-star,
|
||||
.kind-heart {
|
||||
align-self: end;
|
||||
color: var(--shape-color);
|
||||
font-size: calc(var(--shape-size) * 0.78);
|
||||
line-height: 1;
|
||||
text-shadow: 2px 3px 0 color-mix(in srgb, var(--shape-color), black 26%);
|
||||
}
|
||||
|
||||
.selection-outline {
|
||||
position: absolute;
|
||||
inset: 1px;
|
||||
|
||||
+68
-15
@@ -3,6 +3,7 @@
|
||||
import { Clock3, FileUp, Grid3X3, HomeIcon, List, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { SketchForgeEditor, importedShapeFromStl } from "@/components/SketchForgeEditor";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
|
||||
import type { GridSize, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
@@ -44,6 +45,7 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes";
|
||||
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
|
||||
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
|
||||
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
|
||||
const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
|
||||
|
||||
function formatUpdated(timestamp: number) {
|
||||
const age = Date.now() - timestamp;
|
||||
@@ -91,7 +93,18 @@ async function saveProjectShapes(projectId: string, shapes: WorkplaneShape[], re
|
||||
const database = await openProjectShapesDb();
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const transaction = database.transaction(PROJECT_SHAPES_STORE_NAME, "readwrite");
|
||||
transaction.objectStore(PROJECT_SHAPES_STORE_NAME).put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord);
|
||||
const store = transaction.objectStore(PROJECT_SHAPES_STORE_NAME);
|
||||
const existingRequest = store.get(projectId);
|
||||
existingRequest.onerror = () => {
|
||||
transaction.abort();
|
||||
};
|
||||
existingRequest.onsuccess = () => {
|
||||
const existing = existingRequest.result as ProjectShapeRecord | undefined;
|
||||
if (existing && existing.revision > revision) {
|
||||
return;
|
||||
}
|
||||
store.put({ id: projectId, revision, shapes, updatedAt: Date.now() } satisfies ProjectShapeRecord);
|
||||
};
|
||||
transaction.oncomplete = () => {
|
||||
database.close();
|
||||
resolve();
|
||||
@@ -208,7 +221,7 @@ function mergeProjectsForStorage(projects: DashboardProject[]) {
|
||||
function newProject(name: string, index: number, shapeCount = 0): DashboardProject {
|
||||
const now = Date.now();
|
||||
return {
|
||||
id: crypto.randomUUID(),
|
||||
id: createLocalId("project"),
|
||||
name,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -240,6 +253,8 @@ export default function Home() {
|
||||
const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({});
|
||||
const projectsJsonRef = useRef("");
|
||||
const dashboardStlInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const nextProjectRevisionRef = useRef(0);
|
||||
const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({});
|
||||
|
||||
useEffect(() => {
|
||||
const { projects: storedProjects, legacyShapes } = readStoredProjects();
|
||||
@@ -252,7 +267,7 @@ export default function Home() {
|
||||
});
|
||||
});
|
||||
}
|
||||
setDownloadMode(window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY) === "folder" ? "folder" : "browser");
|
||||
setDownloadMode(!STATIC_EXPORT_BUILD && window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY) === "folder" ? "folder" : "browser");
|
||||
setDownloadFolder(window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY) ?? "");
|
||||
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
@@ -386,6 +401,17 @@ export default function Home() {
|
||||
|
||||
const updateProjectSnapshot = useCallback((snapshot: { image: string; projectId: string; shapes: number }) => {
|
||||
const version = Date.now();
|
||||
if (STATIC_EXPORT_BUILD) {
|
||||
setProjects((current) =>
|
||||
current.map((project) =>
|
||||
project.id === snapshot.projectId
|
||||
? { ...project, shapes: snapshot.shapes, thumbnailUrl: snapshot.image, thumbnailVersion: version, updatedAt: version }
|
||||
: project,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setProjects((current) =>
|
||||
current.map((project) => (project.id === snapshot.projectId ? { ...project, shapes: snapshot.shapes, updatedAt: version } : project)),
|
||||
);
|
||||
@@ -414,23 +440,42 @@ export default function Home() {
|
||||
}, []);
|
||||
|
||||
const updateProjectShapes = useCallback((snapshot: { projectId: string; shapes: WorkplaneShape[] }) => {
|
||||
const revision = Date.now();
|
||||
setProjectShapesById((current) => ({
|
||||
...current,
|
||||
[snapshot.projectId]: { revision, shapes: snapshot.shapes },
|
||||
}));
|
||||
void saveProjectShapes(snapshot.projectId, snapshot.shapes, revision)
|
||||
const revision = Math.max(Date.now(), nextProjectRevisionRef.current + 1);
|
||||
nextProjectRevisionRef.current = revision;
|
||||
setProjectShapesById((current) => {
|
||||
const existing = current[snapshot.projectId];
|
||||
if (existing && existing.revision > revision) {
|
||||
return current;
|
||||
}
|
||||
return {
|
||||
...current,
|
||||
[snapshot.projectId]: { revision, shapes: snapshot.shapes },
|
||||
};
|
||||
});
|
||||
|
||||
const previousSave = projectShapeSaveQueuesRef.current[snapshot.projectId] ?? Promise.resolve();
|
||||
const queuedSave = previousSave.catch(() => undefined).then(() => saveProjectShapes(snapshot.projectId, snapshot.shapes, revision));
|
||||
projectShapeSaveQueuesRef.current[snapshot.projectId] = queuedSave;
|
||||
|
||||
void queuedSave
|
||||
.then(() => {
|
||||
setProjects((current) =>
|
||||
current.map((project) =>
|
||||
project.id === snapshot.projectId
|
||||
project.id === snapshot.projectId && (project.revision ?? 0) <= revision
|
||||
? { ...project, shapes: snapshot.shapes.length, updatedAt: revision, revision }
|
||||
: project,
|
||||
),
|
||||
);
|
||||
})
|
||||
.catch((error) => {
|
||||
setDashboardNotice(error instanceof Error ? error.message : "Could not save project shapes");
|
||||
if (projectShapeSaveQueuesRef.current[snapshot.projectId] === queuedSave) {
|
||||
setDashboardNotice(error instanceof Error ? error.message : "Could not save project shapes");
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (projectShapeSaveQueuesRef.current[snapshot.projectId] === queuedSave) {
|
||||
delete projectShapeSaveQueuesRef.current[snapshot.projectId];
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
|
||||
@@ -521,7 +566,9 @@ export default function Home() {
|
||||
if (activeProjectId === projectId) {
|
||||
setActiveProjectId(null);
|
||||
}
|
||||
void fetch(`/api/project-thumbnail?projectId=${encodeURIComponent(projectId)}`, { method: "DELETE" });
|
||||
if (!STATIC_EXPORT_BUILD) {
|
||||
void fetch(`/api/project-thumbnail?projectId=${encodeURIComponent(projectId)}`, { method: "DELETE" });
|
||||
}
|
||||
void deleteProjectShapes(projectId).catch(() => {
|
||||
setDashboardNotice("Could not delete project shapes from local storage");
|
||||
});
|
||||
@@ -570,6 +617,7 @@ export default function Home() {
|
||||
projects={visibleProjects}
|
||||
query={query}
|
||||
settingsOpen={settingsOpen}
|
||||
staticExportBuild={STATIC_EXPORT_BUILD}
|
||||
sortMode={sortMode}
|
||||
viewMode={viewMode}
|
||||
onCloseSettings={() => setSettingsOpen(false)}
|
||||
@@ -612,6 +660,7 @@ function Dashboard({
|
||||
projects,
|
||||
query,
|
||||
settingsOpen,
|
||||
staticExportBuild,
|
||||
sortMode,
|
||||
viewMode,
|
||||
onCloseSettings,
|
||||
@@ -633,6 +682,7 @@ function Dashboard({
|
||||
projects: DashboardProject[];
|
||||
query: string;
|
||||
settingsOpen: boolean;
|
||||
staticExportBuild: boolean;
|
||||
sortMode: string;
|
||||
viewMode: ViewMode;
|
||||
onCloseSettings: () => void;
|
||||
@@ -805,15 +855,18 @@ function Dashboard({
|
||||
</header>
|
||||
<label className="dashboard-setting-row">
|
||||
<span>Save method</span>
|
||||
<select value={downloadMode} onChange={(event) => onDownloadModeChange(event.currentTarget.value === "folder" ? "folder" : "browser")}>
|
||||
<select
|
||||
value={downloadMode}
|
||||
onChange={(event) => onDownloadModeChange(!staticExportBuild && event.currentTarget.value === "folder" ? "folder" : "browser")}
|
||||
>
|
||||
<option value="browser">Browser downloads</option>
|
||||
<option value="folder">Save to folder</option>
|
||||
{!staticExportBuild ? <option value="folder">Save to folder</option> : null}
|
||||
</select>
|
||||
</label>
|
||||
<label className="dashboard-setting-row">
|
||||
<span>Folder path</span>
|
||||
<input
|
||||
disabled={downloadMode !== "folder"}
|
||||
disabled={staticExportBuild || downloadMode !== "folder"}
|
||||
value={downloadFolder}
|
||||
onChange={(event) => onDownloadFolderChange(event.currentTarget.value)}
|
||||
placeholder="C:\\Users\\spiro\\Downloads"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Code2, Download, Home, Menu, Settings, UserRoundPlus, X } from "lucide-react";
|
||||
import { Download, Home, Menu, Settings, UserRoundPlus, X } from "lucide-react";
|
||||
import type manifoldModule from "manifold-3d";
|
||||
import type { ManifoldToplevel } from "manifold-3d";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -8,7 +8,6 @@ import { ADDITION, Brush, Evaluator, HOLLOW_SUBTRACTION, SUBTRACTION, type CSGOp
|
||||
import * as THREE from "three";
|
||||
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry.js";
|
||||
import { FontLoader, type Font, type FontData } from "three/examples/jsm/loaders/FontLoader.js";
|
||||
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
|
||||
import { SVGLoader } from "three/examples/jsm/loaders/SVGLoader.js";
|
||||
import droidMonoFontJson from "three/examples/fonts/droid/droid_sans_mono_regular.typeface.json";
|
||||
import droidSansBoldFontJson from "three/examples/fonts/droid/droid_sans_bold.typeface.json";
|
||||
@@ -42,16 +41,33 @@ import {
|
||||
ToolbarVectorExportIcon,
|
||||
} from "./icons";
|
||||
import { WorkplaneViewport } from "./WorkplaneViewport";
|
||||
import {
|
||||
canonicalizeShape,
|
||||
cleanNearZero,
|
||||
cleanRotationDegrees,
|
||||
fallbackSolidColor,
|
||||
mirroredAxisCount,
|
||||
mirrorSign,
|
||||
normalizeDegrees,
|
||||
serializeShapesForSync,
|
||||
shapeDepth,
|
||||
shapeWidth,
|
||||
workplaneShapesEqual,
|
||||
} from "@/lib/workplaneShapes";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
|
||||
import { importedShapeFromStl } from "@/lib/stlImport";
|
||||
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
type TopPanel = "import" | "export" | "builder" | "tips" | "profile" | "settings" | null;
|
||||
export { importedShapeFromStl };
|
||||
|
||||
type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
|
||||
type ExportFormat = "stl" | "obj";
|
||||
type Vec3 = [number, number, number];
|
||||
type MeshData = { name: string; vertices: Vec3[]; faces: [number, number, number][] };
|
||||
type Cuboid = { minX: number; maxX: number; minY: number; maxY: number; minZ: number; maxZ: number };
|
||||
type ShapeUpdatePatch = Partial<WorkplaneShape> & { bakeTransform?: boolean };
|
||||
type ManifoldSolid = ReturnType<ManifoldToplevel["Manifold"]["cube"]>;
|
||||
type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
|
||||
type DownloadResult = { mode: "browser" } | { mode: "folder"; path: string };
|
||||
type GroupBuildResult = {
|
||||
group: WorkplaneShape | null;
|
||||
@@ -76,36 +92,13 @@ type BooleanAutomationResult = {
|
||||
groupId?: string;
|
||||
error?: string;
|
||||
};
|
||||
type AiCommandPayload = {
|
||||
shape?: Partial<WorkplaneShape>;
|
||||
shapes?: Partial<WorkplaneShape>[];
|
||||
id?: string;
|
||||
ids?: string[];
|
||||
patch?: Partial<WorkplaneShape>;
|
||||
replace?: boolean;
|
||||
count?: number;
|
||||
};
|
||||
|
||||
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
|
||||
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
|
||||
const SHARED_CLIPBOARD_STORAGE_KEY = "sketchForge.clipboard";
|
||||
type SketchForgeAiBridge = {
|
||||
getState: () => { shapes: WorkplaneShape[]; selectedIds: string[]; notice: string };
|
||||
setShapes: (nextShapes: Partial<WorkplaneShape>[], nextSelection?: string[] | string | null) => WorkplaneShape[];
|
||||
addShape: (shape: Partial<WorkplaneShape>) => WorkplaneShape;
|
||||
updateShape: (id: string, patch: Partial<WorkplaneShape>) => WorkplaneShape | null;
|
||||
deleteShape: (id: string) => boolean;
|
||||
select: (ids: string[] | string | null) => string[];
|
||||
clear: () => void;
|
||||
createHouse: (options?: { replace?: boolean }) => WorkplaneShape[];
|
||||
createPerfScene: (count?: number) => WorkplaneShape[];
|
||||
run: (command: string, payload?: AiCommandPayload) => unknown;
|
||||
};
|
||||
const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
sketchforgeAI?: SketchForgeAiBridge;
|
||||
sketchforgeBridge?: SketchForgeAiBridge;
|
||||
__sketchforgeBooleanTest?: BooleanAutomationResult;
|
||||
__sketchforgeBooleanTestImage?: string;
|
||||
}
|
||||
@@ -117,7 +110,6 @@ const CUTTER_RESIDUAL_INSET = CUTTER_PADDING * 0.4;
|
||||
const MIN_SHAPE_DIMENSION = 0.01;
|
||||
const IMPORTED_EXACT_BOOLEAN_TRIANGLE_LIMIT = 150000;
|
||||
const COPLANAR_BOOLEAN_RESCUE_DEGREES = 0.02;
|
||||
const stlLoader = new STLLoader();
|
||||
const svgLoader = new SVGLoader();
|
||||
const booleanFontLoader = new FontLoader();
|
||||
const booleanTextFonts: Record<string, Font> = {
|
||||
@@ -131,87 +123,6 @@ const booleanTextFonts: Record<string, Font> = {
|
||||
};
|
||||
let manifoldRuntimePromise: Promise<ManifoldToplevel> | null = null;
|
||||
|
||||
function normalizeDegrees(value: number) {
|
||||
return ((value % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
function cleanRotationDegrees(value: number, precision = 1) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
const normalized = normalizeDegrees(value);
|
||||
const rounded = Number(normalized.toFixed(precision));
|
||||
const zeroThreshold = precision <= 1 ? 0.5 : 0.05;
|
||||
if (rounded < zeroThreshold || rounded >= 360 - zeroThreshold || Object.is(rounded, -0)) {
|
||||
return 0;
|
||||
}
|
||||
return rounded;
|
||||
}
|
||||
|
||||
function cleanNearZero(value: number, epsilon = 0.005) {
|
||||
return Math.abs(value) < epsilon ? 0 : value;
|
||||
}
|
||||
|
||||
function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
|
||||
const next: WorkplaneShape = {
|
||||
...shape,
|
||||
rotation: cleanRotationDegrees(shape.rotation ?? 0),
|
||||
rotationX: cleanRotationDegrees(shape.rotationX ?? 0),
|
||||
rotationZ: cleanRotationDegrees(shape.rotationZ ?? 0),
|
||||
mirrorX: shape.mirrorX || undefined,
|
||||
mirrorY: shape.mirrorY || undefined,
|
||||
mirrorZ: shape.mirrorZ || undefined,
|
||||
};
|
||||
if (shape.groupedShapes) {
|
||||
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
|
||||
return (
|
||||
a.id === b.id &&
|
||||
a.name === b.name &&
|
||||
a.kind === b.kind &&
|
||||
a.color === b.color &&
|
||||
a.hole === b.hole &&
|
||||
a.x === b.x &&
|
||||
a.z === b.z &&
|
||||
a.elevation === b.elevation &&
|
||||
a.size === b.size &&
|
||||
a.width === b.width &&
|
||||
a.depth === b.depth &&
|
||||
a.height === b.height &&
|
||||
a.rotation === b.rotation &&
|
||||
a.rotationX === b.rotationX &&
|
||||
a.rotationZ === b.rotationZ &&
|
||||
a.mirrorX === b.mirrorX &&
|
||||
a.mirrorY === b.mirrorY &&
|
||||
a.mirrorZ === b.mirrorZ &&
|
||||
a.radius === b.radius &&
|
||||
a.steps === b.steps &&
|
||||
a.sides === b.sides &&
|
||||
a.bevel === b.bevel &&
|
||||
a.segments === b.segments &&
|
||||
a.topRadius === b.topRadius &&
|
||||
a.baseRadius === b.baseRadius &&
|
||||
a.text === b.text &&
|
||||
a.font === b.font &&
|
||||
a.importedMesh === b.importedMesh &&
|
||||
a.imagePlate === b.imagePlate &&
|
||||
a.groupedShapes === b.groupedShapes &&
|
||||
a.groupedBaseWidth === b.groupedBaseWidth &&
|
||||
a.groupedBaseDepth === b.groupedBaseDepth &&
|
||||
a.groupedBaseHeight === b.groupedBaseHeight &&
|
||||
a.locked === b.locked &&
|
||||
a.hidden === b.hidden
|
||||
);
|
||||
}
|
||||
|
||||
function serializeShapesForSync(shapes: WorkplaneShape[]) {
|
||||
return JSON.stringify(shapes.map(canonicalizeShape));
|
||||
}
|
||||
|
||||
function readSharedClipboard() {
|
||||
if (typeof window === "undefined") {
|
||||
return [];
|
||||
@@ -261,7 +172,7 @@ async function importBundledManifoldModule() {
|
||||
function getManifoldRuntime() {
|
||||
const assetBase = typeof window === "undefined" ? "/" : new URL(".", window.location.href).href;
|
||||
const isFileBuild = typeof window !== "undefined" && window.location.protocol === "file:";
|
||||
const manifoldScriptUrl = isFileBuild ? new URL("manifold.js", assetBase).href : "/manifold.js";
|
||||
const manifoldScriptUrl = new URL("manifold.js", assetBase).href;
|
||||
const runtimeModule = isFileBuild
|
||||
? importBundledManifoldModule().then((module) => module.default)
|
||||
: import(/* webpackIgnore: true */ manifoldScriptUrl).then((module) => (module as { default: typeof manifoldModule }).default);
|
||||
@@ -273,7 +184,7 @@ function getManifoldRuntime() {
|
||||
});
|
||||
}
|
||||
return module({
|
||||
locateFile: ((file: string) => (file.endsWith(".wasm") ? "/manifold.wasm" : file)) as () => string,
|
||||
locateFile: ((file: string) => (file.endsWith(".wasm") ? new URL("manifold.wasm", assetBase).href : new URL(file, assetBase).href)) as () => string,
|
||||
});
|
||||
})
|
||||
.then((runtime) => {
|
||||
@@ -282,98 +193,6 @@ function getManifoldRuntime() {
|
||||
});
|
||||
return manifoldRuntimePromise;
|
||||
}
|
||||
const toolbarShapeAssets: ToolbarShapeAsset[] = [
|
||||
{ id: "box", name: "Box", src: "assets/sketchforge/shape-icons-gray/box.png", menuIcon: "assets/sketchforge/shape-icons-gray/box.png", kind: "box", color: "#d41721" },
|
||||
{ id: "cylinder", name: "Cylinder", src: "assets/sketchforge/shape-icons-gray/cylinder.png", menuIcon: "assets/sketchforge/shape-icons-gray/cylinder.png", kind: "cylinder", color: "#d97813" },
|
||||
{ id: "sphere", name: "Sphere", src: "assets/sketchforge/shape-icons-gray/sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/sphere.png", kind: "sphere", color: "#0098c7" },
|
||||
{ id: "cone", name: "Cone", src: "assets/sketchforge/shape-icons-gray/cone.png", menuIcon: "assets/sketchforge/shape-icons-gray/cone.png", kind: "cone", color: "#6e2786" },
|
||||
{ id: "pyramid", name: "Pyramid", src: "assets/sketchforge/shape-icons-gray/pyramid.png", menuIcon: "assets/sketchforge/shape-icons-gray/pyramid.png", kind: "pyramid", color: "#f2cf10" },
|
||||
{ id: "wedge", name: "Wedge", src: "assets/sketchforge/shape-icons-gray/wedge.png", menuIcon: "assets/sketchforge/shape-icons-gray/wedge.png", kind: "wedge", color: "#33983d" },
|
||||
{ id: "text", name: "Text", src: "assets/sketchforge/shape-icons-gray/text.png", menuIcon: "assets/sketchforge/shape-icons-gray/text.png", kind: "text", color: "#cf101b" },
|
||||
{ id: "round-roof", name: "Round Roof", src: "assets/sketchforge/shape-icons-gray/round-roof.png", menuIcon: "assets/sketchforge/shape-icons-gray/round-roof.png", kind: "roundRoof", color: "#67c4ce" },
|
||||
{ id: "half-sphere", name: "Half Sphere", src: "assets/sketchforge/shape-icons-gray/half-sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/half-sphere.png", kind: "halfSphere", color: "#c9009a" },
|
||||
{ id: "torus", name: "Torus", src: "assets/sketchforge/shape-icons-gray/torus.png", menuIcon: "assets/sketchforge/shape-icons-gray/torus.png", kind: "torus", color: "#0098c7" },
|
||||
{ id: "tube", name: "Tube", src: "assets/sketchforge/shape-icons-gray/tube.png", menuIcon: "assets/sketchforge/shape-icons-gray/tube.png", kind: "tube", color: "#ce7013" },
|
||||
];
|
||||
|
||||
function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
|
||||
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
|
||||
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "star" || asset.kind === "heart" || asset.kind === "text";
|
||||
const size = roundProfile ? 22 : 20;
|
||||
const height = asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
|
||||
const width = asset.kind === "text" ? 86 : size;
|
||||
const depth = asset.kind === "text" ? 28 : size;
|
||||
|
||||
return {
|
||||
id: `${asset.id}-${crypto.randomUUID()}`,
|
||||
name: asset.name,
|
||||
kind: asset.kind,
|
||||
color: asset.color,
|
||||
hole: asset.hole,
|
||||
x: point?.x ?? 0,
|
||||
z: point?.z ?? 0,
|
||||
elevation: point?.elevation ?? 0,
|
||||
size,
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
rotation: 0,
|
||||
rotationX: 0,
|
||||
rotationZ: 0,
|
||||
radius: asset.kind === "box" ? 0 : undefined,
|
||||
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? 24 : asset.kind === "halfSphere" ? 32 : undefined,
|
||||
sides: asset.kind === "cylinder" || asset.kind === "cone" ? 96 : asset.kind === "roundRoof" ? 64 : asset.kind === "pyramid" ? 4 : undefined,
|
||||
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? 4 : undefined,
|
||||
segments: asset.kind === "cylinder" ? 1 : undefined,
|
||||
topRadius: asset.kind === "cone" ? 0 : undefined,
|
||||
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
|
||||
text: asset.kind === "text" ? "TEXT" : undefined,
|
||||
font: asset.kind === "text" ? "Multilanguage" : undefined,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
};
|
||||
}
|
||||
|
||||
function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
|
||||
const width = shape.width ?? shape.size ?? 20;
|
||||
const depth = shape.depth ?? shape.size ?? 20;
|
||||
const height = shape.height ?? 20;
|
||||
return canonicalizeShape({
|
||||
id: shape.id ?? `ai-shape-${crypto.randomUUID()}`,
|
||||
name: shape.name,
|
||||
kind: shape.kind,
|
||||
color: shape.color,
|
||||
hole: shape.hole,
|
||||
x: shape.x ?? 0,
|
||||
z: shape.z ?? 0,
|
||||
elevation: shape.elevation ?? 0,
|
||||
size: shape.size ?? Math.max(width, depth),
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
rotation: shape.rotation ?? 0,
|
||||
rotationX: shape.rotationX ?? 0,
|
||||
rotationZ: shape.rotationZ ?? 0,
|
||||
radius: shape.radius,
|
||||
steps: shape.steps,
|
||||
sides: shape.sides,
|
||||
bevel: shape.bevel,
|
||||
segments: shape.segments,
|
||||
topRadius: shape.topRadius,
|
||||
baseRadius: shape.baseRadius,
|
||||
text: shape.text,
|
||||
font: shape.font,
|
||||
importedMesh: shape.importedMesh,
|
||||
imagePlate: shape.imagePlate,
|
||||
groupedShapes: shape.groupedShapes,
|
||||
groupedBaseWidth: shape.groupedBaseWidth,
|
||||
groupedBaseDepth: shape.groupedBaseDepth,
|
||||
groupedBaseHeight: shape.groupedBaseHeight,
|
||||
locked: shape.locked ?? false,
|
||||
hidden: shape.hidden ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
function stlBoxTrianglePositions(width: number, depth: number, height: number) {
|
||||
const x = width / 2;
|
||||
const z = depth / 2;
|
||||
@@ -847,72 +666,6 @@ function makeBlockPerfScene(count = 500): WorkplaneShape[] {
|
||||
});
|
||||
}
|
||||
|
||||
const AI_BUILD_PROMPT = `Create a SketchForge 3D build as JSON only.
|
||||
Return this exact shape:
|
||||
{"shapes":[{"name":"Part name","kind":"box","color":"#d41721","x":0,"z":0,"elevation":0,"width":20,"depth":20,"height":20,"rotation":0}]}
|
||||
Allowed kind values: box, cylinder, sphere, cone, pyramid, roof, roundRoof, halfSphere, torus, tube, ring, wedge, polygon, icosahedron, star, heart, text.
|
||||
Use millimeters. Use x and z for the workplane position. Use elevation for height above the workplane. Return valid JSON with no markdown.`;
|
||||
|
||||
function extractJsonBuild(source: string): Partial<WorkplaneShape>[] {
|
||||
const trimmed = source.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error("Paste build code first");
|
||||
}
|
||||
|
||||
const candidates = [trimmed];
|
||||
const fenced = trimmed.match(/```(?:json|js|javascript)?\s*([\s\S]*?)```/i);
|
||||
if (fenced?.[1]) {
|
||||
candidates.unshift(fenced[1].trim());
|
||||
}
|
||||
|
||||
const buildCall = trimmed.match(/(?:build|createBuild|setShapes)\s*\(\s*(\[[\s\S]*\]|\{[\s\S]*\})\s*\)\s*;?/);
|
||||
if (buildCall?.[1]) {
|
||||
candidates.unshift(buildCall[1].trim());
|
||||
}
|
||||
|
||||
const firstObject = trimmed.match(/\{[\s\S]*\}/);
|
||||
if (firstObject?.[0]) {
|
||||
candidates.push(firstObject[0]);
|
||||
}
|
||||
|
||||
const firstArray = trimmed.match(/\[[\s\S]*\]/);
|
||||
if (firstArray?.[0]) {
|
||||
candidates.push(firstArray[0]);
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const parsed = JSON.parse(candidate) as unknown;
|
||||
if (Array.isArray(parsed)) {
|
||||
return parsed as Partial<WorkplaneShape>[];
|
||||
}
|
||||
if (parsed && typeof parsed === "object" && Array.isArray((parsed as { shapes?: unknown }).shapes)) {
|
||||
return (parsed as { shapes: Partial<WorkplaneShape>[] }).shapes;
|
||||
}
|
||||
} catch {
|
||||
// Try the next candidate.
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Could not read the build code. Use JSON with a shapes array.");
|
||||
}
|
||||
|
||||
function shapeWidth(shape: WorkplaneShape) {
|
||||
return shape.width ?? shape.size;
|
||||
}
|
||||
|
||||
function shapeDepth(shape: WorkplaneShape) {
|
||||
return shape.depth ?? shape.size;
|
||||
}
|
||||
|
||||
function fallbackSolidColor(shape: WorkplaneShape) {
|
||||
if (shape.kind === "cylinder") return "#d97813";
|
||||
if (shape.kind === "sphere") return "#0098c7";
|
||||
if (shape.kind === "cone") return "#6e2786";
|
||||
if (shape.kind === "pyramid") return "#f2cf10";
|
||||
return "#d41721";
|
||||
}
|
||||
|
||||
function withHoleMode(shape: WorkplaneShape, hole: boolean, parentColor?: string): WorkplaneShape {
|
||||
const color = hole ? "#b8c2cc" : (parentColor ?? fallbackSolidColor(shape));
|
||||
return {
|
||||
@@ -927,14 +680,6 @@ function sanitizeName(name: string) {
|
||||
return name.replace(/[^a-z0-9_-]+/gi, "_") || "shape";
|
||||
}
|
||||
|
||||
function mirrorSign(value?: boolean) {
|
||||
return value ? -1 : 1;
|
||||
}
|
||||
|
||||
function mirroredAxisCount(shape: WorkplaneShape) {
|
||||
return [shape.mirrorX, shape.mirrorY, shape.mirrorZ].filter(Boolean).length;
|
||||
}
|
||||
|
||||
function transformMesh(mesh: MeshData, shape: WorkplaneShape): MeshData {
|
||||
const centerY = shape.height / 2;
|
||||
const matrix = new THREE.Matrix4().makeRotationFromEuler(
|
||||
@@ -1516,75 +1261,6 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
|
||||
};
|
||||
}
|
||||
|
||||
export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): WorkplaneShape {
|
||||
const rawGeometry = stlLoader.parse(buffer);
|
||||
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry.clone();
|
||||
geometry.computeBoundingBox();
|
||||
|
||||
const box = geometry.boundingBox;
|
||||
if (!box) {
|
||||
throw new Error("STL has no readable geometry");
|
||||
}
|
||||
|
||||
const size = new THREE.Vector3();
|
||||
const center = new THREE.Vector3();
|
||||
box.getSize(size);
|
||||
box.getCenter(center);
|
||||
|
||||
const maxDimension = Math.max(size.x, size.y, size.z);
|
||||
if (!Number.isFinite(maxDimension) || maxDimension <= 0) {
|
||||
throw new Error("STL geometry is empty");
|
||||
}
|
||||
|
||||
const scale = 1;
|
||||
const position = geometry.getAttribute("position");
|
||||
const normal = geometry.getAttribute("normal");
|
||||
const positions: number[] = [];
|
||||
const normals: number[] = [];
|
||||
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
positions.push(
|
||||
(position.getX(i) - center.x) * scale,
|
||||
(position.getY(i) - box.min.y) * scale,
|
||||
(position.getZ(i) - center.z) * scale,
|
||||
);
|
||||
if (normal) {
|
||||
normals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
|
||||
}
|
||||
}
|
||||
|
||||
const width = Math.max(1, size.x * scale);
|
||||
const height = Math.max(1, size.y * scale);
|
||||
const depth = Math.max(1, size.z * scale);
|
||||
|
||||
return {
|
||||
id: `uploaded-mesh-${crypto.randomUUID()}`,
|
||||
name: fileName.replace(/\.[^.]+$/, "") || "Imported STL",
|
||||
kind: "mesh",
|
||||
color: "#0098c7",
|
||||
x: 10,
|
||||
z: -10,
|
||||
size: Math.max(width, depth),
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
rotation: 0,
|
||||
rotationX: 0,
|
||||
rotationZ: 0,
|
||||
importedMesh: {
|
||||
positions,
|
||||
normals: normals.length ? normals : undefined,
|
||||
baseWidth: width,
|
||||
baseDepth: depth,
|
||||
baseHeight: height,
|
||||
triangleCount: Math.floor(position.count / 3),
|
||||
sourceFormat: "stl",
|
||||
},
|
||||
locked: false,
|
||||
hidden: false,
|
||||
};
|
||||
}
|
||||
|
||||
function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
|
||||
const parsed = svgLoader.parse(source);
|
||||
const rawPositions: number[] = [];
|
||||
@@ -1638,7 +1314,7 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
|
||||
}
|
||||
|
||||
return {
|
||||
id: `uploaded-svg-${crypto.randomUUID()}`,
|
||||
id: createLocalId("uploaded-svg"),
|
||||
name: fileName.replace(/\.[^.]+$/, "") || "Imported SVG",
|
||||
kind: "mesh",
|
||||
color: "#0098c7",
|
||||
@@ -1759,7 +1435,7 @@ async function importedShapeFromImage(file: File): Promise<WorkplaneShape> {
|
||||
const imagePlate = await prepareImportedImage(file);
|
||||
const dimensions = imagePlateDimensions(imagePlate.pixelWidth, imagePlate.pixelHeight);
|
||||
return {
|
||||
id: `uploaded-image-${crypto.randomUUID()}`,
|
||||
id: createLocalId("uploaded-image"),
|
||||
name: file.name.replace(/\.[^.]+$/, "") || "Imported Image",
|
||||
kind: "box",
|
||||
color: "#f4f7f9",
|
||||
@@ -1844,7 +1520,7 @@ function triggerBrowserDownload(filename: string, content: string, type: string)
|
||||
async function downloadTextFile(filename: string, content: string, type: string): Promise<DownloadResult> {
|
||||
const mode = window.localStorage.getItem(DOWNLOAD_MODE_STORAGE_KEY);
|
||||
const folder = window.localStorage.getItem(DOWNLOAD_FOLDER_STORAGE_KEY)?.trim() ?? "";
|
||||
if (mode === "folder" && folder) {
|
||||
if (!STATIC_EXPORT_BUILD && mode === "folder" && folder) {
|
||||
const response = await fetch("/api/local-download", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -2930,7 +2606,7 @@ function booleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
|
||||
}
|
||||
|
||||
return {
|
||||
id: `grouped-boolean-${crypto.randomUUID()}`,
|
||||
id: createLocalId("grouped-boolean"),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -2989,7 +2665,7 @@ function resultGeometryToMeshShape(
|
||||
const firstSolid = solids[0];
|
||||
|
||||
return {
|
||||
id: `${idPrefix}-${crypto.randomUUID()}`,
|
||||
id: createLocalId(idPrefix),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -3069,7 +2745,7 @@ function coplanarRescueCutterShape(shape: WorkplaneShape): WorkplaneShape {
|
||||
function cloneAsGroupChild(shape: WorkplaneShape, centerX: number, centerZ: number, minY: number): WorkplaneShape {
|
||||
return {
|
||||
...shape,
|
||||
id: `${shape.id}-group-child-${crypto.randomUUID()}`,
|
||||
id: createLocalId(`${shape.id}-group-child`),
|
||||
x: shape.x - centerX,
|
||||
z: shape.z - centerZ,
|
||||
elevation: (shape.elevation ?? 0) - minY,
|
||||
@@ -3316,7 +2992,7 @@ function meshPositionsToGroupShape(selection: WorkplaneShape[], solids: Workplan
|
||||
|
||||
const firstSolid = solids[0];
|
||||
return {
|
||||
id: `${idPrefix}-${crypto.randomUUID()}`,
|
||||
id: createLocalId(idPrefix),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -3576,7 +3252,7 @@ function boxedBooleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | nu
|
||||
const firstSolid = solids[0];
|
||||
|
||||
return {
|
||||
id: `grouped-boolean-${crypto.randomUUID()}`,
|
||||
id: createLocalId("grouped-boolean"),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -3631,7 +3307,7 @@ function aabbBooleanMeshShape(selection: WorkplaneShape[]): WorkplaneShape | nul
|
||||
const firstSolid = solids[0];
|
||||
|
||||
return {
|
||||
id: `grouped-boolean-${crypto.randomUUID()}`,
|
||||
id: createLocalId("grouped-boolean"),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -3754,7 +3430,7 @@ function hollowClipMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null
|
||||
|
||||
const firstSolid = solids[0];
|
||||
return {
|
||||
id: `grouped-import-clip-${crypto.randomUUID()}`,
|
||||
id: createLocalId("grouped-import-clip"),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -3860,7 +3536,7 @@ function mergedMeshShape(selection: WorkplaneShape[]): WorkplaneShape | null {
|
||||
const holeOnly = groupable.every((shape) => shape.hole);
|
||||
|
||||
return {
|
||||
id: `grouped-mesh-${crypto.randomUUID()}`,
|
||||
id: createLocalId("grouped-mesh"),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: holeOnly ? "#b8c2cc" : firstSolid.color,
|
||||
@@ -3912,7 +3588,7 @@ function groupedShape(selection: WorkplaneShape[]): WorkplaneShape | null {
|
||||
const holeOnly = groupable.every((shape) => shape.hole);
|
||||
|
||||
return {
|
||||
id: `group-${crypto.randomUUID()}`,
|
||||
id: createLocalId("group"),
|
||||
name: "Group",
|
||||
kind: "mesh",
|
||||
color: firstSolid.color,
|
||||
@@ -4008,7 +3684,7 @@ function restoreGroupedChildren(group: WorkplaneShape): WorkplaneShape[] {
|
||||
const childRotation = rotationFromQuaternion(new THREE.Quaternion().setFromRotationMatrix(childRotationMatrix));
|
||||
const restored: WorkplaneShape = {
|
||||
...child,
|
||||
id: `${child.id}-ungroup-${crypto.randomUUID()}`,
|
||||
id: createLocalId(`${child.id}-ungroup`),
|
||||
x: worldCenter.x,
|
||||
z: worldCenter.z,
|
||||
elevation: worldCenter.y - height / 2,
|
||||
@@ -4187,6 +3863,11 @@ export function SketchForgeEditor({
|
||||
const lastProjectShapesEchoRef = useRef<string | null>(null);
|
||||
const lastProjectIdRef = useRef<string | null>(null);
|
||||
const projectSnapshotRunRef = useRef(0);
|
||||
const shapesRef = useRef(shapes);
|
||||
const historyIndexRef = useRef(historyIndex);
|
||||
const interactionHistoryStartRef = useRef("");
|
||||
const interactionHistoryChangedRef = useRef(false);
|
||||
const interactionHistoryTimerRef = useRef<number | null>(null);
|
||||
const [projectInteractionActive, setProjectInteractionActive] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -4219,6 +3900,14 @@ export function SketchForgeEditor({
|
||||
return () => window.removeEventListener("storage", onStorage);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
shapesRef.current = shapes;
|
||||
}, [shapes]);
|
||||
|
||||
useEffect(() => {
|
||||
historyIndexRef.current = historyIndex;
|
||||
}, [historyIndex]);
|
||||
|
||||
const selectedShapes = useMemo(() => shapes.filter((shape) => selectedIds.includes(shape.id)), [selectedIds, shapes]);
|
||||
const selectedShape = selectedShapes.at(-1) ?? null;
|
||||
const hasSelection = selectedShapes.length > 0;
|
||||
@@ -4324,6 +4013,38 @@ export function SketchForgeEditor({
|
||||
[onProjectShapesChange, projectId],
|
||||
);
|
||||
|
||||
const finalizeInteractionHistory = useCallback(() => {
|
||||
const startFingerprint = interactionHistoryStartRef.current;
|
||||
const hadChanges = interactionHistoryChangedRef.current;
|
||||
interactionHistoryStartRef.current = "";
|
||||
interactionHistoryChangedRef.current = false;
|
||||
if (!hadChanges) {
|
||||
return;
|
||||
}
|
||||
|
||||
const canonicalNext = shapesRef.current.map(canonicalizeShape);
|
||||
const nextFingerprint = projectShapesFingerprint(canonicalNext);
|
||||
if (!startFingerprint || startFingerprint === nextFingerprint) {
|
||||
return;
|
||||
}
|
||||
|
||||
setHistory((current) => {
|
||||
const historyIndex = Math.min(historyIndexRef.current, Math.max(0, current.length - 1));
|
||||
const trimmed = current.slice(0, historyIndex + 1);
|
||||
const latestHistory = trimmed.at(-1) ?? [];
|
||||
if (projectShapesFingerprint(latestHistory) === nextFingerprint) {
|
||||
historyIndexRef.current = Math.max(0, trimmed.length - 1);
|
||||
setHistoryIndex(historyIndexRef.current);
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const nextHistory = [...trimmed, canonicalNext];
|
||||
historyIndexRef.current = nextHistory.length - 1;
|
||||
setHistoryIndex(historyIndexRef.current);
|
||||
return nextHistory;
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (projectInteractionActive || !pendingProjectShapesRef.current) {
|
||||
return;
|
||||
@@ -4334,10 +4055,34 @@ export function SketchForgeEditor({
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [projectInteractionActive, syncProjectShapes]);
|
||||
|
||||
const updateProjectInteractionActive = useCallback((active: boolean) => {
|
||||
projectInteractionActiveRef.current = active;
|
||||
setProjectInteractionActive((current) => (current === active ? current : active));
|
||||
}, []);
|
||||
const updateProjectInteractionActive = useCallback(
|
||||
(active: boolean) => {
|
||||
if (active) {
|
||||
if (interactionHistoryTimerRef.current !== null) {
|
||||
window.clearTimeout(interactionHistoryTimerRef.current);
|
||||
interactionHistoryTimerRef.current = null;
|
||||
}
|
||||
if (!projectInteractionActiveRef.current) {
|
||||
interactionHistoryStartRef.current = projectShapesFingerprint(shapesRef.current);
|
||||
interactionHistoryChangedRef.current = false;
|
||||
}
|
||||
projectInteractionActiveRef.current = true;
|
||||
setProjectInteractionActive((current) => (current ? current : true));
|
||||
return;
|
||||
}
|
||||
|
||||
projectInteractionActiveRef.current = false;
|
||||
setProjectInteractionActive((current) => (current ? false : current));
|
||||
if (interactionHistoryTimerRef.current !== null) {
|
||||
window.clearTimeout(interactionHistoryTimerRef.current);
|
||||
}
|
||||
interactionHistoryTimerRef.current = window.setTimeout(() => {
|
||||
interactionHistoryTimerRef.current = null;
|
||||
finalizeInteractionHistory();
|
||||
}, 0);
|
||||
},
|
||||
[finalizeInteractionHistory],
|
||||
);
|
||||
|
||||
const updateProjectWorkspaceSettings = useCallback(
|
||||
(settings: { workspace: WorkplaneWorkspaceSettings; snap: GridSize }) => {
|
||||
@@ -4354,11 +4099,13 @@ export function SketchForgeEditor({
|
||||
const canonicalNext = next.map(canonicalizeShape);
|
||||
const requestedSelection = Array.isArray(nextSelection) ? nextSelection : nextSelection ? [nextSelection] : [];
|
||||
const validSelection = requestedSelection.filter((id, index) => requestedSelection.indexOf(id) === index && canonicalNext.some((shape) => shape.id === id));
|
||||
shapesRef.current = canonicalNext;
|
||||
setShapes(canonicalNext);
|
||||
setSelectedIds(validSelection);
|
||||
setHistory((current) => {
|
||||
const trimmed = current.slice(0, historyIndex + 1);
|
||||
setHistoryIndex(trimmed.length);
|
||||
historyIndexRef.current = trimmed.length;
|
||||
setHistoryIndex(historyIndexRef.current);
|
||||
return [...trimmed, canonicalNext];
|
||||
});
|
||||
if (message) {
|
||||
@@ -4423,6 +4170,9 @@ export function SketchForgeEditor({
|
||||
if (projectSyncTimerRef.current !== null) {
|
||||
window.clearTimeout(projectSyncTimerRef.current);
|
||||
}
|
||||
if (interactionHistoryTimerRef.current !== null) {
|
||||
window.clearTimeout(interactionHistoryTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -4434,28 +4184,49 @@ export function SketchForgeEditor({
|
||||
[commitShapes, placementElevation, shapes],
|
||||
);
|
||||
|
||||
const updateShape = useCallback((id: string, patch: ShapeUpdatePatch) => {
|
||||
const bakeTransform = Boolean(patch.bakeTransform);
|
||||
const cleanedPatch = cleanShapePatch(patch);
|
||||
setShapes((current) => {
|
||||
let changed = false;
|
||||
const next = current.map((shape) => {
|
||||
if (shape.id !== id) {
|
||||
return shape;
|
||||
}
|
||||
const updateShape = useCallback(
|
||||
(id: string, patch: ShapeUpdatePatch) => {
|
||||
const bakeTransform = Boolean(patch.bakeTransform);
|
||||
const cleanedPatch = cleanShapePatch(patch);
|
||||
const applyPatch = (current: WorkplaneShape[]) => {
|
||||
let changed = false;
|
||||
const next = current.map((shape) => {
|
||||
if (shape.id !== id) {
|
||||
return shape;
|
||||
}
|
||||
|
||||
const patched = { ...shape, ...cleanedPatch };
|
||||
const canonicalBase = canonicalizeShape("hole" in cleanedPatch ? withHoleMode(patched, Boolean(cleanedPatch.hole), cleanedPatch.color) : patched);
|
||||
const canonical = bakeTransform ? canonicalizeShape(bakeShapeTransformIntoMesh(canonicalBase)) : canonicalBase;
|
||||
if (workplaneShapesEqual(shape, canonical)) {
|
||||
return shape;
|
||||
}
|
||||
changed = true;
|
||||
return canonical;
|
||||
});
|
||||
return changed ? next : current;
|
||||
});
|
||||
}, []);
|
||||
const patched = { ...shape, ...cleanedPatch };
|
||||
const canonicalBase = canonicalizeShape("hole" in cleanedPatch ? withHoleMode(patched, Boolean(cleanedPatch.hole), cleanedPatch.color) : patched);
|
||||
const canonical = bakeTransform ? canonicalizeShape(bakeShapeTransformIntoMesh(canonicalBase)) : canonicalBase;
|
||||
if (workplaneShapesEqual(shape, canonical)) {
|
||||
return shape;
|
||||
}
|
||||
changed = true;
|
||||
return canonical;
|
||||
});
|
||||
return { changed, next };
|
||||
};
|
||||
|
||||
if (projectInteractionActiveRef.current) {
|
||||
setShapes((current) => {
|
||||
const { changed, next } = applyPatch(current);
|
||||
if (!changed) {
|
||||
return current;
|
||||
}
|
||||
interactionHistoryChangedRef.current = true;
|
||||
shapesRef.current = next;
|
||||
return next;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const { changed, next } = applyPatch(shapes);
|
||||
if (changed) {
|
||||
commitShapes(next, selectedIds);
|
||||
}
|
||||
},
|
||||
[commitShapes, selectedIds, shapes],
|
||||
);
|
||||
|
||||
const deleteSelected = useCallback(() => {
|
||||
if (!hasSelection) {
|
||||
@@ -4477,7 +4248,7 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const duplicates = selectedShapes.map((shape) => ({
|
||||
...shape,
|
||||
id: `${shape.id}-copy-${crypto.randomUUID()}`,
|
||||
id: createLocalId(`${shape.id}-copy`),
|
||||
x: Math.min(110, shape.x + 8),
|
||||
z: Math.min(110, shape.z + 8),
|
||||
}));
|
||||
@@ -4506,7 +4277,7 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const pasted = sourceClipboard.map((shape) => ({
|
||||
...shape,
|
||||
id: `${shape.id}-paste-${crypto.randomUUID()}`,
|
||||
id: createLocalId(`${shape.id}-paste`),
|
||||
x: Math.min(110, shape.x + 12),
|
||||
z: Math.min(110, shape.z + 12),
|
||||
}));
|
||||
@@ -5040,32 +4811,6 @@ export function SketchForgeEditor({
|
||||
[commitShapes],
|
||||
);
|
||||
|
||||
const buildFromCode = useCallback(
|
||||
(source: string) => {
|
||||
try {
|
||||
const parsedShapes = extractJsonBuild(source);
|
||||
const generated = parsedShapes.map((shape, index) =>
|
||||
sceneShape({
|
||||
name: shape.name ?? `AI part ${index + 1}`,
|
||||
kind: shape.kind ?? "box",
|
||||
color: shape.color ?? "#d41721",
|
||||
...shape,
|
||||
id: shape.id ?? `ai-build-${crypto.randomUUID()}`,
|
||||
}),
|
||||
);
|
||||
if (generated.length === 0) {
|
||||
setNotice("Build code had no shapes");
|
||||
return;
|
||||
}
|
||||
commitShapes([...shapes, ...generated], generated.map((shape) => shape.id), `Built ${generated.length} AI shape${generated.length === 1 ? "" : "s"}`);
|
||||
setTopPanel(null);
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : "Could not build from code");
|
||||
}
|
||||
},
|
||||
[commitShapes, shapes],
|
||||
);
|
||||
|
||||
const saveDesign = useCallback(() => {
|
||||
setNotice(`Saved design with ${shapes.length} shape${shapes.length === 1 ? "" : "s"}`);
|
||||
setMenuOpen(false);
|
||||
@@ -5079,7 +4824,7 @@ export function SketchForgeEditor({
|
||||
}
|
||||
const copies = shapes.map((shape) => ({
|
||||
...shape,
|
||||
id: `${shape.id}-copy-${crypto.randomUUID()}`,
|
||||
id: createLocalId(`${shape.id}-copy`),
|
||||
x: Math.min(110, shape.x + 12),
|
||||
z: Math.min(110, shape.z + 12),
|
||||
}));
|
||||
@@ -5129,101 +4874,6 @@ export function SketchForgeEditor({
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const normalizeShape = (shape: Partial<WorkplaneShape>) =>
|
||||
sceneShape({
|
||||
name: shape.name ?? "AI shape",
|
||||
kind: shape.kind ?? "box",
|
||||
color: shape.color ?? "#d41721",
|
||||
...shape,
|
||||
id: shape.id ?? `ai-${crypto.randomUUID()}`,
|
||||
});
|
||||
|
||||
const api: SketchForgeAiBridge = {
|
||||
getState: () => ({ shapes, selectedIds, notice }),
|
||||
setShapes: (nextShapes, nextSelection = null) => {
|
||||
const normalized = nextShapes.map(normalizeShape);
|
||||
commitShapes(normalized, nextSelection, `AI set ${normalized.length} shape${normalized.length === 1 ? "" : "s"}`);
|
||||
return normalized;
|
||||
},
|
||||
addShape: (shape) => {
|
||||
const nextShape = normalizeShape(shape);
|
||||
commitShapes([...shapes, nextShape], nextShape.id, `AI added ${nextShape.name}`);
|
||||
return nextShape;
|
||||
},
|
||||
updateShape: (id, patch) => {
|
||||
const exists = shapes.some((shape) => shape.id === id);
|
||||
if (!exists) {
|
||||
setNotice(`AI could not find ${id}`);
|
||||
return null;
|
||||
}
|
||||
const next = shapes.map((shape) => (shape.id === id ? normalizeShape({ ...shape, ...patch, id }) : shape));
|
||||
commitShapes(next, id, "AI updated shape");
|
||||
return next.find((shape) => shape.id === id) ?? null;
|
||||
},
|
||||
deleteShape: (id) => {
|
||||
const exists = shapes.some((shape) => shape.id === id);
|
||||
if (!exists) {
|
||||
setNotice(`AI could not find ${id}`);
|
||||
return false;
|
||||
}
|
||||
commitShapes(shapes.filter((shape) => shape.id !== id), selectedIds.filter((selectedId) => selectedId !== id), "AI deleted shape");
|
||||
return true;
|
||||
},
|
||||
select: (ids) => {
|
||||
const requested = Array.isArray(ids) ? ids : ids ? [ids] : [];
|
||||
const valid = requested.filter((id) => shapes.some((shape) => shape.id === id));
|
||||
setSelectedIds(valid);
|
||||
setNotice(valid.length ? `AI selected ${valid.length} shape${valid.length === 1 ? "" : "s"}` : "AI cleared selection");
|
||||
return valid;
|
||||
},
|
||||
clear: clearDesign,
|
||||
createHouse: (options) => createHouseScene(options?.replace ?? true),
|
||||
createPerfScene: (count) => createPerfScene(count),
|
||||
run: (command, payload = {}) => {
|
||||
if (command === "createHouse") return api.createHouse({ replace: payload.replace });
|
||||
if (command === "createPerfScene" || command === "perfScene") return api.createPerfScene(payload.count);
|
||||
if (command === "clear") return api.clear();
|
||||
if (command === "addShape" && payload.shape) return api.addShape(payload.shape);
|
||||
if (command === "setShapes" && payload.shapes) return api.setShapes(payload.shapes, payload.ids ?? null);
|
||||
if (command === "updateShape" && payload.id && payload.patch) return api.updateShape(payload.id, payload.patch);
|
||||
if (command === "deleteShape" && payload.id) return api.deleteShape(payload.id);
|
||||
if (command === "select") return api.select(payload.ids ?? payload.id ?? null);
|
||||
throw new Error(`Unknown AI command: ${command}`);
|
||||
},
|
||||
};
|
||||
|
||||
const handleCommand = (event: Event) => {
|
||||
const detail = (event as CustomEvent<{ command?: string; payload?: AiCommandPayload }>).detail;
|
||||
if (!detail?.command) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = api.run(detail.command, detail.payload);
|
||||
window.dispatchEvent(new CustomEvent("sketchforge:ai-result", { detail: { command: detail.command, ok: true, result } }));
|
||||
} catch (error) {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("sketchforge:ai-result", {
|
||||
detail: { command: detail.command, ok: false, error: error instanceof Error ? error.message : "AI command failed" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
window.sketchforgeAI = api;
|
||||
window.sketchforgeBridge = api;
|
||||
window.addEventListener("sketchforge:ai-command", handleCommand);
|
||||
return () => {
|
||||
window.removeEventListener("sketchforge:ai-command", handleCommand);
|
||||
if (window.sketchforgeAI === api) {
|
||||
delete window.sketchforgeAI;
|
||||
}
|
||||
if (window.sketchforgeBridge === api) {
|
||||
delete window.sketchforgeBridge;
|
||||
}
|
||||
};
|
||||
}, [clearDesign, commitShapes, createHouseScene, createPerfScene, notice, selectedIds, shapes]);
|
||||
|
||||
const nudgeSelected = useCallback(
|
||||
(deltaX: number, deltaZ: number) => {
|
||||
if (!hasSelection) {
|
||||
@@ -5492,7 +5142,6 @@ export function SketchForgeEditor({
|
||||
onExport={exportDesign}
|
||||
onImportFiles={selectFiles}
|
||||
onPickFile={() => fileInputRef.current?.click()}
|
||||
onBuildFromCode={buildFromCode}
|
||||
onNotice={setNotice}
|
||||
/>
|
||||
) : null}
|
||||
@@ -5824,7 +5473,6 @@ function TopActionPanel({
|
||||
panel,
|
||||
shapeCount,
|
||||
scopeLabel,
|
||||
onBuildFromCode,
|
||||
onClose,
|
||||
onExport,
|
||||
onImportFiles,
|
||||
@@ -5834,14 +5482,12 @@ function TopActionPanel({
|
||||
panel: Exclude<TopPanel, null>;
|
||||
shapeCount: number;
|
||||
scopeLabel: "selected" | "total";
|
||||
onBuildFromCode: (source: string) => void;
|
||||
onClose: () => void;
|
||||
onExport: (format: ExportFormat) => void;
|
||||
onImportFiles: (files: FileList | File[]) => void;
|
||||
onPickFile: () => void;
|
||||
onNotice: (message: string) => void;
|
||||
}) {
|
||||
const [buildCode, setBuildCode] = useState("");
|
||||
const title =
|
||||
panel === "profile"
|
||||
? "Profile"
|
||||
@@ -5851,9 +5497,7 @@ function TopActionPanel({
|
||||
? "Tips"
|
||||
: panel === "export"
|
||||
? "Export"
|
||||
: panel === "builder"
|
||||
? "AI Build"
|
||||
: "Import";
|
||||
: "Import";
|
||||
|
||||
return (
|
||||
<div className="top-action-panel" role="dialog" aria-label={title}>
|
||||
@@ -5898,22 +5542,6 @@ function TopActionPanel({
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{panel === "builder" ? (
|
||||
<div className="top-action-body ai-build-body">
|
||||
<label>
|
||||
<span>Prompt for AI</span>
|
||||
<textarea readOnly value={AI_BUILD_PROMPT} />
|
||||
</label>
|
||||
<label>
|
||||
<span>Paste AI code</span>
|
||||
<textarea value={buildCode} onChange={(event) => setBuildCode(event.currentTarget.value)} placeholder='{"shapes":[{"name":"Box","kind":"box","color":"#d41721","width":20,"depth":20,"height":20}]}' />
|
||||
</label>
|
||||
<button onClick={() => onBuildFromCode(buildCode)}>
|
||||
<Code2 size={18} />
|
||||
Build
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{panel === "tips" ? (
|
||||
<div className="top-action-body">
|
||||
<p>Click a shape to select it. Use the inspector for dimensions, rotation, solid/hole, color, duplicate, and delete.</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Box, Check, ChevronDown, ChevronUp, Expand, Home, LockKeyhole, LockKeyholeOpen, Minus, Plus, X } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react";
|
||||
import { Box, Check, Expand, Home, Minus, Plus } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type Dispatch, type DragEvent, type MutableRefObject, type PointerEvent as ReactPointerEvent, type SetStateAction } from "react";
|
||||
import * as THREE from "three";
|
||||
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
|
||||
import { RoundedBoxGeometry } from "three/examples/jsm/geometries/RoundedBoxGeometry.js";
|
||||
@@ -13,9 +13,11 @@ import droidSerifBoldFontJson from "three/examples/fonts/droid/droid_serif_bold.
|
||||
import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.json";
|
||||
import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json";
|
||||
import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json";
|
||||
import { ToolbarHideSelectedIcon } from "@/components/icons";
|
||||
import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays";
|
||||
import { ShapeInspector, SnapGridControl } from "@/components/workplane/ShapeInspector";
|
||||
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
|
||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
|
||||
import { cleanNearZero, cleanRotationDegrees, fallbackSolidColor, mirroredAxisCount, mirrorSign, proportionalResizeScale, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
|
||||
import {
|
||||
TransformOverlay,
|
||||
getElevationMeasureKey,
|
||||
@@ -33,23 +35,11 @@ import {
|
||||
} from "@/components/workplane/TransformOverlay";
|
||||
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
const gridSizes: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||
const WORKPLANE_WIDTH = 200;
|
||||
const WORKPLANE_DEPTH = 140;
|
||||
const MIN_WORKSPACE_SIZE = 60;
|
||||
const MAX_WORKSPACE_SIZE = 2000;
|
||||
const MIN_GRID_BLOCK_SIZE = 1;
|
||||
const MAX_GRID_BLOCK_SIZE = 200;
|
||||
const DEFAULT_WORKSPACE = DEFAULT_WORKPLANE_WORKSPACE;
|
||||
const workspaceSizePresets = [
|
||||
{ label: "200 x 200 mm", width: 200, depth: 200 },
|
||||
{ label: "300 x 300 mm", width: 300, depth: 300 },
|
||||
{ label: "500 x 500 mm", width: 500, depth: 500 },
|
||||
{ label: "1000 x 1000 mm", width: 1000, depth: 1000 },
|
||||
{ label: "2000 x 2000 mm", width: 2000, depth: 2000 },
|
||||
{ label: "Custom", width: 200, depth: 200 },
|
||||
];
|
||||
const gridBlockPresets = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
|
||||
const CAMERA_HOME = new THREE.Vector3(118, 96, 118);
|
||||
const CAMERA_TARGET = new THREE.Vector3(0, 0, 0);
|
||||
const MIN_SHAPE_SIZE = 0.01;
|
||||
@@ -57,37 +47,26 @@ const MIN_ELEVATION = -180;
|
||||
const MAX_ELEVATION = 220;
|
||||
const CAMERA_MIN_TARGET_Y = -70;
|
||||
const CAMERA_MAX_TARGET_Y = 120;
|
||||
const solidColors = [
|
||||
"#d41721",
|
||||
"#ff4b4b",
|
||||
"#ff7a1a",
|
||||
"#d97813",
|
||||
"#f6a21a",
|
||||
"#f2cf10",
|
||||
"#f7e65a",
|
||||
"#a8d642",
|
||||
"#33983d",
|
||||
"#1fb66d",
|
||||
"#18b99a",
|
||||
"#0098c7",
|
||||
"#49c7ef",
|
||||
"#3b82f6",
|
||||
"#294c93",
|
||||
"#5b5ce2",
|
||||
"#6e2786",
|
||||
"#9b3bd2",
|
||||
"#c9009a",
|
||||
"#f062b6",
|
||||
"#8a5a2b",
|
||||
"#b98254",
|
||||
"#f2caa0",
|
||||
"#ffffff",
|
||||
"#cfd8df",
|
||||
"#8a98a6",
|
||||
"#4b5563",
|
||||
"#111111",
|
||||
];
|
||||
const textFontOptions = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
|
||||
const SHAPE_KINDS = new Set<ShapeAsset["kind"]>([
|
||||
"box",
|
||||
"cylinder",
|
||||
"sphere",
|
||||
"sketch",
|
||||
"scribble",
|
||||
"cone",
|
||||
"pyramid",
|
||||
"roof",
|
||||
"text",
|
||||
"roundRoof",
|
||||
"halfSphere",
|
||||
"torus",
|
||||
"tube",
|
||||
"ring",
|
||||
"wedge",
|
||||
"polygon",
|
||||
"icosahedron",
|
||||
"mesh",
|
||||
]);
|
||||
const fontLoader = new FontLoader();
|
||||
const textFonts: Record<string, Font> = {
|
||||
Multilanguage: fontLoader.parse(helvetikerBoldFontJson as FontData),
|
||||
@@ -105,6 +84,36 @@ const importedGeometryCache = new WeakMap<
|
||||
const imageTextureLoader = new THREE.TextureLoader();
|
||||
const IMPORTED_SELECTED_EDGE_TRIANGLE_LIMIT = 40000;
|
||||
|
||||
function parseDroppedShapeAsset(raw: string): ShapeAsset | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(raw);
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const asset = value as Partial<ShapeAsset>;
|
||||
if (
|
||||
typeof asset.id !== "string" ||
|
||||
typeof asset.name !== "string" ||
|
||||
typeof asset.src !== "string" ||
|
||||
typeof asset.color !== "string" ||
|
||||
!SHAPE_KINDS.has(asset.kind as ShapeAsset["kind"]) ||
|
||||
(asset.hole !== undefined && typeof asset.hole !== "boolean")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
src: asset.src,
|
||||
kind: asset.kind as ShapeAsset["kind"],
|
||||
color: asset.color,
|
||||
hole: asset.hole,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type WorkplaneViewportProps = {
|
||||
shapes: WorkplaneShape[];
|
||||
selectedIds: string[];
|
||||
@@ -313,13 +322,6 @@ function snapPositionValue(value: number, step: number, min: number, max: number
|
||||
return clamp(step > 0 ? snapValue(value, step) : value, min, max);
|
||||
}
|
||||
|
||||
function gridBlockSizeForPreset(preset: string, fallback: number) {
|
||||
if (preset === "Custom") {
|
||||
return clamp(fallback, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
|
||||
}
|
||||
return clamp(Number.parseFloat(preset) || DEFAULT_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
|
||||
}
|
||||
|
||||
function projectedScreenY(state: ThreeState, shape: WorkplaneShape, y: number) {
|
||||
return projectedScreenYAt(state, shape.x, shape.z, y);
|
||||
}
|
||||
@@ -347,19 +349,6 @@ function screenAngle(clientX: number, clientY: number, center: { x: number; y: n
|
||||
return Math.atan2(clientY - center.y, clientX - center.x);
|
||||
}
|
||||
|
||||
function normalizeDegrees(value: number) {
|
||||
return ((value % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
function cleanRotationDegrees(value: number) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
const normalized = normalizeDegrees(value);
|
||||
const rounded = Number(normalized.toFixed(1));
|
||||
return rounded < 0.5 || rounded >= 359.5 || Object.is(rounded, -0) ? 0 : rounded;
|
||||
}
|
||||
|
||||
function unwrapRadians(value: number) {
|
||||
if (value > Math.PI) {
|
||||
return value - Math.PI * 2;
|
||||
@@ -551,10 +540,6 @@ function selectionFrameCorners(frame: SelectionFrame) {
|
||||
return corners;
|
||||
}
|
||||
|
||||
function cleanNearZero(value: number, epsilon = 0.005) {
|
||||
return Math.abs(value) < epsilon ? 0 : value;
|
||||
}
|
||||
|
||||
function selectionWorldYBounds(frame: SelectionFrame) {
|
||||
const corners = selectionFrameCorners(frame);
|
||||
const min = cleanNearZero(Math.min(...corners.map((corner) => corner.y)));
|
||||
@@ -594,10 +579,6 @@ function resizeCenterFromAnchor(frame: SelectionFrame, anchor: THREE.Vector3, si
|
||||
.add(frame.zAxis.clone().multiplyScalar(signs.z ? (signs.z * depth) / 2 : 0));
|
||||
}
|
||||
|
||||
function resizedShapeSize(width: number, depth: number) {
|
||||
return Math.max(width, depth);
|
||||
}
|
||||
|
||||
function resizedShapePatchFromFrame(shape: WorkplaneShape, center: THREE.Vector3, width: number, depth: number): Partial<WorkplaneShape> {
|
||||
const patch: Partial<WorkplaneShape> = {
|
||||
x: cleanNearZero(center.x, 0.0005),
|
||||
@@ -779,9 +760,10 @@ function resizeShapeFromFrameHandle(
|
||||
let nextDepth = axisResize(depth, localDelta.z, signs.z);
|
||||
|
||||
if (shiftKey && signs.x && signs.z) {
|
||||
const uniform = Math.max(nextWidth, nextDepth);
|
||||
nextWidth = uniform;
|
||||
nextDepth = uniform;
|
||||
const scale = proportionalResizeScale(width, depth, nextWidth, nextDepth);
|
||||
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(width, depth)), maxSize / Math.max(width, depth));
|
||||
nextWidth = snapDimension(width * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
|
||||
nextDepth = snapDimension(depth * limitedScale, step, MIN_SHAPE_SIZE, maxSize);
|
||||
}
|
||||
|
||||
const nextCenter = altKey
|
||||
@@ -821,14 +803,17 @@ function resizeSelectionFromHandle(
|
||||
let nextX = axisResize(frame.width, localDelta.x, signs.x);
|
||||
let nextZ = axisResize(frame.depth, localDelta.z, signs.z);
|
||||
if (shiftKey && signs.x && signs.z) {
|
||||
const uniform = Math.max(nextX.size, nextZ.size);
|
||||
const scale = proportionalResizeScale(frame.width, frame.depth, nextX.size, nextZ.size);
|
||||
const limitedScale = clamp(scale, MIN_SHAPE_SIZE / Math.max(MIN_SHAPE_SIZE, Math.min(frame.width, frame.depth)), 260 / Math.max(frame.width, frame.depth));
|
||||
const width = snapDimension(frame.width * limitedScale, step, MIN_SHAPE_SIZE, 260);
|
||||
const depth = snapDimension(frame.depth * limitedScale, step, MIN_SHAPE_SIZE, 260);
|
||||
nextX = {
|
||||
size: uniform,
|
||||
scale: uniform / Math.max(MIN_SHAPE_SIZE, frame.width),
|
||||
size: width,
|
||||
scale: width / Math.max(MIN_SHAPE_SIZE, frame.width),
|
||||
};
|
||||
nextZ = {
|
||||
size: uniform,
|
||||
scale: uniform / Math.max(MIN_SHAPE_SIZE, frame.depth),
|
||||
size: depth,
|
||||
scale: depth / Math.max(MIN_SHAPE_SIZE, frame.depth),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2114,7 +2099,10 @@ export function WorkplaneViewport({
|
||||
return;
|
||||
}
|
||||
|
||||
const asset = JSON.parse(raw) as ShapeAsset;
|
||||
const asset = parseDroppedShapeAsset(raw);
|
||||
if (!asset) {
|
||||
return;
|
||||
}
|
||||
const point = toPlanePoint(event.clientX, event.clientY);
|
||||
onAddShape(asset, point ? { ...point, elevation: placementElevationRef.current } : { x: 0, z: 0, elevation: placementElevationRef.current });
|
||||
},
|
||||
@@ -2285,647 +2273,6 @@ export function WorkplaneViewport({
|
||||
);
|
||||
}
|
||||
|
||||
function ShapeInspector({
|
||||
shape,
|
||||
snap,
|
||||
snapOpen,
|
||||
onUpdate,
|
||||
onClose,
|
||||
onSnapChange,
|
||||
onSnapOpenChange,
|
||||
}: {
|
||||
shape: WorkplaneShape;
|
||||
snap: GridSize;
|
||||
snapOpen: boolean;
|
||||
onUpdate: (patch: Partial<WorkplaneShape>) => void;
|
||||
onClose: () => void;
|
||||
onSnapChange: Dispatch<SetStateAction<GridSize>>;
|
||||
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
|
||||
}) {
|
||||
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
|
||||
const locked = Boolean(shape.locked);
|
||||
const properties = getShapeProperties(shape, onUpdate);
|
||||
const [propertiesOpen, setPropertiesOpen] = useState(true);
|
||||
const [colorOpen, setColorOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="shape-inspector-header">
|
||||
<button className="inspector-header-icon" aria-label="Close shape settings" onClick={onClose}>
|
||||
<ChevronUp size={26} strokeWidth={2.8} />
|
||||
</button>
|
||||
<strong>{shape.name}</strong>
|
||||
<div className="inspector-header-actions">
|
||||
<button className={locked ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={locked ? "Unlock shape" : "Lock shape"} onClick={() => onUpdate({ locked: !locked })}>
|
||||
{locked ? <LockKeyhole size={31} strokeWidth={2.4} /> : <LockKeyholeOpen size={31} strokeWidth={2.4} />}
|
||||
</button>
|
||||
<button className={shape.hidden ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={shape.hidden ? "Show shape" : "Hide shape"} onClick={() => onUpdate({ hidden: !shape.hidden })}>
|
||||
<ToolbarHideSelectedIcon />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="shape-state-card" role="group" aria-label="Shape mode">
|
||||
<button
|
||||
className={!shape.hole ? "active solid-choice" : "solid-choice"}
|
||||
onClick={() => {
|
||||
const wasHole = Boolean(shape.hole);
|
||||
onUpdate({ hole: false, color: solidColor });
|
||||
setColorOpen((open) => (wasHole ? false : !open));
|
||||
}}
|
||||
disabled={locked}
|
||||
aria-pressed={!shape.hole}
|
||||
aria-expanded={colorOpen}
|
||||
>
|
||||
<span className="large-solid-swatch" style={{ "--swatch": solidColor } as CSSProperties} />
|
||||
<span>Solid</span>
|
||||
</button>
|
||||
<button
|
||||
className={shape.hole ? "active hole-choice" : "hole-choice"}
|
||||
onClick={() => {
|
||||
onUpdate({ hole: true, color: "#b8c2cc" });
|
||||
setColorOpen(false);
|
||||
}}
|
||||
disabled={locked}
|
||||
aria-pressed={shape.hole}
|
||||
>
|
||||
<span className="large-hole-swatch" />
|
||||
<span>Hole</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{colorOpen ? (
|
||||
<div className="color-card" aria-label="Shape color">
|
||||
<div className="color-card-header">
|
||||
<span>Color</span>
|
||||
<span className="color-value">{solidColor.toUpperCase()}</span>
|
||||
</div>
|
||||
<div className="color-grid">
|
||||
{solidColors.map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
className={solidColor.toLowerCase() === color.toLowerCase() && !shape.hole ? "selected" : ""}
|
||||
type="button"
|
||||
style={{ "--shape-swatch": color } as CSSProperties}
|
||||
title={color.toUpperCase()}
|
||||
aria-label={`Set color ${color}`}
|
||||
disabled={locked}
|
||||
onClick={() => {
|
||||
onUpdate({ color, hole: false });
|
||||
setColorOpen(false);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<label className={locked ? "custom-color disabled" : "custom-color"} title="Custom color">
|
||||
<input
|
||||
type="color"
|
||||
value={solidColor}
|
||||
disabled={locked}
|
||||
onChange={(event) => {
|
||||
onUpdate({ color: event.target.value, hole: false });
|
||||
setColorOpen(false);
|
||||
}}
|
||||
/>
|
||||
<span>Custom</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="property-card">
|
||||
<button
|
||||
className="property-card-header"
|
||||
type="button"
|
||||
aria-expanded={propertiesOpen}
|
||||
aria-controls={`properties-${shape.id}`}
|
||||
onClick={() => setPropertiesOpen((open) => !open)}
|
||||
>
|
||||
<span>Properties</span>
|
||||
<ChevronUp className={propertiesOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
|
||||
</button>
|
||||
{propertiesOpen ? (
|
||||
<div className="property-list" id={`properties-${shape.id}`}>
|
||||
{properties.map((property) => {
|
||||
if (property.type === "text") {
|
||||
return <TextProperty key={property.label} {...property} disabled={locked} />;
|
||||
}
|
||||
if (property.type === "select") {
|
||||
return <SelectProperty key={property.label} {...property} disabled={locked} />;
|
||||
}
|
||||
return <RangeProperty key={property.label} {...property} disabled={locked} />;
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="inspector-snap-dock">
|
||||
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
function SnapGridControl({
|
||||
snap,
|
||||
snapOpen,
|
||||
onSnapChange,
|
||||
onSnapOpenChange,
|
||||
}: {
|
||||
snap: GridSize;
|
||||
snapOpen: boolean;
|
||||
onSnapChange: Dispatch<SetStateAction<GridSize>>;
|
||||
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
|
||||
}) {
|
||||
return (
|
||||
<div className="snap-row">
|
||||
<span>Snap Grid</span>
|
||||
<button className="snap-select" onClick={() => onSnapOpenChange((value) => !value)}>
|
||||
{snap}
|
||||
<ChevronDown size={12} fill="currentColor" />
|
||||
</button>
|
||||
{snapOpen ? (
|
||||
<div className="snap-menu">
|
||||
{gridSizes.map((size) => (
|
||||
<button
|
||||
key={size}
|
||||
className={size === snap ? "selected" : ""}
|
||||
onClick={() => {
|
||||
onSnapChange(size);
|
||||
onSnapOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{size}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type RangePropertyConfig = {
|
||||
type?: "range";
|
||||
label: string;
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
step?: number;
|
||||
onChange: (value: number) => void;
|
||||
};
|
||||
|
||||
type TextPropertyConfig = {
|
||||
type: "text";
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
type SelectPropertyConfig = {
|
||||
type: "select";
|
||||
label: string;
|
||||
value: string;
|
||||
options: string[];
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
type ShapePropertyConfig = RangePropertyConfig | TextPropertyConfig | SelectPropertyConfig;
|
||||
|
||||
function fallbackSolidColor(shape: WorkplaneShape) {
|
||||
if (shape.kind === "cylinder") return "#d97813";
|
||||
if (shape.kind === "sphere") return "#0098c7";
|
||||
if (shape.kind === "cone") return "#6e2786";
|
||||
if (shape.kind === "pyramid") return "#f2cf10";
|
||||
return "#d41721";
|
||||
}
|
||||
|
||||
function formatPanelNumber(value: number) {
|
||||
return (Math.abs(value) < 0.005 ? 0 : value).toFixed(2);
|
||||
}
|
||||
|
||||
function getShapeProperties(shape: WorkplaneShape, onUpdate: (patch: Partial<WorkplaneShape>) => void): ShapePropertyConfig[] {
|
||||
const width = shapeWidth(shape);
|
||||
const depth = shapeDepth(shape);
|
||||
const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) });
|
||||
const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) });
|
||||
const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) });
|
||||
const setBaseRadius = (value: number) => onUpdate({ baseRadius: value, width: value * 2, depth: value * 2, size: value * 2 });
|
||||
|
||||
if (shape.kind === "box") {
|
||||
return [
|
||||
{ label: "Radius", value: shape.radius ?? 0, min: 0, max: 10, onChange: (radius) => onUpdate({ radius }) },
|
||||
{ label: "Steps", value: shape.steps ?? 10, min: 1, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "cylinder") {
|
||||
return [
|
||||
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 10, onChange: (bevel) => onUpdate({ bevel }) },
|
||||
{ label: "Segments", value: shape.segments ?? 1, min: 1, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "sphere") {
|
||||
return [
|
||||
{ label: "Steps", value: shape.steps ?? 24, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "halfSphere") {
|
||||
return [
|
||||
{ label: "Steps", value: shape.steps ?? 32, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
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: "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: (height) => onUpdate({ height }) },
|
||||
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "pyramid") {
|
||||
return [
|
||||
{ label: "Sides", value: shape.sides ?? 4, min: 3, max: 24, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "roundRoof") {
|
||||
return [
|
||||
{ label: "Sides", value: shape.sides ?? 64, min: 4, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "tube" || shape.kind === "ring") {
|
||||
return [
|
||||
{ label: "Thickness", value: shape.bevel ?? 4, min: 0.5, max: 20, onChange: (bevel) => onUpdate({ bevel }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "text") {
|
||||
return [
|
||||
{
|
||||
type: "text",
|
||||
label: "Text",
|
||||
value: shape.text ?? "TEXT",
|
||||
onChange: (text) => {
|
||||
const nextText = text.slice(0, 24) || " ";
|
||||
const nextWidth = clamp(Math.max(46, nextText.length * 19), 46, 260);
|
||||
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
|
||||
},
|
||||
},
|
||||
{ type: "select", label: "Font", value: shape.font ?? "Multilanguage", options: textFontOptions, onChange: (font) => onUpdate({ font }) },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 40, onChange: (height) => onUpdate({ height }) },
|
||||
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 8, onChange: (bevel) => onUpdate({ bevel }) },
|
||||
{ label: "Segments", value: shape.segments ?? 0, min: 0, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange }: RangePropertyConfig & { disabled?: boolean }) {
|
||||
const safeValue = clamp(value, min, max);
|
||||
const position = ((safeValue - min) / Math.max(1, max - min)) * 100;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(formatPanelNumber(safeValue));
|
||||
const commitDraft = () => {
|
||||
const next = Number(draft);
|
||||
onChange(clamp(Number.isFinite(next) ? next : safeValue, min, max));
|
||||
setEditing(false);
|
||||
};
|
||||
return (
|
||||
<label className="range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
|
||||
<span>{label}</span>
|
||||
<div className="range-control">
|
||||
{editing ? (
|
||||
<input
|
||||
className="range-value-input"
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={draft}
|
||||
autoFocus
|
||||
onChange={(event) => setDraft(event.currentTarget.value)}
|
||||
onBlur={commitDraft}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.currentTarget.blur();
|
||||
} else if (event.key === "Escape") {
|
||||
setDraft(formatPanelNumber(safeValue));
|
||||
setEditing(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<output
|
||||
onDoubleClick={(event) => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
setDraft(formatPanelNumber(safeValue));
|
||||
setEditing(true);
|
||||
}}
|
||||
>
|
||||
{formatPanelNumber(safeValue)}
|
||||
</output>
|
||||
)}
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={safeValue}
|
||||
disabled={disabled}
|
||||
onChange={(event) => {
|
||||
const next = Number(event.currentTarget.value);
|
||||
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig & { disabled?: boolean }) {
|
||||
return (
|
||||
<label className="text-property">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
maxLength={24}
|
||||
spellCheck={false}
|
||||
onChange={(event) => onChange(event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectProperty({ label, value, options, disabled, onChange }: SelectPropertyConfig & { disabled?: boolean }) {
|
||||
return (
|
||||
<label className="select-property">
|
||||
<span>{label}</span>
|
||||
<select value={value} disabled={disabled} onChange={(event) => onChange(event.currentTarget.value)}>
|
||||
{options.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function DimensionInput({
|
||||
label,
|
||||
value,
|
||||
min,
|
||||
max,
|
||||
step = 0.01,
|
||||
unit = "mm",
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
step?: number;
|
||||
unit?: string;
|
||||
onChange: (value: number) => void;
|
||||
}) {
|
||||
return (
|
||||
<label className="dimension-input">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={formatPanelNumber(value)}
|
||||
onChange={(event) => {
|
||||
const next = Number(event.currentTarget.value);
|
||||
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
|
||||
}}
|
||||
/>
|
||||
<span>{unit}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceSettingsModal({
|
||||
workspace,
|
||||
snap,
|
||||
onWorkspaceChange,
|
||||
onSnapChange,
|
||||
onClose,
|
||||
}: {
|
||||
workspace: WorkspaceSettings;
|
||||
snap: GridSize;
|
||||
onWorkspaceChange: (next: WorkspaceSettings) => void;
|
||||
onSnapChange: (next: GridSize) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => onWorkspaceChange({ ...workspace, ...patch });
|
||||
const setDimension = (key: "width" | "depth", value: string) => {
|
||||
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
|
||||
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
|
||||
};
|
||||
const setWorkspaceSizePreset = (sizePreset: string) => {
|
||||
const preset = workspaceSizePresets.find((entry) => entry.label === sizePreset);
|
||||
if (!preset || sizePreset === "Custom") {
|
||||
patchWorkspace({ sizePreset: "Custom" });
|
||||
return;
|
||||
}
|
||||
patchWorkspace({ sizePreset, width: preset.width, depth: preset.depth });
|
||||
};
|
||||
const setGridBlockPreset = (gridBlockPreset: string) => {
|
||||
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
|
||||
};
|
||||
const setGridBlockSize = (value: string) => {
|
||||
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
|
||||
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="workspace-modal" role="dialog" aria-modal="true" aria-label="Workspace settings">
|
||||
<div className="workspace-modal-card" onPointerDown={(event) => event.stopPropagation()}>
|
||||
<header className="workspace-modal-header">
|
||||
<strong>Workspace settings</strong>
|
||||
<button aria-label="Close settings" onClick={onClose}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="workspace-modal-body">
|
||||
<div className="workspace-row">
|
||||
<span>Background color</span>
|
||||
<button
|
||||
className="workspace-color-button"
|
||||
style={{ "--workspace-bg": workspace.background } as CSSProperties}
|
||||
aria-label="Background color"
|
||||
onClick={() => patchWorkspace({ background: workspace.background === "#f8fbfc" ? "#eaf7fb" : "#f8fbfc" })}
|
||||
/>
|
||||
</div>
|
||||
<WorkspaceToggle label="Show shadows" checked={workspace.showShadows} onChange={(showShadows) => patchWorkspace({ showShadows })} />
|
||||
<WorkspaceToggle label="Show grid" checked={workspace.showGrid} onChange={(showGrid) => patchWorkspace({ showGrid })} />
|
||||
<WorkspaceToggle
|
||||
label="Cruise when adding new shapes"
|
||||
checked={workspace.cruiseShapes}
|
||||
onChange={(cruiseShapes) => patchWorkspace({ cruiseShapes })}
|
||||
/>
|
||||
|
||||
<label className="workspace-range">
|
||||
<span>Zoom speed</span>
|
||||
<input
|
||||
type="range"
|
||||
min={1}
|
||||
max={10}
|
||||
value={workspace.zoomSpeed}
|
||||
onChange={(event) => patchWorkspace({ zoomSpeed: Number(event.currentTarget.value) })}
|
||||
/>
|
||||
<small>
|
||||
<span>Slow</span>
|
||||
<span>Fast</span>
|
||||
</small>
|
||||
</label>
|
||||
|
||||
<WorkspaceSelect
|
||||
label="Units"
|
||||
value={workspace.units}
|
||||
options={["Metric (Default)", "Imperial", "Bricks"]}
|
||||
onChange={(units) => patchWorkspace({ units })}
|
||||
/>
|
||||
<WorkspaceSelect
|
||||
label="Scale"
|
||||
value={workspace.scale}
|
||||
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
|
||||
onChange={(scale) => patchWorkspace({ scale })}
|
||||
/>
|
||||
<WorkspaceSelect label="Snap Grid" value={snap} options={gridSizes} onChange={(next) => onSnapChange(next as GridSize)} />
|
||||
<WorkspaceSelect
|
||||
label="Workplane size"
|
||||
value={workspace.sizePreset}
|
||||
options={workspaceSizePresets.map((preset) => preset.label)}
|
||||
onChange={setWorkspaceSizePreset}
|
||||
/>
|
||||
|
||||
<div className="workspace-dimensions">
|
||||
<label>
|
||||
<span>Width</span>
|
||||
<input
|
||||
type="number"
|
||||
value={workspace.width.toFixed(2)}
|
||||
min={MIN_WORKSPACE_SIZE}
|
||||
max={MAX_WORKSPACE_SIZE}
|
||||
step={1}
|
||||
onChange={(event) => setDimension("width", event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>Length</span>
|
||||
<input
|
||||
type="number"
|
||||
value={workspace.depth.toFixed(2)}
|
||||
min={MIN_WORKSPACE_SIZE}
|
||||
max={MAX_WORKSPACE_SIZE}
|
||||
step={1}
|
||||
onChange={(event) => setDimension("depth", event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<WorkspaceSelect label="Grid block size" value={workspace.gridBlockPreset} options={gridBlockPresets} onChange={setGridBlockPreset} />
|
||||
{workspace.gridBlockPreset === "Custom" ? (
|
||||
<div className="workspace-dimensions workspace-grid-dimensions">
|
||||
<label>
|
||||
<span>Block size</span>
|
||||
<input
|
||||
type="number"
|
||||
value={workspace.gridBlockSize.toFixed(2)}
|
||||
min={MIN_GRID_BLOCK_SIZE}
|
||||
max={MAX_GRID_BLOCK_SIZE}
|
||||
step={0.5}
|
||||
onChange={(event) => setGridBlockSize(event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<button className="make-default-button" onClick={() => onWorkspaceChange(DEFAULT_WORKSPACE)}>
|
||||
Make default
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button className="workspace-modal-backdrop" aria-label="Close settings" onClick={onClose} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
|
||||
return (
|
||||
<label className="workspace-toggle">
|
||||
<span>{label}</span>
|
||||
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceSelect({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
options: readonly string[];
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<label className="workspace-select">
|
||||
<span>{label}</span>
|
||||
<select value={value} onChange={(event) => onChange(event.currentTarget.value)}>
|
||||
{options.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function createThreeScene(host: HTMLDivElement): ThreeState {
|
||||
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance", preserveDrawingBuffer: shouldPreserveDrawingBufferForLocalAutomation() });
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
@@ -3995,22 +3342,6 @@ function createRotateArc(center: THREE.Vector3, radius: number, start: number, e
|
||||
return new THREE.Line(new THREE.BufferGeometry().setFromPoints(points), material);
|
||||
}
|
||||
|
||||
function shapeWidth(shape: WorkplaneShape) {
|
||||
return shape.width ?? shape.size;
|
||||
}
|
||||
|
||||
function shapeDepth(shape: WorkplaneShape) {
|
||||
return shape.depth ?? shape.size;
|
||||
}
|
||||
|
||||
function mirrorSign(value?: boolean) {
|
||||
return value ? -1 : 1;
|
||||
}
|
||||
|
||||
function mirroredAxisCount(shape: WorkplaneShape) {
|
||||
return [shape.mirrorX, shape.mirrorY, shape.mirrorZ].filter(Boolean).length;
|
||||
}
|
||||
|
||||
function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureReady?: () => void) {
|
||||
const group = new THREE.Group();
|
||||
group.name = shape.name;
|
||||
@@ -4118,12 +3449,6 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
|
||||
case "icosahedron":
|
||||
addMesh(group, new THREE.IcosahedronGeometry(size / 2, 1), material, shape);
|
||||
break;
|
||||
case "star":
|
||||
addMesh(group, createExtrudedShapeGeometry(createStarShape(size / 2), height), material, shape);
|
||||
break;
|
||||
case "heart":
|
||||
addMesh(group, createExtrudedShapeGeometry(createHeartShape(size * 0.95), height), material, shape);
|
||||
break;
|
||||
case "text":
|
||||
addTextShape(group, material, shape);
|
||||
break;
|
||||
@@ -4528,41 +3853,6 @@ function createHalfSphereGeometry(width: number, height: number, depth: number,
|
||||
return geometry;
|
||||
}
|
||||
|
||||
function createExtrudedShapeGeometry(shape: THREE.Shape, height: number) {
|
||||
const geometry = new THREE.ExtrudeGeometry(shape, { depth: height, bevelEnabled: false, steps: 1 });
|
||||
geometry.rotateX(-Math.PI / 2);
|
||||
return geometry;
|
||||
}
|
||||
|
||||
function createStarShape(radius: number) {
|
||||
const shape = new THREE.Shape();
|
||||
const inner = radius * 0.44;
|
||||
for (let i = 0; i < 10; i += 1) {
|
||||
const angle = -Math.PI / 2 + (i * Math.PI) / 5;
|
||||
const r = i % 2 === 0 ? radius : inner;
|
||||
const x = Math.cos(angle) * r;
|
||||
const y = Math.sin(angle) * r;
|
||||
if (i === 0) {
|
||||
shape.moveTo(x, y);
|
||||
} else {
|
||||
shape.lineTo(x, y);
|
||||
}
|
||||
}
|
||||
shape.closePath();
|
||||
return shape;
|
||||
}
|
||||
|
||||
function createHeartShape(size: number) {
|
||||
const s = size / 24;
|
||||
const shape = new THREE.Shape();
|
||||
shape.moveTo(0, -9 * s);
|
||||
shape.bezierCurveTo(-13 * s, -1 * s, -12 * s, 8 * s, -5 * s, 8 * s);
|
||||
shape.bezierCurveTo(-2 * s, 8 * s, 0, 5 * s, 0, 3 * s);
|
||||
shape.bezierCurveTo(0, 5 * s, 2 * s, 8 * s, 5 * s, 8 * s);
|
||||
shape.bezierCurveTo(12 * s, 8 * s, 13 * s, -1 * s, 0, -9 * s);
|
||||
return shape;
|
||||
}
|
||||
|
||||
function disposeChildren(group: THREE.Group) {
|
||||
while (group.children.length > 0) {
|
||||
const child = group.children.pop();
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
"use client";
|
||||
|
||||
import { ChevronDown, ChevronUp, LockKeyhole, LockKeyholeOpen } from "lucide-react";
|
||||
import { useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";
|
||||
import { ToolbarHideSelectedIcon } from "@/components/icons";
|
||||
import { fallbackSolidColor, resizedShapeSize, shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
|
||||
import type { GridSize, WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||
const MIN_SHAPE_SIZE = 0.01;
|
||||
const SOLID_COLORS = [
|
||||
"#d41721",
|
||||
"#ff4b4b",
|
||||
"#ff7a1a",
|
||||
"#d97813",
|
||||
"#f6a21a",
|
||||
"#f2cf10",
|
||||
"#f7e65a",
|
||||
"#a8d642",
|
||||
"#33983d",
|
||||
"#1fb66d",
|
||||
"#18b99a",
|
||||
"#0098c7",
|
||||
"#49c7ef",
|
||||
"#3b82f6",
|
||||
"#294c93",
|
||||
"#5b5ce2",
|
||||
"#6e2786",
|
||||
"#9b3bd2",
|
||||
"#c9009a",
|
||||
"#f062b6",
|
||||
"#8a5a2b",
|
||||
"#b98254",
|
||||
"#f2caa0",
|
||||
"#ffffff",
|
||||
"#cfd8df",
|
||||
"#8a98a6",
|
||||
"#4b5563",
|
||||
"#111111",
|
||||
];
|
||||
const TEXT_FONT_OPTIONS = ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"];
|
||||
|
||||
type RangePropertyConfig = {
|
||||
type?: "range";
|
||||
label: string;
|
||||
value: number;
|
||||
min: number;
|
||||
max: number;
|
||||
step?: number;
|
||||
onChange: (value: number) => void;
|
||||
};
|
||||
|
||||
type TextPropertyConfig = {
|
||||
type: "text";
|
||||
label: string;
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
type SelectPropertyConfig = {
|
||||
type: "select";
|
||||
label: string;
|
||||
value: string;
|
||||
options: string[];
|
||||
onChange: (value: string) => void;
|
||||
};
|
||||
|
||||
type ShapePropertyConfig = RangePropertyConfig | TextPropertyConfig | SelectPropertyConfig;
|
||||
|
||||
function clamp(value: number, min: number, max: number) {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
function formatPanelNumber(value: number) {
|
||||
return (Math.abs(value) < 0.005 ? 0 : value).toFixed(2);
|
||||
}
|
||||
|
||||
function getShapeProperties(shape: WorkplaneShape, onUpdate: (patch: Partial<WorkplaneShape>) => void): ShapePropertyConfig[] {
|
||||
const width = shapeWidth(shape);
|
||||
const depth = shapeDepth(shape);
|
||||
const setWidth = (value: number) => onUpdate({ width: value, size: resizedShapeSize(value, depth) });
|
||||
const setDepth = (value: number) => onUpdate({ depth: value, size: resizedShapeSize(width, value) });
|
||||
const setConeWidth = (value: number) => onUpdate({ width: value, baseRadius: value / 2, size: resizedShapeSize(value, depth) });
|
||||
const setBaseRadius = (value: number) => {
|
||||
const diameter = value * 2;
|
||||
onUpdate({ baseRadius: value, width: diameter, size: resizedShapeSize(diameter, depth) });
|
||||
};
|
||||
|
||||
if (shape.kind === "box") {
|
||||
return [
|
||||
{ label: "Radius", value: shape.radius ?? 0, min: 0, max: 10, onChange: (radius) => onUpdate({ radius }) },
|
||||
{ label: "Steps", value: shape.steps ?? 10, min: 1, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "cylinder") {
|
||||
return [
|
||||
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 10, onChange: (bevel) => onUpdate({ bevel }) },
|
||||
{ label: "Segments", value: shape.segments ?? 1, min: 1, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "sphere") {
|
||||
return [
|
||||
{ label: "Steps", value: shape.steps ?? 24, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "halfSphere") {
|
||||
return [
|
||||
{ label: "Steps", value: shape.steps ?? 32, min: 6, max: 64, step: 1, onChange: (steps) => onUpdate({ steps: Math.round(steps) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
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: "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: (height) => onUpdate({ height }) },
|
||||
{ label: "Sides", value: shape.sides ?? 96, min: 3, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "pyramid") {
|
||||
return [
|
||||
{ label: "Sides", value: shape.sides ?? 4, min: 3, max: 24, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "roundRoof") {
|
||||
return [
|
||||
{ label: "Sides", value: shape.sides ?? 64, min: 4, max: 128, step: 1, onChange: (sides) => onUpdate({ sides: Math.round(sides) }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "tube" || shape.kind === "ring") {
|
||||
return [
|
||||
{ label: "Thickness", value: shape.bevel ?? 4, min: 0.5, max: 20, onChange: (bevel) => onUpdate({ bevel }) },
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
if (shape.kind === "text") {
|
||||
return [
|
||||
{
|
||||
type: "text",
|
||||
label: "Text",
|
||||
value: shape.text ?? "TEXT",
|
||||
onChange: (text) => {
|
||||
const nextText = text.slice(0, 24) || " ";
|
||||
const nextWidth = clamp(Math.max(46, nextText.length * 19), 46, 260);
|
||||
onUpdate({ text: nextText, width: nextWidth, size: nextWidth });
|
||||
},
|
||||
},
|
||||
{ type: "select", label: "Font", value: shape.font ?? "Multilanguage", options: TEXT_FONT_OPTIONS, onChange: (font) => onUpdate({ font }) },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 40, onChange: (height) => onUpdate({ height }) },
|
||||
{ label: "Bevel", value: shape.bevel ?? 0, min: 0, max: 8, onChange: (bevel) => onUpdate({ bevel }) },
|
||||
{ label: "Segments", value: shape.segments ?? 0, min: 0, max: 24, step: 1, onChange: (segments) => onUpdate({ segments: Math.round(segments) }) },
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{ label: "Length", value: depth, min: MIN_SHAPE_SIZE, max: 160, onChange: setDepth },
|
||||
{ label: "Width", value: width, min: MIN_SHAPE_SIZE, max: 160, onChange: setWidth },
|
||||
{ label: "Height", value: shape.height, min: MIN_SHAPE_SIZE, max: 160, onChange: (height) => onUpdate({ height }) },
|
||||
];
|
||||
}
|
||||
|
||||
export function ShapeInspector({
|
||||
shape,
|
||||
snap,
|
||||
snapOpen,
|
||||
onUpdate,
|
||||
onClose,
|
||||
onSnapChange,
|
||||
onSnapOpenChange,
|
||||
}: {
|
||||
shape: WorkplaneShape;
|
||||
snap: GridSize;
|
||||
snapOpen: boolean;
|
||||
onUpdate: (patch: Partial<WorkplaneShape>) => void;
|
||||
onClose: () => void;
|
||||
onSnapChange: Dispatch<SetStateAction<GridSize>>;
|
||||
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
|
||||
}) {
|
||||
const solidColor = shape.hole ? fallbackSolidColor(shape) : shape.color;
|
||||
const locked = Boolean(shape.locked);
|
||||
const properties = getShapeProperties(shape, onUpdate);
|
||||
const [propertiesOpen, setPropertiesOpen] = useState(true);
|
||||
const [colorOpen, setColorOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<aside className="shape-inspector" aria-label={`${shape.name} shape settings`} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<div className="shape-inspector-header">
|
||||
<button className="inspector-header-icon" aria-label="Close shape settings" onClick={onClose}>
|
||||
<ChevronUp size={26} strokeWidth={2.8} />
|
||||
</button>
|
||||
<strong>{shape.name}</strong>
|
||||
<div className="inspector-header-actions">
|
||||
<button className={locked ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={locked ? "Unlock shape" : "Lock shape"} onClick={() => onUpdate({ locked: !locked })}>
|
||||
{locked ? <LockKeyhole size={31} strokeWidth={2.4} /> : <LockKeyholeOpen size={31} strokeWidth={2.4} />}
|
||||
</button>
|
||||
<button className={shape.hidden ? "inspector-header-icon active" : "inspector-header-icon"} aria-label={shape.hidden ? "Show shape" : "Hide shape"} onClick={() => onUpdate({ hidden: !shape.hidden })}>
|
||||
<ToolbarHideSelectedIcon />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="shape-state-card" role="group" aria-label="Shape mode">
|
||||
<button
|
||||
className={!shape.hole ? "active solid-choice" : "solid-choice"}
|
||||
onClick={() => {
|
||||
const wasHole = Boolean(shape.hole);
|
||||
onUpdate({ hole: false, color: solidColor });
|
||||
setColorOpen((open) => (wasHole ? false : !open));
|
||||
}}
|
||||
disabled={locked}
|
||||
aria-pressed={!shape.hole}
|
||||
aria-expanded={colorOpen}
|
||||
>
|
||||
<span className="large-solid-swatch" style={{ "--swatch": solidColor } as CSSProperties} />
|
||||
<span>Solid</span>
|
||||
</button>
|
||||
<button
|
||||
className={shape.hole ? "active hole-choice" : "hole-choice"}
|
||||
onClick={() => {
|
||||
onUpdate({ hole: true, color: "#b8c2cc" });
|
||||
setColorOpen(false);
|
||||
}}
|
||||
disabled={locked}
|
||||
aria-pressed={shape.hole}
|
||||
>
|
||||
<span className="large-hole-swatch" />
|
||||
<span>Hole</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{colorOpen ? (
|
||||
<div className="color-card" aria-label="Shape color">
|
||||
<div className="color-card-header">
|
||||
<span>Color</span>
|
||||
<span className="color-value">{solidColor.toUpperCase()}</span>
|
||||
</div>
|
||||
<div className="color-grid">
|
||||
{SOLID_COLORS.map((color) => (
|
||||
<button
|
||||
key={color}
|
||||
className={solidColor.toLowerCase() === color.toLowerCase() && !shape.hole ? "selected" : ""}
|
||||
type="button"
|
||||
style={{ "--shape-swatch": color } as CSSProperties}
|
||||
title={color.toUpperCase()}
|
||||
aria-label={`Set color ${color}`}
|
||||
disabled={locked}
|
||||
onClick={() => {
|
||||
onUpdate({ color, hole: false });
|
||||
setColorOpen(false);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
<label className={locked ? "custom-color disabled" : "custom-color"} title="Custom color">
|
||||
<input
|
||||
type="color"
|
||||
value={solidColor}
|
||||
disabled={locked}
|
||||
onChange={(event) => {
|
||||
onUpdate({ color: event.target.value, hole: false });
|
||||
setColorOpen(false);
|
||||
}}
|
||||
/>
|
||||
<span>Custom</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="property-card">
|
||||
<button
|
||||
className="property-card-header"
|
||||
type="button"
|
||||
aria-expanded={propertiesOpen}
|
||||
aria-controls={`properties-${shape.id}`}
|
||||
onClick={() => setPropertiesOpen((open) => !open)}
|
||||
>
|
||||
<span>Properties</span>
|
||||
<ChevronUp className={propertiesOpen ? "" : "collapsed"} size={25} strokeWidth={2.8} />
|
||||
</button>
|
||||
{propertiesOpen ? (
|
||||
<div className="property-list" id={`properties-${shape.id}`}>
|
||||
{properties.map((property) => {
|
||||
if (property.type === "text") {
|
||||
return <TextProperty key={property.label} {...property} disabled={locked} />;
|
||||
}
|
||||
if (property.type === "select") {
|
||||
return <SelectProperty key={property.label} {...property} disabled={locked} />;
|
||||
}
|
||||
return <RangeProperty key={property.label} {...property} disabled={locked} />;
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="inspector-snap-dock">
|
||||
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={onSnapChange} onSnapOpenChange={onSnapOpenChange} />
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
||||
export function SnapGridControl({
|
||||
snap,
|
||||
snapOpen,
|
||||
onSnapChange,
|
||||
onSnapOpenChange,
|
||||
}: {
|
||||
snap: GridSize;
|
||||
snapOpen: boolean;
|
||||
onSnapChange: Dispatch<SetStateAction<GridSize>>;
|
||||
onSnapOpenChange: Dispatch<SetStateAction<boolean>>;
|
||||
}) {
|
||||
return (
|
||||
<div className="snap-row">
|
||||
<span>Snap Grid</span>
|
||||
<button className="snap-select" onClick={() => onSnapOpenChange((value) => !value)}>
|
||||
{snap}
|
||||
<ChevronDown size={12} fill="currentColor" />
|
||||
</button>
|
||||
{snapOpen ? (
|
||||
<div className="snap-menu">
|
||||
{GRID_SIZES.map((size) => (
|
||||
<button
|
||||
key={size}
|
||||
className={size === snap ? "selected" : ""}
|
||||
onClick={() => {
|
||||
onSnapChange(size);
|
||||
onSnapOpenChange(false);
|
||||
}}
|
||||
>
|
||||
{size}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RangeProperty({ label, value, min, max, step = 0.01, disabled, onChange }: RangePropertyConfig & { disabled?: boolean }) {
|
||||
const safeValue = clamp(value, min, max);
|
||||
const position = ((safeValue - min) / Math.max(1, max - min)) * 100;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [draft, setDraft] = useState(formatPanelNumber(safeValue));
|
||||
const commitDraft = () => {
|
||||
const next = Number(draft);
|
||||
onChange(clamp(Number.isFinite(next) ? next : safeValue, min, max));
|
||||
setEditing(false);
|
||||
};
|
||||
return (
|
||||
<label className="range-property" style={{ "--slider-pos": `${position}%` } as CSSProperties}>
|
||||
<span>{label}</span>
|
||||
<div className="range-control">
|
||||
{editing ? (
|
||||
<input
|
||||
className="range-value-input"
|
||||
type="number"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={draft}
|
||||
autoFocus
|
||||
onChange={(event) => setDraft(event.currentTarget.value)}
|
||||
onBlur={commitDraft}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter") {
|
||||
event.currentTarget.blur();
|
||||
} else if (event.key === "Escape") {
|
||||
setDraft(formatPanelNumber(safeValue));
|
||||
setEditing(false);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<output
|
||||
onDoubleClick={(event) => {
|
||||
if (disabled) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
setDraft(formatPanelNumber(safeValue));
|
||||
setEditing(true);
|
||||
}}
|
||||
>
|
||||
{formatPanelNumber(safeValue)}
|
||||
</output>
|
||||
)}
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
step={step}
|
||||
value={safeValue}
|
||||
disabled={disabled}
|
||||
onChange={(event) => {
|
||||
const next = Number(event.currentTarget.value);
|
||||
onChange(clamp(Number.isFinite(next) ? next : min, min, max));
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function TextProperty({ label, value, disabled, onChange }: TextPropertyConfig & { disabled?: boolean }) {
|
||||
return (
|
||||
<label className="text-property">
|
||||
<span>{label}</span>
|
||||
<input
|
||||
type="text"
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
maxLength={24}
|
||||
spellCheck={false}
|
||||
onChange={(event) => onChange(event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectProperty({ label, value, options, disabled, onChange }: SelectPropertyConfig & { disabled?: boolean }) {
|
||||
return (
|
||||
<label className="select-property">
|
||||
<span>{label}</span>
|
||||
<select value={value} disabled={disabled} onChange={(event) => onChange(event.currentTarget.value)}>
|
||||
{options.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -102,7 +102,7 @@ export function TransformOverlay({
|
||||
<line className="rotation-zero-line" x1="0" y1="0" x2="0" y2="-92" />
|
||||
<line className="rotation-current-line" x1="0" y1="0" x2={activeLine.x} y2={activeLine.y} />
|
||||
<text className="rotation-zero-label" x="0" y="-75">
|
||||
0Β°
|
||||
0°
|
||||
</text>
|
||||
</g>
|
||||
</svg>
|
||||
@@ -173,7 +173,7 @@ export function TransformOverlay({
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<span>Β°</span>
|
||||
<span>°</span>
|
||||
</label>
|
||||
) : null}
|
||||
{box.handles.map((handle) => (
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
"use client";
|
||||
|
||||
import { X } from "lucide-react";
|
||||
import type { CSSProperties } from "react";
|
||||
import { DEFAULT_WORKPLANE_WORKSPACE } from "@/lib/workplaneSettings";
|
||||
import type { GridSize, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
|
||||
type WorkspaceSettings = WorkplaneWorkspaceSettings;
|
||||
|
||||
const GRID_SIZES: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
|
||||
const MIN_WORKSPACE_SIZE = 60;
|
||||
const MAX_WORKSPACE_SIZE = 2000;
|
||||
const MIN_GRID_BLOCK_SIZE = 1;
|
||||
const MAX_GRID_BLOCK_SIZE = 200;
|
||||
const WORKSPACE_SIZE_PRESETS = [
|
||||
{ label: "200 x 200 mm", width: 200, depth: 200 },
|
||||
{ label: "300 x 300 mm", width: 300, depth: 300 },
|
||||
{ label: "500 x 500 mm", width: 500, depth: 500 },
|
||||
{ label: "1000 x 1000 mm", width: 1000, depth: 1000 },
|
||||
{ label: "2000 x 2000 mm", width: 2000, depth: 2000 },
|
||||
{ label: "Custom", width: 200, depth: 200 },
|
||||
];
|
||||
const GRID_BLOCK_PRESETS = ["1 mm", "2.5 mm", "5 mm", "10 mm", "20 mm", "50 mm", "100 mm", "Custom"] as const;
|
||||
|
||||
function clamp(value: number, min: number, max: number) {
|
||||
return Math.min(max, Math.max(min, value));
|
||||
}
|
||||
|
||||
function gridBlockSizeForPreset(preset: string, fallback: number) {
|
||||
if (preset === "Custom") {
|
||||
return clamp(fallback, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
|
||||
}
|
||||
return clamp(Number.parseFloat(preset) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
|
||||
}
|
||||
|
||||
export function WorkspaceSettingsModal({
|
||||
workspace,
|
||||
snap,
|
||||
onWorkspaceChange,
|
||||
onSnapChange,
|
||||
onClose,
|
||||
}: {
|
||||
workspace: WorkspaceSettings;
|
||||
snap: GridSize;
|
||||
onWorkspaceChange: (next: WorkspaceSettings) => void;
|
||||
onSnapChange: (next: GridSize) => void;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const patchWorkspace = (patch: Partial<WorkspaceSettings>) => onWorkspaceChange({ ...workspace, ...patch });
|
||||
const setDimension = (key: "width" | "depth", value: string) => {
|
||||
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE[key], MIN_WORKSPACE_SIZE, MAX_WORKSPACE_SIZE);
|
||||
patchWorkspace({ [key]: next, sizePreset: "Custom" } as Partial<WorkspaceSettings>);
|
||||
};
|
||||
const setWorkspaceSizePreset = (sizePreset: string) => {
|
||||
const preset = WORKSPACE_SIZE_PRESETS.find((entry) => entry.label === sizePreset);
|
||||
if (!preset || sizePreset === "Custom") {
|
||||
patchWorkspace({ sizePreset: "Custom" });
|
||||
return;
|
||||
}
|
||||
patchWorkspace({ sizePreset, width: preset.width, depth: preset.depth });
|
||||
};
|
||||
const setGridBlockPreset = (gridBlockPreset: string) => {
|
||||
patchWorkspace({ gridBlockPreset, gridBlockSize: gridBlockSizeForPreset(gridBlockPreset, workspace.gridBlockSize) });
|
||||
};
|
||||
const setGridBlockSize = (value: string) => {
|
||||
const next = clamp(Number.parseFloat(value) || DEFAULT_WORKPLANE_WORKSPACE.gridBlockSize, MIN_GRID_BLOCK_SIZE, MAX_GRID_BLOCK_SIZE);
|
||||
patchWorkspace({ gridBlockPreset: "Custom", gridBlockSize: next });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="workspace-modal" role="dialog" aria-modal="true" aria-label="Workspace settings">
|
||||
<div className="workspace-modal-card" onPointerDown={(event) => event.stopPropagation()}>
|
||||
<header className="workspace-modal-header">
|
||||
<strong>Workspace settings</strong>
|
||||
<button aria-label="Close settings" onClick={onClose}>
|
||||
<X size={18} />
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<div className="workspace-modal-body">
|
||||
<div className="workspace-row">
|
||||
<span>Background color</span>
|
||||
<button
|
||||
className="workspace-color-button"
|
||||
style={{ "--workspace-bg": workspace.background } as CSSProperties}
|
||||
aria-label="Background color"
|
||||
onClick={() => patchWorkspace({ background: workspace.background === "#f8fbfc" ? "#eaf7fb" : "#f8fbfc" })}
|
||||
/>
|
||||
</div>
|
||||
<WorkspaceToggle label="Show shadows" checked={workspace.showShadows} onChange={(showShadows) => patchWorkspace({ showShadows })} />
|
||||
<WorkspaceToggle label="Show grid" checked={workspace.showGrid} onChange={(showGrid) => patchWorkspace({ showGrid })} />
|
||||
<WorkspaceToggle
|
||||
label="Cruise when adding new shapes"
|
||||
checked={workspace.cruiseShapes}
|
||||
onChange={(cruiseShapes) => patchWorkspace({ cruiseShapes })}
|
||||
/>
|
||||
|
||||
<label className="workspace-range">
|
||||
<span>Zoom speed</span>
|
||||
<input
|
||||
type="range"
|
||||
min={1}
|
||||
max={10}
|
||||
value={workspace.zoomSpeed}
|
||||
onChange={(event) => patchWorkspace({ zoomSpeed: Number(event.currentTarget.value) })}
|
||||
/>
|
||||
<small>
|
||||
<span>Slow</span>
|
||||
<span>Fast</span>
|
||||
</small>
|
||||
</label>
|
||||
|
||||
<WorkspaceSelect
|
||||
label="Units"
|
||||
value={workspace.units}
|
||||
options={["Metric (Default)", "Imperial", "Bricks"]}
|
||||
onChange={(units) => patchWorkspace({ units })}
|
||||
/>
|
||||
<WorkspaceSelect
|
||||
label="Scale"
|
||||
value={workspace.scale}
|
||||
options={["1:1 (millimeters)", "1:10 (centimeters)", "1:100 (meters)", "1:1000 (meters)"]}
|
||||
onChange={(scale) => patchWorkspace({ scale })}
|
||||
/>
|
||||
<WorkspaceSelect label="Snap Grid" value={snap} options={GRID_SIZES} onChange={(next) => onSnapChange(next as GridSize)} />
|
||||
<WorkspaceSelect
|
||||
label="Workplane size"
|
||||
value={workspace.sizePreset}
|
||||
options={WORKSPACE_SIZE_PRESETS.map((preset) => preset.label)}
|
||||
onChange={setWorkspaceSizePreset}
|
||||
/>
|
||||
|
||||
<div className="workspace-dimensions">
|
||||
<label>
|
||||
<span>Width</span>
|
||||
<input
|
||||
type="number"
|
||||
value={workspace.width.toFixed(2)}
|
||||
min={MIN_WORKSPACE_SIZE}
|
||||
max={MAX_WORKSPACE_SIZE}
|
||||
step={1}
|
||||
onChange={(event) => setDimension("width", event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
<span>Length</span>
|
||||
<input
|
||||
type="number"
|
||||
value={workspace.depth.toFixed(2)}
|
||||
min={MIN_WORKSPACE_SIZE}
|
||||
max={MAX_WORKSPACE_SIZE}
|
||||
step={1}
|
||||
onChange={(event) => setDimension("depth", event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<WorkspaceSelect label="Grid block size" value={workspace.gridBlockPreset} options={GRID_BLOCK_PRESETS} onChange={setGridBlockPreset} />
|
||||
{workspace.gridBlockPreset === "Custom" ? (
|
||||
<div className="workspace-dimensions workspace-grid-dimensions">
|
||||
<label>
|
||||
<span>Block size</span>
|
||||
<input
|
||||
type="number"
|
||||
value={workspace.gridBlockSize.toFixed(2)}
|
||||
min={MIN_GRID_BLOCK_SIZE}
|
||||
max={MAX_GRID_BLOCK_SIZE}
|
||||
step={0.5}
|
||||
onChange={(event) => setGridBlockSize(event.currentTarget.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<button className="make-default-button" onClick={() => onWorkspaceChange(DEFAULT_WORKPLANE_WORKSPACE)}>
|
||||
Make default
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<button className="workspace-modal-backdrop" aria-label="Close settings" onClick={onClose} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
|
||||
return (
|
||||
<label className="workspace-toggle">
|
||||
<span>{label}</span>
|
||||
<input type="checkbox" checked={checked} onChange={(event) => onChange(event.currentTarget.checked)} />
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceSelect({
|
||||
label,
|
||||
value,
|
||||
options,
|
||||
onChange,
|
||||
}: {
|
||||
label: string;
|
||||
value: string;
|
||||
options: readonly string[];
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<label className="workspace-select">
|
||||
<span>{label}</span>
|
||||
<select value={value} onChange={(event) => onChange(event.currentTarget.value)}>
|
||||
{options.map((option) => (
|
||||
<option key={option} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
let fallbackIdCounter = 0;
|
||||
|
||||
export function createLocalId(prefix: string) {
|
||||
const uuid = globalThis.crypto?.randomUUID?.();
|
||||
if (uuid) {
|
||||
return `${prefix}-${uuid}`;
|
||||
}
|
||||
|
||||
fallbackIdCounter = (fallbackIdCounter + 1) % Number.MAX_SAFE_INTEGER;
|
||||
const timestamp = Date.now().toString(36);
|
||||
const counter = fallbackIdCounter.toString(36);
|
||||
const random = Math.random().toString(36).slice(2, 10);
|
||||
return `${prefix}-${timestamp}-${counter}-${random}`;
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { ShapeAsset } from "@/types/sketchforge";
|
||||
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets } from "./shapeCatalog";
|
||||
|
||||
describe("shape catalog", () => {
|
||||
it("does not expose removed decorative shapes in the toolbar catalog", () => {
|
||||
const kinds = toolbarShapeAssets.map((asset) => asset.kind);
|
||||
|
||||
expect(kinds).not.toContain("star");
|
||||
expect(kinds).not.toContain("heart");
|
||||
});
|
||||
|
||||
it("creates placed shapes from toolbar assets", () => {
|
||||
const asset: ShapeAsset = { id: "box", name: "Box", src: "box.png", kind: "box", color: "#d41721" };
|
||||
const placed = makeShapeFromAsset(asset, { x: 12, z: -8, elevation: 4 });
|
||||
|
||||
expect(placed.id).toMatch(/^box-/);
|
||||
expect(placed).toMatchObject({
|
||||
name: "Box",
|
||||
kind: "box",
|
||||
color: "#d41721",
|
||||
x: 12,
|
||||
z: -8,
|
||||
elevation: 4,
|
||||
size: 20,
|
||||
width: 20,
|
||||
depth: 20,
|
||||
height: 20,
|
||||
radius: 0,
|
||||
steps: 10,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("uses shape-specific defaults for text and round profiles", () => {
|
||||
const text = makeShapeFromAsset({ id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" });
|
||||
const torus = makeShapeFromAsset({ id: "torus", name: "Torus", src: "torus.png", kind: "torus", color: "#0098c7" });
|
||||
|
||||
expect(text).toMatchObject({ width: 86, depth: 28, height: 10, text: "TEXT", font: "Multilanguage" });
|
||||
expect(torus).toMatchObject({ size: 22, width: 22, depth: 22, height: 5 });
|
||||
});
|
||||
|
||||
it("creates canonical scene shapes with stable defaults", () => {
|
||||
const created = sceneShape({
|
||||
name: "Part",
|
||||
kind: "box",
|
||||
color: "#d41721",
|
||||
width: 12,
|
||||
depth: 18,
|
||||
rotation: 359.9,
|
||||
mirrorX: false,
|
||||
});
|
||||
|
||||
expect(created.id).toMatch(/^shape-/);
|
||||
expect(created).toMatchObject({
|
||||
name: "Part",
|
||||
kind: "box",
|
||||
color: "#d41721",
|
||||
x: 0,
|
||||
z: 0,
|
||||
elevation: 0,
|
||||
width: 12,
|
||||
depth: 18,
|
||||
height: 20,
|
||||
size: 18,
|
||||
rotation: 0,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
});
|
||||
expect(created.mirrorX).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import { canonicalizeShape } from "@/lib/workplaneShapes";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
|
||||
|
||||
export const toolbarShapeAssets: ToolbarShapeAsset[] = [
|
||||
{ id: "box", name: "Box", src: "assets/sketchforge/shape-icons-gray/box.png", menuIcon: "assets/sketchforge/shape-icons-gray/box.png", kind: "box", color: "#d41721" },
|
||||
{ id: "cylinder", name: "Cylinder", src: "assets/sketchforge/shape-icons-gray/cylinder.png", menuIcon: "assets/sketchforge/shape-icons-gray/cylinder.png", kind: "cylinder", color: "#d97813" },
|
||||
{ id: "sphere", name: "Sphere", src: "assets/sketchforge/shape-icons-gray/sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/sphere.png", kind: "sphere", color: "#0098c7" },
|
||||
{ id: "cone", name: "Cone", src: "assets/sketchforge/shape-icons-gray/cone.png", menuIcon: "assets/sketchforge/shape-icons-gray/cone.png", kind: "cone", color: "#6e2786" },
|
||||
{ id: "pyramid", name: "Pyramid", src: "assets/sketchforge/shape-icons-gray/pyramid.png", menuIcon: "assets/sketchforge/shape-icons-gray/pyramid.png", kind: "pyramid", color: "#f2cf10" },
|
||||
{ id: "wedge", name: "Wedge", src: "assets/sketchforge/shape-icons-gray/wedge.png", menuIcon: "assets/sketchforge/shape-icons-gray/wedge.png", kind: "wedge", color: "#33983d" },
|
||||
{ id: "text", name: "Text", src: "assets/sketchforge/shape-icons-gray/text.png", menuIcon: "assets/sketchforge/shape-icons-gray/text.png", kind: "text", color: "#cf101b" },
|
||||
{ id: "round-roof", name: "Round Roof", src: "assets/sketchforge/shape-icons-gray/round-roof.png", menuIcon: "assets/sketchforge/shape-icons-gray/round-roof.png", kind: "roundRoof", color: "#67c4ce" },
|
||||
{ id: "half-sphere", name: "Half Sphere", src: "assets/sketchforge/shape-icons-gray/half-sphere.png", menuIcon: "assets/sketchforge/shape-icons-gray/half-sphere.png", kind: "halfSphere", color: "#c9009a" },
|
||||
{ id: "torus", name: "Torus", src: "assets/sketchforge/shape-icons-gray/torus.png", menuIcon: "assets/sketchforge/shape-icons-gray/torus.png", kind: "torus", color: "#0098c7" },
|
||||
{ id: "tube", name: "Tube", src: "assets/sketchforge/shape-icons-gray/tube.png", menuIcon: "assets/sketchforge/shape-icons-gray/tube.png", kind: "tube", color: "#ce7013" },
|
||||
];
|
||||
|
||||
export function sceneShape(shape: Partial<WorkplaneShape> & Pick<WorkplaneShape, "name" | "kind" | "color">): WorkplaneShape {
|
||||
const width = shape.width ?? shape.size ?? 20;
|
||||
const depth = shape.depth ?? shape.size ?? 20;
|
||||
const height = shape.height ?? 20;
|
||||
return canonicalizeShape({
|
||||
id: shape.id ?? createLocalId("shape"),
|
||||
name: shape.name,
|
||||
kind: shape.kind,
|
||||
color: shape.color,
|
||||
hole: shape.hole,
|
||||
x: shape.x ?? 0,
|
||||
z: shape.z ?? 0,
|
||||
elevation: shape.elevation ?? 0,
|
||||
size: shape.size ?? Math.max(width, depth),
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
rotation: shape.rotation ?? 0,
|
||||
rotationX: shape.rotationX ?? 0,
|
||||
rotationZ: shape.rotationZ ?? 0,
|
||||
radius: shape.radius,
|
||||
steps: shape.steps,
|
||||
sides: shape.sides,
|
||||
bevel: shape.bevel,
|
||||
segments: shape.segments,
|
||||
topRadius: shape.topRadius,
|
||||
baseRadius: shape.baseRadius,
|
||||
text: shape.text,
|
||||
font: shape.font,
|
||||
importedMesh: shape.importedMesh,
|
||||
imagePlate: shape.imagePlate,
|
||||
groupedShapes: shape.groupedShapes,
|
||||
groupedBaseWidth: shape.groupedBaseWidth,
|
||||
groupedBaseDepth: shape.groupedBaseDepth,
|
||||
groupedBaseHeight: shape.groupedBaseHeight,
|
||||
locked: shape.locked ?? false,
|
||||
hidden: shape.hidden ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
export function makeShapeFromAsset(asset: ShapeAsset, point?: { x: number; z: number; elevation?: number }): WorkplaneShape {
|
||||
const roundProfile = asset.kind === "sphere" || asset.kind === "torus" || asset.kind === "ring" || asset.kind === "halfSphere";
|
||||
const flatProfile = asset.kind === "torus" || asset.kind === "ring" || asset.kind === "text";
|
||||
const size = roundProfile ? 22 : 20;
|
||||
const height = asset.kind === "text" ? 10 : asset.kind === "roundRoof" ? 10 : asset.kind === "halfSphere" ? 11 : flatProfile ? 5 : 20;
|
||||
const width = asset.kind === "text" ? 86 : size;
|
||||
const depth = asset.kind === "text" ? 28 : size;
|
||||
|
||||
return {
|
||||
id: createLocalId(asset.id),
|
||||
name: asset.name,
|
||||
kind: asset.kind,
|
||||
color: asset.color,
|
||||
hole: asset.hole,
|
||||
x: point?.x ?? 0,
|
||||
z: point?.z ?? 0,
|
||||
elevation: point?.elevation ?? 0,
|
||||
size,
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
rotation: 0,
|
||||
rotationX: 0,
|
||||
rotationZ: 0,
|
||||
radius: asset.kind === "box" ? 0 : undefined,
|
||||
text: asset.kind === "text" ? "TEXT" : undefined,
|
||||
font: asset.kind === "text" ? "Multilanguage" : undefined,
|
||||
steps: asset.kind === "box" ? 10 : asset.kind === "sphere" ? 24 : asset.kind === "halfSphere" ? 32 : undefined,
|
||||
sides: asset.kind === "cylinder" || asset.kind === "cone" ? 96 : asset.kind === "roundRoof" ? 64 : asset.kind === "pyramid" ? 4 : undefined,
|
||||
bevel: asset.kind === "cylinder" ? 0 : asset.kind === "tube" || asset.kind === "ring" ? 4 : undefined,
|
||||
segments: asset.kind === "cylinder" ? 1 : undefined,
|
||||
topRadius: asset.kind === "cone" ? 0 : undefined,
|
||||
baseRadius: asset.kind === "cone" ? size / 2 : undefined,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import * as THREE from "three";
|
||||
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
|
||||
import { createLocalId } from "@/lib/localIds";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
const stlLoader = new STLLoader();
|
||||
|
||||
export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): WorkplaneShape {
|
||||
const rawGeometry = stlLoader.parse(buffer);
|
||||
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry.clone();
|
||||
geometry.computeBoundingBox();
|
||||
|
||||
const box = geometry.boundingBox;
|
||||
if (!box) {
|
||||
throw new Error("STL has no readable geometry");
|
||||
}
|
||||
|
||||
const size = new THREE.Vector3();
|
||||
const center = new THREE.Vector3();
|
||||
box.getSize(size);
|
||||
box.getCenter(center);
|
||||
|
||||
const maxDimension = Math.max(size.x, size.y, size.z);
|
||||
if (!Number.isFinite(maxDimension) || maxDimension <= 0) {
|
||||
throw new Error("STL geometry is empty");
|
||||
}
|
||||
|
||||
const scale = 1;
|
||||
const position = geometry.getAttribute("position");
|
||||
const normal = geometry.getAttribute("normal");
|
||||
const positions: number[] = [];
|
||||
const normals: number[] = [];
|
||||
|
||||
for (let i = 0; i < position.count; i += 1) {
|
||||
positions.push((position.getX(i) - center.x) * scale, (position.getY(i) - box.min.y) * scale, (position.getZ(i) - center.z) * scale);
|
||||
if (normal) {
|
||||
normals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
|
||||
}
|
||||
}
|
||||
|
||||
const width = Math.max(1, size.x * scale);
|
||||
const height = Math.max(1, size.y * scale);
|
||||
const depth = Math.max(1, size.z * scale);
|
||||
const triangleCount = Math.floor(position.count / 3);
|
||||
|
||||
return {
|
||||
id: createLocalId("uploaded-mesh"),
|
||||
name: fileName.replace(/\.[^.]+$/, "") || "Imported STL",
|
||||
kind: "mesh",
|
||||
color: "#0098c7",
|
||||
x: 10,
|
||||
z: -10,
|
||||
size: Math.max(width, depth),
|
||||
width,
|
||||
depth,
|
||||
height,
|
||||
rotation: 0,
|
||||
rotationX: 0,
|
||||
rotationZ: 0,
|
||||
importedMesh: {
|
||||
positions,
|
||||
normals: normals.length ? normals : undefined,
|
||||
baseWidth: width,
|
||||
baseDepth: depth,
|
||||
baseHeight: height,
|
||||
triangleCount,
|
||||
sourceFormat: "stl",
|
||||
},
|
||||
locked: false,
|
||||
hidden: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
|
||||
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "./workplaneSettings";
|
||||
|
||||
describe("workplane settings helpers", () => {
|
||||
it("accepts known snap grid values and falls back for unknown values", () => {
|
||||
expect(normalizeSnapGrid("0.5 mm")).toBe("0.5 mm");
|
||||
expect(normalizeSnapGrid("Huge")).toBe(DEFAULT_SNAP_GRID);
|
||||
expect(normalizeSnapGrid(null, "Off")).toBe("Off");
|
||||
});
|
||||
|
||||
it("normalizes workspace settings from partial or invalid data", () => {
|
||||
const fallback: WorkplaneWorkspaceSettings = {
|
||||
...DEFAULT_WORKPLANE_WORKSPACE,
|
||||
width: 300,
|
||||
depth: 250,
|
||||
background: "#ffffff",
|
||||
};
|
||||
|
||||
expect(normalizeWorkspaceSettings(null, fallback)).toEqual(fallback);
|
||||
expect(
|
||||
normalizeWorkspaceSettings(
|
||||
{
|
||||
width: 500,
|
||||
depth: Number.NaN,
|
||||
sizePreset: "",
|
||||
gridBlockSize: 2.5,
|
||||
gridBlockPreset: "Custom",
|
||||
background: "#123456",
|
||||
showShadows: false,
|
||||
showGrid: false,
|
||||
cruiseShapes: false,
|
||||
zoomSpeed: Infinity,
|
||||
units: "Bricks",
|
||||
scale: "1:10 (centimeters)",
|
||||
},
|
||||
fallback,
|
||||
),
|
||||
).toEqual({
|
||||
...fallback,
|
||||
width: 500,
|
||||
gridBlockSize: 2.5,
|
||||
gridBlockPreset: "Custom",
|
||||
background: "#123456",
|
||||
showShadows: false,
|
||||
showGrid: false,
|
||||
cruiseShapes: false,
|
||||
units: "Bricks",
|
||||
scale: "1:10 (centimeters)",
|
||||
});
|
||||
});
|
||||
|
||||
it("fingerprints workspace and snap settings together", () => {
|
||||
const base = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "1.0 mm");
|
||||
const changedSnap = workplaneSettingsFingerprint(DEFAULT_WORKPLANE_WORKSPACE, "5.0 mm");
|
||||
const changedWorkspace = workplaneSettingsFingerprint({ ...DEFAULT_WORKPLANE_WORKSPACE, width: 300 }, "1.0 mm");
|
||||
|
||||
expect(changedSnap).not.toBe(base);
|
||||
expect(changedWorkspace).not.toBe(base);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
import {
|
||||
canonicalizeShape,
|
||||
cleanNearZero,
|
||||
cleanRotationDegrees,
|
||||
fallbackSolidColor,
|
||||
mirroredAxisCount,
|
||||
mirrorSign,
|
||||
normalizeDegrees,
|
||||
proportionalResizeScale,
|
||||
resizedShapeSize,
|
||||
serializeShapesForSync,
|
||||
shapeDepth,
|
||||
shapeWidth,
|
||||
workplaneShapesEqual,
|
||||
} from "./workplaneShapes";
|
||||
|
||||
function shape(overrides: Partial<WorkplaneShape> = {}): WorkplaneShape {
|
||||
return {
|
||||
id: "box-1",
|
||||
name: "Box",
|
||||
kind: "box",
|
||||
color: "#d41721",
|
||||
x: 0,
|
||||
z: 0,
|
||||
elevation: 0,
|
||||
size: 20,
|
||||
width: 20,
|
||||
depth: 20,
|
||||
height: 20,
|
||||
rotation: 0,
|
||||
locked: false,
|
||||
hidden: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("workplane shape helpers", () => {
|
||||
it("normalizes and cleans rotations", () => {
|
||||
expect(normalizeDegrees(-90)).toBe(270);
|
||||
expect(normalizeDegrees(450)).toBe(90);
|
||||
expect(cleanRotationDegrees(Number.NaN)).toBe(0);
|
||||
expect(cleanRotationDegrees(-0.2)).toBe(0);
|
||||
expect(cleanRotationDegrees(359.8)).toBe(0);
|
||||
expect(cleanRotationDegrees(12.34)).toBe(12.3);
|
||||
});
|
||||
|
||||
it("cleans near-zero values and derives dimensions", () => {
|
||||
const base = shape({ size: 30, width: 18, depth: 24 });
|
||||
expect(cleanNearZero(0.004)).toBe(0);
|
||||
expect(cleanNearZero(0.006)).toBe(0.006);
|
||||
expect(shapeWidth(base)).toBe(18);
|
||||
expect(shapeDepth(base)).toBe(24);
|
||||
expect(resizedShapeSize(18, 24)).toBe(24);
|
||||
});
|
||||
|
||||
it("uses proportional scale instead of square dimensions while shift-resizing", () => {
|
||||
expect(proportionalResizeScale(50, 100, 100, 150)).toBe(2);
|
||||
expect(proportionalResizeScale(50, 100, 60, 200)).toBe(2);
|
||||
expect(proportionalResizeScale(50, 100, 25, 80)).toBe(0.5);
|
||||
});
|
||||
|
||||
it("canonicalizes mirror flags and nested group rotations", () => {
|
||||
const canonical = canonicalizeShape(
|
||||
shape({
|
||||
rotation: 360,
|
||||
rotationX: -0.1,
|
||||
rotationZ: 45.04,
|
||||
mirrorX: false,
|
||||
mirrorY: true,
|
||||
groupedShapes: [shape({ id: "child", rotation: 720, mirrorZ: false })],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(canonical.rotation).toBe(0);
|
||||
expect(canonical.rotationX).toBe(0);
|
||||
expect(canonical.rotationZ).toBe(45);
|
||||
expect(canonical.mirrorX).toBeUndefined();
|
||||
expect(canonical.mirrorY).toBe(true);
|
||||
expect(canonical.groupedShapes?.[0].rotation).toBe(0);
|
||||
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps shallow equality strict for shape payload references", () => {
|
||||
const importedMesh = { positions: [0, 0, 0], baseWidth: 1, baseDepth: 1, baseHeight: 1, triangleCount: 0, sourceFormat: "json" as const };
|
||||
const first = shape({ importedMesh });
|
||||
const sameReference = shape({ importedMesh });
|
||||
const sameValues = shape({ importedMesh: { ...importedMesh, positions: [...importedMesh.positions] } });
|
||||
|
||||
expect(workplaneShapesEqual(first, sameReference)).toBe(true);
|
||||
expect(workplaneShapesEqual(first, sameValues)).toBe(false);
|
||||
});
|
||||
|
||||
it("serializes canonical shapes for sync", () => {
|
||||
expect(JSON.parse(serializeShapesForSync([shape({ rotation: 359.9, mirrorX: false })]))).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "box-1",
|
||||
rotation: 0,
|
||||
rotationX: 0,
|
||||
rotationZ: 0,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("maps helper flags and fallback colors", () => {
|
||||
expect(mirrorSign(true)).toBe(-1);
|
||||
expect(mirrorSign(false)).toBe(1);
|
||||
expect(mirroredAxisCount(shape({ mirrorX: true, mirrorY: true }))).toBe(2);
|
||||
expect(fallbackSolidColor(shape({ kind: "sphere" }))).toBe("#0098c7");
|
||||
expect(fallbackSolidColor(shape({ kind: "box" }))).toBe("#d41721");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
export function normalizeDegrees(value: number) {
|
||||
return ((value % 360) + 360) % 360;
|
||||
}
|
||||
|
||||
export function cleanRotationDegrees(value: number, precision = 1) {
|
||||
if (!Number.isFinite(value)) {
|
||||
return 0;
|
||||
}
|
||||
const normalized = normalizeDegrees(value);
|
||||
const rounded = Number(normalized.toFixed(precision));
|
||||
const zeroThreshold = precision <= 1 ? 0.5 : 0.05;
|
||||
if (rounded < zeroThreshold || rounded >= 360 - zeroThreshold || Object.is(rounded, -0)) {
|
||||
return 0;
|
||||
}
|
||||
return rounded;
|
||||
}
|
||||
|
||||
export function cleanNearZero(value: number, epsilon = 0.005) {
|
||||
return Math.abs(value) < epsilon ? 0 : value;
|
||||
}
|
||||
|
||||
export function shapeWidth(shape: WorkplaneShape) {
|
||||
return shape.width ?? shape.size;
|
||||
}
|
||||
|
||||
export function shapeDepth(shape: WorkplaneShape) {
|
||||
return shape.depth ?? shape.size;
|
||||
}
|
||||
|
||||
export function resizedShapeSize(width: number, depth: number) {
|
||||
return Math.max(width, depth);
|
||||
}
|
||||
|
||||
export function proportionalResizeScale(startWidth: number, startDepth: number, nextWidth: number, nextDepth: number) {
|
||||
const widthScale = nextWidth / Math.max(0.001, startWidth);
|
||||
const depthScale = nextDepth / Math.max(0.001, startDepth);
|
||||
if (!Number.isFinite(widthScale) || !Number.isFinite(depthScale)) {
|
||||
return 1;
|
||||
}
|
||||
return Math.abs(widthScale - 1) >= Math.abs(depthScale - 1) ? widthScale : depthScale;
|
||||
}
|
||||
|
||||
export function fallbackSolidColor(shape: WorkplaneShape) {
|
||||
if (shape.kind === "cylinder") return "#d97813";
|
||||
if (shape.kind === "sphere") return "#0098c7";
|
||||
if (shape.kind === "cone") return "#6e2786";
|
||||
if (shape.kind === "pyramid") return "#f2cf10";
|
||||
return "#d41721";
|
||||
}
|
||||
|
||||
export function mirrorSign(value?: boolean) {
|
||||
return value ? -1 : 1;
|
||||
}
|
||||
|
||||
export function mirroredAxisCount(shape: WorkplaneShape) {
|
||||
return [shape.mirrorX, shape.mirrorY, shape.mirrorZ].filter(Boolean).length;
|
||||
}
|
||||
|
||||
export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
|
||||
const next: WorkplaneShape = {
|
||||
...shape,
|
||||
rotation: cleanRotationDegrees(shape.rotation ?? 0),
|
||||
rotationX: cleanRotationDegrees(shape.rotationX ?? 0),
|
||||
rotationZ: cleanRotationDegrees(shape.rotationZ ?? 0),
|
||||
mirrorX: shape.mirrorX || undefined,
|
||||
mirrorY: shape.mirrorY || undefined,
|
||||
mirrorZ: shape.mirrorZ || undefined,
|
||||
};
|
||||
if (shape.groupedShapes) {
|
||||
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function workplaneShapesEqual(a: WorkplaneShape, b: WorkplaneShape) {
|
||||
return (
|
||||
a.id === b.id &&
|
||||
a.name === b.name &&
|
||||
a.kind === b.kind &&
|
||||
a.color === b.color &&
|
||||
a.hole === b.hole &&
|
||||
a.x === b.x &&
|
||||
a.z === b.z &&
|
||||
a.elevation === b.elevation &&
|
||||
a.size === b.size &&
|
||||
a.width === b.width &&
|
||||
a.depth === b.depth &&
|
||||
a.height === b.height &&
|
||||
a.rotation === b.rotation &&
|
||||
a.rotationX === b.rotationX &&
|
||||
a.rotationZ === b.rotationZ &&
|
||||
a.mirrorX === b.mirrorX &&
|
||||
a.mirrorY === b.mirrorY &&
|
||||
a.mirrorZ === b.mirrorZ &&
|
||||
a.radius === b.radius &&
|
||||
a.steps === b.steps &&
|
||||
a.sides === b.sides &&
|
||||
a.bevel === b.bevel &&
|
||||
a.segments === b.segments &&
|
||||
a.topRadius === b.topRadius &&
|
||||
a.baseRadius === b.baseRadius &&
|
||||
a.text === b.text &&
|
||||
a.font === b.font &&
|
||||
a.importedMesh === b.importedMesh &&
|
||||
a.imagePlate === b.imagePlate &&
|
||||
a.groupedShapes === b.groupedShapes &&
|
||||
a.groupedBaseWidth === b.groupedBaseWidth &&
|
||||
a.groupedBaseDepth === b.groupedBaseDepth &&
|
||||
a.groupedBaseHeight === b.groupedBaseHeight &&
|
||||
a.locked === b.locked &&
|
||||
a.hidden === b.hidden
|
||||
);
|
||||
}
|
||||
|
||||
export function serializeShapesForSync(shapes: WorkplaneShape[]) {
|
||||
return JSON.stringify(shapes.map(canonicalizeShape));
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { WorkplaneShape } from "@/types/sketchforge";
|
||||
|
||||
type ImportedShapeFromStl = (fileName: string, buffer: ArrayBuffer) => WorkplaneShape;
|
||||
type BenchRow = {
|
||||
workload: string;
|
||||
step: string;
|
||||
triangles?: number;
|
||||
bytes?: number;
|
||||
runs: number;
|
||||
avgMs: number;
|
||||
minMs: number;
|
||||
maxMs: number;
|
||||
heapDeltaMb: number;
|
||||
};
|
||||
|
||||
const SYNTHETIC_WORKLOADS = [
|
||||
{ label: "synthetic-small", triangles: 1200 },
|
||||
{ label: "synthetic-medium", triangles: 12000 },
|
||||
{ label: "synthetic-large", triangles: 60000 },
|
||||
];
|
||||
|
||||
if (process.env.SKETCHFORGE_PERF_LARGE === "1") {
|
||||
SYNTHETIC_WORKLOADS.push({ label: "synthetic-xl", triangles: 150000 });
|
||||
}
|
||||
|
||||
function formatMs(value: number) {
|
||||
return Number(value.toFixed(2));
|
||||
}
|
||||
|
||||
function formatMb(value: number) {
|
||||
return Number(value.toFixed(2));
|
||||
}
|
||||
|
||||
function heapUsedMb() {
|
||||
return process.memoryUsage().heapUsed / 1024 / 1024;
|
||||
}
|
||||
|
||||
async function measure<T>(
|
||||
rows: BenchRow[],
|
||||
workload: string,
|
||||
step: string,
|
||||
runs: number,
|
||||
metadata: Pick<BenchRow, "triangles" | "bytes">,
|
||||
fn: () => T | Promise<T>,
|
||||
) {
|
||||
const durations: number[] = [];
|
||||
const heapBefore = heapUsedMb();
|
||||
let value: T | undefined;
|
||||
|
||||
for (let run = 0; run < runs; run += 1) {
|
||||
const start = performance.now();
|
||||
value = await fn();
|
||||
durations.push(performance.now() - start);
|
||||
}
|
||||
|
||||
const heapAfter = heapUsedMb();
|
||||
const avgMs = durations.reduce((total, duration) => total + duration, 0) / durations.length;
|
||||
rows.push({
|
||||
workload,
|
||||
step,
|
||||
...metadata,
|
||||
runs,
|
||||
avgMs,
|
||||
minMs: Math.min(...durations),
|
||||
maxMs: Math.max(...durations),
|
||||
heapDeltaMb: heapAfter - heapBefore,
|
||||
});
|
||||
|
||||
return value as T;
|
||||
}
|
||||
|
||||
function writeTriangle(view: DataView, offset: number, normal: number[], a: number[], b: number[], c: number[]) {
|
||||
const values = [...normal, ...a, ...b, ...c];
|
||||
let cursor = offset;
|
||||
values.forEach((value) => {
|
||||
view.setFloat32(cursor, value, true);
|
||||
cursor += 4;
|
||||
});
|
||||
view.setUint16(cursor, 0, true);
|
||||
return cursor + 2;
|
||||
}
|
||||
|
||||
function createSyntheticBinaryStl(requestedTriangles: number) {
|
||||
const cubeCount = Math.ceil(requestedTriangles / 12);
|
||||
const triangleCount = cubeCount * 12;
|
||||
const buffer = new ArrayBuffer(84 + triangleCount * 50);
|
||||
const view = new DataView(buffer);
|
||||
view.setUint32(80, triangleCount, true);
|
||||
|
||||
const faces = [
|
||||
{ normal: [0, 0, 1], corners: [[0, 0, 1], [1, 0, 1], [1, 1, 1], [0, 1, 1]] },
|
||||
{ normal: [0, 0, -1], corners: [[1, 0, 0], [0, 0, 0], [0, 1, 0], [1, 1, 0]] },
|
||||
{ normal: [0, 1, 0], corners: [[0, 1, 1], [1, 1, 1], [1, 1, 0], [0, 1, 0]] },
|
||||
{ normal: [0, -1, 0], corners: [[0, 0, 0], [1, 0, 0], [1, 0, 1], [0, 0, 1]] },
|
||||
{ normal: [1, 0, 0], corners: [[1, 0, 1], [1, 0, 0], [1, 1, 0], [1, 1, 1]] },
|
||||
{ normal: [-1, 0, 0], corners: [[0, 0, 0], [0, 0, 1], [0, 1, 1], [0, 1, 0]] },
|
||||
];
|
||||
|
||||
const columns = Math.ceil(Math.sqrt(cubeCount));
|
||||
let offset = 84;
|
||||
for (let cube = 0; cube < cubeCount; cube += 1) {
|
||||
const x = (cube % columns) * 1.4;
|
||||
const y = Math.floor(cube / (columns * columns)) * 1.4;
|
||||
const z = Math.floor(cube / columns) % columns * 1.4;
|
||||
const translate = ([px, py, pz]: number[]) => [px + x, py + y, pz + z];
|
||||
|
||||
faces.forEach(({ normal, corners }) => {
|
||||
const [a, b, c, d] = corners.map(translate);
|
||||
offset = writeTriangle(view, offset, normal, a, b, c);
|
||||
offset = writeTriangle(view, offset, normal, a, c, d);
|
||||
});
|
||||
}
|
||||
|
||||
return { buffer, triangleCount };
|
||||
}
|
||||
|
||||
function toArrayBuffer(bytes: Buffer) {
|
||||
const copy = new Uint8Array(bytes.byteLength);
|
||||
copy.set(bytes);
|
||||
return copy.buffer;
|
||||
}
|
||||
|
||||
function findRealStlFiles() {
|
||||
const configured = process.env.SKETCHFORGE_PERF_STL_DIR?.trim();
|
||||
if (!configured) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const directory = path.resolve(configured);
|
||||
if (!existsSync(directory) || !statSync(directory).isDirectory()) {
|
||||
throw new Error(`SKETCHFORGE_PERF_STL_DIR is not a directory: ${directory}`);
|
||||
}
|
||||
|
||||
return readdirSync(directory)
|
||||
.filter((entry) => entry.toLowerCase().endsWith(".stl"))
|
||||
.map((entry) => path.join(directory, entry))
|
||||
.filter((entry) => statSync(entry).isFile())
|
||||
.slice(0, 12);
|
||||
}
|
||||
|
||||
function printReport(rows: BenchRow[]) {
|
||||
const table = rows.map((row) => ({
|
||||
workload: row.workload,
|
||||
step: row.step,
|
||||
triangles: row.triangles ?? "",
|
||||
mb: row.bytes ? formatMb(row.bytes / 1024 / 1024) : "",
|
||||
runs: row.runs,
|
||||
avgMs: formatMs(row.avgMs),
|
||||
minMs: formatMs(row.minMs),
|
||||
maxMs: formatMs(row.maxMs),
|
||||
heapDeltaMb: formatMb(row.heapDeltaMb),
|
||||
msPer10kTriangles: row.triangles ? formatMs((row.avgMs / row.triangles) * 10000) : "",
|
||||
}));
|
||||
|
||||
const bottlenecks = [...table].sort((a, b) => Number(b.avgMs) - Number(a.avgMs)).slice(0, 8);
|
||||
const totalsByStep = new Map<string, number>();
|
||||
rows.forEach((row) => totalsByStep.set(row.step, (totalsByStep.get(row.step) ?? 0) + row.avgMs));
|
||||
const stepTotals = [...totalsByStep.entries()]
|
||||
.map(([step, totalMs]) => ({ step, totalMs: formatMs(totalMs) }))
|
||||
.sort((a, b) => Number(b.totalMs) - Number(a.totalMs));
|
||||
|
||||
console.log("\nSketchForge STL performance report");
|
||||
console.log("Tip: set SKETCHFORGE_PERF_STL_DIR=C:\\path\\to\\stls to include real STL files.");
|
||||
console.table(table);
|
||||
console.log("\nRanked bottlenecks by average duration");
|
||||
console.table(bottlenecks);
|
||||
console.log("\nTotal time by pipeline step");
|
||||
console.table(stepTotals);
|
||||
}
|
||||
|
||||
describe("STL performance benchmark", () => {
|
||||
it("measures import and local-first persistence costs", async () => {
|
||||
const rows: BenchRow[] = [];
|
||||
const stlModule = await measure(rows, "startup", "load STL import module", 1, {}, () => import("../lib/stlImport"));
|
||||
const importedShapeFromStl = stlModule.importedShapeFromStl as ImportedShapeFromStl;
|
||||
|
||||
for (const workload of SYNTHETIC_WORKLOADS) {
|
||||
const stl = await measure(rows, workload.label, "generate synthetic binary STL", 1, { triangles: workload.triangles }, () =>
|
||||
createSyntheticBinaryStl(workload.triangles),
|
||||
);
|
||||
const runs = stl.triangleCount >= 60000 ? 2 : 3;
|
||||
const shape = await measure(rows, workload.label, "import STL into WorkplaneShape", runs, { triangles: stl.triangleCount, bytes: stl.buffer.byteLength }, () =>
|
||||
importedShapeFromStl(`${workload.label}.stl`, stl.buffer),
|
||||
);
|
||||
expect(shape.importedMesh?.triangleCount).toBe(stl.triangleCount);
|
||||
|
||||
const json = await measure(rows, workload.label, "serialize shape JSON", runs, { triangles: stl.triangleCount }, () => JSON.stringify(shape));
|
||||
await measure(rows, workload.label, "parse shape JSON", runs, { triangles: stl.triangleCount, bytes: json.length }, () => JSON.parse(json));
|
||||
}
|
||||
|
||||
for (const filePath of findRealStlFiles()) {
|
||||
const label = `real-${path.basename(filePath)}`;
|
||||
const bytes = await measure(rows, label, "read STL file", 1, { bytes: statSync(filePath).size }, () => readFileSync(filePath));
|
||||
const shape = await measure(rows, label, "import STL into WorkplaneShape", 2, { bytes: bytes.byteLength }, () =>
|
||||
importedShapeFromStl(path.basename(filePath), toArrayBuffer(bytes)),
|
||||
);
|
||||
const triangles = shape.importedMesh?.triangleCount ?? 0;
|
||||
expect(triangles).toBeGreaterThan(0);
|
||||
const json = await measure(rows, label, "serialize shape JSON", 2, { triangles }, () => JSON.stringify(shape));
|
||||
await measure(rows, label, "parse shape JSON", 2, { triangles, bytes: json.length }, () => JSON.parse(json));
|
||||
}
|
||||
|
||||
printReport(rows);
|
||||
});
|
||||
});
|
||||
@@ -16,8 +16,6 @@ export type ShapeKind =
|
||||
| "wedge"
|
||||
| "polygon"
|
||||
| "icosahedron"
|
||||
| "star"
|
||||
| "heart"
|
||||
| "mesh";
|
||||
|
||||
export type ShapeAsset = {
|
||||
|
||||
Generated
+872
-5
File diff suppressed because it is too large
Load Diff
+7
-2
@@ -7,7 +7,11 @@
|
||||
"build": "next build apps/web",
|
||||
"export": "set STATIC_EXPORT=true&& next build apps/web",
|
||||
"start": "next start apps/web",
|
||||
"typecheck": "tsc -p apps/web/tsconfig.json --noEmit"
|
||||
"typecheck": "tsc -p apps/web/tsconfig.json --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"perf": "vitest run --config vitest.perf.config.ts --reporter verbose",
|
||||
"ci": "npm run typecheck && npm run test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/postcss": "^4.1.8",
|
||||
@@ -27,6 +31,7 @@
|
||||
"@types/node": "^22.15.18",
|
||||
"@types/react": "^19.1.4",
|
||||
"@types/react-dom": "^19.1.5",
|
||||
"typescript": "^5.8.3"
|
||||
"typescript": "^5.8.3",
|
||||
"vitest": "^4.1.8"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import path from "node:path";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "apps/web/src"),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: "node",
|
||||
include: ["apps/web/src/**/*.test.ts"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import path from "node:path";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(__dirname, "apps/web/src"),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: "node",
|
||||
include: ["apps/web/src/perf/**/*.perf.ts"],
|
||||
testTimeout: 120000,
|
||||
hookTimeout: 120000,
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user