Add SVG import extrusion

This commit is contained in:
Francisco Rivero
2026-07-07 23:59:36 +09:00
parent 4d2d59cb94
commit fd76c5bd96
6 changed files with 57 additions and 22 deletions
+18 -15
View File
@@ -2,7 +2,7 @@
import { Clock3, EllipsisVertical, FileUp, Grid3X3, HomeIcon, List, Pencil, Plus, Search, Settings, SlidersHorizontal, Trash2, X } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { SketchForgeEditor, importedShapeFromStl } from "@/components/SketchForgeEditor";
import { SketchForgeEditor, importedShapeFromStl, importedShapeFromSvg } from "@/components/SketchForgeEditor";
import { createLocalId } from "@/lib/localIds";
import { importExtensionSupported } from "@/lib/stlImport";
import { DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings } from "@/lib/workplaneSettings";
@@ -236,7 +236,7 @@ function newProject(name: string, index: number, shapeCount = 0): DashboardProje
}
function projectNameFromFileName(fileName: string) {
return fileName.replace(/\.[^.]+$/, "").trim() || "Imported STL design";
return fileName.replace(/\.[^.]+$/, "").trim() || "Imported design";
}
export default function Home() {
@@ -255,7 +255,7 @@ export default function Home() {
const [dashboardNotice, setDashboardNotice] = useState("");
const [projectShapesById, setProjectShapesById] = useState<Record<string, ProjectShapeCacheEntry>>({});
const projectsJsonRef = useRef("");
const dashboardStlInputRef = useRef<HTMLInputElement | null>(null);
const dashboardImportInputRef = useRef<HTMLInputElement | null>(null);
const nextProjectRevisionRef = useRef(0);
const projectShapeSaveQueuesRef = useRef<Record<string, Promise<void>>>({});
@@ -513,15 +513,18 @@ export default function Home() {
openEditor(project.id, { allowMissingFromStorage: true });
};
const importStlFileFromDashboard = useCallback(
const importFileFromDashboard = useCallback(
async (file: File) => {
if (!importExtensionSupported(file.name)) {
setDashboardNotice("Unsupported file type. Use STL.");
const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml";
if (!isSvg && !importExtensionSupported(file.name)) {
setDashboardNotice("Unsupported file type. Use STL or SVG.");
return;
}
try {
const shape = importedShapeFromStl(file.name, await file.arrayBuffer());
const shape = isSvg
? importedShapeFromSvg(file.name, await file.text())
: importedShapeFromStl(file.name, await file.arrayBuffer());
const project = newProject(projectNameFromFileName(file.name), projects.length, 1);
const revision = project.revision ?? project.updatedAt;
await saveProjectShapes(project.id, [shape], revision);
@@ -608,14 +611,14 @@ export default function Home() {
{JSON.stringify(projectDebugSummary)}
</pre>
<input
ref={dashboardStlInputRef}
ref={dashboardImportInputRef}
className="hidden-file-input"
type="file"
accept=".stl"
accept=".stl,.svg,image/svg+xml"
onChange={(event) => {
const file = event.currentTarget.files?.[0];
if (file) {
void importStlFileFromDashboard(file);
void importFileFromDashboard(file);
}
event.currentTarget.value = "";
}}
@@ -637,7 +640,7 @@ export default function Home() {
onDeleteProject={deleteProject}
onDownloadFolderChange={setDownloadFolder}
onDownloadModeChange={setDownloadMode}
onImportStl={() => dashboardStlInputRef.current?.click()}
onImportFile={() => dashboardImportInputRef.current?.click()}
onChallenges={() => {
setDashboardSection("challenges");
setDashboardNotice("");
@@ -688,7 +691,7 @@ function Dashboard({
onDeleteProject,
onDownloadFolderChange,
onDownloadModeChange,
onImportStl,
onImportFile,
onChallenges,
onDashboardHome,
onOpenProject,
@@ -714,7 +717,7 @@ function Dashboard({
onDeleteProject: (projectId: string) => void;
onDownloadFolderChange: (value: string) => void;
onDownloadModeChange: (value: DownloadMode) => void;
onImportStl: () => void;
onImportFile: () => void;
onChallenges: () => void;
onDashboardHome: () => void;
onOpenProject: (projectId: string) => void;
@@ -810,11 +813,11 @@ function Dashboard({
</span>
<span>Create new 3D design</span>
</button>
<button className="dashboard-action-tile" type="button" onClick={onImportStl}>
<button className="dashboard-action-tile" type="button" onClick={onImportFile}>
<span className="dashboard-action-icon">
<FileUp size={24} strokeWidth={2.4} />
</span>
<span>Import STL</span>
<span>Import STL/SVG</span>
</button>
<button className="dashboard-action-tile" type="button" onClick={onWorkspace}>
<span className="dashboard-action-icon">
+21 -5
View File
@@ -79,7 +79,7 @@ import {
import type { CadModifierComponentMesh, CadModifierDisplayEdge, CadModifierEdge, CadModifierKind, CadModifierMeshPart, CadModifierPrimitivePart, CadModifierQuality, CadModifierWorkerRequest, CadModifierWorkerResponse } from "@/lib/cadModifierTypes";
import type { AlignAxis, AlignHandleStatus, AlignTarget, GridSize, ShapeAsset, SketchImage, SketchPoint, SketchProfile, SketchSegment, WorkplaneShape, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export { importedShapeFromStl };
export { importedShapeFromStl, importedShapeFromSvg };
type TopPanel = "import" | "export" | "tips" | "profile" | "settings" | null;
type ExportFormat = "stl" | "obj";
@@ -2102,6 +2102,7 @@ function bakeShapeTransformIntoMesh(shape: WorkplaneShape): WorkplaneShape {
function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape {
const parsed = svgLoader.parse(source);
const rawPositions: number[] = [];
const rawNormals: number[] = [];
parsed.paths.forEach((path) => {
SVGLoader.createShapes(path).forEach((svgShape) => {
@@ -2113,10 +2114,17 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
});
rawGeometry.rotateX(-Math.PI / 2);
const geometry = rawGeometry.index ? rawGeometry.toNonIndexed() : rawGeometry;
geometry.computeVertexNormals();
const position = geometry.getAttribute("position");
const normal = geometry.getAttribute("normal");
for (let i = 0; i < position.count; i += 1) {
rawPositions.push(position.getX(i), position.getY(i), position.getZ(i));
if (normal) {
rawNormals.push(normal.getX(i), normal.getY(i), normal.getZ(i));
}
}
if (geometry !== rawGeometry) geometry.dispose();
rawGeometry.dispose();
});
});
@@ -2146,9 +2154,13 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
const height = Math.max(1, maxY - minY);
const depth = Math.max(1, maxZ - minZ);
const positions: number[] = [];
const normals: number[] = [];
for (let i = 0; i < rawPositions.length; i += 3) {
positions.push(rawPositions[i] - centerX, rawPositions[i + 1] - minY, rawPositions[i + 2] - centerZ);
if (rawNormals.length === rawPositions.length) {
normals.push(rawNormals[i], rawNormals[i + 1], rawNormals[i + 2]);
}
}
return {
@@ -2167,6 +2179,7 @@ function importedShapeFromSvg(fileName: string, source: string): WorkplaneShape
rotationZ: 0,
importedMesh: {
positions,
normals: normals.length ? normals : undefined,
baseWidth: width,
baseDepth: depth,
baseHeight: height,
@@ -7552,8 +7565,9 @@ export function SketchForgeEditor({
const selectFile = useCallback(async (file: File) => {
const isStep = /\.(step|stp)$/i.test(file.name);
if (!isStep && !importExtensionSupported(file.name)) {
setNotice("Unsupported file type. Use STL or STEP.");
const isSvg = /\.svg$/i.test(file.name) || file.type === "image/svg+xml";
if (!isStep && !isSvg && !importExtensionSupported(file.name)) {
setNotice("Unsupported file type. Use STL, STEP, or SVG.");
return;
}
@@ -7563,6 +7577,8 @@ export function SketchForgeEditor({
setNotice("Reading STEP… first import loads the OpenCascade kernel (~22 MB), one time per session");
const { importedShapeFromStep } = await import("@/lib/stepImport");
nextShape = await importedShapeFromStep(file.name, await file.arrayBuffer());
} else if (isSvg) {
nextShape = importedShapeFromSvg(file.name, await file.text());
} else {
nextShape = importedShapeFromStl(file.name, await file.arrayBuffer());
}
@@ -8044,7 +8060,7 @@ export function SketchForgeEditor({
ref={fileInputRef}
className="hidden-file-input"
type="file"
accept=".stl,.step,.stp"
accept=".stl,.step,.stp,.svg,image/svg+xml"
onChange={(event) => {
if (event.currentTarget.files) {
selectFiles(event.currentTarget.files);
@@ -8565,7 +8581,7 @@ function TopActionPanel({
}}
>
<ToolbarImportIcon />
<strong>Drop STL or STEP files</strong>
<strong>Drop STL, STEP, or SVG files</strong>
<span>or click to choose from your computer</span>
</button>
</div>
@@ -4437,7 +4437,7 @@ function createShapeObject(shape: WorkplaneShape, showEdges = false, onTextureRe
opacity: shape.hole ? (shape.importedMesh ? 0.34 : 0.52) : 1,
roughness: shape.hole ? 0.88 : 0.57,
metalness: 0.02,
side: shape.importedMesh?.sourceFormat === "json" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide,
side: shape.importedMesh?.sourceFormat === "json" || shape.importedMesh?.sourceFormat === "svg" || mirroredAxisCount(shape) % 2 === 1 ? THREE.DoubleSide : THREE.FrontSide,
});
const width = shapeWidth(shape);
+1 -1
View File
@@ -4,7 +4,7 @@ import { createLocalId } from "@/lib/localIds";
import type { WorkplaneShape } from "@/types/sketchforge";
const stlLoader = new STLLoader();
const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl"]);
const SUPPORTED_IMPORT_EXTENSIONS = new Set(["stl", "svg"]);
function fileExtension(fileName: string) {
return fileName.split(".").pop()?.toLowerCase() ?? "";