Load STL and CAD geometry
Every SHORE command reads its body through one Geometry interface, whether the file is a triangulated STL or a STEP, IGES or BREP model. These recipes load both, list what a CAD model contains, and show when the exact CAD projection matters.
The code is examples/cookbook/load_geometry.py (about 4 s). CAD input needs the cad extra: pip install "shore-mesh[cad]" (build123d and OCP); STL needs nothing extra.
Load a file and list its entities
The CAD test model is a half wing–body built with build123d and written in the three CAD formats:
# A half wing-body (fuselage + NACA 0012 wing, cut at the symmetry plane z = 0),
# written as STEP, BREP and IGES. Any CAD tool's export works the same way.
radius, length, span = 0.5, 5.0, 3.0
fuselage = bd.Cylinder(radius, length, rotation=(0, 90, 0))
fuselage += bd.Pos(-length / 2, 0, 0) * bd.Sphere(radius) + bd.Pos(length / 2, 0, 0) * bd.Sphere(
radius
)
sec = naca("0012", 40, closed_te=False)
le = int(np.argmin(sec[:, 0]))
upper = [(float(x), float(y), 0.0) for x, y in sec[: le + 1]]
lower = [(float(x), float(y), 0.0) for x, y in sec[le:]]
wire = bd.Wire([bd.Spline(*upper), bd.Spline(*lower), bd.Line(lower[-1], upper[0])])
wing = bd.extrude(bd.make_face(wire), amount=span)
model = (fuselage + wing) & (bd.Pos(0, 0, 10) * bd.Box(40, 40, 20))
bd.export_step(model, "wing_body.step")
bd.export_brep(model, "wing_body.brep")
writer = IGESControl_Writer()
writer.AddShape(model.wrapped)
writer.ComputeModel()
writer.Write("wing_body.igs")load_geometry picks the backend from the suffix: .stl gives an StlGeometry, .step/.stp, .iges/.igs and .brep/.brp give an OcctGeometry.
for path in ("wing_body.step", "wing_body.brep", "wing_body.igs"):
geo = load_geometry(path) # backend chosen by suffix
counts = {kind.value: len(geo.entities(kind)) for kind in EntityKind}
print(f"{path:15s} {counts}")
geo = load_geometry("wing_body.step")
print("bounds", np.round(geo.bounds, 3).tolist())
display = geo.display() # what the GUI draws: triangles per face, edge polylines
print(f"tessellation: {len(display.triangles)} triangles over {len(geo.faces)} faces")wing_body.step {'body': 1, 'surface': 8, 'curve': 19, 'point': 12}
wing_body.brep {'body': 1, 'surface': 8, 'curve': 19, 'point': 12}
wing_body.igs {'body': 1, 'surface': 8, 'curve': 19, 'point': 12}
bounds [[-3.0, -0.5, -0.0], [3.0, 0.5, 3.0]]
tessellation: 5078 triangles over 8 faces

- Entities have four kinds:
BODY(always one),SURFACE(CAD faces),CURVE(CAD edges) andPOINT(CAD vertices). AnEntityRef(kind, index)names one; the index is whatProject.associate(..., indices=...)and the GUI's Association dock use. - An STL has one
BODYand no faces. ItsCURVEandPOINTentities are the feature curves found at load time: see Feature curves of an STL. - IGES stores faces as independent trimmed surfaces; the loader sews them (tolerance
1e-6) so adjacent faces share their edges, which association needs. The counts above match the STEP file after sewing. - A CAD file without the
cadextra raisesMeshInputErrorwith thepip installhint; an unknown suffix raises too.
Choose between tessellated and exact projection
A CAD geometry answers project from a tessellation by default (tier 1) and from the exact B-rep with exact=True (tier 2). The recipe projects 200 points onto a unit sphere three ways:
# A STEP sphere of radius 1 and the same sphere as a 1280-triangle STL.
bd.export_step(bd.Sphere(1.0), "sphere.step")
shapes.sphere(radius=1.0, subdivisions=3).export("sphere.stl")
points = np.random.default_rng(0).normal(size=(200, 3))
points *= 1.3 / np.linalg.norm(points, axis=1, keepdims=True) # on a sphere of radius 1.3
cad = load_geometry("sphere.step")
stl = load_geometry("sphere.stl")
for label, geom, exact in (
("STL", stl, False),
("CAD tier 1", cad, False),
("CAD exact", cad, True),
):
proj = geom.project(points, exact=exact) # closest point on the whole body
err = np.abs(np.linalg.norm(proj.points, axis=1) - 1.0).max()
print(f"{label:10s} max |r - 1| = {err:.1e}")
face = EntityRef(EntityKind.SURFACE, 0)
on_face = cad.project(points, face, exact=True)
print("(u, v) of the first point on face 0:", np.round(on_face.params[0], 4))STL max |r - 1| = 4.3e-03
CAD tier 1 max |r - 1| = 2.6e-03
CAD exact max |r - 1| = 1.1e-16
(u, v) of the first point on face 0: [5.4731 1.2934]- The tier-1 tessellation has a linear deflection of
1e-3times the bounding-box diagonal (OcctGeometry(rel_deflection=...)ordeflection=changes it). Its error is the same order as a fine STL's. - Use the exact tier when the wall spacing is near the faceting error: a first cell of
1e-5on a body of unit size cannot sit on a surface that is wrong by1e-3.Project.snap(exact=True)andProject.premesh(exact=True)put the nodes on the exact surface. - Projecting onto one
SURFACEreturns its(u, v)parameters inProjection.params; projecting onto aCURVEreturns the curve parameter. An STL has no parametrisation (paramsisNone). - On a trimmed face, when the foot point on the underlying surface falls outside the trim, the exact projection returns the closest point of the face itself, which lies on its boundary.
Name geometries in a project
A project holds several geometries under names; the commands refer to them by name (geometry="wing_body"). Body.from_file is the single-body entry point the marching topologies use.
p = Project()
p.load_geometry("wing_body.step", name="wing_body")
p.load_geometry("sphere.stl", name="ball")
for name, body in p.geometries.items():
print(f"{name}: {type(body.geometry).__name__}, CAD={body.is_cad}")
body = Body.from_file("sphere.step") # what the marching topologies take
print("anchor", np.round(body.anchor, 6), "CAD", body.is_cad)wing_body: OcctGeometry, CAD=True
ball: StlGeometry, CAD=False
anchor [0. 0. 0.] CAD TrueProject.load_geometry(path, name=...)defaults to the name"body". Loading a second file under the same name replaces the first and discards the meshes of the components built on it (undo restores them).Body.from_filealso resolves the anchor, the interior point from which the cubed-sphere and O-grid topologies cast rays. On CAD the anchor is found on the merged tessellation. A body without a valid anchor (an open half model) still loads; the error is raised only when something needs the ray caster.The CLI takes CAD wherever it takes STL; for example a cubed sphere on the STEP sphere:
bashshore mesh sphere.step --ni 33 --nj 64 --nk 21 --theta-cap-deg 35 -o sphere_cad
See also
- Geometry: the backends, the two projection tiers, entity fingerprints.
- Associate with geometry and Rebuild a face on a CAD surface: what the entity indices are for.
- ADR 0002: one geometry protocol, two backends.
- API:
load_geometry,OcctGeometry,StlGeometry,Body.