Builds CAD models from 3d scan data
README.md

scan2cad #

Localhost tool that turns a 3D scan (STL/OBJ) into SolidWorks parametric output by user-guided reverse engineering: you view the scan, click the features you care about, feed in real-world measurements (calipers / thread specs), and export a clean STEP B-rep plus a SolidWorks VBA macro that rebuilds the part as a parametric feature tree.

The design assumption (from the motorcycle-frame use case): you don't reconstruct the whole messy scan — you pick the mounting face as a datum and the holes that matter, and get a clean parametric plate + holes interface out.

How it works #

 STL/OBJ ─► Three.js viewer ─► 🔍 Auto-discover ─► finds planar faces + holes automatically
                          │                          (datum = largest face; Ø/axis/depth per hole)
                          └─► or pick manually ───► click datum face / holes
                                 │  measured Ø / thread (M5…) locks any fit
                                 ▼
                       OpenCASCADE B-rep  ─► STEP  (watertight solid, FeatureWorks-ready)
                       VBA generator      ─► .vba  (parametric tree in SolidWorks on Windows)

Automatic discovery #

/api/discover runs a two-pass, model-based region-growing segmentation in C++:

  1. Per-vertex normals + surface-variation curvature over welded mesh topology.
  2. Pass 1 — cylinders first. Seeds (flattest-first) whose local neighbourhood fits a cylinder better than a plane grow a wall region by a radial + normal test, refit on the full ring (Taubin circle fit), and are validated by radius range, residual, and angular coverage (a real hole wraps the axis; a stray blob spans a small arc). Coaxial duplicates are merged. Growing holes first stops planar faces from bleeding over a rim and eating a wall.
  3. Pass 2 — planar faces grow over the remaining vertices; the largest becomes the datum.
  4. Holes are classified hole vs boss by whether wall normals point toward the axis (concave).
  • Fitting runs in C++: a Taubin circle fit + normal-perpendicularity filtering makes the cylinder fit robust even on off-centre picks; the datum normal is used as an axis hint.
  • STEP is a real B-rep solid built with OpenCASCADE booleans (plate prism − hole cylinders).
  • Macro recreates the plate sketch + boss-extrude + hole circles + cut-through, in SI units, with thread specs noted, and exports a STEP from SolidWorks itself.

Real scans (Revopoint / Revo Scan) #

Revopoint MetroX / Revo Scan exports meshes as binary PLY (model_mesh.ply, fuse_mesh.ply inside a .revo project). The loader reads binary_little_endian and ASCII PLY with arbitrary property layouts (x y z [nx ny nz] + a property list uchar uint vertex_indices face list), so those drop straight in.

On a real raw scan of a Yamaha R6 fairing bracket (31 k verts / 62 k tris) auto-discovery runs in ~30 ms and isolates the mounting holes: the concave (isHole) cylinders are the real bores (Ø3–7 mm bolt holes clustered on the mounting face), while the bracket's tubular arms and cast fillets fit as convex "boss" cylinders. Raw casts are organic, so the full cylinder list is long. The viewer's discovery panel has a hole-Ø range (Min/Max mm) plus a Holes only toggle so you constrain discovery to the bolt sizes you expect — e.g. 4–10 mm, or "> M5" (min 5.5, max 0 = unbounded). On the R6 bracket, 4–10 mm + holes-only yields 3 clean bores (Ø6.3 / 6.9 / 7.6 mm, angular coverage 0.5–1.0) instead of 80-plus fits. The bounds map to minDiameterMM / maxDiameterMM / holesOnly on /api/discover (0 disables a bound). You can also pick the holes you care about by hand. Fusing/smoothing in Revo Scan first tightens the fits.

To hint where to look, switch to ▭ Box mode and drag a rectangle over an area: that screen rectangle becomes a view-column (four world-space clip planes sent as region on /api/discover), and discovery runs only on the vertices inside it. Combined with the Ø range this isolates a single mounting pad's holes on a busy scan without touching the rest of the part.

Build & run (macOS) #

Dependencies (one-time):

brew install cmake opencascade

Then:

./run.sh                 # builds and serves on http://127.0.0.1:8765
# or a custom port:
./run.sh 9000

To let a VM reach the API (e.g. Claude Code next to SolidWorks in Parallels, which sees the Mac as 10.211.55.2), run the server with --host 0.0.0.0 (the API is unauthenticated, so wider exposure is opt-in). The windows/ folder holds the VM-side kit: CLAUDE.md briefing + sw.ps1 COM helpers.

Open http://127.0.0.1:8765 in a browser.

Workflow in the UI #

  1. Load an STL/OBJ (button or drag-drop).
  2. 🔍 Discover features → auto-detects the datum face + all holes, drawn as overlays and listed in the panel. (Or work manually: Datum mode → click the face; Hole mode → click each hole. Manual picking also adds any hole the auto-pass missed.)
  3. Per hole: type the measured Ø from calipers, or pick a thread (M5 → tap-drill Ø). This re-runs the fit with the radius locked for a tighter axis/centre.
  4. Set plate thickness + margin, and the Windows STEP path the macro should export to.
  5. Build → download scan2cad_part.step and scan2cad_macro.vba.

