1/**
2 * Import a STEP or IGES file into an OCCT shape, using Emscripten's virtual
3 * filesystem (adapted from opencascade.js-examples' `loadSTEPorIGES`).
4 */
5import type { OpenCascade, Shape } from './types'
7export interface ImportResult {
8 shape: Shape
9 format: 'step' | 'iges'
10}
12function formatFor(name: string): 'step' | 'iges' {
13 const ext = name.toLowerCase().split('.').pop()
14 if (ext === 'step' || ext === 'stp') return 'step'
15 if (ext === 'iges' || ext === 'igs') return 'iges'
16 throw new Error(`Unsupported file ".${ext}". Use .step/.stp or .iges/.igs.`)
17}
19export function importCadFile(oc: OpenCascade, name: string, bytes: Uint8Array): ImportResult {
20 const format = formatFor(name)
21 const fname = `import.${format}`
22 try {
23 oc.FS.unlink(`/${fname}`)
24 } catch {
25 /* no stale file */
26 }
27 oc.FS.createDataFile('/', fname, bytes, true, true, true)
29 const reader = format === 'step' ? new oc.STEPControl_Reader_1() : new oc.IGESControl_Reader_1()
30 const status = reader.ReadFile(fname)
31 if (status !== oc.IFSelect_ReturnStatus.IFSelect_RetDone) {
32 try {
33 oc.FS.unlink(`/${fname}`)
34 } catch {
35 /* ignore */
36 }
37 throw new Error(`OpenCASCADE could not read this ${format.toUpperCase()} file.`)
38 }
39 reader.TransferRoots(new oc.Message_ProgressRange_1())
40 const shape = reader.OneShape()
41 try {
42 oc.FS.unlink(`/${fname}`)
43 } catch {
44 /* ignore */
45 }
46 if (shape.IsNull()) throw new Error('The file contained no usable geometry.')
47 return { shape, format }
48}