From b292cc14ebee0ad583b3affd205102fc5f17a607 Mon Sep 17 00:00:00 2001 From: Andy Aragon Date: Thu, 25 Jun 2026 16:38:47 -0700 Subject: [PATCH] feat: add B-Rep STEP export via brepjs + OpenCascade Reconstruct parametric box/cylinder/sphere shapes as exact OpenCascade B-Rep solids and write a named, colored multi-body STEP assembly, cutting holes via boolean subtraction (only against bodies they overlap). brepjs and the 22 MB occt-wasm kernel load lazily on first export, so the initial bundle is unchanged. Unsupported shape kinds are skipped with an in-app notice. Cones are exact in the kernel but skipped pending an upstream occt-wasm multi-solid STEP writer fix that drops conical surfaces. occt-wasm runtime is staged into public/occt by scripts/copy-occt-wasm.mjs (gitignored) and loaded outside the bundler; the optional brepkit / opencascade kernel backends are aliased away in next.config. --- .gitignore | 6 + apps/web/next.config.ts | 11 + apps/web/src/components/SketchForgeEditor.tsx | 41 +++ apps/web/src/lib/exportNames.ts | 2 +- apps/web/src/lib/stepExport.ts | 233 ++++++++++++++++++ package-lock.json | 98 +++++++- package.json | 6 +- scripts/copy-occt-wasm.mjs | 26 ++ 8 files changed, 417 insertions(+), 6 deletions(-) create mode 100644 apps/web/src/lib/stepExport.ts create mode 100644 scripts/copy-occt-wasm.mjs diff --git a/.gitignore b/.gitignore index d507561..c6b403a 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,9 @@ Thumbs.db .vscode/ *.swp *.swo + +# Claude Code local settings (machine-specific) +.claude/settings.local.json + +# Staged occt-wasm runtime (copied from node_modules by scripts/copy-occt-wasm.mjs) +apps/web/public/occt/ diff --git a/apps/web/next.config.ts b/apps/web/next.config.ts index 19331c8..f714ce3 100644 --- a/apps/web/next.config.ts +++ b/apps/web/next.config.ts @@ -15,6 +15,17 @@ const nextConfig: NextConfig = { images: { unoptimized: true }, + // brepjs (loaded lazily by the STEP exporter) ships an auto-init helper that + // tries optional kernel backends via guarded `import().catch()`. We only install + // and use occt-wasm, so silence the resolution warnings for the backends we omit. + webpack: (config) => { + config.resolve.alias = { + ...config.resolve.alias, + "brepkit-wasm": false, + "brepjs-opencascade": false, + }; + return config; + }, ...(isStaticExport ? { output: "export" as const, diff --git a/apps/web/src/components/SketchForgeEditor.tsx b/apps/web/src/components/SketchForgeEditor.tsx index c496b16..87680e4 100644 --- a/apps/web/src/components/SketchForgeEditor.tsx +++ b/apps/web/src/components/SketchForgeEditor.tsx @@ -4710,6 +4710,7 @@ export function SketchForgeEditor({ const [workplaneMode, setWorkplaneMode] = useState(false); const [menuOpen, setMenuOpen] = useState(false); const [topPanel, setTopPanel] = useState(null); + const [stepExporting, setStepExporting] = useState(false); const [alignMode, setAlignMode] = useState(false); const [alignAnchorId, setAlignAnchorId] = useState(null); const [alignPreview, setAlignPreview] = useState<{ axis: AlignAxis; target: AlignTarget } | null>(null); @@ -6392,6 +6393,35 @@ export function SketchForgeEditor({ .catch((error: unknown) => failNotice("OBJ", error)); }, [hasSelection, projectName, selectedShapes, shapes]); + const exportStepDesign = useCallback(async () => { + if (stepExporting) { + return; + } + const sourceShapes = hasSelection ? selectedShapes : shapes; + if (sourceShapes.some((shape) => shape.hole) && !sourceShapes.some((shape) => !shape.hole)) { + setNotice("Select at least one solid shape before exporting STEP"); + return; + } + setStepExporting(true); + setNotice("Building B-Rep… first STEP export loads the OpenCascade kernel (~22 MB), one time per session"); + try { + const { exportShapesToStep } = await import("@/lib/stepExport"); + const { blob, exportedCount, skipped } = await exportShapesToStep(sourceShapes); + const text = await blob.text(); + const result = await downloadTextFile(projectExportFileName(projectName, "step"), text, "application/step"); + const skipNote = skipped.length > 0 ? `; skipped ${skipped.length} non-primitive shape${skipped.length === 1 ? "" : "s"}` : ""; + if (result.mode === "folder") { + setNotice(`Saved STEP (${exportedCount} bod${exportedCount === 1 ? "y" : "ies"}) to ${result.path}${skipNote}`); + } else { + setNotice(`Exported STEP B-Rep with ${exportedCount} bod${exportedCount === 1 ? "y" : "ies"}${skipNote}`); + } + } catch (error: unknown) { + setNotice(error instanceof Error ? error.message : "Could not export STEP"); + } finally { + setStepExporting(false); + } + }, [hasSelection, projectName, selectedShapes, shapes, stepExporting]); + const clearDesign = useCallback(() => { commitShapes([], [], "New empty design"); setClipboard([]); @@ -6902,6 +6932,8 @@ export function SketchForgeEditor({ scopeLabel={exportScopeLabel} onClose={() => setTopPanel(null)} onExport={exportDesign} + onExportStep={exportStepDesign} + stepExporting={stepExporting} onImportFiles={selectFiles} onPickFile={() => fileInputRef.current?.click()} onNotice={setNotice} @@ -7356,6 +7388,8 @@ function TopActionPanel({ scopeLabel, onClose, onExport, + onExportStep, + stepExporting, onImportFiles, onPickFile, onNotice, @@ -7365,6 +7399,8 @@ function TopActionPanel({ scopeLabel: "selected" | "total"; onClose: () => void; onExport: (format: ExportFormat) => void; + onExportStep: () => void; + stepExporting: boolean; onImportFiles: (files: FileList | File[]) => void; onPickFile: () => void; onNotice: (message: string) => void; @@ -7421,6 +7457,11 @@ function TopActionPanel({ Download OBJ + +

