diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx
index 87680e4..86fa1fc 100644
--- a/apps/web/src/components/SketchForgeEditor.tsx
+++ b/apps/web/src/components/SketchForgeEditor.tsx
@@ -6474,13 +6474,21 @@ export function SketchForgeEditor({
}, [commitShapes, shapes]);
const selectFile = useCallback(async (file: File) => {
- if (!importExtensionSupported(file.name)) {
- setNotice("Unsupported file type. Use STL.");
+ const isStep = /\.(step|stp)$/i.test(file.name);
+ if (!isStep && !importExtensionSupported(file.name)) {
+ setNotice("Unsupported file type. Use STL or STEP.");
return;
}
try {
- const nextShape = importedShapeFromStl(file.name, await file.arrayBuffer());
+ let nextShape: WorkplaneShape;
+ if (isStep) {
+ 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 {
+ nextShape = importedShapeFromStl(file.name, await file.arrayBuffer());
+ }
commitShapes([...shapes, nextShape], nextShape.id, `Imported ${file.name}`);
setTopPanel(null);
} catch (error) {
@@ -6954,7 +6962,7 @@ export function SketchForgeEditor({
ref={fileInputRef}
className="hidden-file-input"
type="file"
- accept=".stl"
+ accept=".stl,.step,.stp"
onChange={(event) => {
if (event.currentTarget.files) {
selectFiles(event.currentTarget.files);
@@ -7441,7 +7449,7 @@ function TopActionPanel({
}}
>
- Drop STL files
+ Drop STL or STEP files
or click to choose from your computer
diff --git a/apps/web/src/lib/brepKernel.ts b/apps/web/src/lib/brepKernel.ts
new file mode 100644
index 0000000..2545285
--- /dev/null
+++ b/apps/web/src/lib/brepKernel.ts
@@ -0,0 +1,28 @@
+// Shared lazy loader for brepjs + the occt-wasm (OpenCascade) kernel. Both the
+// STEP exporter and importer call this so the 22 MB kernel loads at most once
+// per session, on first use, and stays out of the initial bundle.
+//
+// occt-wasm is staged into public/occt by scripts/copy-occt-wasm.mjs and loaded
+// at runtime, deliberately outside the Next bundler — the Emscripten glue self
+// loads ./occt-wasm.js relative to its own URL and does not survive bundling.
+// OCCT_INDEX_URL is typed as string (not a literal) so TypeScript treats the
+// dynamic import as runtime-resolved rather than a module to resolve.
+const OCCT_INDEX_URL: string = "/occt/index.js";
+const OCCT_WASM_URL = "/occt/occt-wasm.wasm";
+
+export type Brep = typeof import("brepjs");
+export type BrepSolid = ReturnType;
+type OcctWasmModule = typeof import("occt-wasm");
+
+let brepReady: Promise | null = null;
+
+export async function loadBrepWithOcct(): Promise {
+ brepReady ??= (async () => {
+ const brep = await import("brepjs");
+ const occt = (await import(/* webpackIgnore: true */ OCCT_INDEX_URL)) as unknown as OcctWasmModule;
+ const kernel = await occt.OcctKernel.init({ wasm: OCCT_WASM_URL });
+ brep.registerKernel("occt-wasm", brep.OcctWasmAdapter.fromKernel(kernel));
+ return brep;
+ })();
+ return brepReady;
+}
diff --git a/apps/web/src/lib/stepExport.ts b/apps/web/src/lib/stepExport.ts
index ef64d21..34fdd74 100644
--- a/apps/web/src/lib/stepExport.ts
+++ b/apps/web/src/lib/stepExport.ts
@@ -1,5 +1,6 @@
import type { WorkplaneShape } from "@/types/sketchforge";
import { shapeDepth, shapeWidth } from "@/lib/workplaneShapes";
+import { loadBrepWithOcct, type Brep, type BrepSolid } from "@/lib/brepKernel";
export type SkippedShape = {
name: string;
@@ -32,31 +33,6 @@ function unsupportedReason(kind: WorkplaneShape["kind"]): string {
return "no exact B-Rep mapping";
}
-// occt-wasm is staged into public/occt by scripts/copy-occt-wasm.mjs and loaded
-// at runtime, deliberately outside the Next bundler — the Emscripten glue self
-// loads ./occt-wasm.js relative to its own URL and does not survive bundling.
-// Typed as string (not a string literal) so TypeScript treats the dynamic import
-// as runtime-resolved and does not try to resolve the public/ URL as a module.
-const OCCT_INDEX_URL: string = "/occt/index.js";
-const OCCT_WASM_URL = "/occt/occt-wasm.wasm";
-
-type Brep = typeof import("brepjs");
-type BrepSolid = ReturnType;
-type OcctWasmModule = typeof import("occt-wasm");
-
-let brepReady: Promise | null = null;
-
-async function loadBrepWithOcct(): Promise {
- brepReady ??= (async () => {
- const brep = await import("brepjs");
- const occt = (await import(/* webpackIgnore: true */ OCCT_INDEX_URL)) as unknown as OcctWasmModule;
- const kernel = await occt.OcctKernel.init({ wasm: OCCT_WASM_URL });
- brep.registerKernel("occt-wasm", brep.OcctWasmAdapter.fromKernel(kernel));
- return brep;
- })();
- return brepReady;
-}
-
// SketchForge composes rotation as a THREE Euler in "XYZ" order, so the world
// matrix is Rx·Ry·Rz. Re-applying the same rotations about world axes through
// the origin (Z, then Y, then X) reproduces that product before the shape is
@@ -133,6 +109,53 @@ function toCadZUp(brep: Brep, solid: BrepSolid): BrepSolid {
return brep.rotate(solid, 90, { axis: [1, 0, 0] });
}
+// Place a STEP-imported body (stored in its normalized local frame: x/z-centred,
+// y in [0, baseHeight], Y-up) into world space, reproducing the editor's
+// transformMesh exactly. Built from rigid kernel ops (rotate/translate/uniform
+// scale) which preserve analytic surfaces and the original geometry losslessly;
+// only genuinely non-uniform resize falls back to applyMatrix, which validly
+// turns the affected primitives into B-splines. The shared toCadZUp applies the
+// final Y-up→Z-up flip afterwards, as for primitives.
+async function buildImportedBody(brep: Brep, shape: WorkplaneShape): Promise {
+ const mesh = shape.importedMesh;
+ if (!mesh?.brepStep) {
+ return { skip: "imported mesh has no B-Rep source; re-import as STEP to round-trip" };
+ }
+ const imported = await brep.importSTEP(new Blob([mesh.brepStep]));
+ if (!imported.ok) {
+ return { skip: "stored B-Rep failed to re-import" };
+ }
+
+ const h = shape.height;
+ const sx = shapeWidth(shape) / Math.max(0.001, mesh.baseWidth);
+ const sy = h / Math.max(0.001, mesh.baseHeight);
+ const sz = shapeDepth(shape) / Math.max(0.001, mesh.baseDepth);
+ let body = imported.value as unknown as BrepSolid;
+
+ if (Math.abs(sx - sy) < 1e-6 && Math.abs(sy - sz) < 1e-6) {
+ if (Math.abs(sx - 1) > 1e-6) body = brep.scale(body, sx);
+ } else {
+ const scaled = brep.applyMatrix(body, { linear: [sx, 0, 0, 0, sy, 0, 0, 0, sz], translation: [0, 0, 0] });
+ if (!scaled.ok) {
+ return { skip: `non-uniform scale failed: ${String(scaled.error.message ?? scaled.error)}` };
+ }
+ body = scaled.value as unknown as BrepSolid;
+ }
+
+ body = brep.translate(body, [0, -h / 2, 0]);
+ if (shape.mirrorX) body = brep.mirror(body, { normal: [1, 0, 0] });
+ if (shape.mirrorY) body = brep.mirror(body, { normal: [0, 1, 0] });
+ if (shape.mirrorZ) body = brep.mirror(body, { normal: [0, 0, 1] });
+ const rotZ = shape.rotationZ ?? 0;
+ const rotY = shapeYawDegrees(shape);
+ const rotX = shape.rotationX ?? 0;
+ if (rotZ) body = brep.rotate(body, rotZ, { axis: [0, 0, 1] });
+ if (rotY) body = brep.rotate(body, rotY, { axis: [0, 1, 0] });
+ if (rotX) body = brep.rotate(body, rotX, { axis: [1, 0, 0] });
+ body = brep.translate(body, [shape.x, (shape.elevation ?? 0) + h / 2, shape.z]);
+ return { solid: body };
+}
+
function describe(shape: WorkplaneShape, reason: string): SkippedShape {
return { name: shape.name, kind: shape.kind, reason };
}
@@ -193,13 +216,20 @@ export async function exportShapesToStep(shapes: WorkplaneShape[]): Promise shape.kind === "mesh" && Boolean(shape.importedMesh?.brepStep);
+
const parts: { shape: BrepSolid; name: string; color: string }[] = [];
for (const shape of shapes.filter((s) => !s.hole)) {
- if (!EXACT_KINDS.has(shape.kind)) {
- skipped.push(describe(shape, unsupportedReason(shape.kind)));
+ let built: BuildOutcome;
+ if (isImportedBody(shape)) {
+ built = await buildImportedBody(brep, shape);
+ } else if (EXACT_KINDS.has(shape.kind)) {
+ built = buildExactSolid(brep, shape);
+ } else {
+ const reason = shape.kind === "mesh" ? "imported mesh has no B-Rep source; re-import as STEP to round-trip" : unsupportedReason(shape.kind);
+ skipped.push(describe(shape, reason));
continue;
}
- const built = buildExactSolid(brep, shape);
if ("skip" in built) {
skipped.push(describe(shape, built.skip));
continue;
@@ -221,7 +251,7 @@ export async function exportShapesToStep(shapes: WorkplaneShape[]): Promise {
+ const brep = await loadBrepWithOcct();
+
+ const imported = await brep.importSTEP(new Blob([buffer]));
+ if (!imported.ok) {
+ throw new Error(`Could not read STEP: ${String(imported.error.message ?? imported.error)}`);
+ }
+
+ // STEP/CAD space is Z-up; SketchForge is Y-up. Rotating −90° about X maps CAD
+ // +Z (up) to SketchForge +Y — the inverse of the exporter's +90°·X. Rigid
+ // kernel ops (rotate/translate) are used throughout normalization because they
+ // preserve the exact geometry; a matrix transform here corrupts later export.
+ const flipped = brep.rotate(imported.value, -90, { axis: [1, 0, 0] });
+ const tess = brep.mesh(flipped);
+ if (tess.vertices.length < 9) {
+ throw new Error("STEP file has no solid geometry to import");
+ }
+
+ const positions: number[] = [];
+ const normals: number[] = [];
+ const hasNormals = tess.normals.length === tess.vertices.length;
+ for (let i = 0; i < tess.triangles.length; i += 1) {
+ const v = tess.triangles[i] * 3;
+ positions.push(tess.vertices[v], tess.vertices[v + 1], tess.vertices[v + 2]);
+ if (hasNormals) {
+ normals.push(tess.normals[v], tess.normals[v + 1], tess.normals[v + 2]);
+ }
+ }
+
+ // importedShapeFromTriangleSoup recenters the mesh to x/z-centered, bottom at
+ // y=0. Recenter the stored B-Rep by the same offset so the exact geometry and
+ // the displayed mesh share one local frame, and the editor's transforms apply
+ // identically to both.
+ let minX = Infinity;
+ let minY = Infinity;
+ let minZ = Infinity;
+ let maxX = -Infinity;
+ let maxZ = -Infinity;
+ for (let i = 0; i < positions.length; i += 3) {
+ minX = Math.min(minX, positions[i]);
+ maxX = Math.max(maxX, positions[i]);
+ minY = Math.min(minY, positions[i + 1]);
+ minZ = Math.min(minZ, positions[i + 2]);
+ maxZ = Math.max(maxZ, positions[i + 2]);
+ }
+ const normalized = brep.translate(flipped, [-(minX + maxX) / 2, -minY, -(minZ + maxZ) / 2]);
+ const exported = brep.exportSTEP(normalized);
+ const stepText = exported.ok ? await exported.value.text() : undefined;
+
+ const shape = importedShapeFromTriangleSoup(fileName, positions, hasNormals ? normals : undefined, "step");
+ if (shape.importedMesh && stepText) {
+ shape.importedMesh.brepStep = stepText;
+ }
+ return shape;
+}
diff --git a/apps/web/src/lib/stlImport.ts b/apps/web/src/lib/stlImport.ts
index 0344299..83aa362 100644
--- a/apps/web/src/lib/stlImport.ts
+++ b/apps/web/src/lib/stlImport.ts
@@ -10,7 +10,12 @@ function fileExtension(fileName: string) {
return fileName.split(".").pop()?.toLowerCase() ?? "";
}
-function importedShapeFromTriangleSoup(fileName: string, rawPositions: number[], rawNormals: number[] | undefined): WorkplaneShape {
+export function importedShapeFromTriangleSoup(
+ fileName: string,
+ rawPositions: number[],
+ rawNormals: number[] | undefined,
+ sourceFormat: NonNullable["sourceFormat"] = "stl",
+): WorkplaneShape {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute(rawPositions, 3));
if (rawNormals?.length === rawPositions.length) {
@@ -55,7 +60,7 @@ function importedShapeFromTriangleSoup(fileName: string, rawPositions: number[],
return {
id: createLocalId("uploaded-mesh"),
- name: fileName.replace(/\.[^.]+$/, "") || "Imported STL",
+ name: fileName.replace(/\.[^.]+$/, "") || `Imported ${sourceFormat.toUpperCase()}`,
kind: "mesh",
color: "#0098c7",
x: 10,
@@ -74,7 +79,7 @@ function importedShapeFromTriangleSoup(fileName: string, rawPositions: number[],
baseDepth: depth,
baseHeight: height,
triangleCount,
- sourceFormat: "stl",
+ sourceFormat,
},
locked: false,
hidden: false,
diff --git a/apps/web/src/types/sketchforge.ts b/apps/web/src/types/sketchforge.ts
index a14b7bf..5731839 100644
--- a/apps/web/src/types/sketchforge.ts
+++ b/apps/web/src/types/sketchforge.ts
@@ -155,7 +155,11 @@ export type WorkplaneShape = {
baseDepth: number;
baseHeight: number;
triangleCount: number;
- sourceFormat: "stl" | "obj" | "svg" | "json";
+ sourceFormat: "stl" | "obj" | "svg" | "json" | "step";
+ // Exact OpenCascade B-Rep of the body (single-shape STEP text) in the same
+ // local frame as `positions`. Set only for STEP imports; lets the exporter
+ // re-emit the original analytic geometry instead of the tessellation.
+ brepStep?: string;
};
imagePlate?: {
dataUrl: string;