release: publish v1.0.0

This commit is contained in:
Formsmith
2026-08-10 16:15:32 +03:00
parent decf33521a
commit a42922c4f3
56 changed files with 3914 additions and 125 deletions
+166
View File
@@ -0,0 +1,166 @@
import { timingSafeEqual } from "node:crypto";
import { NextResponse } from "next/server";
import { appUpdateIsAvailable, OFFICIAL_UPDATE_GUIDE_URL, type AppUpdateStatus } from "@/lib/appUpdates";
import { SKF_CREATED_WITH_VERSION } from "@/lib/skfProject";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export const revalidate = false;
const DEFAULT_MANIFEST_URL = "https://raw.githubusercontent.com/Formsmith746/SketchForge-3D/main/package.json";
const UPDATE_CACHE_MS = 5 * 60 * 1000;
const UPDATE_TRIGGER_COOLDOWN_MS = 15 * 1000;
let cachedLatest: { version: string; expiresAt: number } | null = null;
let nextTriggerAt = 0;
function sameOriginRequest(request: Request) {
const origin = request.headers.get("origin");
if (!origin) return true;
try {
const requestUrl = new URL(request.url);
const forwardedHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim();
const forwardedProtocol = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
const host = forwardedHost || request.headers.get("host") || requestUrl.host;
const protocol = forwardedProtocol || requestUrl.protocol.replace(/:$/, "");
return new URL(origin).origin === `${protocol}://${host}`;
} catch {
return false;
}
}
function safeEqual(left: string, right: string) {
const leftBytes = Buffer.from(left);
const rightBytes = Buffer.from(right);
return leftBytes.length === rightBytes.length && timingSafeEqual(leftBytes, rightBytes);
}
function updateTriggerUrl() {
const configured = process.env.SKETCHFORGE_UPDATE_TRIGGER_URL?.trim();
if (!configured) return null;
try {
const url = new URL(configured);
return url.protocol === "http:" || url.protocol === "https:" ? url : null;
} catch {
return null;
}
}
async function latestOfficialVersion(force = false) {
if (!force && cachedLatest && cachedLatest.expiresAt > Date.now()) return cachedLatest.version;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 7_500);
try {
const response = await fetch(process.env.SKETCHFORGE_UPDATE_MANIFEST_URL?.trim() || DEFAULT_MANIFEST_URL, {
cache: "no-store",
headers: { Accept: "application/json", "User-Agent": "SketchForge update checker" },
signal: controller.signal,
});
if (!response.ok) throw new Error(`Update server returned ${response.status}`);
const payload = await response.json() as { version?: unknown };
const version = typeof payload.version === "string" ? payload.version.trim() : "";
if (!/^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) {
throw new Error("Update server returned an invalid version");
}
cachedLatest = { version, expiresAt: Date.now() + UPDATE_CACHE_MS };
return version;
} finally {
clearTimeout(timeout);
}
}
function updateGuideUrl() {
return process.env.SKETCHFORGE_UPDATE_GUIDE_URL?.trim() || OFFICIAL_UPDATE_GUIDE_URL;
}
async function statusResponse(force = false): Promise<AppUpdateStatus> {
const trigger = updateTriggerUrl();
const adminKeyConfigured = Boolean(process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim());
try {
const latestVersion = await latestOfficialVersion(force);
return {
currentVersion: SKF_CREATED_WITH_VERSION,
latestVersion,
updateAvailable: appUpdateIsAvailable(SKF_CREATED_WITH_VERSION, latestVersion),
checkedAt: new Date().toISOString(),
updateUrl: updateGuideUrl(),
installationReady: Boolean(trigger && adminKeyConfigured),
requiresUpdateKey: Boolean(trigger && adminKeyConfigured),
};
} catch (error) {
return {
currentVersion: SKF_CREATED_WITH_VERSION,
latestVersion: null,
updateAvailable: false,
checkedAt: new Date().toISOString(),
updateUrl: updateGuideUrl(),
installationReady: Boolean(trigger && adminKeyConfigured),
requiresUpdateKey: Boolean(trigger && adminKeyConfigured),
checkError: error instanceof Error ? error.message : "Could not check for updates",
};
}
}
export async function GET(request: Request) {
const force = new URL(request.url).searchParams.get("force") === "1";
return NextResponse.json(await statusResponse(force), { headers: { "Cache-Control": "no-store" } });
}
export async function POST(request: Request) {
if (!sameOriginRequest(request)) return NextResponse.json({ error: "Updates only accept same-origin requests" }, { status: 403 });
const trigger = updateTriggerUrl();
const adminKey = process.env.SKETCHFORGE_UPDATE_ADMIN_KEY?.trim() || "";
if (!trigger || !adminKey) {
return NextResponse.json(
{ error: "One-click installation is not configured on this server", updateUrl: updateGuideUrl() },
{ status: 409 },
);
}
const suppliedKey = request.headers.get("x-sketchforge-update-key")?.trim() || "";
if (!suppliedKey || !safeEqual(suppliedKey, adminKey)) {
return NextResponse.json({ error: "The update key is incorrect" }, { status: 401 });
}
if (Date.now() < nextTriggerAt) {
return NextResponse.json({ error: "An update was already requested. Wait a moment before trying again." }, { status: 429 });
}
const status = await statusResponse(true);
if (status.checkError) return NextResponse.json({ error: status.checkError }, { status: 502 });
if (!status.updateAvailable || !status.latestVersion) {
return NextResponse.json({ error: "SketchForge is already up to date", status }, { status: 409 });
}
nextTriggerAt = Date.now() + UPDATE_TRIGGER_COOLDOWN_MS;
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10_000);
try {
const triggerToken = process.env.SKETCHFORGE_UPDATE_TRIGGER_TOKEN?.trim();
const response = await fetch(trigger, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
...(triggerToken ? { Authorization: `Bearer ${triggerToken}` } : {}),
},
body: JSON.stringify({
application: "SketchForge",
currentVersion: status.currentVersion,
latestVersion: status.latestVersion,
preserveProjectStorage: true,
}),
cache: "no-store",
signal: controller.signal,
});
if (!response.ok) throw new Error(`Update service returned ${response.status}`);
return NextResponse.json(
{ accepted: true, currentVersion: status.currentVersion, latestVersion: status.latestVersion },
{ status: 202, headers: { "Cache-Control": "no-store" } },
);
} catch (error) {
nextTriggerAt = 0;
return NextResponse.json({ error: error instanceof Error ? error.message : "Could not start the update" }, { status: 502 });
} finally {
clearTimeout(timeout);
}
}
File diff suppressed because it is too large Load Diff
+230 -10
View File
@@ -1,9 +1,12 @@
"use client";
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
import { Clock3, EllipsisVertical, FileUp, FolderKanban, Grid3X3, HomeIcon, List, Palette, Pencil, Plus, RefreshCw, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import ChallengesDashboard from "@/components/official/ChallengesDashboard";
import { applyAppTheme, readStoredAppTheme, resolveAppTheme, storeAppTheme, type AppThemePreference, type ResolvedAppTheme } from "@/lib/appTheme";
import type { AppUpdateStatus } from "@/lib/appUpdates";
import { isChallengeTutorialId, type ChallengeTutorialId } from "@/lib/challenges";
import { hydrateEditorHistoryState, type EditorHistoryEntry } from "@/lib/editorHistory";
import { createLocalId } from "@/lib/localIds";
import {
@@ -21,7 +24,7 @@ import type { GridSize, ProjectAsset, WorkplaneShape, WorkplaneWorkspaceSettings
type AppView = "dashboard" | "editor";
type ViewMode = "grid" | "list";
type DashboardSection = "home" | "shared" | "challenges";
type DashboardSection = "home" | "shared" | "challenges" | "customization";
type DownloadMode = "browser" | "folder";
type DashboardProject = {
@@ -107,8 +110,11 @@ const PROJECT_SHAPES_STORE_NAME = "projectShapes";
const PROJECT_SHAPE_RESOURCES_STORE_NAME = "projectShapeResources";
const DOWNLOAD_MODE_STORAGE_KEY = "sketchForge.downloadMode";
const DOWNLOAD_FOLDER_STORAGE_KEY = "sketchForge.downloadFolder";
const ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY = "sketchForge.activeChallengeTutorial";
const DISMISSED_UPDATE_VERSION_STORAGE_KEY = "sketchForge.dismissedUpdateVersion";
const PROJECT_ACCENTS: DashboardProject["accent"][] = ["cyan", "green", "gold", "red"];
const STATIC_EXPORT_BUILD = process.env.NEXT_PUBLIC_STATIC_EXPORT === "true";
const SOURCE_CODE_URL = process.env.NEXT_PUBLIC_SOURCE_CODE_URL?.trim() || "https://github.com/Formsmith746/SketchForge-3D";
const EDITOR_SKELETON_MIN_DURATION_MS = 320;
const knownProjectResourceKeys = new Map<string, Set<string>>();
@@ -507,6 +513,7 @@ export default function Home() {
const [sharedProjects, setSharedProjects] = useState<SharedProject[]>([]);
const [sharedProjectsEnabled, setSharedProjectsEnabled] = useState(false);
const [sharedProjectsLoading, setSharedProjectsLoading] = useState(false);
const [activeChallengeTutorial, setActiveChallengeTutorial] = useState<ChallengeTutorialId | null>(null);
const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({});
const projectsJsonRef = useRef("");
const dashboardImportInputRef = useRef<HTMLInputElement | null>(null);
@@ -562,6 +569,14 @@ export default function Home() {
const requestedProjectId = params.get("project");
if (requestedProjectId && storedProjects.some((project) => project.id === requestedProjectId)) {
setActiveProjectId(requestedProjectId);
try {
const storedChallenge = JSON.parse(window.localStorage.getItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY) ?? "null") as { projectId?: string; tutorial?: ChallengeTutorialId } | null;
if (storedChallenge?.projectId === requestedProjectId && isChallengeTutorialId(storedChallenge.tutorial)) {
setActiveChallengeTutorial(storedChallenge.tutorial);
}
} catch {
window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY);
}
}
startEditorTransition();
setEditorStarted(true);
@@ -704,7 +719,7 @@ export default function Home() {
return sortMode === "name" ? [...filtered].sort((a, b) => a.name.localeCompare(b.name)) : [...filtered].sort((a, b) => b.updatedAt - a.updatedAt);
}, [query, sharedProjects, sortMode]);
const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean } = {}) => {
const openEditor = (projectId: string | null, options: { allowMissingFromStorage?: boolean; challengeTutorial?: ChallengeTutorialId | null } = {}) => {
if (projectId && typeof window !== "undefined" && !options.allowMissingFromStorage) {
const storedProjects = readProjects();
const storedProject = storedProjects.find((project) => project.id === projectId);
@@ -720,6 +735,25 @@ export default function Home() {
setProjects((current) => current.map((project) => (project.id === projectId ? { ...project, updatedAt: Date.now() } : project)));
}
startEditorTransition();
let nextChallengeTutorial = options.challengeTutorial ?? null;
if (typeof window !== "undefined" && projectId) {
if (nextChallengeTutorial) {
window.localStorage.setItem(
ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY,
JSON.stringify({ projectId, tutorial: nextChallengeTutorial }),
);
} else {
try {
const storedChallenge = JSON.parse(window.localStorage.getItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY) ?? "null") as { projectId?: string; tutorial?: ChallengeTutorialId } | null;
if (storedChallenge?.projectId === projectId && isChallengeTutorialId(storedChallenge.tutorial)) {
nextChallengeTutorial = storedChallenge.tutorial;
}
} catch {
window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY);
}
}
}
setActiveChallengeTutorial(nextChallengeTutorial);
setActiveProjectId(projectId);
setEditorStarted(true);
setView("editor");
@@ -884,7 +918,7 @@ export default function Home() {
});
}, []);
const createAndOpenProject = (name?: string) => {
const createAndOpenProject = (name?: string, challengeTutorial: ChallengeTutorialId | null = null) => {
const project = newProject(name ?? `Untitled design ${projects.length + 1}`, projects.length);
setProjectShapesById((current) => ({
...current,
@@ -898,7 +932,7 @@ export default function Home() {
setDashboardNotice("Could not prepare project shape storage");
});
setProjects((current) => [project, ...current]);
openEditor(project.id, { allowMissingFromStorage: true });
openEditor(project.id, { allowMissingFromStorage: true, challengeTutorial });
};
const openSkfProjectFromFile = useCallback(async (file: File, sharedProject?: SharedProject) => {
@@ -1072,6 +1106,7 @@ export default function Home() {
setProjects((current) => current.map((project) => (project.id === activeProjectId ? { ...project, updatedAt: Date.now() } : project)));
}
setDashboardSection("home");
setActiveChallengeTutorial(null);
setEditorLoading(false);
setView("dashboard");
if (typeof window !== "undefined") {
@@ -1158,6 +1193,7 @@ export default function Home() {
viewMode={viewMode}
onCloseSettings={() => setSettingsOpen(false)}
onCreate={() => createAndOpenProject()}
onStartChallenge={(challenge) => createAndOpenProject(challenge === "nameplate" ? "Personalized Nameplate" : "Key Tag", challenge)}
onDeleteProject={deleteProject}
onDownloadFolderChange={setDownloadFolder}
onDownloadModeChange={setDownloadMode}
@@ -1166,6 +1202,10 @@ export default function Home() {
setDashboardSection("challenges");
setDashboardNotice("");
}}
onCustomization={() => {
setDashboardSection("customization");
setDashboardNotice("");
}}
onDashboardHome={() => setDashboardSection("home")}
onOpenSharedProject={(project) => void openSharedProject(project)}
onOpenProject={openEditor}
@@ -1206,6 +1246,11 @@ export default function Home() {
projectModifiedAt={activeProject?.updatedAt}
projectRevision={activeProjectShapeEntry?.revision ?? activeProject?.revision ?? 0}
sharedProjectsEnabled={sharedProjectsEnabled}
challengeTutorial={activeChallengeTutorial}
onChallengeTutorialFinish={() => {
setActiveChallengeTutorial(null);
window.localStorage.removeItem(ACTIVE_CHALLENGE_TUTORIAL_STORAGE_KEY);
}}
themePreference={themePreference}
resolvedTheme={resolvedTheme}
onThemePreferenceChange={setThemePreference}
@@ -1302,11 +1347,13 @@ function Dashboard({
viewMode,
onCloseSettings,
onCreate,
onStartChallenge,
onDeleteProject,
onDownloadFolderChange,
onDownloadModeChange,
onImportFile,
onChallenges,
onCustomization,
onDashboardHome,
onOpenSharedProject,
onOpenProject,
@@ -1334,11 +1381,13 @@ function Dashboard({
viewMode: ViewMode;
onCloseSettings: () => void;
onCreate: () => void;
onStartChallenge: (challenge: ChallengeTutorialId) => void;
onDeleteProject: (projectId: string) => void;
onDownloadFolderChange: (value: string) => void;
onDownloadModeChange: (value: DownloadMode) => void;
onImportFile: () => void;
onChallenges: () => void;
onCustomization: () => void;
onDashboardHome: () => void;
onOpenSharedProject: (project: SharedProject) => void;
onOpenProject: (projectId: string) => void;
@@ -1355,6 +1404,13 @@ function Dashboard({
const [projectPendingDeleteId, setProjectPendingDeleteId] = useState<string | null>(null);
const [projectPendingRenameId, setProjectPendingRenameId] = useState<string | null>(null);
const [projectNameDraft, setProjectNameDraft] = useState("");
const [updateStatus, setUpdateStatus] = useState<AppUpdateStatus | null>(null);
const [updateChecking, setUpdateChecking] = useState(false);
const [updatePromptOpen, setUpdatePromptOpen] = useState(false);
const [updateKey, setUpdateKey] = useState("");
const [updateStarting, setUpdateStarting] = useState(false);
const [updateMessage, setUpdateMessage] = useState("");
const updateCheckedRef = useRef(false);
const projectPendingDelete = projects.find((project) => project.id === projectPendingDeleteId) ?? null;
const projectPendingRename = projects.find((project) => project.id === projectPendingRenameId) ?? null;
@@ -1387,6 +1443,79 @@ function Dashboard({
closeProjectRename();
};
const checkForUpdates = useCallback(async (force: boolean, alwaysPrompt: boolean) => {
if (staticExportBuild) return;
setUpdateChecking(true);
setUpdateMessage("");
try {
const response = await fetch(`/api/app-update${force ? "?force=1" : ""}`, { cache: "no-store" });
const payload = await response.json() as AppUpdateStatus & { error?: string };
if (!response.ok) throw new Error(payload.error || "Could not check for updates");
setUpdateStatus(payload);
if (payload.updateAvailable && payload.latestVersion) {
const dismissedVersion = window.localStorage.getItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY);
if (alwaysPrompt || dismissedVersion !== payload.latestVersion) {
onCloseSettings();
setUpdatePromptOpen(true);
}
} else if (alwaysPrompt && !payload.checkError) {
setUpdateMessage("SketchForge is up to date.");
}
} catch (error) {
setUpdateMessage(error instanceof Error ? error.message : "Could not check for updates");
} finally {
setUpdateChecking(false);
}
}, [onCloseSettings, staticExportBuild]);
useEffect(() => {
if (staticExportBuild || updateCheckedRef.current) return;
updateCheckedRef.current = true;
void checkForUpdates(false, false);
}, [checkForUpdates, staticExportBuild]);
const dismissUpdate = () => {
if (updateStatus?.latestVersion) {
window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion);
}
setUpdatePromptOpen(false);
setUpdateKey("");
setUpdateMessage("");
};
const requestUpdate = async () => {
if (!updateStatus?.updateAvailable) return;
if (!updateStatus.installationReady) {
window.open(updateStatus.updateUrl, "_blank", "noopener,noreferrer");
dismissUpdate();
return;
}
if (updateStatus.requiresUpdateKey && !updateKey.trim()) {
setUpdateMessage("Enter the server update key to continue.");
return;
}
setUpdateStarting(true);
setUpdateMessage("");
try {
const response = await fetch("/api/app-update", {
method: "POST",
headers: { "x-sketchforge-update-key": updateKey.trim() },
});
const payload = await response.json() as { accepted?: boolean; error?: string; updateUrl?: string };
if (!response.ok || !payload.accepted) throw new Error(payload.error || "Could not start the update");
if (updateStatus.latestVersion) {
window.localStorage.setItem(DISMISSED_UPDATE_VERSION_STORAGE_KEY, updateStatus.latestVersion);
}
setUpdateMessage("Update started. The server may briefly go offline; reopen this page after it restarts.");
setUpdateKey("");
} catch (error) {
setUpdateMessage(error instanceof Error ? error.message : "Could not start the update");
} finally {
setUpdateStarting(false);
}
};
return (
<main className="dashboard-shell">
<header className="dashboard-topbar">
@@ -1421,15 +1550,23 @@ function Dashboard({
<SlidersHorizontal size={20} />
<span>Challenges</span>
</button>
<button className={`dashboard-nav-item ${dashboardSection === "customization" ? "active" : ""}`} type="button" aria-label="Customization" title="Customization" onClick={onCustomization}>
<Palette size={20} />
<span>Customization</span>
</button>
</div>
<div className="dashboard-sidebar-footer">
<button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Settings" title="Settings" onClick={onOpenSettings}>
<Settings size={20} />
<span>Settings</span>
</button>
</div>
<button className="dashboard-nav-item dashboard-settings-button" type="button" aria-label="Settings" title="Settings" onClick={onOpenSettings}>
<Settings size={20} />
<span>Settings</span>
</button>
</aside>
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : dashboardSection === "shared" ? "Shared projects" : "Dashboard"}>
<section className="dashboard-main" aria-label={dashboardSection === "challenges" ? "Challenges" : dashboardSection === "shared" ? "Shared projects" : dashboardSection === "customization" ? "Customization" : "Dashboard"}>
{dashboardSection === "challenges" ? (
<ChallengesDashboard onStartChallenge={onStartChallenge} />
) : dashboardSection === "customization" ? (
<div className="dashboard-coming-soon" role="status">
<strong>Coming soon</strong>
</div>
@@ -1634,6 +1771,49 @@ function Dashboard({
</section>
) : null}
{updatePromptOpen && updateStatus?.updateAvailable && updateStatus.latestVersion ? (
<section className="dashboard-confirm-overlay" role="dialog" aria-modal="true" aria-labelledby="app-update-title">
<div className="dashboard-confirm-dialog dashboard-update-dialog">
<header>
<strong id="app-update-title">SketchForge {updateStatus.latestVersion} is available</strong>
<button type="button" aria-label="Dismiss update" onClick={dismissUpdate} disabled={updateStarting}>
<X size={18} />
</button>
</header>
<div className="dashboard-update-copy">
<p>Do you want to update from version {updateStatus.currentVersion}?</p>
<div className="dashboard-update-safety">
Your projects are kept. Private projects stay in this browser, and Docker shared projects remain in the persistent <code>/data/projects</code> volume.
</div>
{!updateStatus.installationReady ? (
<div className="dashboard-update-note">One-click installation is not configured on this server. Continue to the safe update guide.</div>
) : null}
{updateStatus.requiresUpdateKey ? (
<label className="dashboard-update-key">
<span>Server update key</span>
<input
type="password"
autoComplete="off"
value={updateKey}
onChange={(event) => setUpdateKey(event.currentTarget.value)}
disabled={updateStarting}
/>
</label>
) : null}
{updateMessage ? <div className="dashboard-update-message" role="status">{updateMessage}</div> : null}
</div>
<div className="dashboard-confirm-actions">
<button className="dashboard-confirm-cancel" type="button" onClick={dismissUpdate} disabled={updateStarting}>
Not now
</button>
<button className="dashboard-confirm-save" type="button" onClick={() => void requestUpdate()} disabled={updateStarting}>
{updateStarting ? "Starting…" : updateStatus.installationReady ? "Update" : "Open update guide"}
</button>
</div>
</div>
</section>
) : null}
{settingsOpen ? (
<section className="dashboard-settings-panel" role="dialog" aria-modal="true" aria-label="Settings">
<header>
@@ -1665,6 +1845,46 @@ function Dashboard({
<span>SketchForge version</span>
<strong>{SKF_CREATED_WITH_VERSION}</strong>
</div>
<section className="dashboard-update-settings" aria-label="Software updates">
<div>
<strong>Software updates</strong>
<span>Updates are checked automatically but are never installed without your approval.</span>
</div>
{staticExportBuild ? (
<span className="dashboard-update-status">Managed by the website owner</span>
) : updateStatus?.checkError ? (
<span className="dashboard-update-status error">{updateStatus.checkError}</span>
) : updateStatus?.updateAvailable && updateStatus.latestVersion ? (
<button
className="dashboard-update-available"
type="button"
onClick={() => {
onCloseSettings();
setUpdateMessage("");
setUpdatePromptOpen(true);
}}
>
Update to {updateStatus.latestVersion}
</button>
) : updateStatus ? (
<span className="dashboard-update-status ready">Up to date</span>
) : null}
{!staticExportBuild ? (
<button className="dashboard-check-update" type="button" onClick={() => void checkForUpdates(true, true)} disabled={updateChecking}>
<RefreshCw size={15} className={updateChecking ? "spin" : ""} />
<span>{updateChecking ? "Checking…" : "Check for updates"}</span>
</button>
) : null}
{updateMessage && settingsOpen ? <span className="dashboard-update-status" role="status">{updateMessage}</span> : null}
</section>
<div className="dashboard-version-row">
<span>License</span>
<a href="https://www.gnu.org/licenses/agpl-3.0.html" target="_blank" rel="noreferrer">AGPLv3</a>
</div>
<div className="dashboard-version-row">
<span>Corresponding source</span>
<a href={SOURCE_CODE_URL} target="_blank" rel="noreferrer">View source</a>
</div>
</section>
) : null}
</main>
+121 -60
View File
@@ -16,6 +16,7 @@ import gentilisBoldFontJson from "three/examples/fonts/gentilis_bold.typeface.js
import helvetikerBoldFontJson from "three/examples/fonts/helvetiker_bold.typeface.json";
import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json";
import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme";
import type { ChallengeTutorialId } from "@/lib/challenges";
import { manifoldModuleSource } from "@/generated/manifoldModuleSource";
import { manifoldWasmBase64 } from "@/generated/manifoldWasmBase64";
import { sphereTessellation } from "@/lib/sphereTessellation";
@@ -84,12 +85,14 @@ import { appendEditorHistorySnapshot, boundedEditorHistoryState, editorHistoryEn
import { snapShapeFootprintToVisibleGrid, visibleGridStep } from "@/lib/gridSnap";
import { createLocalId } from "@/lib/localIds";
import { projectExportFileName } from "@/lib/exportNames";
import { exportMeshesToObj } from "@/lib/objExport";
import { attachProjectAsset, dedupeProjectAssets, projectAssetFromBytes, sourceFormatForFileName } from "@/lib/projectAssets";
import { findSketchOutlineIntersection } from "@/lib/sketchProfileValidation";
import { buildSketchRevolveMesh, DEFAULT_SKETCH_REVOLVE_SETTINGS, normalizeSketchRevolveSettings, type SketchRevolveMesh } from "@/lib/sketchRevolve";
import { exportSkfProject, SKF_MEDIA_TYPE } from "@/lib/skfProject";
import { makeShapeFromAsset, sceneShape, toolbarShapeAssets, type ToolbarShapeAsset } from "@/lib/shapeCatalog";
import { importedShapeFromStl, importExtensionSupported } from "@/lib/stlImport";
import { exportMeshesToStl } from "@/lib/stlExport";
import { importedShapeFromSvg, invalidSvgMeshReason } from "@/lib/svgImport";
import { toSvgProjection, type SvgProjectionLayer } from "@/lib/svgExport";
import { normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint } from "@/lib/workplaneSettings";
@@ -113,6 +116,7 @@ import {
type SketchForgeMcpViewFace,
} from "@/lib/sketchforgeMcpProtocol";
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { SketchCadBuildResponse } from "@/lib/sketchCadTypes";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ProjectAsset, ShapeAsset, SketchImage, SketchOperation, SketchPoint, SketchProfile, SketchRevolveSettings, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export { importedShapeFromStl, importedShapeFromSvg };
@@ -529,6 +533,76 @@ async function shapeFromSketchProfile(profile: SketchProfile, height: number, ex
} satisfies WorkplaneShape);
}
let sketchCadWorker: Worker | null = null;
let sketchCadRequestId = 0;
const sketchCadPending = new Map<number, {
resolve: (response: SketchCadBuildResponse) => void;
reject: (error: Error) => void;
timer: number;
}>();
function ensureSketchCadWorker() {
if (sketchCadWorker) return sketchCadWorker;
const worker = new Worker(new URL("../workers/sketchCad.worker.ts", import.meta.url), { type: "module" });
worker.onmessage = (event: MessageEvent<SketchCadBuildResponse>) => {
const pending = sketchCadPending.get(event.data.requestId);
if (!pending) return;
window.clearTimeout(pending.timer);
sketchCadPending.delete(event.data.requestId);
pending.resolve(event.data);
};
worker.onerror = () => {
sketchCadPending.forEach((pending) => {
window.clearTimeout(pending.timer);
pending.reject(new Error("The OpenCascade sketch worker failed to start"));
});
sketchCadPending.clear();
worker.terminate();
sketchCadWorker = null;
};
sketchCadWorker = worker;
return worker;
}
async function cadShapeFromSketchProfile(profile: SketchProfile, height: number, existing?: WorkplaneShape | null) {
const safeHeight = Math.max(MIN_SHAPE_DIMENSION, height);
const worker = ensureSketchCadWorker();
const requestId = ++sketchCadRequestId;
const response = await new Promise<SketchCadBuildResponse>((resolve, reject) => {
const timer = window.setTimeout(() => {
sketchCadPending.delete(requestId);
reject(new Error("OpenCascade timed out while building the sketch"));
}, 30_000);
sketchCadPending.set(requestId, { resolve, reject, timer });
worker.postMessage({ type: "build", requestId, profile: cloneSketchProfile(profile), height: safeHeight });
});
if (response.type === "error") throw new Error(response.message);
const source = canonicalizeShape({
...(existing ?? {
id: createLocalId("sketch-extrusion"),
name: "Sketch extrusion",
kind: "mesh" as const,
color: "#d41721",
x: 0,
z: 0,
size: 1,
width: 1,
depth: 1,
height: safeHeight,
rotation: 0,
}),
sketchProfile: cloneSketchProfile(profile),
sketchOperation: "extrude",
edgeTreatments: undefined,
edgeTreatmentHistory: undefined,
cadDisplayEdges: undefined,
cadDisplayEdgesVersion: undefined,
});
const shape = shapeFromCadMesh(source, response.positions, response.normals, response.indices, response.brep);
if (!shape) throw new Error("OpenCascade returned an empty sketch solid");
return { ...shape, sketchProfile: cloneSketchProfile(profile), sketchOperation: "extrude" as const };
}
async function shapeFromRevolvedSketchProfile(
profile: SketchProfile,
settings: Partial<SketchRevolveSettings>,
@@ -2263,7 +2337,10 @@ function cadModifierPrimitiveForShape(shape: WorkplaneShape): CadModifierPrimiti
}
function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
if (!shapeHasTransformToBake(shape)) {
// Rotation is a non-destructive transform for editable text. Baking it would
// change the shape to `kind: "mesh"`, hiding the Text and Font controls even
// though the user never grouped or otherwise converted the object.
if (shape.kind === "text" || !shapeHasTransformToBake(shape)) {
return shape;
}
@@ -2459,53 +2536,6 @@ async function importedShapeFromImage(file: File): Promise<WorkplaneShape> {
};
}
function normalFor(a: Vec3, b: Vec3, c: Vec3): Vec3 {
const ux = b[0] - a[0];
const uy = b[1] - a[1];
const uz = b[2] - a[2];
const vx = c[0] - a[0];
const vy = c[1] - a[1];
const vz = c[2] - a[2];
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const length = Math.hypot(nx, ny, nz) || 1;
return [nx / length, ny / length, nz / length];
}
function toStl(meshes: MeshData[]) {
const lines = ["solid sketchforge_design"];
meshes.forEach((mesh) => {
mesh.faces.forEach(([ai, bi, ci]) => {
const a = mesh.vertices[ai];
const b = mesh.vertices[bi];
const c = mesh.vertices[ci];
const n = normalFor(a, b, c);
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
lines.push(" outer loop");
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
lines.push(" endloop");
lines.push(" endfacet");
});
});
lines.push("endsolid sketchforge_design");
return lines.join("\n");
}
function toObj(meshes: MeshData[]) {
const lines = ["# SketchForge OBJ export"];
let offset = 1;
meshes.forEach((mesh) => {
lines.push(`o ${mesh.name}`);
mesh.vertices.forEach(([x, y, z]) => lines.push(`v ${x} ${y} ${z}`));
mesh.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`));
offset += mesh.vertices.length;
});
return lines.join("\n");
}
async function toSvg(shapes: WorkplaneShape[], title: string) {
const runtime = await getManifoldRuntime();
const layers: SvgProjectionLayer[] = [];
@@ -3118,6 +3148,12 @@ function separateMeshParts(shape: WorkplaneShape) {
.filter((part): part is WorkplaneShape => Boolean(part));
}
function cadModifierSourceParts(shape: WorkplaneShape) {
if (shape.kind !== "text" || shape.importedMesh || shape.cadBrep) return [shape];
const glyphParts = separateMeshParts(shape);
return glyphParts.length > 1 ? glyphParts : [shape];
}
function separablePartCount(shape: WorkplaneShape) {
if (shape.locked || shape.hole) return 0;
if (shape.groupedShapes?.length && !shape.importedMesh) return shape.groupedShapes.length;
@@ -5279,6 +5315,8 @@ export function SketchForgeEditor({
projectModifiedAt = Date.now(),
projectRevision = 0,
sharedProjectsEnabled = false,
challengeTutorial = null,
onChallengeTutorialFinish,
themePreference = "system",
resolvedTheme = "light",
onThemePreferenceChange,
@@ -5323,6 +5361,8 @@ export function SketchForgeEditor({
projectModifiedAt?: number;
projectRevision?: number;
sharedProjectsEnabled?: boolean;
challengeTutorial?: ChallengeTutorialId | null;
onChallengeTutorialFinish?: () => void;
themePreference?: AppThemePreference;
resolvedTheme?: ResolvedAppTheme;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
@@ -6566,8 +6606,9 @@ export function SketchForgeEditor({
if (sketchOperation === "revolve") {
resolved = await shapeFromRevolvedSketchProfile(sketchProfile, sketchRevolveSettings, existing);
} else {
const extrusion = await shapeFromSketchProfile(sketchProfile, height, existing);
resolved = extrusion ? placeSketchExtrusion(extrusion, activeSketchWorkplane, existing) : null;
setNotice("Building exact sketch geometry…");
const extrusion = await cadShapeFromSketchProfile(sketchProfile, height, existing);
resolved = placeSketchExtrusion(extrusion, activeSketchWorkplane, existing);
}
} catch (error) {
setNotice(error instanceof Error ? error.message : `The sketch profile cannot be ${sketchOperation === "revolve" ? "revolved" : "extruded"} to 3D`);
@@ -6579,7 +6620,7 @@ export function SketchForgeEditor({
}
const nextShapes = existing ? shapes.map((shape) => (shape.id === existing.id ? resolved : shape)) : [...shapes, resolved];
const action = sketchOperation === "revolve" ? "Revolve sketch" : "Sketch";
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Sketch created at 10 mm height");
commitShapes(nextShapes, resolved.id, existing ? `${action} updated` : sketchOperation === "revolve" ? "Revolved sketch created" : "Exact sketch created at 10 mm height");
setSketchActive(false);
setSketchRevolvePreview(null);
setEditingSketchShapeId(null);
@@ -7072,7 +7113,9 @@ export function SketchForgeEditor({
invalidateCadModifierSession();
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(selectedShape);
const hasAppliedEdgeTreatment = Boolean(selectedShape.importedMesh && selectedShape.edgeTreatments?.length);
const sourceParts = selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(selectedShape) : [selectedShape];
const sourceParts = (selectedShape.groupedShapes?.length && !hasAppliedEdgeTreatment
? restoreGroupedChildren(selectedShape)
: [selectedShape]).flatMap(cadModifierSourceParts);
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((shape) => {
const frame = shape.cadBrepFrame;
const preserveNeedsRetessellation = preservesEdgeTreatmentSize(shape) && Boolean(frame) && (
@@ -7145,7 +7188,9 @@ export function SketchForgeEditor({
}
const appliedEdgeTreatmentCount = edgeTreatmentFeatureCount(shape);
const hasAppliedEdgeTreatment = Boolean(shape.importedMesh && shape.edgeTreatments?.length);
const sourceParts = shape.groupedShapes?.length && !hasAppliedEdgeTreatment ? restoreGroupedChildren(shape) : [shape];
const sourceParts = (shape.groupedShapes?.length && !hasAppliedEdgeTreatment
? restoreGroupedChildren(shape)
: [shape]).flatMap(cadModifierSourceParts);
const partInputs: Array<{ shape: WorkplaneShape; mesh?: MeshData; brep?: string; brepTransform?: number[]; primitive?: CadModifierPrimitivePart }> = sourceParts.map((partShape) => {
const frame = partShape.cadBrepFrame;
const preserveNeedsRetessellation = preservesEdgeTreatmentSize(partShape) && Boolean(frame) && (
@@ -7711,8 +7756,7 @@ export function SketchForgeEditor({
let shape: WorkplaneShape;
if (kind === "sketch") {
const profile = defaultMcpSketchProfile(width, depth);
const extruded = await shapeFromSketchProfile(profile, height);
if (!extruded) throw new Error("Could not create the sketch profile");
const extruded = await cadShapeFromSketchProfile(profile, height);
shape = canonicalizeShape({
...extruded,
name,
@@ -7724,7 +7768,7 @@ export function SketchForgeEditor({
rotationX: mcpNumber(params.rotationX, 0),
rotationZ: mcpNumber(params.rotationZ, 0),
});
} else if (kind === "box" || kind === "cylinder") {
} else if (kind === "box" || kind === "cylinder" || kind === "text") {
shape = sceneShape({
name,
kind,
@@ -7740,9 +7784,13 @@ export function SketchForgeEditor({
rotationX: mcpNumber(params.rotationX, 0),
rotationZ: mcpNumber(params.rotationZ, 0),
sides: kind === "cylinder" ? Math.max(3, Math.floor(mcpNumber(params.sides, 96))) : undefined,
text: kind === "text" ? mcpString(params.text, "TEXT") : undefined,
font: kind === "text" ? mcpString(params.font, "Multilanguage") : undefined,
bevel: kind === "text" ? Math.max(0, mcpNumber(params.bevel, 0)) : undefined,
segments: kind === "text" ? Math.max(1, Math.floor(mcpNumber(params.segments, 2))) : undefined,
});
} else {
throw new Error("MCP create_shape currently supports box, cube, cylinder, and sketch");
throw new Error("MCP create_shape currently supports box, cube, cylinder, text, and sketch");
}
const committedShape = canonicalizeShape(bakeShapeTransformIntoMesh(shape));
commitShapes([...currentShapes(), committedShape], committedShape.id, `${committedShape.name} added by MCP`);
@@ -7822,6 +7870,9 @@ export function SketchForgeEditor({
if (typeof params.color === "string") patch.color = params.color;
if (typeof params.name === "string") patch.name = params.name;
if (typeof params.hole === "boolean") patch.hole = params.hole;
if (typeof params.text === "string") patch.text = params.text;
if (typeof params.font === "string") patch.font = params.font;
if (typeof params.bevel === "number" && Number.isFinite(params.bevel)) patch.bevel = Math.max(0, params.bevel);
const nextShapes = currentShapes().map((shape) => {
if (shape.id !== target.id) return shape;
const patched = { ...shape, ...cleanShapePatch(patch) };
@@ -8272,12 +8323,12 @@ export function SketchForgeEditor({
}
const meshes = exportable.map(meshForShape);
if (format === "stl") {
void downloadTextFile(projectExportFileName(exportName, "stl"), toStl(meshes), "model/stl")
void downloadTextFile(projectExportFileName(exportName, "stl"), exportMeshesToStl(meshes), "model/stl")
.then((result) => finishNotice("STL", result))
.catch((error: unknown) => failNotice("STL", error));
return;
}
void downloadTextFile(projectExportFileName(exportName, "obj"), toObj(meshes), "text/plain")
void downloadTextFile(projectExportFileName(exportName, "obj"), exportMeshesToObj(meshes), "text/plain")
.then((result) => finishNotice("OBJ", result))
.catch((error: unknown) => failNotice("OBJ", error));
}, [hasSelection, projectName, selectedShapes, shapes]);
@@ -8897,6 +8948,8 @@ export function SketchForgeEditor({
modifierEdges={edgeModifier?.edges.filter((edge) => modifierAvailableEdgeIds.includes(edge.id)) ?? []}
selectedModifierEdgeIds={edgeModifier?.selectedEdgeIds ?? []}
onModifierEdgeToggle={toggleModifierEdge}
challengeTutorial={challengeTutorial}
onChallengeTutorialFinish={onChallengeTutorialFinish}
themePreference={themePreference}
resolvedTheme={resolvedTheme}
onThemePreferenceChange={onThemePreferenceChange}
@@ -9274,7 +9327,15 @@ function SecondaryToolbar({
const { icon: Icon, action, enabled, label } = tool;
const active = "active" in tool && Boolean(tool.active);
return (
<button className={`toolbar-icon ${enabled ? "" : "disabled"} ${active ? "active" : ""}`} key={label} aria-label={label} title={label} onClick={action} disabled={!enabled}>
<button
className={`toolbar-icon ${enabled ? "" : "disabled"} ${active ? "active" : ""}`}
key={label}
data-sketchforge-tool={label === "Fillet" ? "fillet" : undefined}
aria-label={label}
title={label}
onClick={action}
disabled={!enabled}
>
<Icon />
</button>
);
+2 -10
View File
@@ -608,14 +608,7 @@ export function SketchWorkspace({
const end = pointById.get(segment.endId);
return Boolean(start && end && (contains(start) || contains(end) || contains({ x: (start.x + end.x) / 2, z: (start.z + end.z) / 2 })));
}).map((segment) => segment.id);
const imageIds = (profile.images ?? []).filter((image) => {
const imageMinX = image.x - image.width / 2;
const imageMaxX = image.x + image.width / 2;
const imageMinZ = image.z - image.depth / 2;
const imageMaxZ = image.z + image.depth / 2;
return imageMaxX >= minX && imageMinX <= maxX && imageMaxZ >= minZ && imageMinZ <= maxZ;
}).map((image) => image.id);
onSelectMany(pointIds, segmentIds, imageIds);
onSelectMany(pointIds, segmentIds, []);
setPointerAction(null);
return;
}
@@ -745,7 +738,6 @@ export function SketchWorkspace({
if (event.button !== 0 || tool !== "select") return;
const point = pointFromEvent(event);
if (!point) return;
onSelectImage(image.id);
beginEntityDrag(event, {
kind: "move-image",
pointerId: event.pointerId,
@@ -989,7 +981,7 @@ export function SketchWorkspace({
<button type="button" title="Split handles" onClick={() => onSetPointMode(selectedPoint.id, "split")}><Split /><span>Split</span></button>
</div>
) : null}
<div className="grid-settings sketch-grid-settings">
<div className="grid-settings">
<SnapGridControl snap={snap} snapOpen={snapOpen} onSnapChange={setSnap} onSnapOpenChange={setSnapOpen} />
</div>
</main>
+36 -2
View File
@@ -21,8 +21,11 @@ import optimerBoldFontJson from "three/examples/fonts/optimer_bold.typeface.json
import { AlignOverlay, MirrorOverlay, type AlignOverlayState, type MirrorOverlayState } from "@/components/workplane/ActionOverlays";
import { MoveDimensionOverlay } from "@/components/workplane/MoveDimensionOverlay";
import { ShapeInspector, SnapGridControl, type ShapeInspectorUpdateOptions } from "@/components/workplane/ShapeInspector";
import { KeyTagTutorialPanel } from "@/components/workplane/KeyTagTutorialPanel";
import { NameplateTutorialPanel } from "@/components/workplane/NameplateTutorialPanel";
import { WorkspaceSettingsModal } from "@/components/workplane/WorkspaceSettingsModal";
import type { AppThemePreference, ResolvedAppTheme } from "@/lib/appTheme";
import type { ChallengeTutorialId } from "@/lib/challenges";
import { cadModifierPrimitiveForBakedShape, cadTransformFromMatrix, cadTransformToMatrix } from "@/lib/cadBakeMetadata";
import { createGearGeometry } from "@/lib/gearGeometry";
import { parseMeasurementInput } from "@/lib/measurementUnits";
@@ -201,6 +204,8 @@ type WorkplaneViewportProps = {
modifierEdges?: CadModifierEdge[];
selectedModifierEdgeIds?: number[];
onModifierEdgeToggle?: (id: number, singleEdge: boolean) => void;
challengeTutorial?: ChallengeTutorialId | null;
onChallengeTutorialFinish?: () => void;
themePreference?: AppThemePreference;
resolvedTheme?: ResolvedAppTheme;
onThemePreferenceChange?: (preference: AppThemePreference) => void;
@@ -2223,6 +2228,8 @@ export function WorkplaneViewport({
modifierEdges = [],
selectedModifierEdgeIds = [],
onModifierEdgeToggle,
challengeTutorial = null,
onChallengeTutorialFinish,
themePreference = "system",
resolvedTheme = "light",
onThemePreferenceChange,
@@ -2254,6 +2261,12 @@ export function WorkplaneViewport({
const [rulerOverlay, setRulerOverlay] = useState<RulerOverlayState | null>(null);
const [moveDimensionOverlay, setMoveDimensionOverlay] = useState<MoveDimensionOverlayState | null>(null);
const [moveDimensionsEnabled, setMoveDimensionsEnabled] = useState(true);
const [challengeTutorialCollapsed, setChallengeTutorialCollapsed] = useState(false);
useEffect(() => {
setChallengeTutorialCollapsed(false);
}, [challengeTutorial]);
const hostRef = useRef<HTMLDivElement | null>(null);
const threeRef = useRef<ThreeState | null>(null);
const shapesRef = useRef(shapes);
@@ -3220,6 +3233,7 @@ export function WorkplaneViewport({
}
return shapesRef.current
.filter((shape) => !shape.hidden)
.filter((shape) => !shape.imagePlate)
.filter((shape) => {
const bounds = shapeScreenBounds(state, shape);
return bounds ? boundsIntersectRect(bounds, rect) : false;
@@ -3778,7 +3792,12 @@ export function WorkplaneViewport({
state.raycaster.layers.set(RENDER_LAYER_SHAPES);
const intersections = state.raycaster.intersectObjects(state.shapeLayer.children, true);
const hit = intersections.find((entry) => typeof entry.object.userData.shapeId === "string");
const hit = intersections.find((entry) => {
const shapeId = entry.object.userData.shapeId;
if (typeof shapeId !== "string") return false;
const shape = shapesRef.current.find((candidate) => candidate.id === shapeId);
return shape ? !shape.imagePlate : false;
});
if (hit) {
return hit.object.userData.shapeId as string;
}
@@ -3786,6 +3805,7 @@ export function WorkplaneViewport({
let nearestId: string | null = null;
let nearestDistance = Number.POSITIVE_INFINITY;
shapesRef.current.forEach((shape) => {
if (shape.imagePlate) return;
const center = new THREE.Vector3(shape.x, (shape.elevation ?? 0) + shape.height / 2, shape.z).project(state.camera);
const screenX = rect.left + ((center.x + 1) / 2) * rect.width;
const screenY = rect.top + ((1 - center.y) / 2) * rect.height;
@@ -4757,7 +4777,7 @@ export function WorkplaneViewport({
}, [onWorkplaneModeChange, resetView, rulerToolsOpen, setPlacementWorkplaneAtSelection, setRulerActive, togglePlacementWorkplane, toggleProjection, zoomCamera]);
return (
<main className="workplane-stage">
<main className={`workplane-stage ${challengeTutorial ? `key-tag-tutorial-active ${challengeTutorialCollapsed ? "key-tag-tutorial-collapsed" : ""}` : ""}`}>
<div className="view-cube" aria-label="View orientation cube" onPointerDown={(event) => event.stopPropagation()}>
<div className="view-cube-inner" ref={viewCubeRef}>
<button type="button" className="cube-face cube-top" aria-label="Bottom view" onClick={() => setViewCubeFace("bottom")}>BOTTOM</button>
@@ -4939,6 +4959,20 @@ export function WorkplaneViewport({
onClose={() => setSettingsOpen(false)}
/>
) : null}
{challengeTutorial === "key-tag" ? (
<KeyTagTutorialPanel
onFinish={onChallengeTutorialFinish}
collapsed={challengeTutorialCollapsed}
onCollapsedChange={setChallengeTutorialCollapsed}
/>
) : challengeTutorial === "nameplate" ? (
<NameplateTutorialPanel
onFinish={onChallengeTutorialFinish}
collapsed={challengeTutorialCollapsed}
onCollapsedChange={setChallengeTutorialCollapsed}
/>
) : null}
</main>
);
}
@@ -0,0 +1,106 @@
"use client";
import { AlignCenter, Box, CircleDotDashed, Group, LockKeyhole, MoveUp, Type } from "lucide-react";
import type { ChallengeTutorialId } from "@/lib/challenges";
function KeyTagPreview() {
return (
<>
<img
className="challenge-key-tag-photo challenge-key-tag-photo-light"
src="/assets/challenges/key-tag/card-key-tag-light.webp"
alt="Finished red Key Tag model on the SketchForge workplane"
/>
<img
className="challenge-key-tag-photo challenge-key-tag-photo-dark"
src="/assets/challenges/key-tag/card-key-tag-dark.webp"
alt="Finished red Key Tag model on the dark SketchForge workplane"
/>
</>
);
}
function NameplatePreview() {
return (
<>
<img
className="challenge-key-tag-photo challenge-key-tag-photo-light"
src="/assets/challenges/nameplate/card-nameplate-light.webp"
alt="Finished blue ALEX nameplate on the SketchForge workplane"
/>
<img
className="challenge-key-tag-photo challenge-key-tag-photo-dark"
src="/assets/challenges/nameplate/card-nameplate-dark.webp"
alt="Finished blue ALEX nameplate on the dark SketchForge workplane"
/>
</>
);
}
export default function ChallengesDashboard({ onStartChallenge }: { onStartChallenge: (challenge: ChallengeTutorialId) => void }) {
return (
<div className="challenge-key-tag-page">
<div className="challenge-key-tag-rail" aria-hidden="true">
<span />
<span />
</div>
<div className="challenge-card-stack">
<article className="challenge-key-tag-card">
<div className="challenge-key-tag-preview">
<KeyTagPreview />
</div>
<div className="challenge-key-tag-content">
<div className="challenge-key-tag-title-row">
<span>01</span>
<h2>Key Tag</h2>
</div>
<p>Build your first Key Tag from simple shapes.</p>
<div className="challenge-key-tag-skills" aria-label="Skills used in this challenge">
<span><Box size={16} aria-hidden="true" /> Basic shapes</span>
<span><AlignCenter size={16} aria-hidden="true" /> Align</span>
<span><CircleDotDashed size={16} aria-hidden="true" /> Hole</span>
<span><LockKeyhole size={16} aria-hidden="true" /> Lock</span>
<span><Group size={16} aria-hidden="true" /> Group</span>
</div>
<button type="button" className="challenge-key-tag-start" onClick={() => onStartChallenge("key-tag")}>
Start Challenge
</button>
</div>
</article>
<article className="challenge-key-tag-card">
<div className="challenge-key-tag-preview">
<NameplatePreview />
</div>
<div className="challenge-key-tag-content">
<div className="challenge-key-tag-title-row">
<span>02</span>
<h2>Personalized Nameplate</h2>
</div>
<p>Create a printable nameplate with rounded edges and raised custom text.</p>
<div className="challenge-key-tag-skills" aria-label="Skills used in this challenge">
<span><Box size={16} aria-hidden="true" /> Box</span>
<span><CircleDotDashed size={16} aria-hidden="true" /> Fillet</span>
<span><Type size={16} aria-hidden="true" /> Text</span>
<span><MoveUp size={16} aria-hidden="true" /> Elevation</span>
<span><AlignCenter size={16} aria-hidden="true" /> Align</span>
<span><Group size={16} aria-hidden="true" /> Group</span>
</div>
<button type="button" className="challenge-key-tag-start" onClick={() => onStartChallenge("nameplate")}>
Start Challenge
</button>
</div>
</article>
</div>
</div>
);
}
@@ -0,0 +1,233 @@
"use client";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { useState } from "react";
const KEY_TAG_STEP_STORAGE_KEY = "sketchforge:key-tag-tutorial-step";
type TutorialDimension = {
label: "Length" | "Width" | "Height";
value: string;
slider: number;
};
type TutorialStep = {
eyebrow: string;
title: string;
body: string;
image: string;
alt: string;
dimensions?: TutorialDimension[];
snapGrid?: string;
};
const STEPS: TutorialStep[] = [
{
eyebrow: "Before you start",
title: "Build a Key Tag",
body: "Set Snap Grid to 0.5 mm, then build the Key Tag from simple shapes.",
image: "/assets/challenges/key-tag/01-finished-target.png",
alt: "Finished Key Tag shown in the SketchForge workplane",
snapGrid: "0.5 mm",
},
{
eyebrow: "Step 1",
title: "Make the middle",
body: "Add a Box, then set its size in the shape panel.",
image: "/assets/challenges/key-tag/02-middle-box.png",
alt: "The middle box of the Key Tag in SketchForge",
dimensions: [
{ label: "Length", value: "25.50 mm", slider: 38 },
{ label: "Width", value: "11.50 mm", slider: 20 },
{ label: "Height", value: "1.00 mm", slider: 5 },
],
},
{
eyebrow: "Step 2",
title: "Add the left round end",
body: "Add a solid Cylinder and place half of it over the left end of the box.",
image: "/assets/challenges/key-tag/03-left-round-end.png",
alt: "A solid cylinder added to the left end of the Key Tag",
dimensions: [
{ label: "Length", value: "11.50 mm", slider: 20 },
{ label: "Width", value: "11.50 mm", slider: 20 },
{ label: "Height", value: "1.00 mm", slider: 5 },
],
},
{
eyebrow: "Step 3",
title: "Make the other end",
body: "Duplicate the solid cylinder and place the copy on the right end.",
image: "/assets/challenges/key-tag/04-right-round-end.png",
alt: "Two solid cylinders forming both rounded ends of the Key Tag",
},
{
eyebrow: "Step 4",
title: "Lock the left circle",
body: "Select the left solid cylinder and press Lock. It will be the alignment reference.",
image: "/assets/challenges/key-tag/05-select-left-circle.png",
alt: "The left solid cylinder selected in the SketchForge workplane",
},
{
eyebrow: "Step 5",
title: "Create the hole",
body: "Add another Cylinder, set its size, then change it from Solid to Hole.",
image: "/assets/challenges/key-tag/06-hole-cylinder.png",
alt: "The small hole cylinder added near the left end of the Key Tag",
dimensions: [
{ label: "Length", value: "3.00 mm", slider: 8 },
{ label: "Width", value: "3.00 mm", slider: 8 },
{ label: "Height", value: "2.00 mm", slider: 7 },
],
},
{
eyebrow: "Step 6",
title: "Align the hole",
body: "Select the hole and the locked left circle. Press Align and choose the middle on both horizontal axes.",
image: "/assets/challenges/key-tag/07-align-hole.png",
alt: "The hole aligned to the center of the left solid cylinder",
},
{
eyebrow: "Step 7",
title: "Unlock the circle",
body: "Select the left solid circle again and press Unlock.",
image: "/assets/challenges/key-tag/08-unlock-left-circle.png",
alt: "The left solid cylinder selected again after the hole has been aligned",
},
{
eyebrow: "Step 8",
title: "Group the Key Tag",
body: "Select the box, both solid circles, and the hole. Press Group.",
image: "/assets/challenges/key-tag/09-grouped-key-tag.png",
alt: "The finished grouped Key Tag selected in SketchForge",
},
];
function storedStepIndex() {
if (typeof window === "undefined") return 0;
const parsed = Number.parseInt(window.localStorage.getItem(KEY_TAG_STEP_STORAGE_KEY) ?? "0", 10);
return Number.isFinite(parsed) ? Math.max(0, Math.min(STEPS.length - 1, parsed)) : 0;
}
export function KeyTagTutorialPanel({
onFinish,
collapsed = false,
onCollapsedChange,
}: {
onFinish?: () => void;
collapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
}) {
const [stepIndex, setStepIndex] = useState(storedStepIndex);
const step = STEPS[stepIndex];
const first = stepIndex === 0;
const last = stepIndex === STEPS.length - 1;
const goToStep = (index: number) => {
const next = Math.max(0, Math.min(STEPS.length - 1, index));
setStepIndex(next);
window.localStorage.setItem(KEY_TAG_STEP_STORAGE_KEY, String(next));
};
if (collapsed) {
return (
<aside className="key-tag-tutorial-panel key-tag-tutorial-panel-collapsed" aria-label="Key Tag challenge instructions">
<button
type="button"
className="key-tag-tutorial-expand"
title="Expand challenge instructions"
aria-label="Expand challenge instructions"
onClick={() => onCollapsedChange?.(false)}
>
<ChevronLeft size={19} />
</button>
<span className="key-tag-tutorial-collapsed-label">Key Tag</span>
<span className="key-tag-tutorial-collapsed-count">{stepIndex + 1}/{STEPS.length}</span>
</aside>
);
}
return (
<aside
className="key-tag-tutorial-panel"
aria-label="Key Tag challenge instructions"
onPointerDown={(event) => event.stopPropagation()}
onWheel={(event) => event.stopPropagation()}
>
<header className="key-tag-tutorial-header">
<div>
<span>Challenge 1</span>
<strong>Key Tag</strong>
</div>
<div className="key-tag-tutorial-header-actions">
<span className="key-tag-tutorial-count">{stepIndex + 1} / {STEPS.length}</span>
<button
type="button"
className="key-tag-tutorial-collapse"
title="Minimize challenge instructions"
aria-label="Minimize challenge instructions"
onClick={() => onCollapsedChange?.(true)}
>
<ChevronRight size={18} />
</button>
</div>
</header>
<div className="key-tag-tutorial-body">
<div className="key-tag-tutorial-copy">
<span className="key-tag-tutorial-eyebrow">{step.eyebrow}</span>
<h2>{step.title}</h2>
<p>{step.body}</p>
{step.snapGrid ? (
<div className="key-tag-snap-row" aria-label={`Snap Grid ${step.snapGrid}`}>
<span>Snap Grid</span>
<strong>{step.snapGrid}</strong>
</div>
) : null}
{step.dimensions ? (
<div className="key-tag-tutorial-dimensions" aria-label="Required dimensions">
{step.dimensions.map((dimension) => (
<div className="key-tag-tutorial-dimension-control" key={dimension.label}>
<div className="key-tag-tutorial-dimension-heading">
<span>{dimension.label}</span>
<strong>{dimension.value}</strong>
</div>
<div className="key-tag-tutorial-slider" aria-hidden="true">
<span style={{ width: `${dimension.slider}%` }} />
<i style={{ left: `${dimension.slider}%` }} />
</div>
</div>
))}
</div>
) : null}
</div>
<div className="key-tag-tutorial-image-box">
<img className="key-tag-tutorial-capture" src={step.image} alt={step.alt} draggable={false} />
</div>
</div>
<footer className="key-tag-tutorial-footer">
<button type="button" className="secondary" disabled={first} onClick={() => goToStep(stepIndex - 1)}>
<ChevronLeft size={17} /> Previous
</button>
<button
type="button"
className="primary"
onClick={() => {
if (last) {
window.localStorage.removeItem(KEY_TAG_STEP_STORAGE_KEY);
onFinish?.();
return;
}
goToStep(stepIndex + 1);
}}
>
{last ? "Finish" : "Next"} {!last ? <ChevronRight size={17} /> : null}
</button>
</footer>
</aside>
);
}
@@ -0,0 +1,270 @@
"use client";
import { ArrowUp, ChevronLeft, ChevronRight } from "lucide-react";
import { useLayoutEffect, useState } from "react";
const NAMEPLATE_STEP_STORAGE_KEY = "sketchforge:nameplate-tutorial-step";
type TutorialDimension = {
label: "Length" | "Width" | "Height" | "Elevation";
value: string;
slider: number;
};
type TutorialStep = {
eyebrow: string;
title: string;
body: string;
image: string;
alt: string;
dimensions?: TutorialDimension[];
snapGrid?: string;
callout?: string;
};
const STEPS: TutorialStep[] = [
{
eyebrow: "Before you start",
title: "Build a Nameplate",
body: "Create a rounded base, personalize a Text object, then combine both parts into one printable design.",
image: "/assets/challenges/nameplate/01-finished-target.webp",
alt: "Finished blue ALEX nameplate on the SketchForge workplane",
snapGrid: "0.5 mm",
},
{
eyebrow: "Step 1",
title: "Make the base",
body: "Add a Box and enter these dimensions in the shape panel.",
image: "/assets/challenges/nameplate/02-base-box.webp",
alt: "Plain rectangular blue nameplate base",
dimensions: [
{ label: "Length", value: "24.00 mm", slider: 24 },
{ label: "Width", value: "70.00 mm", slider: 70 },
{ label: "Height", value: "3.00 mm", slider: 12 },
],
},
{
eyebrow: "Step 2",
title: "Round the outside",
body: "Select the base, press Fillet, select its outside edges, and apply the treatment.",
image: "/assets/challenges/nameplate/03-rounded-base.webp",
alt: "Blue nameplate base with softly rounded outer edges",
callout: "Use a 1.00 mm fillet amount.",
},
{
eyebrow: "Step 3",
title: "Add a Text object",
body: "Open Shapes and add Text. The new object starts with the letter T.",
image: "/assets/challenges/nameplate/04-text-added.webp",
alt: "A red capital T Text object on the blue nameplate base",
},
{
eyebrow: "Step 4",
title: "Personalize the text",
body: "Change the Text field to your name. This example uses ALEX. Pick any font you like.",
image: "/assets/challenges/nameplate/05-text-customized.webp",
alt: "Raised red ALEX text placed off-center on the blue base",
dimensions: [
{ label: "Height", value: "2.00 mm", slider: 9 },
],
},
{
eyebrow: "Step 5",
title: "Place it on top",
body: "Lift the Text object until its bottom sits exactly on the top face of the 3 mm base.",
image: "/assets/challenges/nameplate/05-text-customized.webp",
alt: "Raised red ALEX text resting on the blue nameplate base",
dimensions: [
{ label: "Elevation", value: "3.00 mm", slider: 12 },
],
},
{
eyebrow: "Step 6",
title: "Center the name",
body: "Lock the base, select the Text and base, then Align to the middle on both horizontal axes. Unlock the base afterward.",
image: "/assets/challenges/nameplate/06-text-centered.webp",
alt: "Red ALEX text centered on the blue nameplate base",
callout: "The locked base stays fixed as your alignment reference.",
},
{
eyebrow: "Step 7",
title: "Group the Nameplate",
body: "Select the base and Text object, then press Group to make one finished printable model.",
image: "/assets/challenges/nameplate/07-grouped-nameplate.webp",
alt: "Finished grouped blue ALEX nameplate",
},
];
function storedStepIndex() {
if (typeof window === "undefined") return 0;
const parsed = Number.parseInt(window.localStorage.getItem(NAMEPLATE_STEP_STORAGE_KEY) ?? "0", 10);
return Number.isFinite(parsed) ? Math.max(0, Math.min(STEPS.length - 1, parsed)) : 0;
}
function FilletButtonCoachmark() {
const [position, setPosition] = useState<{ left: number; top: number } | null>(null);
useLayoutEffect(() => {
const target = document.querySelector<HTMLButtonElement>('button[data-sketchforge-tool="fillet"]');
if (!target) return;
const updatePosition = () => {
const rect = target.getBoundingClientRect();
setPosition({
left: rect.left + rect.width / 2,
top: rect.bottom + 42,
});
};
target.classList.add("nameplate-fillet-button-target");
updatePosition();
window.addEventListener("resize", updatePosition);
window.addEventListener("scroll", updatePosition, true);
const observer = new ResizeObserver(updatePosition);
observer.observe(target);
return () => {
target.classList.remove("nameplate-fillet-button-target");
window.removeEventListener("resize", updatePosition);
window.removeEventListener("scroll", updatePosition, true);
observer.disconnect();
};
}, []);
if (!position) return null;
return (
<div className="nameplate-fillet-coachmark" style={position} role="status">
<ArrowUp size={30} strokeWidth={3} aria-hidden="true" />
<strong>Click Fillet</strong>
</div>
);
}
export function NameplateTutorialPanel({
onFinish,
collapsed = false,
onCollapsedChange,
}: {
onFinish?: () => void;
collapsed?: boolean;
onCollapsedChange?: (collapsed: boolean) => void;
}) {
const [stepIndex, setStepIndex] = useState(storedStepIndex);
const step = STEPS[stepIndex];
const first = stepIndex === 0;
const last = stepIndex === STEPS.length - 1;
const goToStep = (index: number) => {
const next = Math.max(0, Math.min(STEPS.length - 1, index));
setStepIndex(next);
window.localStorage.setItem(NAMEPLATE_STEP_STORAGE_KEY, String(next));
};
if (collapsed) {
return (
<aside className="key-tag-tutorial-panel key-tag-tutorial-panel-collapsed" aria-label="Personalized Nameplate challenge instructions">
<button
type="button"
className="key-tag-tutorial-expand"
title="Expand challenge instructions"
aria-label="Expand challenge instructions"
onClick={() => onCollapsedChange?.(false)}
>
<ChevronLeft size={19} />
</button>
<span className="key-tag-tutorial-collapsed-label">Nameplate</span>
<span className="key-tag-tutorial-collapsed-count">{stepIndex + 1}/{STEPS.length}</span>
</aside>
);
}
return (
<>
{stepIndex === 2 ? <FilletButtonCoachmark /> : null}
<aside
className="key-tag-tutorial-panel"
aria-label="Personalized Nameplate challenge instructions"
onPointerDown={(event) => event.stopPropagation()}
onWheel={(event) => event.stopPropagation()}
>
<header className="key-tag-tutorial-header">
<div>
<span>Challenge 2</span>
<strong>Personalized Nameplate</strong>
</div>
<div className="key-tag-tutorial-header-actions">
<span className="key-tag-tutorial-count">{stepIndex + 1} / {STEPS.length}</span>
<button
type="button"
className="key-tag-tutorial-collapse"
title="Minimize challenge instructions"
aria-label="Minimize challenge instructions"
onClick={() => onCollapsedChange?.(true)}
>
<ChevronRight size={18} />
</button>
</div>
</header>
<div className="key-tag-tutorial-body">
<div className="key-tag-tutorial-copy">
<span className="key-tag-tutorial-eyebrow">{step.eyebrow}</span>
<h2>{step.title}</h2>
<p>{step.body}</p>
{step.snapGrid ? (
<div className="key-tag-snap-row" aria-label={`Snap Grid ${step.snapGrid}`}>
<span>Snap Grid</span>
<strong>{step.snapGrid}</strong>
</div>
) : null}
{step.callout ? <div className="nameplate-tutorial-callout">{step.callout}</div> : null}
{step.dimensions ? (
<div className="key-tag-tutorial-dimensions" aria-label="Required dimensions">
{step.dimensions.map((dimension) => (
<div className="key-tag-tutorial-dimension-control" key={dimension.label}>
<div className="key-tag-tutorial-dimension-heading">
<span>{dimension.label}</span>
<strong>{dimension.value}</strong>
</div>
<div className="key-tag-tutorial-slider" aria-hidden="true">
<span style={{ width: `${dimension.slider}%` }} />
<i style={{ left: `${dimension.slider}%` }} />
</div>
</div>
))}
</div>
) : null}
</div>
<div className="key-tag-tutorial-image-box">
<img className="key-tag-tutorial-capture" src={step.image} alt={step.alt} draggable={false} />
</div>
</div>
<footer className="key-tag-tutorial-footer">
<button type="button" className="secondary" disabled={first} onClick={() => goToStep(stepIndex - 1)}>
<ChevronLeft size={17} /> Previous
</button>
<button
type="button"
className="primary"
onClick={() => {
if (last) {
window.localStorage.removeItem(NAMEPLATE_STEP_STORAGE_KEY);
onFinish?.();
return;
}
goToStep(stepIndex + 1);
}}
>
{last ? "Finish" : "Next"} {!last ? <ChevronRight size={17} /> : null}
</button>
</footer>
</aside>
</>
);
}
+65
View File
@@ -0,0 +1,65 @@
export const OFFICIAL_UPDATE_GUIDE_URL = "https://github.com/Formsmith746/SketchForge-3D#update-sketchforge-later";
export type AppUpdateStatus = {
currentVersion: string;
latestVersion: string | null;
updateAvailable: boolean;
checkedAt: string;
updateUrl: string;
installationReady: boolean;
requiresUpdateKey: boolean;
checkError?: string;
};
type ParsedVersion = {
major: number;
minor: number;
patch: number;
prerelease: string[];
};
function parseVersion(value: string): ParsedVersion | null {
const match = value.trim().match(/^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);
if (!match) return null;
return {
major: Number(match[1]),
minor: Number(match[2]),
patch: Number(match[3]),
prerelease: match[4] ? match[4].split(".") : [],
};
}
function comparePrereleasePart(left: string, right: string) {
const leftNumber = /^\d+$/.test(left) ? Number(left) : null;
const rightNumber = /^\d+$/.test(right) ? Number(right) : null;
if (leftNumber !== null && rightNumber !== null) return Math.sign(leftNumber - rightNumber);
if (leftNumber !== null) return -1;
if (rightNumber !== null) return 1;
return left.localeCompare(right);
}
export function compareAppVersions(leftValue: string, rightValue: string) {
const left = parseVersion(leftValue);
const right = parseVersion(rightValue);
if (!left || !right) return leftValue.trim().localeCompare(rightValue.trim());
for (const key of ["major", "minor", "patch"] as const) {
if (left[key] !== right[key]) return Math.sign(left[key] - right[key]);
}
if (!left.prerelease.length && !right.prerelease.length) return 0;
if (!left.prerelease.length) return 1;
if (!right.prerelease.length) return -1;
const partCount = Math.max(left.prerelease.length, right.prerelease.length);
for (let index = 0; index < partCount; index += 1) {
if (left.prerelease[index] === undefined) return -1;
if (right.prerelease[index] === undefined) return 1;
const comparison = comparePrereleasePart(left.prerelease[index], right.prerelease[index]);
if (comparison !== 0) return comparison;
}
return 0;
}
export function appUpdateIsAvailable(currentVersion: string, latestVersion: string) {
return compareAppVersions(latestVersion, currentVersion) > 0;
}
+7
View File
@@ -0,0 +1,7 @@
export const CHALLENGE_TUTORIAL_IDS = ["key-tag", "nameplate"] as const;
export type ChallengeTutorialId = (typeof CHALLENGE_TUTORIAL_IDS)[number];
export function isChallengeTutorialId(value: unknown): value is ChallengeTutorialId {
return typeof value === "string" && CHALLENGE_TUTORIAL_IDS.includes(value as ChallengeTutorialId);
}
+11
View File
@@ -0,0 +1,11 @@
export type MeshPoint = readonly [number, number, number];
/** Maps the Z-up coordinate convention used by slicers/CAD files into SketchForge's Y-up scene. */
export function zUpToSketchForge([x, y, z]: MeshPoint): [number, number, number] {
return [x, z, -y];
}
/** Maps SketchForge's Y-up scene into the Z-up coordinate convention expected by slicers. */
export function sketchForgeToZUp([x, y, z]: MeshPoint): [number, number, number] {
return [x, -z, y];
}
+79
View File
@@ -0,0 +1,79 @@
import type { MeshPoint } from "@/lib/meshCoordinates";
export type ObjExportMesh = {
name: string;
vertices: readonly MeshPoint[];
faces: readonly (readonly [number, number, number])[];
};
const OBJ_WELD_TOLERANCE = 0.00001;
function bucketKey(x: number, y: number, z: number) {
return `${x}:${y}:${z}`;
}
function weldMeshVertices(mesh: ObjExportMesh) {
const vertices: Array<[number, number, number]> = [];
const buckets = new Map<string, number[]>();
const remappedIndices: number[] = [];
mesh.vertices.forEach((sourceVertex) => {
// OBJ tools conventionally treat Y as up. Keep SketchForge's Y-up
// coordinates here so slicers do not apply their OBJ axis conversion a
// second time. STL is exported separately using explicit Z-up coordinates.
const vertex: [number, number, number] = [...sourceVertex];
const bucketX = Math.floor(vertex[0] / OBJ_WELD_TOLERANCE);
const bucketY = Math.floor(vertex[1] / OBJ_WELD_TOLERANCE);
const bucketZ = Math.floor(vertex[2] / OBJ_WELD_TOLERANCE);
let weldedIndex: number | undefined;
for (let xOffset = -1; xOffset <= 1 && weldedIndex === undefined; xOffset += 1) {
for (let yOffset = -1; yOffset <= 1 && weldedIndex === undefined; yOffset += 1) {
for (let zOffset = -1; zOffset <= 1 && weldedIndex === undefined; zOffset += 1) {
const candidates = buckets.get(bucketKey(bucketX + xOffset, bucketY + yOffset, bucketZ + zOffset)) ?? [];
weldedIndex = candidates.find((candidateIndex) => {
const candidate = vertices[candidateIndex];
return (
Math.abs(candidate[0] - vertex[0]) <= OBJ_WELD_TOLERANCE &&
Math.abs(candidate[1] - vertex[1]) <= OBJ_WELD_TOLERANCE &&
Math.abs(candidate[2] - vertex[2]) <= OBJ_WELD_TOLERANCE
);
});
}
}
}
if (weldedIndex === undefined) {
weldedIndex = vertices.length;
vertices.push(vertex);
const key = bucketKey(bucketX, bucketY, bucketZ);
buckets.set(key, [...(buckets.get(key) ?? []), weldedIndex]);
}
remappedIndices.push(weldedIndex);
});
const faces = mesh.faces
.map(([a, b, c]) => [remappedIndices[a], remappedIndices[b], remappedIndices[c]] as [number, number, number])
.filter(([a, b, c]) => a !== b && b !== c && c !== a);
return { vertices, faces };
}
function objNumber(value: number) {
return Math.abs(value) < 1e-12 ? "0" : String(value);
}
export function exportMeshesToObj(meshes: readonly ObjExportMesh[]) {
const lines = ["# SketchForge OBJ export"];
let offset = 1;
meshes.forEach((mesh) => {
const welded = weldMeshVertices(mesh);
lines.push(`o ${mesh.name}`);
welded.vertices.forEach(([x, y, z]) => lines.push(`v ${objNumber(x)} ${objNumber(y)} ${objNumber(z)}`));
welded.faces.forEach(([a, b, c]) => lines.push(`f ${a + offset} ${b + offset} ${c + offset}`));
offset += welded.vertices.length;
});
return lines.join("\n");
}
+151
View File
@@ -0,0 +1,151 @@
import type { SketchPoint, SketchProfile, SketchSegment } from "@/types/sketchforge";
export type OrderedCadSketchStep = { segment: SketchSegment; from: SketchPoint; to: SketchPoint };
export type OrderedCadSketchPath = { id: string; points: SketchPoint[]; steps: OrderedCadSketchStep[]; closed: boolean };
export type CadSketchRegion = { outer: OrderedCadSketchPath; holes: OrderedCadSketchPath[] };
export function orderedCadSketchPaths(profile: SketchProfile): OrderedCadSketchPath[] {
const pointById = new Map(profile.points.map((point) => [point.id, point]));
const adjacency = new Map<string, Array<{ pointId: string; segment: SketchSegment }>>();
profile.points.forEach((point) => adjacency.set(point.id, []));
const valid = profile.segments.filter((segment) => {
if (segment.startId === segment.endId || !pointById.has(segment.startId) || !pointById.has(segment.endId)) return false;
adjacency.get(segment.startId)?.push({ pointId: segment.endId, segment });
adjacency.get(segment.endId)?.push({ pointId: segment.startId, segment });
return true;
});
const unvisited = new Set(valid.map((segment) => segment.id));
const paths: OrderedCadSketchPath[] = [];
while (unvisited.size > 0) {
const seedId = unvisited.values().next().value as string;
const seed = valid.find((segment) => segment.id === seedId);
if (!seed) break;
const component = new Set<string>();
const queue = [seed.startId, seed.endId];
while (queue.length > 0) {
const id = queue.pop();
if (!id || component.has(id)) continue;
component.add(id);
adjacency.get(id)?.forEach((edge) => queue.push(edge.pointId));
}
const startId = [...component].find((id) => (adjacency.get(id)?.filter((edge) => unvisited.has(edge.segment.id)).length ?? 0) === 1) ?? seed.startId;
const first = pointById.get(startId);
if (!first) {
unvisited.delete(seed.id);
continue;
}
const points = [first];
const steps: OrderedCadSketchStep[] = [];
let currentId = startId;
for (let guard = 0; guard <= valid.length; guard += 1) {
const edge = adjacency.get(currentId)?.find((candidate) => unvisited.has(candidate.segment.id));
if (!edge) break;
const from = pointById.get(currentId);
const to = pointById.get(edge.pointId);
if (!from || !to) break;
unvisited.delete(edge.segment.id);
steps.push({ segment: edge.segment, from, to });
currentId = to.id;
if (currentId === startId) break;
points.push(to);
}
paths.push({ id: seed.id, points, steps, closed: currentId === startId && steps.length >= 3 });
}
return paths;
}
function sampledPath(path: OrderedCadSketchPath) {
const samples: Array<{ x: number; z: number }> = [];
path.steps.forEach(({ segment, from, to }, stepIndex) => {
if (stepIndex === 0) samples.push({ x: from.x, z: from.z });
const forward = segment.startId === from.id;
const first = forward ? from.handleOut : from.handleIn;
const second = forward ? to.handleIn : to.handleOut;
if (segment.kind === "line" || !first || !second) {
samples.push({ x: to.x, z: to.z });
return;
}
for (let index = 1; index <= 16; index += 1) {
const amount = index / 16;
const inverse = 1 - amount;
samples.push({
x: inverse ** 3 * from.x + 3 * inverse ** 2 * amount * first.x + 3 * inverse * amount ** 2 * second.x + amount ** 3 * to.x,
z: inverse ** 3 * from.z + 3 * inverse ** 2 * amount * first.z + 3 * inverse * amount ** 2 * second.z + amount ** 3 * to.z,
});
}
});
return samples;
}
function signedArea(points: Array<{ x: number; z: number }>) {
return points.reduce((area, point, index) => {
const next = points[(index + 1) % points.length];
return area + point.x * next.z - next.x * point.z;
}, 0) / 2;
}
function pointInPolygon(point: { x: number; z: number }, polygon: Array<{ x: number; z: number }>) {
let inside = false;
for (let index = 0, previous = polygon.length - 1; index < polygon.length; previous = index, index += 1) {
const current = polygon[index];
const before = polygon[previous];
if ((current.z > point.z) !== (before.z > point.z)
&& point.x < ((before.x - current.x) * (point.z - current.z)) / (before.z - current.z) + current.x) inside = !inside;
}
return inside;
}
export function cadSketchRegions(profile: SketchProfile): CadSketchRegion[] {
const allPaths = orderedCadSketchPaths(profile);
const openCount = allPaths.filter((path) => !path.closed).length;
const records = allPaths
.filter((path) => path.closed)
.map((path) => {
const polygon = sampledPath(path);
return { path, polygon, area: Math.abs(signedArea(polygon)) };
})
.filter((record) => record.polygon.length >= 3 && record.area > 1e-8)
.sort((a, b) => b.area - a.area);
// Compute nesting depth: count how many larger closed paths contain each record.
// Even depth = solid (outer boundary), odd depth = hole.
const depths = records.map((record, index) => {
let depth = 0;
for (let i = 0; i < records.length; i++) {
if (i === index) continue;
if (records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) {
depth++;
}
}
return depth;
});
const regions: CadSketchRegion[] = [];
records.forEach((record, index) => {
const depth = depths[index];
if (depth % 2 === 0) {
regions.push({ outer: record.path, holes: [] });
} else {
// Odd depth: find the nearest even-depth ancestor (smallest containing solid)
let bestParent: (typeof records)[number] | null = null;
for (let i = 0; i < records.length; i++) {
if (i === index) continue;
if (depths[i] % 2 === 0 && depths[i] < depth && records[i].area > record.area && pointInPolygon(record.polygon[0], records[i].polygon)) {
if (!bestParent || records[i].area < bestParent.area) {
bestParent = records[i];
}
}
}
if (bestParent) {
const region = regions.find((r) => r.outer === bestParent!.path);
if (region) region.holes.push(record.path);
}
}
});
if (regions.length === 0 && openCount > 0 && allPaths.length > 0) {
throw new Error("All profile paths are open. Close at least one loop before finishing the sketch.");
}
return regions;
}
+20
View File
@@ -0,0 +1,20 @@
import type { SketchProfile } from "@/types/sketchforge";
export type SketchCadBuildRequest = {
type: "build";
requestId: number;
profile: SketchProfile;
height: number;
};
export type SketchCadBuildResponse =
| {
type: "built";
requestId: number;
positions: Float32Array;
normals: Float32Array;
indices: Uint32Array;
triangleCount: number;
brep: string;
}
| { type: "error"; requestId: number; message: string };
+1 -1
View File
@@ -11,7 +11,7 @@ import type { GridSize, ProjectAsset, ProjectAssetSourceFormat, SketchOperation,
export const SKF_SCHEMA_ID = "com.sketchforge.project";
export const SKF_FORMAT_VERSION = 1;
export const SKF_MINIMUM_READER_VERSION = 1;
export const SKF_CREATED_WITH_VERSION = "0.9.0";
export const SKF_CREATED_WITH_VERSION = "1.0.0";
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
export const SKF_LIMITS = {
+41
View File
@@ -0,0 +1,41 @@
import { sketchForgeToZUp, type MeshPoint } from "@/lib/meshCoordinates";
export type StlExportMesh = {
vertices: readonly MeshPoint[];
faces: readonly (readonly [number, number, number])[];
};
function normalFor(a: MeshPoint, b: MeshPoint, c: MeshPoint): [number, number, number] {
const ux = b[0] - a[0];
const uy = b[1] - a[1];
const uz = b[2] - a[2];
const vx = c[0] - a[0];
const vy = c[1] - a[1];
const vz = c[2] - a[2];
const nx = uy * vz - uz * vy;
const ny = uz * vx - ux * vz;
const nz = ux * vy - uy * vx;
const length = Math.hypot(nx, ny, nz) || 1;
return [nx / length, ny / length, nz / length];
}
export function exportMeshesToStl(meshes: readonly StlExportMesh[]) {
const lines = ["solid sketchforge_design"];
meshes.forEach((mesh) => {
mesh.faces.forEach(([ai, bi, ci]) => {
const a = sketchForgeToZUp(mesh.vertices[ai]);
const b = sketchForgeToZUp(mesh.vertices[bi]);
const c = sketchForgeToZUp(mesh.vertices[ci]);
const n = normalFor(a, b, c);
lines.push(` facet normal ${n[0]} ${n[1]} ${n[2]}`);
lines.push(" outer loop");
lines.push(` vertex ${a[0]} ${a[1]} ${a[2]}`);
lines.push(` vertex ${b[0]} ${b[1]} ${b[2]}`);
lines.push(` vertex ${c[0]} ${c[1]} ${c[2]}`);
lines.push(" endloop");
lines.push(" endfacet");
});
});
lines.push("endsolid sketchforge_design");
return lines.join("\n");
}
+34 -2
View File
@@ -1,6 +1,7 @@
import * as THREE from "three";
import { STLLoader } from "three/examples/jsm/loaders/STLLoader.js";
import { createLocalId } from "@/lib/localIds";
import { zUpToSketchForge } from "@/lib/meshCoordinates";
import type { WorkplaneShape } from "@/types/sketchforge";
const stlLoader = new STLLoader();
@@ -10,6 +11,34 @@ function fileExtension(fileName: string) {
return fileName.split(".").pop()?.toLowerCase() ?? "";
}
function stlHeader(buffer: ArrayBuffer) {
return new TextDecoder("ascii").decode(new Uint8Array(buffer, 0, Math.min(80, buffer.byteLength))).toLowerCase();
}
function stlUsesSketchForgeYUp(buffer: ArrayBuffer, position: THREE.BufferAttribute | THREE.InterleavedBufferAttribute) {
// SketchForge's older ASCII STL exports were already Y-up. Preserve those,
// including tall models where geometry alone cannot reveal an up axis.
if (stlHeader(buffer).includes("sketchforge")) return true;
let minY = Number.POSITIVE_INFINITY;
let maxY = Number.NEGATIVE_INFINITY;
let minZ = Number.POSITIVE_INFINITY;
let maxZ = Number.NEGATIVE_INFINITY;
for (let i = 0; i < position.count; i += 1) {
minY = Math.min(minY, position.getY(i));
maxY = Math.max(maxY, position.getY(i));
minZ = Math.min(minZ, position.getZ(i));
maxZ = Math.max(maxZ, position.getZ(i));
}
const ySpan = maxY - minY;
const zSpan = maxZ - minZ;
// Some legacy/model-library STLs (including the Raspberry Pi fixture) are
// unmistakably flat on Y. Keep that established orientation; ambiguous STL
// files follow the slicer-standard Z-up convention.
return Number.isFinite(ySpan) && Number.isFinite(zSpan) && ySpan <= zSpan * 0.55;
}
export function importedShapeFromTriangleSoup(
fileName: string,
rawPositions: number[],
@@ -97,11 +126,14 @@ export function importedShapeFromStl(fileName: string, buffer: ArrayBuffer): Wor
const normal = geometry.getAttribute("normal");
const rawPositions: number[] = [];
const rawNormals: number[] = [];
const usesSketchForgeYUp = stlUsesSketchForgeYUp(buffer, position);
for (let i = 0; i < position.count; i += 1) {
rawPositions.push(position.getX(i), position.getY(i), position.getZ(i));
const sourcePosition: [number, number, number] = [position.getX(i), position.getY(i), position.getZ(i)];
rawPositions.push(...(usesSketchForgeYUp ? sourcePosition : zUpToSketchForge(sourcePosition)));
if (normal) {
rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
const sourceNormal: [number, number, number] = [normal.getX(i), normal.getY(i), normal.getZ(i)];
rawNormals.push(...(usesSketchForgeYUp ? sourceNormal : zUpToSketchForge(sourceNormal)));
}
}
+78
View File
@@ -0,0 +1,78 @@
/// <reference lib="webworker" />
import { OcctKernel, type ShapeHandle } from "occt-wasm";
import { cadSketchRegions, type OrderedCadSketchPath } from "@/lib/sketchCadProfile";
import type { SketchCadBuildRequest, SketchCadBuildResponse } from "@/lib/sketchCadTypes";
let kernelPromise: Promise<OcctKernel> | null = null;
function kernel() {
const moduleUrl = "/occt/occt-wasm.js";
kernelPromise ??= import(/* webpackIgnore: true */ moduleUrl)
.then((imported: { default: (options?: { locateFile?: (path: string) => string }) => Promise<unknown> }) => imported.default({
locateFile: (path) => path.endsWith(".wasm") ? "/occt/occt-wasm.wasm" : path,
}))
.then((module) => {
const KernelConstructor = OcctKernel as unknown as new (rawModule: unknown) => OcctKernel;
return new KernelConstructor(module);
});
return kernelPromise;
}
function post(message: SketchCadBuildResponse, transfer: Transferable[] = []) {
self.postMessage(message, { transfer });
}
function pathWire(cad: OcctKernel, path: OrderedCadSketchPath) {
const edges = path.steps.map(({ segment, from, to }) => {
const forward = segment.startId === from.id;
const first = forward ? from.handleOut : from.handleIn;
const second = forward ? to.handleIn : to.handleOut;
if (segment.kind !== "line" && first && second) {
return cad.makeBezierEdge([
{ x: from.x, y: 0, z: from.z },
{ x: first.x, y: 0, z: first.z },
{ x: second.x, y: 0, z: second.z },
{ x: to.x, y: 0, z: to.z },
]);
}
return cad.makeLineEdge({ x: from.x, y: 0, z: from.z }, { x: to.x, y: 0, z: to.z });
});
return cad.makeWire(edges);
}
self.onmessage = async (event: MessageEvent<SketchCadBuildRequest>) => {
const request = event.data;
let cad: OcctKernel | null = null;
try {
cad = await kernel();
cad.releaseAll();
const regions = cadSketchRegions(request.profile);
if (regions.length === 0) throw new Error("No closed profile found. Draw at least one closed loop and ensure it has no degenerate (zero-area) geometry.");
const solids: ShapeHandle[] = regions.map((region) => {
let face = cad!.makeFace(pathWire(cad!, region.outer));
if (region.holes.length > 0) face = cad!.addHolesInFace(face, region.holes.map((hole) => pathWire(cad!, hole)));
return cad!.extrude(face, 0, request.height, 0);
});
const result = solids.length === 1 ? solids[0] : cad.makeCompound(solids);
if (!cad.isValid(result)) throw new Error("OpenCascade produced invalid sketch topology");
const mesh = cad.tessellate(result, { linearDeflection: 0.05, angularDeflection: 0.16 });
const positions = new Float32Array(mesh.positions);
const normals = new Float32Array(mesh.normals);
const indices = new Uint32Array(mesh.indices);
const brep = cad.toBREP(result);
post({ type: "built", requestId: request.requestId, positions, normals, indices, triangleCount: mesh.triangleCount, brep }, [positions.buffer, normals.buffer, indices.buffer]);
} catch (error) {
const message = error instanceof Error ? error.message : String(error ?? "The CAD kernel could not build this sketch");
post({ type: "error", requestId: request.requestId, message });
if (/memory|WebAssembly|abort/i.test(message)) kernelPromise = null;
} finally {
try {
cad?.releaseAll();
} catch {
// The arena may already have reset after a kernel error.
}
}
};
export {};