Testing & validation #

./build_out/gen_test bracket testdata/bracket.stl testdata/bracket.json   # synth part + ground truth
python3 scripts/validate.py                                               # discover vs ground truth

gen_test builds watertight parts (plate + varied holes) with OpenCASCADE, tessellates and densifies them to a scan-like resolution (optionally with Gaussian noise), and writes a ground-truth JSON. validate.py uploads each part, runs discovery, and checks detected hole count / diameter / position against ground truth. Current result on the clean suite:

✓ bracket.stl   holes 5/5    planes 11   ~0.8 s   (Ø5.5 ×4 + Ø12)
✓ dense.stl     holes 12/12  planes 23   ~0.8 s   (Ø4.2–6.2, 12 holes)
✓ varied.stl    holes 5/5    planes 12   ~0.7 s   (Ø3.4 / 5 / 6 / 8.5 / 10.2)
ALL PASS — 22/22 holes, 0 spurious, diameters within ~0.05 mm

In SolidWorks (Windows): Tools ▸ Macro ▸ New, paste the .vba, Run. Targets SW 2020+ with an English default part template; constants are at the top of the macro to tweak.

Layout #

src/
  geom.hpp      Vec3 + tiny linear algebra (Jacobi 3x3 eigen)
  mesh.*        STL (binary/ASCII) + OBJ + PLY loaders, normals, adjacency, curvature
  meshedit.*    mesh repair: topology analysis, QEM decimation, Liepa hole filling,
                component removal, mesh↔mesh deviation (uniform-grid closest-triangle)
  mesh_test.cpp mesh_test — degrade a test STL, repair it, assert watertight + accuracy
  fit.*         plane fit + robust cylinder fit (Taubin + IRLS + axis hint); point-set + radius-query
  discover.*    automatic feature discovery (two-pass model-based segmentation)
  builder.*     OpenCASCADE B-rep reconstruction + STEP export (buildSolid shared via solid.hpp)
  macro.*       SolidWorks VBA generator
  gentest.cpp   gen_test — synthetic watertight test parts + ground truth
  main.cpp      cpp-httplib localhost server + JSON API
web/            Three.js viewer + auto-discovery + picking UI
third_party/    vendored cpp-httplib + nlohmann/json (single headers)
scripts/        make_test_stl.py (simple), validate.py (discovery validation harness)

API (localhost) #

Method Path Body Returns
POST /api/upload multipart file mesh stats + bbox
POST /api/fit_plane {point,radius,viewDir} {origin,normal,u,v,rms}
POST /api/fit_cylinder {point,radius,knownDiameter?,axisHint?} {center,axis,diameter,depth,p1,p2,rms}
POST /api/discover {smoothPasses?,curvCap?,minCoverage?,…} {planes[],cyls[],datumIndex,ms}
POST /api/build {datum,thickness,margin,holes[],stepWinPath} download links
GET /api/download?f=step|macro — the generated file
GET /api/mesh/status — {status:{ntris,components[],holes[],watertight,…}}
POST /api/mesh/decimate {count|percent,tolerance?} status + deviation vs pre-op
POST /api/mesh/fill_holes {holes:[ids]|"all",method?,maxEdges?} {filled} + status
POST /api/mesh/remove_components {ids|minTris|minArea|keepLargest} {removed} + status
POST /api/mesh/undo — status (one level)
GET /api/mesh/current — binary STL of the edited mesh
GET /api/mesh/component?id=N — binary STL of one component
POST /api/prim/select {mode:wand|paint|clear,…} {nsel,preview}
POST /api/prim/fit {type:plane|cylinder|cone|sphere} fitted primitive + rms
POST /api/prim/construct {kind:line|point,how,ids[]} reference line/point
POST /api/surface/fit {u,v,smooth,auto,tol,extend} surface + deviation preview
GET /api/surface/step?id=N — the surface as a STEP file
POST /api/align/frame {slots:[{id,target,flip}],translate?} R, t, DOF lock state (preview)
POST /api/align/apply same transforms mesh/cloud/primitives/surfaces

Known limits / next steps #

  • Auto-discovery targets clean, dense scans (uniformly sampled, low noise — what Revopoint MetroX / Revo Scan exports after fusion). On heavy raw noise (≳0.05 mm on ~0.6 mm sampling) cylinder fits degrade and detection drops; smooth the mesh in Revo Scan first, raise the Noise smoothing passes in the UI, or just pick those holes manually (with a measured Ø).
  • Discovery detects planar faces, cylindrical holes, and bosses. Fillets, cones, spheres, counterbores, and pockets are not yet recognised. Reconstruction still models a flat datum plate + holes (the mounting-interface case).
  • Thread handling models the tap-drill hole + notes the spec; cosmetic threads aren't inserted by the macro yet (stub is marked in the generated VBA).
  • The mesh radius query (for manual picks) is a brute-force scan; a KD-tree would help on very large scans. Discovery is O(n) over vertices and runs ~0.8 s on a 1.4 M-triangle mesh.
  • The macro's FeatureExtrusion3/FeatureCut4 signatures target SW 2020+; older versions may need the parameter lists adjusted.