STEP keeps boxes, cylinders and spheres as exact CAD geometry (OpenCascade). Other shapes are skipped.

) : null} {panel === "tips" ? ( diff --git a/apps/web/src/lib/exportNames.ts b/apps/web/src/lib/exportNames.ts index 2ccfb7f..04a956a 100644 --- a/apps/web/src/lib/exportNames.ts +++ b/apps/web/src/lib/exportNames.ts @@ -1,4 +1,4 @@ -export type ProjectExportFormat = "stl" | "obj"; +export type ProjectExportFormat = "stl" | "obj" | "step"; export function projectExportFileName(projectName: string, format: ProjectExportFormat) { const safeProjectName = projectName diff --git a/apps/web/src/lib/stepExport.ts b/apps/web/src/lib/stepExport.ts new file mode 100644 index 0000000..ef64d21 --- /dev/null +++ b/apps/web/src/lib/stepExport.ts @@ -0,0 +1,233 @@ +import type { WorkplaneShape } from "@/types/sketchforge"; +import { shapeDepth, shapeWidth } from "@/lib/workplaneShapes"; + +export type SkippedShape = { + name: string; + kind: WorkplaneShape["kind"]; + reason: string; +}; + +export type StepExportResult = { + blob: Blob; + exportedCount: number; + skipped: SkippedShape[]; +}; + +// Only primitives that OCCT can represent as exact analytic surfaces under a +// rigid placement are mapped to B-Rep. Everything else (swept/tessellated/text +// shapes) is reported as skipped rather than faceted into a low-fidelity STEP. +// +// Cone construction is correct in the kernel (verified volume/bbox), but the +// occt-wasm multi-solid STEP writer drops a cone's lateral CONICAL_SURFACE when +// more than one solid is written to a file (both exportAssemblySTEP and a plain +// compound). A lone cone via exportSTEP is fine. Until that upstream writer bug +// is fixed, cones are reported as skipped rather than exported as a corrupt disk. +const EXACT_KINDS: ReadonlySet = new Set(["box", "cylinder", "sphere"]); +const SIZE_EPS = 0.0005; + +function unsupportedReason(kind: WorkplaneShape["kind"]): string { + if (kind === "cone") { + return "cone STEP export blocked by an upstream occt-wasm multi-solid writer bug (drops CONICAL_SURFACE)"; + } + 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 +// translated off-origin. Circular cylinders/cones ignore yaw, matching the +// editor's meshYawDegrees so the exported diameter is invariant. +function shapeYawDegrees(shape: WorkplaneShape): number { + const round = shape.kind === "cylinder" || shape.kind === "cone"; + const circular = Math.abs(shapeWidth(shape) - shapeDepth(shape)) < SIZE_EPS; + return round && circular ? 0 : shape.rotation; +} + +type BuildOutcome = { solid: BrepSolid } | { skip: string }; + +// Builds the shape in SketchForge's Y-up world frame (Y is the vertical/height +// axis). The caller converts the whole assembly to CAD Z-up afterwards. +function buildExactSolid(brep: Brep, shape: WorkplaneShape): BuildOutcome { + const width = shapeWidth(shape); + const depth = shapeDepth(shape); + const height = shape.height; + if (width <= SIZE_EPS || depth <= SIZE_EPS || height <= SIZE_EPS) { + return { skip: "degenerate dimensions" }; + } + + let solid: BrepSolid; + switch (shape.kind) { + case "box": { + // brep.box maps args to (X, Y, Z); in the Y-up frame that is (width, height, depth). + solid = brep.box(width, height, depth, { centered: true }); + break; + } + case "sphere": { + const rx = width / 2; + const ry = height / 2; + const rz = depth / 2; + const uniform = Math.abs(rx - ry) < SIZE_EPS && Math.abs(ry - rz) < SIZE_EPS; + solid = uniform ? brep.sphere(rx) : brep.ellipsoid(rx, ry, rz); + break; + } + case "cylinder": { + if (Math.abs(width - depth) >= SIZE_EPS) { + return { skip: "elliptical base is not an exact OCCT primitive" }; + } + solid = brep.cylinder(width / 2, height, { axis: [0, 1, 0], centered: true }); + break; + } + case "cone": { + if (Math.abs(width - depth) >= SIZE_EPS) { + return { skip: "elliptical base is not an exact OCCT primitive" }; + } + const baseRadius = width / 2; + const topScale = shape.baseRadius ? (shape.topRadius ?? 0) / shape.baseRadius : 0; + solid = brep.cone(baseRadius, baseRadius * topScale, height, { axis: [0, 1, 0], centered: true }); + break; + } + default: + return { skip: "no exact B-Rep mapping" }; + } + + const rotZ = shape.rotationZ ?? 0; + const rotY = shapeYawDegrees(shape); + const rotX = shape.rotationX ?? 0; + if (rotZ) solid = brep.rotate(solid, rotZ, { axis: [0, 0, 1] }); + if (rotY) solid = brep.rotate(solid, rotY, { axis: [0, 1, 0] }); + if (rotX) solid = brep.rotate(solid, rotX, { axis: [1, 0, 0] }); + + const center: [number, number, number] = [shape.x, (shape.elevation ?? 0) + height / 2, shape.z]; + solid = brep.translate(solid, center); + return { solid }; +} + +// +90° about world X maps SketchForge +Y (up) to CAD +Z (up) so the file opens +// upright in FreeCAD/SolidWorks instead of lying on its side. +function toCadZUp(brep: Brep, solid: BrepSolid): BrepSolid { + return brep.rotate(solid, 90, { axis: [1, 0, 0] }); +} + +function describe(shape: WorkplaneShape, reason: string): SkippedShape { + return { name: shape.name, kind: shape.kind, reason }; +} + +type Aabb = { min: [number, number, number]; max: [number, number, number] }; + +// World-space AABB used to decide whether a hole actually reaches a body. A hole +// is only cut from a body when their boxes overlap, so a body far from every hole +// skips the boolean entirely — which both avoids the per-cut color loss in the +// STEP writer and keeps the export O(bodies + intersections), not O(bodies×holes). +// +// Axis-aligned shapes get a tight box. Rotated shapes fall back to the box that +// encloses the bounding sphere (rotation-invariant, never under-reports), trading +// tightness for the guarantee that a real intersection is never missed. +function worldAabb(shape: WorkplaneShape): Aabb { + const w = shapeWidth(shape); + const d = shapeDepth(shape); + const h = shape.height; + const cx = shape.x; + const cy = (shape.elevation ?? 0) + h / 2; + const cz = shape.z; + const rotated = (shape.rotationX ?? 0) !== 0 || (shape.rotationZ ?? 0) !== 0 || shapeYawDegrees(shape) !== 0; + const [hx, hy, hz] = rotated + ? (() => { + const r = 0.5 * Math.sqrt(w * w + h * h + d * d); + return [r, r, r]; + })() + : [w / 2, h / 2, d / 2]; + return { min: [cx - hx, cy - hy, cz - hz], max: [cx + hx, cy + hy, cz + hz] }; +} + +function aabbsOverlap(a: Aabb, b: Aabb): boolean { + return ( + a.min[0] <= b.max[0] && + a.max[0] >= b.min[0] && + a.min[1] <= b.max[1] && + a.max[1] >= b.min[1] && + a.min[2] <= b.max[2] && + a.max[2] >= b.min[2] + ); +} + +export async function exportShapesToStep(shapes: WorkplaneShape[]): Promise { + const brep = await loadBrepWithOcct(); + + const skipped: SkippedShape[] = []; + const holes: { box: Aabb; solid: BrepSolid }[] = []; + for (const shape of shapes.filter((s) => s.hole)) { + if (!EXACT_KINDS.has(shape.kind)) { + skipped.push(describe(shape, `hole ${unsupportedReason(shape.kind)}; cut omitted`)); + continue; + } + const built = buildExactSolid(brep, shape); + if ("skip" in built) { + skipped.push(describe(shape, `hole ${built.skip}; cut omitted`)); + continue; + } + holes.push({ box: worldAabb(shape), solid: built.solid }); + } + + 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))); + continue; + } + const built = buildExactSolid(brep, shape); + if ("skip" in built) { + skipped.push(describe(shape, built.skip)); + continue; + } + + let solid = built.solid; + const solidBox = worldAabb(shape); + const overlapping = holes.filter((hole) => aabbsOverlap(solidBox, hole.box)); + if (overlapping.length > 0) { + const cut = brep.cutAll(solid, overlapping.map((hole) => hole.solid)); + if (cut.ok) { + solid = cut.value; + } else { + skipped.push(describe(shape, "hole subtraction failed; exported solid without holes")); + } + } + + parts.push({ shape: toCadZUp(brep, solid), name: shape.name, color: shape.color }); + } + + if (parts.length === 0) { + throw new Error("No box/cylinder/sphere solids to export as B-Rep STEP"); + } + + const result = brep.exportAssemblySTEP(parts, { unit: "MM" }); + if (!result.ok) { + throw new Error(`STEP export failed: ${String(result.error.message ?? result.error)}`); + } + + return { blob: result.value, exportedCount: parts.length, skipped }; +} diff --git a/package-lock.json b/package-lock.json index e483648..24490a6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,11 +10,12 @@ "dependencies": { "@tailwindcss/postcss": "^4.1.8", "@types/three": "^0.184.1", + "brepjs": "^18.118.0", "clsx": "^2.1.1", "lucide-react": "^0.511.0", "manifold-3d": "^3.5.0", "next": "^15.3.2", - "occt-wasm": "^3.5.0", + "occt-wasm": "^3.6.0", "react": "^19.1.0", "react-dom": "^19.1.0", "tailwind-merge": "^3.3.0", @@ -1573,6 +1574,52 @@ "node": ">=12" } }, + "node_modules/brepjs": { + "version": "18.118.0", + "resolved": "https://registry.npmjs.org/brepjs/-/brepjs-18.118.0.tgz", + "integrity": "sha512-rFO8xDh0RE8mF1hiP7vxiSI/DRQqA2znKGfojMTHg9p6AjFg3J+MGoVvo0r9z0bWC6SgT33LYZe57neZ3fAm2w==", + "license": "Apache-2.0", + "workspaces": [ + "packages/brepjs-opencascade", + "packages/brepjs-bim", + "packages/brepjs-sheetmetal", + "packages/brepjs-manifold", + "packages/brepjs-voxel-wasm", + "packages/brepjs-voxel", + "packages/brepjs-cad", + "packages/brepjs-viewer", + "packages/brepjs-vscode", + "apps/playground", + "apps/docs" + ], + "dependencies": { + "flatbush": "4.6.2", + "opentype.js": "1.3.4" + }, + "engines": { + "node": ">=24" + }, + "peerDependencies": { + "brepjs-manifold": "^0.1.0", + "brepjs-opencascade": "^0.5.1 || ^0.6.0 || ^0.7.0 || ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^0.14.0 || ^0.15.0 || ^0.16.0", + "brepkit-wasm": "^0.10.1 || ^1.0.0 || ^2.0.0", + "occt-wasm": "^3.6.0" + }, + "peerDependenciesMeta": { + "brepjs-manifold": { + "optional": true + }, + "brepjs-opencascade": { + "optional": true + }, + "brepkit-wasm": { + "optional": true + }, + "occt-wasm": { + "optional": true + } + } + }, "node_modules/caniuse-lite": { "version": "1.0.30001792", "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001792.tgz", @@ -1779,6 +1826,21 @@ "integrity": "sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==", "license": "MIT" }, + "node_modules/flatbush": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/flatbush/-/flatbush-4.6.2.tgz", + "integrity": "sha512-nNT7MFJ58Q4IAm3aYsEg+zgZGpdRcmR1i4U+aa8c+r91jmYZg7FTQwNnIMC0FyBqVZTbClKdAnrJkKkfp1BOvw==", + "license": "ISC", + "dependencies": { + "flatqueue": "^3.1.0" + } + }, + "node_modules/flatqueue": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/flatqueue/-/flatqueue-3.1.0.tgz", + "integrity": "sha512-Ia4qIYrrsEqIRx3c3XhkT+QDLQuUV5ovsr6ah1rIgKT5wclhoGK3lAMS1bWRAWxlx7wtlTBpV7QXB5d9fOSRxA==", + "license": "ISC" + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -2282,14 +2344,30 @@ } }, "node_modules/occt-wasm": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/occt-wasm/-/occt-wasm-3.5.0.tgz", - "integrity": "sha512-aKcaX7S2MKMafTFXFNCXrVQgQjK6kfvcTtlxDFtqoZHb+gx5Vzh4pH8P6mIobBhmLcyCiKbwyQrXWFj2zVX5jw==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/occt-wasm/-/occt-wasm-3.6.0.tgz", + "integrity": "sha512-qDTnqaRL73DkrqM7cdCJN8FStJm28W9TVXqJXofZQihlA/mX6mnkmE19FkWNrSsixVE676FMtL3V80lzAbG+GQ==", "license": "MIT OR Apache-2.0", "dependencies": { "comlink": "^4.4.2" } }, + "node_modules/opentype.js": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/opentype.js/-/opentype.js-1.3.4.tgz", + "integrity": "sha512-d2JE9RP/6uagpQAVtJoF0pJJA/fgai89Cc50Yp0EJHk+eLp6QQ7gBoblsnubRULNY132I0J1QKMJ+JTbMqz4sw==", + "license": "MIT", + "dependencies": { + "string.prototype.codepointat": "^0.2.1", + "tiny-inflate": "^1.0.3" + }, + "bin": { + "ot": "bin/ot" + }, + "engines": { + "node": ">= 8.0.0" + } + }, "node_modules/path-expression-matcher": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz", @@ -2512,6 +2590,12 @@ "dev": true, "license": "MIT" }, + "node_modules/string.prototype.codepointat": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/string.prototype.codepointat/-/string.prototype.codepointat-0.2.1.tgz", + "integrity": "sha512-2cBVCj6I4IOvEnjgO/hWqXjqBGsY+zwPmHl12Srk9IXSZ56Jwwmy+66XO5Iut/oQVR7t5ihYdLB0GMa4alEUcg==", + "license": "MIT" + }, "node_modules/strnum": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz", @@ -2602,6 +2686,12 @@ "three": ">= 0.159.0" } }, + "node_modules/tiny-inflate": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/tiny-inflate/-/tiny-inflate-1.0.3.tgz", + "integrity": "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw==", + "license": "MIT" + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", diff --git a/package.json b/package.json index 9f93786..9f9bbe6 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,10 @@ "version": "0.2.0", "private": true, "scripts": { + "copy:occt": "node scripts/copy-occt-wasm.mjs", + "predev": "npm run copy:occt", "dev": "next dev apps/web", + "prebuild": "npm run copy:occt", "build": "next build apps/web", "export": "set STATIC_EXPORT=true&& next build apps/web", "start": "next start apps/web", @@ -20,11 +23,12 @@ "dependencies": { "@tailwindcss/postcss": "^4.1.8", "@types/three": "^0.184.1", + "brepjs": "^18.118.0", "clsx": "^2.1.1", "lucide-react": "^0.511.0", "manifold-3d": "^3.5.0", "next": "^15.3.2", - "occt-wasm": "^3.5.0", + "occt-wasm": "^3.6.0", "react": "^19.1.0", "react-dom": "^19.1.0", "tailwind-merge": "^3.3.0", diff --git a/scripts/copy-occt-wasm.mjs b/scripts/copy-occt-wasm.mjs new file mode 100644 index 0000000..091eed2 --- /dev/null +++ b/scripts/copy-occt-wasm.mjs @@ -0,0 +1,26 @@ +// Stages the occt-wasm runtime (Emscripten glue + 22 MB WASM) into the web app's +// public/ folder so the STEP exporter can load it lazily at runtime. The kernel is +// imported via a webpackIgnore dynamic import from /occt/, deliberately bypassing +// the Next.js bundler — Emscripten glue does not survive bundling. The copied files +// are gitignored; this script runs before dev/build to recreate them from the package. +import { cp, mkdir, readdir } from "node:fs/promises"; +import { existsSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const src = join(root, "node_modules", "occt-wasm", "dist"); +const dest = join(root, "apps", "web", "public", "occt"); + +if (!existsSync(src)) { + console.error(`[copy-occt-wasm] occt-wasm not installed at ${src}. Run \`npm install\` first.`); + process.exit(1); +} + +await mkdir(dest, { recursive: true }); + +const entries = await readdir(src); +const wanted = entries.filter((name) => name.endsWith(".js") || name.endsWith(".wasm")); +await Promise.all(wanted.map((name) => cp(join(src, name), join(dest, name)))); + +console.log(`[copy-occt-wasm] staged ${wanted.length} files into apps/web/public/occt/`);