Python API
Everything below is importable from smlibpy directly. The same API in JavaScript is smlibwasm's,
WASM, and with three.js objects smlibpy-three's, three.js; both name it in
camelCase.
Shapes
Part
Part()
A solid: one or more closed volumes.
Combine parts with + (union), - (difference) and & (intersection).
The right-hand side may be a single part or any iterable of parts.
area(property): Total surface area.bbox(): The box along the axes around the body.bend(angle, *, radius=None, plane=Plane.XZ, start=None, end=None, tolerance=None): Bend around an axis byangledegrees (default: along X, toward +Z); seesmlibpy.bend.bends(*, k_factor=None): The bends of this sheet metal part (seesmlibpy.sheetmetal.bends).cell_at(point, tolerance=None): The cell of a merged part (seemerge) that holds the point, as incells; None outside, in a cavity and on a face (also one between two cells). For a part that is one solid: the part itself or None.cells(): The cells of a part made bymerge, each as a part of its own (every closed region of the body; a cavity is not a cell). A part that is one solid:[itself].center(): Center of mass (uniform density).chamfer(edges, length, *, length2=None, angle=None, reference=None, propagate=True, corners: 'patch' | 'mitre' | 'miter' = 'patch'): Bevel edges.lengthis the setback measured along both adjacent faces.check(level=2): What the kernel's own validity checks find wrong with the body: per failed test aProblemwith the face, edge or vertex it is about (or the body), a message, and the value and tolerance it measured. An empty list: nothing found.classify(point, tolerance=None): Where a point lies:("inside", None)in the material,("outside", None)(also in a cavity), or("on", shape)on the surface withintolerance(default: the part's own tolerance, 1e-5 for most parts), with the vertex, edge or face it lies on (the vertex rather than its edges, an edge rather than its faces).closest_point(point): The point of the body's surface nearest to a point (also from inside a part).closest_points(other): The nearest points of this body and another body, a face, an edge or a wire (ClosestPoints): the point on this body, the point on the other, their distance and the faces they lie on. The points are exact surface points (and curve points), as fordistance_to; where the shapes touch or overlap, the distance is 0 and the points are one place where they meet.colored(color, *, faces=None): The same body with a display color ("steelblue","#4682b4"or(r, g, b)).compact(): Free what the kernel keeps from earlier queries of this body: the caches thatbbox,distance_to,closest_point,raycastandmesh()leave on its curves, its surfaces and the body itself (evaluation grids, trimmed-surface data, spatial trees). The body does not change, nor do its faces and edges; a later query builds what it needs again.contains(point, tolerance=None): True if the point lies in the material of this part or on its surface (withintolerance, seeclassify); False outside and in a cavity.cut(*others): Subtract other parts.deform(lattice, *, tolerance=None): Deform with asmlibpy.Lattice(same aslattice.apply(part)); seesmlibpy.deform.distance_to(other): Minimum distance to a point, another body, a face, an edge or a wire.draft(faces, angle, neutral_plane): Tilt faces by a draft angle, so that a molded or cast part comes out of its mold.draft_analysis(direction, *, min_angle=1.0): Draft angle of every face for the pull direction, with the faces grouped by whether they release (seesmlibpy.molding.DraftAnalysis).edges(*, seams=False): All edges. Seam edges (where a closed surface such as a cylinder meets itself) are left out unlessseamsis true.export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).faces(): The body's faces.fillet(edges, radius, *, continuity=None, fullness=1.0, propagate=True, corners: 'patch' | 'mitre' | 'miter' = 'patch', setback=None): Round edges.fillet_preview(edges, radius, *, propagate=True): The surfaces of the rounds a fillet ofedgeswithradiuswould make, as sheets, without rounding the part: one per edge, untrimmed (each runs along its whole edge, before the corners are made and the rounds trimmed to meet). For a quick look at a fillet before making it (show them with the part), or to see where its rounds would run. Circular rounds of one radius, the kernel's preview (SmApiFilletPreview); the part does not change.flange(edge, length, *, angle=90.0, radius, k_factor=0.44): Add a flange along a straight outer edge of this sheet (seesmlibpy.flange).flat_pattern(*, k_factor=None, fixed=None): The flat pattern of this sheet metal part on XY (seesmlibpy.flat_pattern).flatten(face, region, plane, *, continuity: 'crease' | 'G1' | 'G2' = 'G2'): Press a region of a face onto a plane: a flat area (a seat, a pad, a label area) on a curved face, blended into the rest of it.fold(line, angle, *, radius, k_factor=0.44, fixed=None, partial=False): Fold this sheet along a line on its top or bottom face (seesmlibpy.fold).from_mesh(mesh, max_faces=5000): A faceted part of a closed mesh (seeMesh.to_part).fuse(*others): Union with other parts.heal(): Repair gaps, tolerances and topology (mostly needed for imported data). A sheet whose faces close around a volume once healed comes back as aPart.imprint(tool, direction=None, *, nearest=True): The part with its faces split where a tool crosses them, without changing its shape: split lines for drafts, patches for the loads and supports of a simulation, regions of a face of their own to color, draft or select (a label area, a parting line, a seal track). Nothing is added or taken away: the volume stays.info(): Counts and measures in one dictionary: as for every body, andsolids(how manysolids) andvoids(how many cavities,voids).intersect(*others): Keep only the volume shared with the other parts. With one sheet (a Shell or a face) instead: the piece of the sheet inside the part, as a Shell (sheet & part).intersection_curves(other): The curves where this body's surface meets another body's surface, each one once.is_valid(*, strict=False): True if the part is a closed, manifold solid that encloses a positive volume and whose faces meet.mass_properties(density=1.0, accuracy=None): Mass, center of mass and inertia tensor for a uniformdensity.merge(*others): This part and others as one part made of cells. Where parts overlap, the overlap becomes a cell of its own; cells that touch share the faces between them (each such face bounds two cells: the body is non-manifold). For simulation meshes that must match across materials, and for models of several materials.mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).move_faces(faces, by): Move faces of the part, and extend or trim the faces around them to meet them again: push or pull a face, move a hole, a boss or a pocket.moved(location): A copy of this shape moved by a location (location * shape).named(name, *, faces=None): The same body with a name (used by exporters and the viewer).offset(distance, *, corners: 'sharp' | 'round' = 'sharp'): Grow (positive) or shrink (negative) the part bydistanceeverywhere (0 gives an equal copy).offset_faces(faces, distance): Offset faces of the part along their normals bydistance, and extend or trim the faces around them to meet them again: push-pull by a distance, resize a hole or a boss.on(target): Place this shape, designed around the world XY plane, onto a plane or face.outline(plane=Plane.XY, *, hidden=False, tangent_edges=False): The body's edges and contours projected onto a plane (a 2D drawing view), seen from the side the plane's normal points to: the visible lines.parting_line(direction): The closed lines where the part's surface turns from facingdirectionto facing away from it: where the halves of a mold part (seesmlibpy.molding.parting_line).project(curve, direction=(0, 0, -1), *, nearest=False): Project a curve onto the body alongdirection(an axis or a vector); returns the curves on its faces, fitted within 1e-7 of the size of the body and the curve.push(face, at, *, by=None, to=None, normal=None, radius=None, continuity: 'G0' | 'G1' | 'G2' = 'G1'): Push or pull a face at a point: a smooth dent or bump, local to the point, its edges in place.raycast(origin, direction=None): Where a ray meets this body's faces, nearest first: the exact points (Hit: point, distance from the start, the face, its outward normal there).raycast_many(origins, directions): The first hit of each of many rays, one per ray (HitorNone), notraycastmany times (which gives every hit of a ray): for each origin, theHitthatraycastgives first (the exact point on the face, the distance, the face, its outward normal),Nonewhere the ray misses.remove_faces(faces, *, partial=False): The part withfaces(a hole, a boss, a pocket) cut out and the gap closed by the faces around it. Withpartialthe features the kernel cannot close stay. See :mod:smlibpy.defeature.remove_fillets(faces=None, *, max_radius=None, partial=False): The part with fillets taken out and their edges sharp again:faces(fillet faces of this part), or all fillets up tomax_radius. Withpartialthe fillets the kernel cannot take out stay. See :mod:smlibpy.defeature.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).section(plane=Plane.XY): The cross-section of the part in a plane, as a sketch. Of a part made bymerge, the sections of the cells the plane cuts, side by side (a region per cell).shell(thickness, openings=None, *, outward=False, corners: 'round' | 'sharp' | None = None, walls=None): Hollow the part out to walls ofthickness, removing theopeningsfaces.shells(): The closed sheets that bound the part, each aShellof copies of its faces (joined along their edges): first the outside of each solid, then the wall of each cavity (and the outside of a body that floats in one). For a part with a cavity,shells()[1]is the cavity's wall: the faces to check the wall thickness on or to put a boundary condition on, whichpart.faces().derived_from(part.shells()[1])selects on the part itself. Faces between two cells of a merged part bound no space around it and lie in no shell (seeShapeList.shared).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).silhouette(direction=(0, 0, 1)): The contour of the body seen alongdirection(an axis or a vector, from the body towards the viewer): the curves on its faces where the surface turns away from the viewer (n . d = 0), and the edges between faces that face the viewer and faces that face away. All of them, seen or not, as standalone 3D edges; arcs of one circle come joined (a sphere's rim is one circle). Faces seen edge-on go with the faces behind them, so their near edges are the contour (a box seen from +Z: its 4 top edges). A sheet's free edges are not part of it. The curves are exact for spheres, cylinders and tori around the direction, traced (within 1e-6 of the body's size) otherwise.slices(step, axis=Axis.Z): Sections (section) acrossaxis,stepapart: the part cut into layers of thicknessstepfrom its lowest point along the axis up, each cut in its middle (atstep / 2,3 * step / 2, ... above the lowest point; the contours of a printer's layers). Each sketch lies in its plane (sketch.plane); layers whose plane misses the part are left out.solids(): The separate bodies of this part: those that share no face, a body inside a cavity of another (a captive part) too. Cells of a merged part that touch stay one solid (seemerge); a body keeps its cavities.sources(property): For a cell of a merged part (seecells): the parts given tomergewhosesplit(plane, keep: 'above' | 'below' | 'both' = 'above'): Cut the part with a plane or along a sheet.taper(scale, *, axis=Axis.Z, start=None, end=None, tolerance=None): Scale cross-sections toward an axis (default Z) from 1 toscale; seesmlibpy.taper.to_nurbs(): A copy whose faces and edges are all NURBS (analytic types converted).translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).twist(angle, *, axis=Axis.Z, start=None, end=None, tolerance=None): Twist about an axis (default Z) byangledegrees over the part; seesmlibpy.twist.unfold(*, k_factor=None, fixed=None): This sheet metal part unfolded flat (seesmlibpy.unfold).unroll(*, radius, axis=Axis.Z, start=None, tolerance=None): Unroll this part from around an axis (default Z) into a flat one, the layer atradiuskeeping its length; seesmlibpy.unroll.vertices(): The body's vertices.voids(): The cavities of the part (closed spaces inside it, kernel plan T7), each a part of its own: the space inside a cavity's wall, less a body that floats in it. With them the part fills its outside:part.volume + sum(v.volume for v in part.voids()). Empty for a part without cavities.info()counts them.volume(property): The part's volume (mm³).warp(face, region, by, *, continuity: 'crease' | 'G1' | 'G2' = 'G2'): Raise or sink a region of a face: a smooth bump over an outline drawn on the face.wires(): The boundaries of all the body's faces.
Sketch
Sketch()
A planar region (with holes, possibly several pieces) on a plane.
Sketch constructors build in the world XY plane around the origin; place a sketch
with .on(plane_or_face), Plane * sketch or Pos(...) * sketch. Combine
sketches with +, -, & and ^, change them with offset,
fillet, chamfer and mirror, then turn them into parts with
extrude, revolve, sweep or smlibpy.loft. Outlines that
are awkward as combinations of shapes are drawn with smlibpy.Profile.
area(property): The total area of the faces.bbox(): The box along the axes around the body.center(): Area centroid of the region.chamfer(length, vertices=None): Bevel corners of the region: cut backlengthalong both edges of each corner (measured along the edge) and join the two points with a line.check(level=2): What the kernel's own validity checks find wrong with the body: per failed test aProblemwith the face, edge or vertex it is about (or the body), a message, and the value and tolerance it measured. An empty list: nothing found.closest_point(point): The point of the body's surface nearest to a point (also from inside a part).closest_points(other): The nearest points of this body and another body, a face, an edge or a wire (ClosestPoints): the point on this body, the point on the other, their distance and the faces they lie on. The points are exact surface points (and curve points), as fordistance_to; where the shapes touch or overlap, the distance is 0 and the points are one place where they meet.colored(color, *, faces=None): The same body with a display color ("steelblue","#4682b4"or(r, g, b)).compact(): Free what the kernel keeps from earlier queries of this body: the caches thatbbox,distance_to,closest_point,raycastandmesh()leave on its curves, its surfaces and the body itself (evaluation grids, trimmed-surface data, spatial trees). The body does not change, nor do its faces and edges; a later query builds what it needs again.cut(*others): The region less other sketches (-).distance_to(other): Minimum distance to a point, another body, a face, an edge or a wire.edges(*, seams=False): All edges. Seam edges (where a closed surface such as a cylinder meets itself) are left out unlessseamsis true.export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).extend(distance, *, sides=None, continuity: 'natural' | 'G1' | 'G2' = 'natural'): The sheet (of one face) grown past its sides: seeFace.extend.extrude(amount, *, both=False, taper=0.0, direction=None, corners: 'sharp' | 'round' = 'sharp'): Extrude the region into a solid.faces(): The body's faces.fillet(radius, vertices=None): Round corners of the region with tangent arcs ofradius.flatten(face, region, plane, *, continuity: 'crease' | 'G1' | 'G2' = 'G2'): Press a region of a face of the sheet onto a plane: seePart.flatten. Returns a new sheet; a Sketch's comes back as a Shell.flipped(): The sketch turned over: its faces and its plane face the other way (an extrusion then grows to the other side).from_nurbs(nurbs): The sheet of a NURBS surface given by its data: the inverse ofFace.nurbs, asEdge.from_nurbsis for curves (smlibpy.nurbs_surfacewith the data insmlibpy.NurbsSurface's order)::fuse(*others): The union with other sketches (+).heal(): Repair gaps, tolerances and topology (mostly needed for imported data). A sheet whose faces close around a volume once healed comes back as aPart.info(): Counts and measures in one dictionary. A body made byshelloroffsetalso says how the corners of its new walls came out:"corners"is"round"or"sharp".intersect(*others): The region common to this and other sketches (&).intersection_curves(other): The curves where this body's surface meets another body's surface, each one once.match_edge(edge, target, *, extent=0.25): The sheet with an edge moved onto a curve: the edge runs alongtargetfrom end to end, exactly, and its face bends to follow, smoothly, near the edge only. To close a gap between two sheets beforesmlibpy.stitch, match one sheet's edge to the other's; to give a sheet a styling line, match it to that curve.merge_faces(a, b): The sheet with two faces made one: one surface over both, where they share a whole side, such as the halves of a sheet split along a curve of its surface, or patches built through the same curves. The joint's knot goes where the faces meet smoothly enough (within the sheet's tolerance), so a split sheet comes back as it was.mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).mirror(plane=Plane.XZ): A mirrored copy: about anAxisin the sketch plane (s.mirror(Y)), or in a plane or planar face (by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).named(name, *, faces=None): The same body with a name (used by exporters and the viewer).offset(distance, *, corners: 'round' | 'sharp' | 'chamfer' = 'round'): Grow (positivedistance) or shrink (negative) the region; holes move the other way.on(target): Place this shape, designed around the world XY plane, onto a plane or face.outline(plane=Plane.XY, *, hidden=False, tangent_edges=False): The body's edges and contours projected onto a plane (a 2D drawing view), seen from the side the plane's normal points to: the visible lines.perimeter(property): Total length of the boundary: outlines and holes.plane(property): The sketch plane; extrusions follow its normal.project(curve, direction=(0, 0, -1), *, nearest=False): Project a curve onto the body alongdirection(an axis or a vector); returns the curves on its faces, fitted within 1e-7 of the size of the body and the curve.push(face, at, *, by=None, to=None, normal=None, radius=None, continuity: 'G0' | 'G1' | 'G2' = 'G1'): Push or pull a face of the sheet at a point: seePart.push(byas a distance moves along the face's normal). Returns a new sheet; a Sketch's comes back as a Shell.raycast(origin, direction=None): Where a ray meets this body's faces, nearest first: the exact points (Hit: point, distance from the start, the face, its outward normal there).raycast_many(origins, directions): The first hit of each of many rays, one per ray (HitorNone), notraycastmany times (which gives every hit of a ray): for each origin, theHitthatraycastgives first (the exact point on the face, the distance, the face, its outward normal),Nonewhere the ray misses.revolve(axis=None, angle=360.0): Revolve the region about an axis in its plane.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).section_properties(): Area, centroid and second moments of area of the region (a beam's or an extrusion's profile):ixx,iyyandixyabout the centroid in the axes of the sketch plane, the principal moments and axes, the polar moment, the radii of gyration and the section moduli (seeSectionProperties).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).silhouette(direction=(0, 0, 1)): The contour of the body seen alongdirection(an axis or a vector, from the body towards the viewer): the curves on its faces where the surface turns away from the viewer (n . d = 0), and the edges between faces that face the viewer and faces that face away. All of them, seen or not, as standalone 3D edges; arcs of one circle come joined (a sphere's rim is one circle). Faces seen edge-on go with the faces behind them, so their near edges are the contour (a box seen from +Z: its 4 top edges). A sheet's free edges are not part of it. The curves are exact for spheres, cylinders and tori around the direction, traced (within 1e-6 of the body's size) otherwise.sweep(path, *, orient=True, translational=False, sharp_corners=None, up=None, twist=0.0, scale=None, anchor='center'): Sweep the region along a path (seesmlibpy.sweep: the center of the region's box, or the pointanchornames, goes to the start of the path;upandtwistset its attitude along it,scaleits size).swing(outline): Swing the region around an outline: a revolve about Z whose circle is the outline (seesmlibpy.swing: the region drawn as for a lathe in the XZ plane, the outline a closed curve around the Z axis parallel to XY, scaled at each height to pass through the region's outline on the +X side).thicken(thickness, *, both=False): Turn the sheet into a solid ofthickness(along the face normals; a negative thickness grows against them). Withboththe solid isthicknessthick in total, half of it to each side of the sheet.to_nurbs(): A copy whose faces and edges are all NURBS (analytic types converted).translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).trim(curves, keep): Cut the sheet along curves that lie on it, and keep one side, or both as faces of their own.vertices(): The body's vertices.warp(face, region, by, *, continuity: 'crease' | 'G1' | 'G2' = 'G2'): Raise or sink a region of a face of the sheet: seePart.warp. Returns a new sheet; a Sketch's comes back as a Shell.wires(): The boundaries of all the body's faces.xor(*others): The region in exactly one of the sketches (^).
Shell
Shell()
A sheet body: one or more faces that do not enclose a volume (surfaces).
area(property): The total area of the faces.bbox(): The box along the axes around the body.center(): The center of the faces' area (each face weighted by its area).check(level=2): What the kernel's own validity checks find wrong with the body: per failed test aProblemwith the face, edge or vertex it is about (or the body), a message, and the value and tolerance it measured. An empty list: nothing found.closest_point(point): The point of the body's surface nearest to a point (also from inside a part).closest_points(other): The nearest points of this body and another body, a face, an edge or a wire (ClosestPoints): the point on this body, the point on the other, their distance and the faces they lie on. The points are exact surface points (and curve points), as fordistance_to; where the shapes touch or overlap, the distance is 0 and the points are one place where they meet.colored(color, *, faces=None): The same body with a display color ("steelblue","#4682b4"or(r, g, b)).compact(): Free what the kernel keeps from earlier queries of this body: the caches thatbbox,distance_to,closest_point,raycastandmesh()leave on its curves, its surfaces and the body itself (evaluation grids, trimmed-surface data, spatial trees). The body does not change, nor do its faces and edges; a later query builds what it needs again.cut(*others): The sheet trimmed by parts: the pieces outside them (sheet - part).distance_to(other): Minimum distance to a point, another body, a face, an edge or a wire.edges(*, seams=False): All edges. Seam edges (where a closed surface such as a cylinder meets itself) are left out unlessseamsis true.export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).extend(distance, *, sides=None, continuity: 'natural' | 'G1' | 'G2' = 'natural'): The sheet (of one face) grown past its sides: seeFace.extend.faces(): The body's faces.flatten(face, region, plane, *, continuity: 'crease' | 'G1' | 'G2' = 'G2'): Press a region of a face of the sheet onto a plane: seePart.flatten. Returns a new sheet; a Sketch's comes back as a Shell.flipped(): The sheet turned over: a copy whose faces' normals all point the other way.from_nurbs(nurbs): The sheet of a NURBS surface given by its data: the inverse ofFace.nurbs, asEdge.from_nurbsis for curves (smlibpy.nurbs_surfacewith the data insmlibpy.NurbsSurface's order)::fuse(*others): Union with other sheets (sheet + other).heal(): Repair gaps, tolerances and topology (mostly needed for imported data). A sheet whose faces close around a volume once healed comes back as aPart.info(): Counts and measures in one dictionary. A body made byshelloroffsetalso says how the corners of its new walls came out:"corners"is"round"or"sharp".intersect(*others): The sheet trimmed by parts: the pieces inside them (sheet & part; alsopart & sheet).intersection_curves(other): The curves where this body's surface meets another body's surface, each one once.match_edge(edge, target, *, extent=0.25): The sheet with an edge moved onto a curve: the edge runs alongtargetfrom end to end, exactly, and its face bends to follow, smoothly, near the edge only. To close a gap between two sheets beforesmlibpy.stitch, match one sheet's edge to the other's; to give a sheet a styling line, match it to that curve.merge_faces(a, b): The sheet with two faces made one: one surface over both, where they share a whole side, such as the halves of a sheet split along a curve of its surface, or patches built through the same curves. The joint's knot goes where the faces meet smoothly enough (within the sheet's tolerance), so a split sheet comes back as it was.mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).named(name, *, faces=None): The same body with a name (used by exporters and the viewer).offset(distance): The sheet moved bydistancealong its face normals (a negative distance against them): each face offset, and where faces meet, extended or trimmed to meet again (sharp edges, asPart.offset). 0 gives an equal copy. Faces that touch along edges they do not share (faces copied one by one, or put together with+) are joined along them first, where their normals agree (smlibpy.stitchwithout turning a face); faces apart from the others, or whose normals disagree with their neighbours', move each on its own.on(target): Place this shape, designed around the world XY plane, onto a plane or face.outline(plane=Plane.XY, *, hidden=False, tangent_edges=False): The body's edges and contours projected onto a plane (a 2D drawing view), seen from the side the plane's normal points to: the visible lines.project(curve, direction=(0, 0, -1), *, nearest=False): Project a curve onto the body alongdirection(an axis or a vector); returns the curves on its faces, fitted within 1e-7 of the size of the body and the curve.push(face, at, *, by=None, to=None, normal=None, radius=None, continuity: 'G0' | 'G1' | 'G2' = 'G1'): Push or pull a face of the sheet at a point: seePart.push(byas a distance moves along the face's normal). Returns a new sheet; a Sketch's comes back as a Shell.raycast(origin, direction=None): Where a ray meets this body's faces, nearest first: the exact points (Hit: point, distance from the start, the face, its outward normal there).raycast_many(origins, directions): The first hit of each of many rays, one per ray (HitorNone), notraycastmany times (which gives every hit of a ray): for each origin, theHitthatraycastgives first (the exact point on the face, the distance, the face, its outward normal),Nonewhere the ray misses.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).silhouette(direction=(0, 0, 1)): The contour of the body seen alongdirection(an axis or a vector, from the body towards the viewer): the curves on its faces where the surface turns away from the viewer (n . d = 0), and the edges between faces that face the viewer and faces that face away. All of them, seen or not, as standalone 3D edges; arcs of one circle come joined (a sphere's rim is one circle). Faces seen edge-on go with the faces behind them, so their near edges are the contour (a box seen from +Z: its 4 top edges). A sheet's free edges are not part of it. The curves are exact for spheres, cylinders and tori around the direction, traced (within 1e-6 of the body's size) otherwise.thicken(thickness, *, both=False): Turn the sheet into a solid ofthickness(along the face normals; a negative thickness grows against them). Withboththe solid isthicknessthick in total, half of it to each side of the sheet.to_nurbs(): A copy whose faces and edges are all NURBS (analytic types converted).translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).trim(curves, keep): Cut the sheet along curves that lie on it, and keep one side, or both as faces of their own.vertices(): The body's vertices.warp(face, region, by, *, continuity: 'crease' | 'G1' | 'G2' = 'G2'): Raise or sink a region of a face of the sheet: seePart.warp. Returns a new sheet; a Sketch's comes back as a Shell.wires(): The boundaries of all the body's faces.
Face
Face(owner, kface)
A bounded piece of a surface, belonging to a body (a part, shell or sketch).
area(property): The face's area.axis(property): Axis of a cylinder, cone, sphere, torus or surface of revolution.bbox(): The box along the axes around the face.cells(property): The cells of its part that this face bounds, as indices intoPart.cells: one for acenter(): Area centroid. For curved faces it may lie off the face; seeinterior_point.closest_point(point): The point of the face nearest topoint(within its boundary).color(property): The face's own color as(r, g, b)from 0 to 1, or None: then it shows in its body's color.cone_angle(property): Half the opening angle of a cone, in degrees: the angle between its axis and its side.curvature_at(point=None): The curvature of the face at its point nearest topoint(default: a point inside the face): both principal curvatures, their directions and the outward normal (Curvature). Curvatures are positive where the face bends away from its outward normal (a ball, a boss), negative where it bends towards it (a bore): a cylinder of radius 5 hask1 = 0.2, k2 = 0, its borek1 = 0, k2 = -0.2.distance_to(point): Distance to a point, or to a body (seePart.distance_to).edges(*, seams=False): The face's edges (seam edges only withseams=True).export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).extend(distance, *, sides=None, continuity: 'natural' | 'G1' | 'G2' = 'natural'): The face's surface grown past its sides, as a sheet of one face: to make a sheet reach across a part before cutting or splitting it with it, or to give a blend room.extrude(amount, *, both=False, taper=0.0, direction=None, corners: 'sharp' | 'round' = 'sharp'): Extrude a planar face along its normal (seeSketch.extrude).faces(): This face, in a list.flipped(): A copy of this face, turned over: a sheet of one face whose normal points the other way (seeShell.flipped).geom_type(property):"plane","cylinder","cone","sphere","torus","revolution",inner_wires(): The boundaries of the face's holes.interior_point(): A point guaranteed to lie on the face.is_planar(property): True for planes and for flat B-spline faces (control points in one plane).iso(*, u=None, v=None): The curve of the face along which one of its surface parameters is constant:uorvas a fraction (0 to 1) of the face's range of that parameter. Trimmed to the face: several pieces where the face has holes or notches. For styling lines, inspection curves and rails on freeform faces. Which parameter runs which way depends on the surface: on a cylinder's sidevis constant around it (iso(v=0.5): the circle half way up) andualong it. ::major_radius(property): Major radius of a torus: from its axis to the middle of its tube (radiusis themesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).min_radius(): The smallest radius of curvature on the face,1 / max(|k1|, |k2|):inffor a plane, the radius of a cylinder or sphere, the smaller of a torus' tube radius and its inner radius, at the narrow end of a cone. Free-form faces are sampled on a 24 x 24 grid of their parameters and refined from the sharpest points (singular points such as a pole are left out). Compare it with a wall thickness or a cutter radius.mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).name(property): The face's name (body.named(name, faces=...), or from theADVANCED_FACEof a STEPneighbors(): Faces sharing an edge with this one.normal_at(point=None): Outward unit normal at the face point closest topoint(default: the center).nurbs(): The face's surface as a NURBS (NurbsSurface): degrees, knots, control points and weights. Exact for every kind (planes, cylinders, cones, spheres, tori as rational surfaces). It is the whole surface, untrimmed: the face may cover only part of it.offset(distance): A sheet of this face moved bydistancealong its normal (normal_at: out of the part it bounds; a negative distance moves it in): the offset surface, trimmed as the face is (seeShell.offset).on(target): Place this shape, designed around the world XY plane, onto a plane or face.outer_wire(): The face's outer boundary.owner(property): The body this face belongs to.plane(property): The face's plane: origin at its centroid, normal pointing out of the body.position_at(u, v): The point of the face's surface at(u, v), fractions (0 to 1) of the face's parameter box. A trimmed face (a plate with a hole, a face cut by another) does not cover its whole box: points there lie on the surface beyond the face's boundary.project(curve): The curve projected onto this face along its normals: every point to the nearest point of the face's surface, the result trimmed to the face (pieces where it leaves the face and comes back). Within 1e-7 of the size of the face and the curve. For curves drawn near a freeform face; along one direction, seePart.project. ::radius(property): Radius of a cylinder, sphere or cone (at its base), minor radius of a torus.raycast(origin, direction=None): Where a ray meets this face, nearest first (seePart.raycast).rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).split(curves): The pieces of this face cut along curves that lie on it, as the faces of a new sheet.to_shell(): A sheet body holding a copy of this face.to_sketch(): A sketch holding a copy of this (planar) face.translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).untrimmed(): The whole surface this face lies on, as a sheet of one face: its holes and cut borders are gone.uv_at(point): The parameters(u, v)of the face's point nearest topoint, as fractions (0 to 1) of the face's parameter box:face.position_at(*face.uv_at(p))isface.closest_point(p).vertices(): The face's vertices.wires(): The face's boundaries: the outer one first, then those of its holes.wrap(shape, at=None, *, direction=None): A drawing on XY wrapped onto this face, as a label onto a can: its origin goes toat(a point of the face; default its middle), its X axis along the face indirection(default: the face's first parameter direction there; it follows the parameter line nearest to it), its Y axis across, so that it reads from outside. Lengths stay along the two parameter lines throughat: on planes and cylinders the whole drawing keeps its size (text around a cylinder); on cones and doubly curved faces it stretches away from those lines. Around a closed face (a cylinder) the drawing continues across the seam; what leaves the face is cut off (also in its holes). Returns the curves on the face, fitted within 1e-7 of its size; a curve across the seam comes back as one edge.
Edge
Edge()
A bounded curve: a line segment, an arc, a circle, an ellipse or a NURBS curve.
Edges come from bodies (part.edges()) or from curve constructors such as
smlibpy.Line, smlibpy.CenterArc and smlibpy.Spline.
Parameters along an edge (point_at(t)) run from 0 at the start to 1 at the end,
proportional to arc length.
arc_center(property): Center of a circular edge.bbox(): The box along the axes around the edge.center(): The point halfway along the edge (usearc_centerfor a circle's center).closest_point(point): The point of the edge nearest topoint.continuity(samples=16, *, angle_tolerance=0.5, curvature_tolerance=0.01): How the two faces of the edge meet, checked atsamplespoints along it (Continuity):"G2"where their curvatures across the edge agree as well,"G1"where they meet tangentially (a circular fillet's border),"G0"at a crease,Nonewhere they leave a gap wider than the edge's tolerance.convexity(property):"convex"for an outside corner (material angle below 180 degrees),"concave"curvature_at(t=0.5): The curvature at fractiontof the length (aspoint_at): one over the radius of the circle that fits the edge best there; 0 where it runs straight.dihedral_angle(property): The angle between the two faces of the edge through the material, in degrees, at thedirection(property): Unit direction of a straight edge (start to end).distance_to(point): Distance to a point, or to a body (seePart.distance_to).edges(): This edge, in a list.end(property): The point where the edge ends (in its direction).export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).extend(distance, *, end: 'start' | 'end' | 'both' = 'end', continuity: 'G1' | 'G2' | 'natural' = 'G1'): The edge made longer bydistanceat itsend("end","start"or"both"), for cut tools and paths that must run past a body.faces(): The faces of the body that meet at this edge (none for an edge of no body).from_nurbs(nurbs): The edge of a NURBS curve given by its data: the inverse ofnurbs, for control points read from a file or another program, curves edited by moving control points and B-splines of many spans (asmlibpy.Bezieris one span).geom_type(property):"line","circle"(also arcs),"ellipse","bspline"or"other".inflections(): Where the edge changes the side it bends to (an S-curve has one), as fractions of its length (aspoint_at), in order: points where its curvature passes through zero. Lines, arcs and curves that bend one way only have none; a straight stretch between two bends counts once, at its middle, where the bends go opposite ways.intersection_params(other, *, tolerance=None): Where this edge meetsother(seeintersections), as fractions of its length (aspoint_atandsplittake them), in order.intersections(other, *, tolerance=None): Points where this edge meetsother: an edge, a wire, a face, a body (its faces) or a list of them, in order along this edge.is_closed(property): True if the edge ends where it starts (a circle, a closed spline).is_convex(): True on an outside corner (seeconvexity).is_seam(property): True for the seam of a closed surface (an edge used twice by one face).length(property): The edge's length.match(*, start=None, end=None, start_tangent=None, end_tangent=None): This edge with its ends moved tostartandendand its directions there set tostart_tangentandend_tangent(each optional: what is not given stays), bent smoothly in between: the parts near the ends move as a whole, the middle blends. For closing gaps, snapping a curve onto a point or another curve, and making it leave or arrive tangentially. Lines and arcs become B-splines (cubic at least).mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).min_radius(): The smallest radius of curvature of the edge (asFace.min_radiusis the face's):inffor a line, an arc's radius. A sweep profile that reaches farther from the path than this folds over itself. Where it is:min_radius_at. ::min_radius_at(): Where the edge bends most tightly (min_radius): a fraction of its length, aspoint_attakes it (0 for a line or an arc).mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).normal(property): Axis direction of a circular edge.nurbs(): This edge as a NURBS curve, from its start to its end: degree, knots, control points and weights. Exact for lines, arcs (rational) and B-splines; other curves are approximated within 1e-7.offset(distance, *, plane=None): The edge moveddistancesideways in its plane: an open edge to its left for a positive distance (seen from the side the plane's normal points to), to its right for a negative one; a closed edge (a circle, a closed spline) outward for a positive distance.on(target): Place this shape, designed around the world XY plane, onto a plane or face.param_at_point(point): Where on the edge the point nearest topointlies, as a fraction of the edge's length from its start (0) to its end (1), aspoint_attakes it:edge.point_at(edge.param_at_point(p))isedge.closest_point(p)(build123d's name).point_at(t=0.5): Point at fractiontof the edge length (0 = start, 1 = end).radius(property): Radius of a circular edge.radius_at(t=0.5): The radius of curvature at fractiontof the length (math.infwhere the edge runs straight): the radius of the circle that fits the edge best there.remove_knots(): The same curve with the knots it does not need taken out: a B-spline with fewer control points (the kernel's knot removal, which keeps the curve within about 1e-6 of where it was). Lines, arcs and other analytic curves come back as they are.reversed(): The same edge traversed the other way.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).self_intersections(*, tolerance=None): Points where the edge crosses itself (a figure eight, a looping spline), in order along it; the closing point of a closed edge does not count.show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).split(at): The edge cut in two atat, a fraction of the length or a point on the edge: the part before and the part after, each keeping the curve. ::start(property): The point where the edge starts (in its direction).tangent_at(t=0.5): Unit tangent at fractiontof the edge length, pointing along the edge.tangent_chain(): This edge and the edges that continue it tangentially, through vertices where the next edge runs on in the same direction (within 10 degrees) between faces that meet this edge's faces smoothly, and so on along the run: all top edges of a plate with rounded corners, the outline of a slot. This edge comes first.filletandchamferround the whole run of each selected edge (theirpropagate). An edge of no part is its own chain.through(point, *, tangent=None, at=None): This edge bent to pass throughpoint(and there in the directiontangent, if given): the smallest move of its control points that does it, with the ends of the edge and its directions at the ends kept. For "make this curve pass here" edits of splines, sweep paths and outlines; lines and arcs become cubic B-splines.to_arcs(tolerance=0.01): The edge as lines and circular arcs withintoleranceof it, end to end along it: for CNC, laser and plasma cutters and DXF readers that take only LINE and ARC (export_dxf(..., curves="arcs")). Lines and arcs come back as they are; splines and ellipses become chains of arcs that join tangentially (lines where they run straight). Both ways, every point of one lies withintoleranceof the other. ::tolerance(property): How far this edge's curve, its ends and the faces it bounds may lie apart: thetranslate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).trim(start, end): The part of the edge fromstarttoend, each a fraction of the length (as inpoint_at) or a point on the edge. The part keeps the curve: a trimmed arc is an arc, a trimmed spline the same spline.startmust come beforeendalong the edge.vertices(): The vertices at the edge's ends, start first (one for a closed edge).wires(): All wires (closed edge loops of faces, or the shape itself if it is a wire).
Wire
Wire(edges, *, sort=True)
A chain of edges, open or closed. Wire([edge, edge, ...]) orders and orients the edges.
bbox(): The box along the axes around the wire.center(): Length-weighted average of the edge midpoints.close(): This wire closed with a straight line from its end to its start.closest_point(point): The point of the wire nearest topoint.continuity(*, angle_tolerance=0.5, curvature_tolerance=0.01): How the edges of the wire meet at its joints (and where a closed wire closes) (Continuity):"G2"where their curvature vectors agree as well,"G1"where they meet tangentially (withinangle_tolerancedegrees),"G0"at a corner,Nonewhere an edge does not start where the one before ends (within 1e-6).curvature_toleranceis relative to the larger curvature (and at least1e-3 / length).ValueErrorfor a wire of one open edge, which has no joint.distance_to(point): Distance to a point, or to a body (seePart.distance_to).edges(): The wire's edges, in order.end(property): The point where the wire's last edge ends.export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).faces(): All faces of this shape.fillet(radius, vertices=None): Round corners with tangent arcs ofradius: every sharp corner, or those atvertices(points or vertices). A planar wire's corners are rounded in its plane, asSketch.filletdoes: between lines and arcs exactly, next to splines and ellipses with the arc whose center lies atradiusfrom both curves (the curves are cut where it touches them). A wire that is not planar has its corners between lines rounded. A corner a wire that is not planar has next to another curve, a smooth corner that is named and a point that is not a corner raiseModelingError; a radius that does not fit raisesValueError. Open wires keep their ends.intersections(other, *, tolerance=None): Points where this wire meetsother(seeEdge.intersections), in order along the wire; a point where two of its edges meet counts once.is_closed(property): True if the wire ends where it starts.length(property): The sum of the edges' lengths.mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).min_radius(): The smallest radius of curvature of the wire's edges. The corners where edges meet do not count (a corner has no radius; seefillet). Where it is:min_radius_at.min_radius_at(): Where the wire bends most tightly (min_radius): a fraction of its length, aspoint_attakes it.mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).offset(distance, *, corners: 'round' | 'sharp' | 'chamfer' = 'round', plane=None): The wire moveddistancesideways in its plane, as a parallel curve: an open wire to its left for a positive distance (seen from the side the plane's normal points to), to its right for a negative one; a closed wire outward for a positive distance, inward for a negative one (asSketch.offsetgrows and shrinks).on(target): Place this shape, designed around the world XY plane, onto a plane or face.plane(): The plane of a planar wire (normal by the right-hand rule along the wire).point_at(t=0.5): Point at fractiontof the total length.reversed(): The wire run the other way: its edges reversed, in reverse order.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).split(at): The wire cut in two atat, a fraction of its length or a point on it: the part before and the part after. At a vertex the edges stay as they are; elsewhere the edge there is split (Edge.split).start(property): The point where the wire's first edge starts.tangent_at(t=0.5): The direction of the wire (length 1) att, a fraction of its length from its start.to_arcs(tolerance=0.01): The wire as lines and circular arcs withintolerance(seeEdge.to_arcs).to_edge(): The wire as one edge: its curves joined into one B-spline curve (a wire of one edge gives that edge). The edges must meet end to end (within 1e-6); where they meet at a corner, the edge has a corner there too.to_sketch(): The planar region bounded by this closed wire.translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).trim(start, end): The part of the wire fromstarttoend, each a fraction of its length or a point on it;startmust come beforeendalong the wire.vertices(): The vertices of the wire's edges, each once.wires(): This wire, in a list.
Vertex
Vertex(x=0.0, y=0.0, z=0.0)
A point. Vertices of bodies come from .vertices(); Vertex(x, y, z) makes one.
bbox(): A box of size 0 at the vertex.center(): Where the vertex is (aspoint).convexity(property): For a corner of a sketch:"convex"where the region's angle is below 180distance_to(other): The distance to a point or to a shape.edges(): The edges of the body that meet at this vertex (none for a vertex of no body).export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).faces(): The faces of the body that meet at this vertex (none for a vertex of no body).mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).on(target): Place this shape, designed around the world XY plane, onto a plane or face.point(property): Where the vertex is.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).tolerance(property): How far the edges and faces that meet at this vertex may pass from its point: thetranslate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).vertices(): This vertex, in a list.wires(): All wires (closed edge loops of faces, or the shape itself if it is a wire).x(property): The vertex's x coordinate.y(property): The vertex's y coordinate.z(property): The vertex's z coordinate.
ShapeList
ShapeList(iterable=())
A list of shapes with selection helpers.
Every selector returns a new ShapeList, so selectors chain::
part.edges().parallel_to(Z).max_by(X)
part.faces().planar().facing(-Z)
A one-element list can be used wherever a single shape is expected
(sketch.on(part.faces().top())). Use one to require exactly one.
append(object): Append object to the end of the list.at(point, tolerance=0.0001): Shapes passing throughpoint(vertices at, edges/faces touching it), at mosttolerance(mm) from it.back(): Shapes furthest along +Y.bbox(): The box around all the shapes; IndexError for an empty list.bottom(): Lowest shapes (smallest Z).center(): Average of the members' centers.circles(): Circular edges (full circles and arcs).clear(): Remove all items from list.concave(): Edges on inside corners (material angle above 180 degrees), and the inside corners of a sketch.convex(): Edges on outside corners (material angle below 180 degrees), and the outside corners of a sketch (vertices where the region's angle is below 180 degrees).copy(): Return a shallow copy of the list.count(value): Return number of occurrences of value.cylinders(): Cylindrical faces.derived_from(*shapes): The faces or edges that descend from the given shapes: faces from faces, edges from edges, both from a body (part, shell, sketch). A face that an operation split, trimmed, moved along with the part or merged with another descends from it; one the operation made anew does not.edges(): The edges of all the shapes, each once.extend(iterable): Extend list by appending elements from the iterable.faces(): The faces of all the shapes, each once.facing(direction, max_angle=0.001): Faces whose outward normal points alongdirection(withinmax_angledegrees).fillets(max_radius=None): Fillet faces: rounds of convex edges and fillets of concave ones, found by geometry (with the corner patches where fillets meet), up tomax_radius. See :mod:smlibpy.defeature.filter(predicate): Keep the shapes for whichpredicate(shape)is true.filter_by(criterion):parallel_to(axis),of_type(name)orfilter(predicate), depending on the argument.first(property): The first shape; IndexError for an empty list.front(): Shapes furthest along -Y.g1(): Edges whose two faces meet at least tangentially all along them ("G1"or"G2"byEdge.continuity): the borders of fillets and blends.g2(): Edges whose two faces meet with equal curvature as well ("G2"byEdge.continuity): the borders of curvature-continuous blends (fillet(..., continuity="G2")), seams of smooth surfaces.group_by(key=Axis.Z, tolerance=0.0001): Group shapes with equal key (withintolerance), groups in ascending key order.hit_by(origin, direction=None): The faces (or bodies) of the list that a ray meets, nearest first: each once, in the order the ray meets them (seePart.raycast). Only the shapes in the list count, sopart.faces().planar().hit_by(...)looks past the faces that are not planar.index(value, start=0, stop=9223372036854775807): Return first index of value.insert(index, object): Insert object before index.joining(a, b): The edges that lie on the surfaces of bothaandb: where two bodies that a Boolean combined meet, the edges to round or chamfer after it.(plate + boss).edges().joining(plate, boss)gives the circle where the boss stands on the plate, also where the boss's bottom face lay on the plate's top (whichnewdoes not count as new: the circle is the boss's bottom edge),(block - hole).edges().joining(block, hole)the rims of the hole.aandbare bodies (parts, shells, sketches) or lists of them (an edge on any of them counts).largest(): The biggest shape by volume, area or length.last(property): The last shape; IndexError for an empty list.left(): Shapes furthest along -X.lines(): Straight edges (also straight B-spline edges, such as the edges of a chamfer).max_by(key=Axis.Z, tolerance=0.0001): The shapes with the largest key (all of them, if several tie withintolerance).min_by(key=Axis.Z, tolerance=0.0001): The shapes with the smallest key (all of them, if several tie withintolerance).moved(location): Each shape moved by a location.nearest(point): The shape whose center is closest topoint.new(since): The faces or edges that are new since the given bodies: made by the operations that led from them to this list's body, descending from no face or edge of theirs.of_type(*geom_types): Keep shapes of the given geometry types, e.g."line","circle","plane","cylinder","bspline".on(target): Every shape placed onto a plane or face (seeShape.on).one(): The only element; raises if the list does not hold exactly one shape.parallel_to(axis): Straight edges alongaxis, or planar faces whose normal is alongaxis.perpendicular_to(axis): Straight edges perpendicular toaxis, or planar faces containing it.planar(): Planar faces (also flat B-spline faces).pop(index=-1): Remove and return item at index (default last).remove(value): Remove first occurrence of value.reverse(): Reverse IN PLACE.right(): Shapes furthest along +X.rotate(axis=Axis.Z, angle=0.0): Each shape rotated about an axis byangledegrees.shared(): The faces that lie between two cells of a merged part (seePart.merge): where two materials meet, the faces a simulation mesh must match across or a contact condition goes on.merge(block, insert).faces().shared();Face.cellssays which two cells.smallest(): The smallest shape by volume, area or length.smooth(): Edges where two faces meet tangentially, such as the borders of a fillet, and the vertices of a sketch where two edges meet tangentially.sort(*, key=None, reverse=False): Sort the list in ascending order and return None.sort_by(key=Axis.Z, reverse=False): Sort by position along an axis, by"length"/"area"/"volume"/"radius", or by any function of a shape.sort_by_distance(point, reverse=False): The shapes by the distance of their centers from a point, nearest first (farthest first withreverse).tangent_chain(): The edges of the list and the edges that continue them tangentially (seeEdge.tangent_chain): whatfilletandchamferround for this selection. Other shapes are left out.top(): Highest shapes (largest Z).translate(x=0.0, y=0.0, z=0.0): Each shape moved by(x, y, z).vertices(): The vertices of all the shapes, each once.wires(): The wires of all the shapes.within(box): Shapes whose bounding box lies insidebox.
Shape
Shape()
Base class of all shapes.
bbox(): Tight axis-aligned bounding box.center(): Center of mass (centroid) of the shape.edges(): All edges of this shape.export(path, **kwargs): Write the shape to a file; the format follows the extension (step, stl, glb, ...).faces(): All faces of this shape.mesh(tolerance=None, angle=15.0, *, max_edge=None): Triangulate the shape (seesmlibpy.mesh.tessellate;max_edgeis the longest edge a triangle may have).mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y).moved(location): A copy of this shape moved by a location (location * shape).on(target): Place this shape, designed around the world XY plane, onto a plane or face.rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError: that would flatten the shape).show(*, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True): Show the shape in the browser viewer (seesmlibpy.show).translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).vertices(): All vertices of this shape.wires(): All wires (closed edge loops of faces, or the shape itself if it is a wire).
MassProperties
MassProperties(mass, volume, area, center, inertia, density)
Mass properties of a part.
inertia is the inertia tensor about the center of mass (axes parallel to the
world axes); principal_moments and principal_axes are its eigen-decomposition.
inertia_about(point): The inertia tensor aboutpoint(axes parallel to the world axes):inertiamoved by the parallel-axis theorem,inertia + mass * (d.d * I - d d^T)withdfrom the center of mass to the point.moment_about(axis): The moment of inertia about an axis (for example a shaft's axis or a pivot):n^T I nwith the inertia tensor about a point of the axis and its unit directionn.principal_axes(property): The principal axes of inertia (directions), in the order ofprincipal_moments.principal_moments(property): The principal moments of inertia, smallest first.radii_of_gyration(property): The radius of gyration about each principal axis,sqrt(moment / mass), in the order
SectionProperties
SectionProperties(area, plane, ixx, iyy, ixy, extent)
Section properties of a planar region (see Sketch.section_properties): the area
and the second moments of area of a profile, for beams, frames and extrusions.
The moments are about the centroid, in the axes of plane (the sketch plane moved to
the centroid): ixx = ∫ y² dA about its x axis, iyy = ∫ x² dA about its y axis and the
product ixy = ∫ x y dA, in mm⁴.
polar(property): The polar moment about the centroid,ixx + iyy(the torsion constant only of a circleprincipal_axes(property): Unit directions (in world coordinates, in the plane) of the principal axes, in theprincipal_moments(property): The second moments about the principal axes through the centroid, ascending.radii_of_gyration(property):(sqrt(ixx / area), sqrt(iyy / area)).section_moduli(property): The elastic section moduli(ixx / c_y, iyy / c_x), withcthe distance from the
Problem
Problem(shape, message, value=None, tolerance=None, category='', test='', other=None)
Something the kernel's validity checks find wrong with a body (see Part.check).
Attributes
-
shape: The face, edge or vertex the problem is about, or the body itself. -
message: What is wrong, with the value measured and the tolerance where there are. -
value: The value measured (a gap, a distance, an angle), orNone. -
tolerance: The tolerance it was held against, orNone. -
category: The kind of test:"gap","geometric","topological","values","degenerate", ... (the kernel's SmAssertType). -
test: The test's short name ("Bad Gap","Bad Loop Connection Vertex"). -
other: A second face, edge or vertex the test compared with, orNone. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
Geometry
Vector
Vector(*args)
An immutable 3D vector or point.
Vector(1, 2), Vector(1, 2, 3), Vector((1, 2, 3)) and Vector(other)
are all accepted. Vectors support +, -, * (by a number), /,
unary -, abs() (length), iteration and indexing.
angle_to(other): Angle to another vector in degrees (0..180).any_perpendicular(): A unit vector perpendicular to this one.cross(other): The cross product with another vector: at right angles to both (right-handed).distance_to(other): The distance to another point.dot(other): The dot product with another vector.is_close(other, tolerance=1e-06): True if the two points are at mosttoleranceapart (mm).is_parallel(other, angle_tolerance=0.0001): True if both vectors point along the same line (either sense), withinangle_tolerancedegrees.is_perpendicular(other, angle_tolerance=0.0001): True if the vectors are at right angles, withinangle_tolerancedegrees.length(property): The length (for a point: its distance from the origin).normalized(): The vector scaled to length 1; ValueError for a zero-length vector.project_to(plane): Orthogonal projection of this point onto a plane.rotate(axis, angle): Rotate this point about an axis (through the origin for a plain vector).to_tuple(): The coordinates as a tuple(x, y, z).x(property): The x coordinate.y(property): The y coordinate.z(property): The z coordinate.
Axis
Axis(origin=(0, 0, 0), direction=(0, 0, 1))
An infinite line through origin along direction.
Axis.X, Axis.Y and Axis.Z (also exported as X, Y, Z) are the
world axes. Axes are used to rotate, revolve, mirror, and to sort or filter shapes.
at(origin): The same direction through another point.direction(property): The axis's direction, of length 1.distance_to(point): The distance of a point from the axis (the whole line).is_parallel(other, angle_tolerance=0.0001): True if the axis runs along another axis or a direction (either sense), withinangle_tolerancedegrees.moved(location): The axis moved by a location: its origin moved, its direction turned.origin(property): A point of the axis (the one it was made with).position_along(point): Signed coordinate ofpointalong this axis.project(point): The point of the axis (the whole line) nearest to a point.reversed(): The axis through the same point, pointing the other way.
Plane
Plane(origin=(0, 0, 0), x_dir=None, z_dir=(0, 0, 1))
A coordinate system: an origin, an x direction and a normal (z_dir).
Planes are where sketches live and where parts are placed. Named planes:
Plane.XY (= Plane.top), Plane.XZ (= Plane.front), Plane.YZ
(= Plane.right), plus back, left and bottom. Their local Y
axis points up (world +Z) for the side views, so a sketch drawn "upwards" stands
up on the front plane.
A planar smlibpy.Face converts to a plane at its center with its
outward normal: Plane(face) or face.plane.
at(origin): The same orientation through another origin.contains(point, tolerance=1e-06): True if the point lies in the plane, at mosttolerance(mm) off it.distance_to(point): Signed distance of a point above the plane.flipped(): The same plane seen from the other side (normal reversed, x kept).from_local(point): The world coordinates of a point given in the plane's coordinates (seeto_local).is_coplanar(other, tolerance=1e-06): True if the other plane is the same plane (either facing), its origin at mosttolerance(mm) off this one.location(property): The location that maps the world XY plane onto this plane.moved(location): The plane moved by a location: its origin moved, its axes turned.normal(property): The plane normal.offset(distance): This plane moveddistancealong its normal.origin(property): The plane's origin.project(point): The point of the plane nearest to a point (straight along the normal).rotated(x=0.0, y=0.0, z=0.0): Rotate about the plane's own X, then Y, then Z axis (degrees).shifted(x=0.0, y=0.0, z=0.0): This plane moved within its own coordinates.to_local(point): A point in the plane's coordinates: along its X and Y directions, and its height above it.x_dir(property): The plane's X direction, of length 1.y_dir(property): The plane's Y direction, of length 1:z_dir.cross(x_dir).z_dir(property): The plane normal.
Location
Location(position=None, rotation=None)
A rigid placement (rotation + translation), stored as a 4x4 matrix.
Build them with Pos and Rot and combine with *. Applying a
location to a shape moves the shape: Pos(10, 0, 0) * Rot(z=45) * Box(1, 1, 1)
first rotates the box about the world Z axis, then moves it 10 along X.
about(axis, angle): Rotation byangledegrees about an arbitrary axis.inverse(): The location that undoes this one.matrix(property): The 4x4 homogeneous matrix (column-vector convention).plane(property): The XY plane moved by this location.position(property): Where the location moves the origin to.rotate_vector(v): A direction turned by the location's rotation (its translation left out).rotation(property): Rotation as X, Y, Z angles in degrees (applied in that order about world axes).x_dir(property): Where the location turns the X direction to.y_dir(property): Where the location turns the Y direction to.z_dir(property): Where the location turns the Z direction to.
Pos
Pos(x=0.0, y=0.0, z=0.0)
A translation. Pos(10, 0, 5) or Pos((10, 0, 5)) or Pos(vector).
Rot
Rot(x=0.0, y=0.0, z=0.0)
A rotation in degrees about the world X, then Y, then Z axis.
BoundBox
BoundBox(min, max)
An axis-aligned bounding box.
center(property): The middle of the box.contains(point, tolerance=1e-06): True if the point lies in the box or on its sides, or at mosttolerance(mm) outside.diagonal(property): The length of the box's diagonal.of_points(points): The smallest box along the axes around the points.size(property): The box's extent along X, Y and Z, as a vector.union(other): The smallest box around both boxes.
Hit
Hit(point, distance, normal, face=None, triangle=None)
Where a ray meets a shape or a mesh (see raycast).
Attributes
-
point: The point where the ray meets the surface. -
distance: How far along the ray, from its start. -
normal: The outward unit normal of the surface there (of the face, or the triangle). -
face: The face that was hit (shapes), orNone. -
triangle: The index of the triangle that was hit (meshes), orNone. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
Nurbs
Nurbs(degree, knots, points, weights)
A curve as a NURBS (see Edge.nurbs).
Attributes
-
degree: The degree of the curve. -
knots: The knot vector, every knot as often as its multiplicity (len(points) + degree + 1of them). -
points: The control points. -
weights: The weight of each control point, orNonefor a non-rational curve. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
NurbsSurface
NurbsSurface(degrees, knots, points, weights)
A surface as a NURBS (see Face.nurbs).
Attributes
-
degrees: The degrees(u, v). -
knots: The knot vectors(u_knots, v_knots), every knot as often as its multiplicity. -
points: The control points, one row per u index:points[i][j]is the pointialong u andjalong v. -
weights: The weights in the same rows, orNonefor a non-rational surface. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
ClosestPoints
ClosestPoints(point, other_point, distance, face=None, other_face=None)
The nearest points of two shapes (see Part.closest_points).
Attributes
-
point: The point on the body the method was called on. -
other_point: The point on the other shape. -
distance: Their distance. -
face: The face of the body the point lies on (at an edge or a corner, one of the faces there). -
other_face: The face of the other shape, orNonewhen it is an edge or a wire. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
Curvature
Curvature(k1, k2, dir1, dir2, normal, point)
The curvature of a face at a point (see Face.curvature_at).
Attributes
-
k1: The larger principal curvature (1/mm): positive where the face bends away from its outward normal (convex, a ball seen from outside), negative where it bends towards it (a bore). -
k2: The smaller principal curvature. -
dir1: The unit direction ofk1, tangent to the face. -
dir2: The unit direction ofk2, square todir1. -
normal: The outward unit normal. -
point: The point on the face. -
count(value): Return number of occurrences of value. -
gaussian(property): The Gaussian curvaturek1 * k2(positive on a ball, zero on a cylinder, negative at a -
index(value, start=0, stop=9223372036854775807): Return first index of value. -
mean(property): The mean curvature(k1 + k2) / 2.
Continuity
Continuity(level, gap, angle, curvature_jump, point)
How two faces meet at an edge, or two edges at the joints of a wire (see
Edge.continuity, Wire.continuity).
Attributes
-
level:"G2"(curvature continuous),"G1"(tangent),"G0"(they meet at an angle) orNone(they do not meet: a gap above the tolerance). -
gap: The largest distance between the two sides. -
angle: The largest angle between the two sides' normals (faces) or tangents (wires), in degrees. -
curvature_jump: The largest difference of the curvatures on the two sides (1/mm): across the edge for faces, of the curvature vectors for wires. NaN where it cannot be had. -
point: Where the sides differ most in what decides the level: the largest gap forNone, the largest angle for"G0", the largest curvature jump for"G1"and"G2". -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
Align
Align(*values)
How a new shape sits relative to the origin along an axis.
MIN puts the shape's lower bound at the origin, CENTER centers it,
MAX puts its upper bound at the origin. Constructors take one value for
all axes or one per axis: Box(10, 10, 2, align=(Align.CENTER, Align.CENTER, Align.MIN))
stands the box on the XY plane.
Parts
Box
Box(length, width, height, *, align=Align.CENTER)
A box of length (X) by width (Y) by height (Z).
Cylinder
Cylinder(radius, height, *, arc_size=360.0, align=Align.CENTER)
A cylinder along Z.
arc_size (degrees, at most 360) makes a sector: the part of the cylinder from the +X axis
counter-clockwise about +Z (planes on its two sides). Like every primitive it is centered by its
bounding box, so a sector's axis moves off Z; align=None keeps it on Z (the sector of the
centered cylinder).
Cone
Cone(bottom_radius, top_radius, height, *, arc_size=360.0, align=Align.CENTER)
A cone (or frustum) along Z; one of the radii may be zero. arc_size makes a sector, as for
Cylinder.
Sphere
Sphere(radius, *, arc_size1=-90.0, arc_size2=90.0, arc_size3=360.0, align=Align.CENTER)
A sphere, or a part of one.
arc_size1 and arc_size2 are the latitudes (degrees, -90 at the bottom pole to 90 at the
top) it reaches from and to: planes parallel to XY cut it there. arc_size3 (at most 360) is the
longitude it spans, from the +X axis counter-clockwise about +Z (planes through the Z axis on its
sides). A part of a sphere is centered by its bounding box; align=None keeps the sphere's center
at the origin.
Torus
Torus(major_radius, minor_radius, *, minor_start_angle=0.0, minor_end_angle=360.0, major_angle=360.0, align=Align.CENTER)
A torus around Z.
major_angle (degrees, at most 360) makes a sector of it, from the +X axis counter-clockwise
about +Z, with round ends. minor_start_angle and minor_end_angle (degrees) keep the part of
the tube's circle between them, as build123d does: measured in the tube's section from the side
away from the axis (0) towards +Z (90), the section a slice of the circle from its center (cones,
planes or cylinders where the slice's straight sides go round). A part of a torus is centered by its
bounding box (align=None keeps the torus's center at the origin)::
top_half = Torus(20, 5, minor_start_angle=0, minor_end_angle=180)
bead = Torus(20, 5, minor_start_angle=-90, minor_end_angle=90) # the outer half
Wedge
Wedge(length, width, height, top_length=0.0, *, align=Align.CENTER)
A ramp: a length (X) by width (Y) base whose high side, height tall, is the
face at x = -length/2; the slope runs down towards +X. top_length gives a flat top of
that length, measured from the -X end.
AnnularSector
AnnularSector(inner_radius, outer_radius, height, arc_size, *, align=Align.CENTER)
A sector of a tube along Z: between inner_radius and outer_radius from the Z axis,
height tall, arc_size degrees (at most 360: a whole tube) from the +X axis counter-clockwise
about +Z. An inner_radius of 0 gives a sector of a cylinder. Centered by its bounding box;
align=None keeps the axis on Z (z from -height/2 to height/2).
Pyramid
Pyramid(length, width, height, *, align=Align.CENTER)
A pyramid: a length (X) by width (Y) rectangle at the bottom, its apex height (Z)
above the rectangle's center; five planes. Centered by its bounding box.
Hole
Hole(radius, depth)
A drilling tool: a cylinder from the origin down to -depth.
CounterBoreHole
CounterBoreHole(radius, counter_bore_radius, counter_bore_depth, depth)
A drilling tool with a counterbore at the top.
CounterSinkHole
CounterSinkHole(radius, counter_sink_radius, depth, angle=82.0)
A drilling tool with a conical countersink of included angle at the top.
Sketches
Profile
Profile(start=(0, 0), *, heading=0.0)
A pen that draws an outline in the XY plane, segment by segment.
Start it at a point with a heading (degrees counterclockwise from +X), then move::
section = (Profile((0, 0))
.line_to(12, 0).line_to(y=4).fillet(1.5)
.line_to(x=6).line_to(y=20).chamfer(1)
.line_to(x=0)
.close()) # a Sketch: extrude or revolve it
Moves: line_to (to a point, or to an x or y), line_by (by an offset),
forward (along the heading, or until x or y reaches a value), arc (tangent, by
radius and angle; a positive angle turns left), arc_to (tangent to an end point, or
through a point). turn/turn_to change the heading without drawing. fillet
and chamfer round or bevel the corner at the pen, between the segment before and
the segment after. mirror(axis) adds the mirror image of the path drawn so far.
close() makes the region, wire() the open path.
Each call returns a new Profile; point and heading tell where the pen is.
Errors name the segment (the call that drew it) and the numbers that do not fit.
arc(radius, angle): A tangent arc ofradiusthat turns the heading byangledegrees: positive turns left (counterclockwise), negative right.arc(5, 180)is a U-turn.arc_to(*point, through=None): An arc to an end point: tangent to the heading (arc_to(20, 10)), or through a point (arc_to(20, 10, through=(15, 12)), which need not be tangent).chamfer(length): Bevel the corner at the pen: cut backlengthalong the segment before and the segment after (measured along them) and join the two points with a line.close(*, align=None): The region inside the outline, as a Sketch on XY: a straight line goes back to the start if the pen is not there.alignmoves the result (Noneleaves the outline where it was drawn).fillet(radius): Round the corner at the pen with a tangent arc ofradius: the corner between the segment just drawn and the next one (at the start point: between the closing segment and the first one).forward(length=None, *, x=None, y=None): A straight line along the heading:lengthlong, or until x reachesx(or y reachesy).heading(property): The direction the pen moves in, degrees counterclockwise from +X (-180 to 180).line_by(dx=0.0, dy=0.0): A straight line by an offset from the pen:line_by(10, -5)orline_by((10, -5)).line_to(*point, x=None, y=None): A straight line to a point:line_to(30, 5)orline_to((30, 5)); or to a coordinate, keeping the other one:line_to(x=30)(horizontal),line_to(y=5)(vertical).mirror(axis): Continue with the mirror image of the path drawn so far, so that the whole outline is symmetric aboutaxis(an axis in the XY plane:X,YorAxis((x, y), direction)). Draw half the outline from the axis back to the axis; an end that is off the axis is joined straight across to its mirror image. Corners rounded on the half are rounded on the mirrored half too.point(property): Where the pen is.start(property): Where the drawing started.turn(angle): Turn the heading byangledegrees (positive: left) without drawing; the next segment starts at a corner.turn_to(heading): Set the heading (degrees counterclockwise from +X) without drawing.wire(): The path as drawn, as an open Wire of exact lines and arcs (a sweep path, or a centerline for Stroke).
Rectangle
Rectangle(width, height, *, fillet=0.0, chamfer=0.0, rotation=0.0, align=Align.CENTER)
A width (X) by height (Y) rectangle.
fillet rounds the four corners with that radius, chamfer bevels them by that
length (at most half the shorter side). rotation turns it about its center (degrees
counterclockwise); align then works on the turned outline.
RoundedRectangle
RoundedRectangle(width, height, radius, *, align=Align.CENTER)
A rectangle with rounded corners; the same as Rectangle(width, height, fillet=radius).
Circle
Circle(radius, *, align=Align.CENTER)
A disk of radius.
Ellipse
Ellipse(x_radius, y_radius, *, rotation=0.0, align=Align.CENTER)
An ellipse with semi-axes x_radius and y_radius, turned by rotation
degrees about its center.
Polygon
Polygon(*points, fillet=0.0, chamfer=0.0, align=None)
The polygon through the points (closed automatically). Points stay where they are
unless align is given. fillet rounds every corner with that radius, chamfer
bevels every corner by that length.
RegularPolygon
RegularPolygon(radius, sides, *, inscribed=False, fillet=0.0, chamfer=0.0, rotation=0.0, align=Align.CENTER)
A regular polygon with sides corners.
radius is the distance to the corners, or to the middle of the sides when
inscribed is true (handy for hexagons measured across flats: radius = flats / 2).
fillet and chamfer round or bevel every corner.
Triangle
Triangle(width, height, *, apex=None, fillet=0.0, chamfer=0.0, rotation=0.0, align=Align.CENTER)
A triangle with a base of width along X and its top corner height above it.
apex is the x position of the top corner measured from the left end of the base:
the middle by default (an isosceles triangle), 0 for a right angle at the left end,
width for one at the right end. The triangle is centered on its bounding box;
fillet and chamfer round or bevel the three corners.
Trapezoid
Trapezoid(width, height, left_angle, right_angle=None, *, fillet=0.0, chamfer=0.0, rotation=0.0, align=Align.CENTER)
A trapezoid with a base of width; the side angles are measured inside the base
corners (right_angle defaults to left_angle). fillet and chamfer round or
bevel the four corners.
Slot
Slot(length, width, *, rotation=0.0, align=Align.CENTER)
An obround slot length long overall (round ends included) and width wide, along
X. For a slot between two centers use Stroke(Line(a, b), width); for one along an
arc, ArcSlot.
ArcSlot
ArcSlot(radius, width, angle, *, rotation=0.0, align=None)
A slot along an arc around the origin: its centerline has radius and runs
counterclockwise over angle degrees from the X axis (turned by rotation); it is
width wide with round ends. The arc's center stays on the origin unless align
is given.
Stroke
Stroke(path, width, *, ends: 'round' | 'flat' = 'round', corners: 'round' | 'sharp' | 'chamfer' = 'round')
The region a pen width wide covers along a path: a slot between two centers
(Stroke(Line(a, b), 6)), a slot along an arc, a rib from its centerline, a groove along a
spline. Lines and arcs give exact lines and arcs; splines and ellipses their offsets
(Edge.offset), within 1e-6 of the path's size.
ends: "round" (half circles, the default) or "flat" (cut square at the end
points). corners: how the outside of a bend is shaped, "round", "sharp" or
"chamfer". A closed path makes a ring. The path stays where it is (in its plane).
Hull
Hull(*items)
The convex hull of points and shapes: the smallest convex region around them, as if a string were pulled tight around them. Around circles and arcs the outline follows the arcs exactly, joined by tangent lines.
items: points (tuples, Vectors, Vertices), edges, wires, sketches or faces, or lists
of them. Hull(Circle(10), Pos(60, 0) * Circle(6)) is a lever outline.
make_face
make_face(outer, *holes)
The planar region inside a closed wire, minus the regions inside holes.
Text
Text(text, size, *, font=None, align=Align.CENTER, spacing=0.0, line_spacing=1.6, kerning=True, path=None)
Lettering as a sketch in the XY plane, with the exact outlines of the font.
Args
text: The text;"\n"starts a new line.size: Height of the capital letters (H, E, T) in mm, the nominal height of technical lettering:Text("H", 10)is 10 mm tall. Round letters overshoot it by a few percent; descenders go below the baseline.font: Path of a TrueType or OpenType font (.ttf,.otf,.ttc,.woff,.woff2), the bytes of such a file (an upload, a font from a package's data), or asmlibpy.font.Fontthatload_fontread. Default: the bundled Lato Regular.align: Placement of the text's layout box (from the start to the end of the longest line, and from the baseline of the last line to the cap height of the first).CENTERcenters it on the origin;MINstarts the text at x = 0 with the last baseline on y = 0;MAXends it at x = 0 with the first cap height on y = 0. One value or one per axis; the lines of a block are aligned the same way (left, centered, right).spacing: Extra distance between neighbouring letters in mm (negative: closer).line_spacing: Distance between baselines as a multiple ofsize.kerning: Apply the font's kerning pairs.path: An edge or wire in the XY plane to set one line of text along. Each letter stands upright on the path at the arc length of the middle of its advance, turned with the tangent; the text reads in the direction of the path and stands on its left side.alignplaces it along the path (MINat its start) and across it (MIN: baseline on the path,CENTER: the middle of the capitals,MAX: their top).
Returns
A Sketch on Plane.XY: one face per separate piece of a letter, counters as holes.
Outlines are exact: straight segments are lines, curved runs are B-splines through the
font's on-curve points.
Raises
ValueError: An empty text, a size that is not positive, a character the font does not have, or a path the text does not fit on. A font file that cannot be read raisessmlibpy.font.FontError, aValueError.
Curves
Line
Line(start, end)
A straight edge from start to end.
Polyline
Polyline(*points, close=False)
Straight segments through the points. close=True connects the last point to the first.
PolarLine
PolarLine(start, length, angle, plane=Plane.XY)
A line of length leaving start at angle degrees from the plane's X axis.
CenterArc
CenterArc(center, radius, start_angle, arc_size, plane=Plane.XY)
An arc around center starting at start_angle and spanning arc_size degrees
(angles counterclockwise from the plane's X axis; a negative arc_size runs
clockwise). CenterArc(c, r, 0, 360) is a full circle.
center is given in plane coordinates.
ThreePointArc
ThreePointArc(start, through, end)
The circular arc from start through through to end.
RadiusArc
RadiusArc(start, end, radius, plane=Plane.XY)
The shorter arc of radius from start to end in plane.
A positive radius bulges to the left of the direction start→end, a negative one to the right.
SagittaArc
SagittaArc(start, end, sagitta, plane=Plane.XY)
An arc from start to end whose middle is sagitta away from the chord
(positive to the left of start→end).
TangentArc
TangentArc(start, end, tangent)
An arc from start to end leaving start along tangent.
Spline
Spline(*points, tangents=None, closed=False)
A smooth cubic curve through the points.
Args
points: Two or more points.tangents: Optional(start_tangent, end_tangent)directions; either may be None. Or one direction for every point (a list as long as the points): the curve passes through each point in its direction.closed: Make a closed loop (smooth at the join).
fit_curve
fit_curve(points, *, tolerance=None, degree=3, tangents=None, closed=False)
A smooth curve near many points, with as few control points as keep it within
tolerance of every one: for scanned or digitized outlines, sampled curves and long
polylines, where Spline passes through every point, follows every wiggle and needs a
control point per point.
A least-squares B-spline: it averages noise smaller than the tolerance out instead of following
it, and takes more control points (spread evenly over the points) until every point is within
the tolerance, measured to the nearest point of the curve. An open curve runs from the first
point to the last; where the points run smoothly there and no tangent is given, it leaves them
in the points' own direction. Below the points' noise it takes up to a control point per point,
and where even that does not keep within the tolerance it raises ModelingError with the
distance it reached (Spline passes through every point).
Args
points: The points in order along the curve: a list of points or an (n, 2) or (n, 3) array (2D points lie at z = 0).tolerance: The largest distance from any point to the curve. Default: 1/1000 of the size of the points.degree: The degree of the curve, 2 to 9.tangents: Optional(start, end)directions; either may be None. Or a direction at every point (as many as there are points, none None; a cubic curve then): the curve leaves each point near that direction, as the curve through the points along them (Spline(*points, tangents=[...])) does, simplified within the tolerance. Not for closed curves.closed: A closed curve, starting and ending near the first point (within the tolerance), as smooth there as elsewhere.
Few points (fewer than six) give the curve through them (Spline). Where no fit
keeps within the tolerance, ModelingError gives the distance it reached. ::
outline = fit_curve(scan_points, tolerance=0.02)
print(len(outline.nurbs().points), "control points")
Bezier
Bezier(*control_points, weights=None)
A Bézier curve (rational if weights are given) from its control points.
Helix
Helix(pitch, height, radius, *, center=(0, 0, 0), direction=(0, 0, 1), end_radius=None, left_handed=False)
A helix around direction through center.
direction is a vector or an axis (only its direction counts; center places the
helix). end_radius makes a conical helix; pitch is the rise per turn. Any number of
turns: beyond 120 the helix is fitted in pieces of whole turns, joined into one curve.
Spiral
Spiral(start_radius, end_radius, turns, plane=Plane.XY, *, clockwise=False)
A flat (Archimedean) spiral around the plane's origin: its radius grows (or shrinks) evenly
with the angle from start_radius to end_radius over turns turns. It starts on the
plane's X axis and turns counterclockwise seen from the plane's normal (clockwise=True:
the other way). Either radius may be 0 (a spiral from or to the center). For spiral springs,
scroll grooves and coils; a B-spline within 1e-4 of the exact spiral, as Helix. Less
than a turn with a large change of radius (Spiral(2, 20, 0.5)) and very many turns
(Spiral(20, 0, 130)) are beyond the kernel's approximation: KernelError, whose hint
says what makes such a curve.
Spiral(2, 20, 5) runs from (2, 0) to (20, 0) in five turns, 9/5 = 3.6 apart.
EllipticalArc
EllipticalArc(center, x_radius, y_radius, start_angle=0.0, end_angle=360.0, plane=Plane.XY)
An ellipse (or elliptical arc) around center in plane.
The angles are ellipse angles in degrees (the point at angle a is
(x_radius cos a, y_radius sin a)). The arc runs counterclockwise from start_angle
to end_angle, also across 0 (300 to 60 passes through the X axis); equal angles give
the whole ellipse.
ParabolicArc
ParabolicArc(vertex, focal_length, start, end, plane=Plane.XY)
A piece of the parabola y = x² / (4 focal_length): its vertex at vertex (in plane
coordinates), opening along the plane's Y axis, from x = start to x = end (measured
from the vertex along the plane's X axis). Exact: a quadratic B-spline. For reflectors, horns
and nozzle contours; a negative focal length opens it along -Y.
ParabolicArc((0, 0), 10, -20, 20) runs from (-20, 10) through (0, 0) to (20, 10); its
focus is at (0, 10).
HyperbolicArc
HyperbolicArc(center, x_radius, y_radius, start, end, plane=Plane.XY)
A piece of the hyperbola x²/x_radius² - y²/y_radius² = 1, the branch on the +X side of
center (in plane coordinates), from y = start to y = end (measured from the center
along the plane's Y axis). Exact: a rational quadratic B-spline. Its vertex is at
(x_radius, 0) from the center and its asymptotes have the slopes ±y_radius / x_radius.
HyperbolicArc((0, 0), 10, 20, -30, 30) revolved about the Y axis is a cooling tower with a
waist of radius 10.
ConicArc
ConicArc(start, apex, end, rho=0.5)
A conic arc from start to end, tangent there to the lines toward apex (the
point where the end tangents meet), with the fullness rho (0 < rho < 1): the arc passes
rho of the way from the middle of the chord to the apex. 0.5 is a parabola, less an
ellipse (flatter), more a hyperbola (closer to the apex). The rho conic of styling: a corner
blend whose shape a single number sets. Exact: a rational quadratic B-spline.
ConicArc((0, 0), (10, 0), (10, 10), 0.4142) is nearly the quarter circle of radius 10
(exactly for rho = sqrt(2) - 1).
FilletPolyline
FilletPolyline(*points, radius, close=False)
A polyline whose corners are rounded with radius.
make_compatible
make_compatible(*edges)
Copies of the curves as B-splines of one degree and one knot vector, with the same shapes: their control points correspond one to one, as surfaces through the curves (a loft, a skin) need them in other systems. Lines and arcs become B-splines too (arcs rational ones).
Args
edges: Two or more edges (or lists of them).
Patterns
Locations
Locations(*items)
A list of locations. Locations((0, 0), (10, 5), ...) takes points, locations,
planes, faces (their center planes) or vertices.
append(object): Append object to the end of the list.clear(): Remove all items from list.copy(): Return a shallow copy of the list.count(value): Return number of occurrences of value.extend(iterable): Extend list by appending elements from the iterable.index(value, start=0, stop=9223372036854775807): Return first index of value.insert(index, object): Insert object before index.on(target): The pattern placed onto a plane or face.points(property): Where the locations move the origin to.pop(index=-1): Remove and return item at index (default last).remove(value): Remove first occurrence of value.reverse(): Reverse IN PLACE.sort(*, key=None, reverse=False): Sort the list in ascending order and return None.
GridLocations
GridLocations(x_spacing, y_spacing, x_count, y_count, *, centered=True)
A rectangular grid in the XY plane, centered on the origin unless centered=False.
PolarLocations
PolarLocations(radius, count, *, start_angle=0.0, angular_range=360.0, rotate=True)
count locations on a circle of radius in the XY plane.
With rotate the copies turn with the pattern (their X axis points outward).
A full circle (angular_range=360) spaces them evenly without repeating the start.
HexLocations
HexLocations(spacing, x_count, y_count, *, centered=True)
A honeycomb pattern: rows spacing apart along X, every other row shifted by half.
Operations
extrude
extrude(profile, amount, *, both=False, taper=0.0, direction=None, corners: 'sharp' | 'round' = 'sharp')
Extrude a sketch, a planar face or a closed wire into a solid (see Sketch.extrude).
An open curve extrudes into a surface (a Shell), along direction (an axis or a
vector) or the normal of the curve's plane; it takes no taper (ValueError).
revolve
revolve(profile, axis=None, angle=360.0)
Revolve a sketch about an axis into a solid (see Sketch.revolve).
An open curve revolves into a surface of revolution (a Shell).
loft
loft(sections, *, ruled=False, smooth=True, start_tangent=None, end_tangent=None, closed=False, rails=None)
A solid through a sequence of cross sections, or a surface through open curves.
start_tangent and end_tangent set the direction the loft leaves its first section in and
reaches its last in, so that it meets the bodies there smoothly; a face there (one that ends at
the section) makes the loft continue it::
neck = loft([Circle(10), Circle(4).moved(Location((0, 0, 30)))], start_tangent=Z, end_tangent=Z)
cap = loft([top_rim, Circle(4).moved(Location((0, 0, 30)))], start_tangent=can.faces().cylinders()[0])
rails are curves a loft of open sections runs along from its first section to its last,
through every section (guide curves): the surface passes through them as through the sections::
panel = loft([s0, s1, s2], rails=[keel, chine])
Args
sections: Two or more sections in order: sketches, planar faces or closed wires for a solid; open edges or wires for a surface (aShell). Sections with holes make a hollow solid; every section needs the same number of holes.ruled: Straight transitions between neighbouring sections.smooth: With four or more sections, pass through them with a cubic surface (False: quadratic). Three sections always give a quadratic one.start_tangent: The direction (an axis or a vector) the loft leaves the first section in: across it, usually along its normal (Zfor a section in the XY plane, as an extrusion of it leaves it). Only the direction counts. The loft is cubic then. Or a face that ends at the first section (the section lies on it, usually along its edge): the loft leaves the section continuing the face, tangent to it all along the section (within 1e-6 radians where the face is a plane, a cylinder, a cone or a sphere about the section, 1e-3 on others).end_tangent: The direction the loft reaches the last section in, or a face that ends at the last section, which the loft runs into tangentially.closed: Run on from the last section through the first again, smoothly (three sections or more): a ring without ends.rails: A curve (an edge or a wire) or a list of them that run from the first section to the last and cross every section once, for open sections (a surface): the loft passes through them as through the sections, within about 3e-7 (a Gordon surface through the sections and the rails, cubic or as near as the counts allow). Where no rail runs along the sections' starts or their ends, the loft's border there runs smoothly through them. Sections and rails must be smooth curves (each is joined into one). Not withruled, the tangents orclosed; closed sections along rails are not supported.
sweep
sweep(profile, path, *, orient=True, translational=False, sharp_corners=None, up=None, twist=0.0, scale=None, anchor='center', rails=None)
Sweep a profile along a path.
The profile is moved so that the center of its box (along the axes of its plane) sits at the
start of the path and (with orient) turned to face along the path, so profiles can be
drawn anywhere, usually in the XY plane::
tube = sweep(Circle(2), Spline((0, 0, 0), (0, 10, 20), (30, 10, 40)))
rail = sweep(Rectangle(4, 2), Helix(pitch=10, height=40, radius=20))
anchor puts another point of the profile on the path: "origin" (the origin of the
sketch's plane) or a point of the profile's plane::
lip = sweep(Rectangle(4, 2, align=(Align.MIN, Align.MIN)), rim, anchor=(0, 0)) # its corner
Edges of a path that meet tangentially are swept as one; at a corner of a path that is not
planar, the profile goes on turned by the smallest rotation from one tangent to the next. Where
the kernel cannot sweep an open path of several edges so, each edge is swept on its own, turned
to its own start, and the pieces are fused (with a RuntimeWarning unless the profile is
round: it turns where the edges meet). A closed path it cannot sweep so (the fuse where the
halves of a loop closed with a kink cross) is swept in pieces, each turned from the path's start
to its own, where that puts the profile on the path. Faces without area that a fuse leaves are taken out (or the sweep
raises ModelingError). The corners of a planar path of several edges are mitered, the
profile placed as on any other path; where they cannot be (arcs that meet at a corner), the path
is swept piece by piece, with a RuntimeWarning.
Along the path the profile turns as little as it can (a rotation-minimizing frame: on a planar
path it keeps its attitude to the plane), except along a helix (also a conical one), where it
keeps its attitude to the helix's axis, as a thread or a flat spring wire does. up and
twist set the attitude instead::
rail = sweep(Rectangle(4, 2), path, up=Z) # stays upright: its angle to Z kept
bar = sweep(Rectangle(10, 2), Line((0, 0, 0), (0, 0, 100)), twist=180) # a half turn
scale grows or shrinks the profile along the path, about the point that sits on it::
horn = sweep(Circle(2), Spline((0, 0, 0), (0, 10, 20), (30, 10, 40)), scale=(1, 3))
spring = sweep(Circle(1), Helix(pitch=8, height=40, radius=15), scale=[(0, 1), (0.5, 1.5), (1, 1)])
A single line or arc is swept as an extrusion or a revolve (planes, cylinders, cones, spheres and
tori, not B-spline surfaces); a profile that reaches across the axis of an arc raises
ModelingError (it would sweep through itself).
Args
profile: A sketch (holes allowed), a planar face or a closed wire.path: An edge, or a wire of connected edges.orient: Turn the profile to be perpendicular to the path at its start.translational: Keep the profile's orientation fixed instead of turning it with the path.sharp_corners: For paths of several edges: miter the corners of a planar path (default for planar paths);Falsesweeps the path piece by piece (each run of tangent edges in one go) and joins the pieces.up: An axis or a direction the profile keeps its attitude to: along the whole path it stands at the angle it starts at toupmade perpendicular to the path (the path must not run alongup)."frenet": to the path's principal normal (towards the center of its curvature; the path must bend everywhere). Default: the axis of a helical path, the smallest turn on others.twist: Degrees the profile turns about the path on top of that, spread evenly along its length; or a function of the fraction of the length (0 at the start, 1 at the end) that gives the angle in degrees there (the profile starts turned bytwist(0)). Along a closed path the profile must come round into itself (a whole number of turns, or of its symmetry).scale: The profile's scale along the path, about the point of it that sits on the path:(start, end)changes evenly along the length;[(t, s), ...]passes through the scalessat the fractionstof the length (from 0 to 1; a smooth curve that does not overshoot them); a function of the fraction gives it. Positive everywhere; along a closed path the same at both ends. Planar paths of several edges are then swept piece by piece (sharp_corners=False).anchor: The point of the profile that goes on the path (and thatscalescales about):"center"(the center of its box along the axes of its plane),"origin"(the origin of the sketch's plane,Sketch.plane: (0, 0) of aPolygonorProfiledrawn on XY, the middle of a centered shape such asCircle, moved with it; for a face, a wire or an edge the point (0, 0, 0)), or a point (a vector or a vertex) of the profile's plane.rails: A second rail (an edge or a wire; the path is the first) for an open profile that runs from the path to it: the profile is moved, turned and scaled (the same in every direction) so that its ends stay on both, and the surface (aShell) passes through both rails, within about 2e-7. The profile's frame turns with the line from the path to the rail and with the rails' mean direction; the rails are matched by the fraction of their lengths, from where the profile meets them to their ends. Not withorient,translational,sharp_corners,up,twist,scaleoranchor, which the rails decide:: hood = sweep(ThreePointArc((0, 0, 0), (10, 0, 4), (20, 0, 0)), left, rails=right)
swing
swing(profile, outline)
Swing a profile around an outline: a revolve about Z whose circle is the outline.
Args
profile: Drawn as for a lathe (seerevolve): in the XZ plane (Plane.front), x the distance from the Z axis (at least 0), z the height. A region (a sketch, a planar face or a closed wire) gives a solid; its edges on the Z axis swing to nothing and are left out, its holes are swung and cut out. An open curve gives a surface (aShell).outline: A closed curve around the Z axis in a plane parallel to XY (its height does not matter), such asEllipse(30, 20)or aRoundedRectangle: a single region or a closed wire or edge. Every ray from the Z axis must cross it once.
At each height the section is the outline scaled about the Z axis so that it passes through the profile's point on the +X side: the cut of the result by the XZ plane on the +X side is the profile. A circle around the origin gives the revolve. The faces are exact (NURBS products of the two curves).
fillet
fillet(edges, radius, **kwargs)
Round edges of the part they belong to (see Part.fillet), or corners of the
sketch they belong to: fillet(s.vertices().concave(), 2) (see Sketch.fillet).
chamfer
chamfer(edges, length, **kwargs)
Bevel edges of the part they belong to (see Part.chamfer), or corners of the
sketch they belong to (see Sketch.chamfer).
fillet_preview
fillet_preview(edges, radius, *, propagate=True)
The surfaces of a fillet's rounds as untrimmed sheets, the part unchanged (see
Part.fillet_preview); takes the edges, as fillet does.
shell
shell(part, thickness, openings=None, *, outward=False, corners: 'round' | 'sharp' | None = None, walls=None)
Hollow out a part (see Part.shell).
offset
offset(shape, distance, **kwargs)
Grow or shrink a part or a sketch by distance (also corners: for a part
"sharp" | "round", see Part.offset; for a sketch "round" | "sharp" | "chamfer",
see Sketch.offset), move a sheet or a face along its normals (Shell.offset,
Face.offset: a sheet), or move a wire or an edge sideways (Wire.offset,
Edge.offset).
draft
draft(part, faces, angle, neutral_plane)
Tilt faces by a draft angle about a neutral plane (see Part.draft).
mirror
mirror(shape, plane=Plane.XZ)
A mirrored copy of a shape (see Shape.mirror; a sketch also in an axis of its
plane, Sketch.mirror).
scale
scale(shape, factor, center=(0, 0, 0))
A scaled copy of a shape or a mesh, about center (see Shape.scale).
split
split(part, plane, keep: 'above' | 'below' | 'both' = 'above')
Cut a part with a plane or along a sheet (see Part.split). Edges and wires split at
parameters or points with their own Edge.split.
merge
merge(*parts)
Parts as one part made of cells: overlaps become cells of their own, touching cells share
their faces (see Part.merge; cells() gives them as parts).
section
section(part, plane=Plane.XY)
Cross-section of a part (see Part.section; of a mesh, Mesh.section).
thicken
thicken(surface, thickness, *, both=False)
Turn a face or sheet into a solid of thickness (both: half of it to each side; see
Shell.thicken).
fuse
fuse(shape, *others)
Union of bodies, a + b (see Part.fuse, Shell.fuse, Sketch.fuse).
cut
cut(shape, *others)
A body less others, a - b (see Part.cut, Shell.cut, Sketch.cut).
intersect
intersect(shape, *others)
What bodies share, a & b (see Part.intersect, Shell.intersect,
Sketch.intersect).
xor
xor(sketch, *others)
The region in exactly one of the sketches, a ^ b (see Sketch.xor).
imprint
imprint(part, tool, direction=None, *, nearest=True)
The part's faces split where a tool crosses them (see Part.imprint).
move_faces
move_faces(part, faces, by)
Move faces by a vector or a location, the part rebuilt around them (see Part.move_faces).
offset_faces
offset_faces(part, faces, distance)
Offset faces along their normals, the part rebuilt around them (see Part.offset_faces).
remove_faces
remove_faces(part, faces, *, partial=False)
The part with a hole, a boss or a pocket taken out (see Part.remove_faces).
remove_fillets
remove_fillets(part, faces=None, *, max_radius=None, partial=False)
The part with fillets taken out and their edges sharp again (see Part.remove_fillets).
push
push(shape, face, at, *, by=None, to=None, normal=None, radius=None, continuity: 'G0' | 'G1' | 'G2' = 'G1')
A smooth dent or bump in a face at a point (see Part.push, Shell.push).
warp
warp(shape, face, region, by, *, continuity: 'crease' | 'G1' | 'G2' = 'G2')
Raise or sink a region of a face (see Part.warp, Shell.warp).
flatten
flatten(shape, face, region, plane, *, continuity: 'crease' | 'G1' | 'G2' = 'G2')
Press a region of a face onto a plane (see Part.flatten, Shell.flatten).
extend
extend(shape, distance, **kwargs)
Extend a sheet or a face past its edges (sides, continuity: see Shell.extend,
Face.extend), or an edge past an end (end, continuity: see Edge.extend).
trim
trim(shape, *args)
Trim a sheet with curves on it, keeping a side (trim(sheet, curves, keep): see
Shell.trim), or an edge or a wire to a stretch of it (trim(edge, start, end): see
Edge.trim, Wire.trim).
match_edge
match_edge(sheet, edge, target, *, extent=0.25)
An edge of a sheet moved onto a curve (see Shell.match_edge).
merge_faces
merge_faces(sheet, a, b)
Two faces of a sheet that share a side made one (see Shell.merge_faces).
project
project(shape, curve, *args, **kwargs)
A curve projected onto a body along a direction (see Part.project), or onto a face
along its normals (see Face.project).
outline
outline(shape, plane=Plane.XY, *, hidden=False, tangent_edges=False)
The lines of a view of a body, also its hidden ones (see Part.outline).
silhouette
silhouette(shape, direction=(0, 0, 1))
The contour of a body seen along a direction (see Part.silhouette).
intersection_curves
intersection_curves(shape, other)
The curves where a body meets another, a face or a plane (see Part.intersection_curves).
parting_line
parting_line(part, direction)
The parting lines of a part for a pull direction (see Part.parting_line).
slices
slices(shape, step, axis=Axis.Z)
Sections of a part (sketches) or a mesh (wires) every step along an axis (see
Part.slices, smlibpy.Mesh.slices).
Deformations
twist
twist(shape, angle, *, axis=Axis.Z, start=None, end=None, tolerance=None)
Twist a part about an axis by angle degrees over its length (or from start to end).
Every cross-section turns by an angle that grows evenly from 0 at start to angle
at end. A cylinder, cone, sphere or torus about the axis maps onto itself and stays as
it was (a twisted tube's walls are its cylinders).
Args
shape: a Part (or a Shell), an Edge, a Wire, or points (a point or a list of them).angle: the turn in degrees betweenstartandend, counterclockwise seen from the tip ofaxis(right-hand rule, likerotate). May exceed 360.axis: the line to twist about (default the world Z axis through the origin).start: where the twist begins, as a distance along the axis fromaxis.origin. Default: where the part begins along the axis. What lies beforestartstays.end: where the twist ends, measured the same way. Default: where the part ends along the axis. What lies beyondendis turned by the wholeangle.tolerance: largest distance of the twisted faces from the exact twist (mm).
Returns a Part (a Shell for a shell). The volume does not change. An Edge gives an Edge, a
Wire a Wire (see bend), a point a Vector, a list of points a list of Vectors; for
points, give start and end (the range of the part they belong to), since a point has
no length along the axis.
taper
taper(shape, scale, *, axis=Axis.Z, start=None, end=None, tolerance=None)
Taper a part along an axis: its cross-sections scale from 1 to scale (exact result).
The cross-sections are scaled toward the axis by a factor that changes evenly from 1 at
start to scale at end.
Args
shape: a Part (or a Shell), an Edge, a Wire, or points (a point or a list of them).scale: size of the cross-section atendrelative tostart(> 0): 0.5 halves it, 2 doubles it. Lines along the axis stay straight.axis: the line the cross-sections shrink toward (default the world Z axis).start: where the tapered range begins, as a distance along the axis fromaxis.origin. Default: where the part begins. What lies beforestartstays.end: where the tapered range ends, measured the same way. Default: where the part ends. What lies beyondendis scaled byscaleacross the axis.tolerance: only for faces whose exact image would exceedMAX_DEGREE(mm).
The result is exact: a cylinder becomes a cone, a box a frustum of a pyramid. Edges, wires
and points give edges, wires and points (see twist).
bend
bend(shape, angle, *, radius=None, plane=Plane.XZ, start=None, end=None, tolerance=None)
Bend a part around an axis by angle degrees, like a bar bent over a mandrel.
plane sets the bend: its x_dir runs along the part, a positive angle bends
the part toward y_dir, and the bend axis is parallel to the plane normal. The layer
of the part through plane.origin (spanned by x_dir and the normal) is the
neutral layer: it keeps its length; material on the inside of the bend is compressed,
material on the outside stretched. With the default Plane.XZ, a part lying along X
bends up (toward +Z) about an axis parallel to Y.
Args
shape: a Part (or a Shell), an Edge, a Wire, or points (a point or a list of them).angle: how far the part turns, in degrees (positive: towardplane.y_dir), less than 360.radius: the bend radius of the neutral layer. Withradiusand nostartorend, the bend (lengthradius * angle) is centered on the plane origin; with one of them, it starts or ends there.start: where the bend begins, as a distance alongx_dirfromplane.origin. Default: where the part begins. What lies beforestartstays.end: where the bend ends, measured the same way. Default: where the part ends, sobend(part, 90)bends the whole part into a quarter circle. What lies beyondendgoes on straight, turned byangle. Withoutradius,startandendset it: radius = (end - start) / angle, with the angle in radians.tolerance: largest distance of the bent faces from the exact bend (mm).
The bend axis lies radius from the neutral layer on the side the part bends toward;
the part must not reach it. Plane faces across the bend become exact cylinders about the
bend axis (and lines across it circles), so a bent plate is a sheet metal part to
Part.bends and smlibpy.unfold. That holds for bends of up to 90 degrees and
of 120, 135, 180, 240 and 270; at other angles the faces are NURBS within tolerance, which
bends() and unfold do not take for bends. The K-factor its neutral layer gives
(where it lies in the thickness) is kept with it. For sheet metal, smlibpy.fold
bends at a line with an inside radius and a K-factor, with flat legs on both sides.
Edges and wires bend too, into paths for sweeps: every edge is split where it crosses
start and end, a line across the bend becomes an exact arc, and lines before and
after it stay lines. A Wire comes back with every piece an edge of its own (a straight path
bent in its middle: line, arc, line), an Edge as one edge (the pieces joined into one
B-spline; pass Wire([edge]) to keep them apart). Points give points (see twist).
unroll
unroll(shape, *, radius, axis=Axis.Z, start=None, tolerance=None)
Unroll a part wrapped around an axis into a flat one: the inverse of bend.
A point at distance r from the axis and at the angle a (radians) about it from
start goes to distance r from the axis along start and radius * a across:
the layer at radius (the neutral layer) keeps its length, material inside it gets
longer and outside it shorter. A rolled sheet (a ring segment of inside radius R and
thickness t) unrolls into a flat plate; as sheet metal, with radius = R + k_factor * t
(smlibpy.unfold does that, also for rolled parts). Cylinders about the axis become
planes, circles about it lines; the faces are exact where their image is a plane, cone,
cylinder, line or circle, and within tolerance elsewhere.
Args
shape: a Part (or a Shell), an Edge, a Wire or points around the axis: it must not reach the axis and must cover less than a full turn about it.radius: the radius of the neutral layer (mm, > 0).axis: the axis the part is rolled about (default the world Z axis).start: a direction across the axis: the line (at every distance from the axis) that stays in place; the unrolled part lies in the plane through it perpendicular tostart. Default: the middle of the part's angle about the axis. The part must not reach the half-plane opposite it.tolerance: largest distance of fitted faces from the exact unroll (mm).
Returns a Part (a Shell for a shell); an Edge, a Wire or points give an Edge, a Wire or points (a helix about the axis unrolls at its own radius into a straight line).
deform
deform(shape, lattice, *, tolerance=None)
Deform a part, a sheet, a curve or points with a lattice: lattice.apply(shape) (see
Lattice and smlibpy.Part.deform).
Lattice
Lattice(box, counts=3, *, margin=0.0)
A grid of control points around a part for free-form deformation (exact results).
The points start evenly spaced over a box (counts points per direction, corners
included). Move them, then apply the lattice to a part: space inside the box moves
smoothly with the points (a Bezier volume; space outside the box follows the same
polynomial). A lattice whose points were not moved changes nothing.
A lattice is a global map, for the overall shape: every point pulls the whole box (most near
itself), so one moved point changes every face it does not leave in place. For a bump or dent
on one face, push or warp that face instead (Part.push, Part.warp): they
change it near a point or within a region and leave the other faces as they are.
points is a writable (nx, ny, nz, 3) numpy array of world positions, indexed
[i, j, k] along X, Y and Z: lat.points[1, 1, -1] += (0, 0, 5) lifts one point.
move, scale and rotate take the same indices ((i, j, k) with ints and
slices, or layer(...)); they change the lattice in place and return it.
Args
-
box: a BoundBox, or a shape whose bounding box is used. -
counts: points per direction, one int or three, 2 to 12. 2 moves the corners only (a trilinear map), 3 adds the midpoints (default). Every point pulls the whole box (Bernstein weights); more points concentrate a point's pull nearer to it without confining it. The degree of the exact result grows with the counts (seeMAX_DEGREE). -
margin: grow the box by this much on every side (mm). -
apply(shape, *, tolerance=None): Deform a part (or a shell) with the lattice; returns the deformed copy. -
box(property): The box the points started on. -
copy(): An independent copy. -
counts(property): Points per direction (X, Y, Z). -
layer(axis, index): The points of one layer across an axis, as an index:lat.layer(Z, -1)is the top layer,lat.layer(X, 0)the points at the smallest X. -
map(point): Where the lattice moves a point. -
move(index, offset): Move the selected points byoffset. In place; returns the lattice. -
offsets(property): How far each point was moved (points - rest). -
reset(): Put every point back where it started. In place; returns the lattice. -
rest(property): The starting positions (read-only). -
rotate(index, axis, angle): Turn the selected points byangledegrees aboutaxis. In place; returns the lattice. -
scale(index, factor, center=None): Scale the selected points aboutcenter(default: their centroid) byfactor, one number or three (X, Y, Z). In place; returns the lattice.
Surfaces
surface
surface(points, *, interpolate=True, controls=None, smoothing=0.01, report=False)
A freeform NURBS surface through a grid of points, or fitted to a cloud of points.
Args
points: Rows of points,points[i][j](a grid: all rows the same length, at least 4 x 4: the surface is bicubic). Or a cloud: points in any order (a list of points, an(n, 3)array, at least 4), such as a scan; the surface approximates them.interpolate: Grids: pass through the points (default).Falseuses them as control points, which gives a smoother surface that only approaches them.controls: Clouds: control points of the surface per direction, a number or(along, across)(4 to 64), "along" the longer side of the cloud. Default: about one per 8 points, shaped like the cloud. More follow finer detail, and noise.smoothing: Clouds: how much the surface resists bending, against how close it comes to the points: 0 to 1, default 1e-2. For noisy points raise it (0.1 to 1), or take fewer control points.report: True returns(sheet, report), aFitReport: how far each point lies from the surface (to its closest point), the largest and the rms distance. About 0.13 s for 1,500 points, 3 s for 20,000.
A cloud must be a height field over its best-fit plane (no overhangs, nothing folded over).
The surface spans the smallest rectangle around the points in that plane; where there are
no points, the smoothing shapes it. Its normal points up (+Z); for a cloud that stands
upright, to +Y, else to +X. A cloud that is not a height field gets a surface that misses it
by millimetres, without an error: check report.max_distance against the noise you expect.
FitReport
FitReport(max_distance, rms_distance, distances)
How far the points given to surface lie from the surface (surface(..., report=True)).
Attributes
max_distance: The largest distance of a point from the surface, to its closest point on it.rms_distance: The root mean square of the distances.distances: The distance of each point (a numpy array, in the order given; a grid's rows one after the other).
The distances are true ones, to each point's closest point on the surface. (A fit's own residuals, at the parameters it gave the points, overstate how far a cloud that is not a height field lies from its surface: 18.3 where the worst point lies 7.4 from it.)
count(value): Return number of occurrences of value.index(value, start=0, stop=9223372036854775807): Return first index of value.
nurbs_surface
nurbs_surface(points, knots=None, degrees=None, weights=None)
A surface from its NURBS data: control points, knots, degrees and weights, as other programs,
files or papers give them (also rational surfaces, other degrees than 3, knots that are not
uniform). The inverse of Face.nurbs().
Args
points: The control points in rows,points[i][j]the pointialong u andjalong v (all rows the same length, at leastdegree + 1each way); or aNurbsSurface(Face.nurbs(): its degrees, knots, points and weights), with nothing else given.knots: The knot vectors(u_knots, v_knots), every knot as often as its multiplicity:len(rows) + u_degree + 1andlen(row) + v_degree + 1knots, not decreasing. The ends need not repeat: the surface spansknots[degree]toknots[-degree - 1]each way (inside the control net where they do not). Default: uniform and clamped (the surface starts and ends at the net's corner points).degrees: The degrees(u, v)(1 to 32), or one for both. Default: from the knots (len(knots) - len(points) - 1), or 3 (less where there are fewer than 4 points).weights: A positive weight per control point, in the same rows;Nonefor a non-rational surface.
Returns
A sheet of one face over the whole surface, its normal along du x dv.
ruled
ruled(a, b)
The ruled surface between two curves (straight lines join matching points).
stitch
stitch(*pieces, tolerance=None, report=False)
Sew faces and sheets along their common edges.
Args
pieces: Faces, sheets, sketches or parts, and lists of them.tolerance: The widest gap to close (default: 1e-4 of the size of all pieces together). Edges and vertices further apart stay open: a gap is never closed silently. Edges that meet closely are sewn first, looser ones after them, up to the tolerance.report: True returns(body, report), aStitchReport: the edges sewn, the free edges left and the widest gap closed.
Returns
A Part when the pieces close around a volume (its faces then point outward),
otherwise a Shell. The faces of an open result are turned to agree with their
neighbours; each connected piece keeps the normal of its first face (in the order given),
so that the sheet thickens.
StitchReport
StitchReport(sewn_edges, open_edges, max_gap, turned_faces, tolerance)
What stitch sewed (stitch(..., report=True)).
Attributes
-
sewn_edges: Pairs of free edges sewn into one edge. -
open_edges: Free edges left: the border of a sheet, and edges whose partner lies further away than the tolerance. -
max_gap: The widest gap closed, between vertices or edges that were sewn (0 where the pieces met exactly). Every gap closed is at mosttolerance. -
turned_faces: Faces turned over so that their normals agree with their neighbours' (on open results; a closed result faces outward anyway). -
tolerance: The widest gap stitch looked for: thetolerancegiven, or its default, or less where every edge was sewn before. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
surface_fillet
surface_fillet(a, b, radius, *, radius2=None, shape: 'round' | 'chamfer' = 'round', sides=(1, 1), trim=False)
A round blend between the surfaces of two faces, as a sheet: for surfaces that are not the
faces of one part, such as two sheets that cross (fillet rounds the edges of a part). Or a
flat one, a chamfer, between the same lines.
Args
a: The first face (or a sheet of one face). Its surface is blended, as far as the surface reaches: the blend may run past the face.b: The second face (or a sheet of one face), the same way.radius: The radius of the blend: of the ball that rolls between the two surfaces.radius2: Chamfers only: a second distance, fromb. The chamfer then runs between the lines below wherea's surface moved out byradiusandb's moved out byradius2cross: for faces at right angles its edge onbliesradiusfroma, its edge onaradius2fromb. Default:radius.shape:"round"(default): a circular cross-section;"chamfer": a flat one, straight across between the lines where the round of the same radius meets the two surfaces (on faces at right angles, legs ofradius).sides: The side of each face the blend lies on: 1 the side its normal (normal_at()) points to, -1 the other. Two crossing surfaces leave four places for a ball to roll, one per combination.trim: True cuts both faces back to the blend's long edges and sews the three into one sheet. The blend's edges must run across both faces, from border to border.
Returns
The blend, a sheet (Shell) whose edges along its length lie on the two surfaces;
with trim the two faces, cut back, and the blend between them as one sheet.
blend
blend(edge_a, edge_b, *, continuity='G2', tension=(1, 1), join=False)
A smooth bridge between free edges of two sheets: a sheet that leaves one sheet across one edge and reaches the other across the other, tangent to both (or curvature-continuous).
Args
edge_a: An edge on the border of a sheet (one face uses it), such assheet.edges().filter(lambda e: len(e.faces()) == 1).edge_b: An edge on the border of another sheet (or of the same one).continuity: How smoothly the blend meets the sheets:"G1"tangent,"G2"with the same curvature across the edges too (default),"G3"also the same change of curvature.tension: How far the blend runs on in each sheet's direction before it turns: its take-off atedge_aandedge_bas a part of the gap between the edges (default 1). One number for both, or a pair. Less is tighter, more bulges.join: True sews the blend to both sheets (stitch) and returns the one sheet.
The blend joins the nearest ends of the two edges (its side edges never cross), and its
normal follows edge_a's sheet. Two closed edges (the rims of two tubes, full circles or
closed loops) are bridged all round: each point of edge_a is joined to the point of
edge_b at the same fraction of its length, counted from its point nearest edge_a's
start and running the same way round. Such a blend is two faces sewn along two seams (the
kernel offsets no face that closes around), as smooth across them as elsewhere. A closed edge
and an open one cannot be bridged.
Returns
The blend, a sheet of one face, of two between closed edges (with join, the two sheets
and the blend sewn into one).
fill
fill(boundary, *, tangent=True)
A surface that fills a closed loop of curves: a hole in a sheet, or the frame of a patch.
Args
boundary: The curves around the hole, in any order and direction: edges on the border of sheets (sheet.edges().filter(lambda e: len(e.faces()) == 1)), curves (smlibpy.Spline,smlibpy.ThreePointArc, ...) or wires. One closed curve (the round edge of a hole), or two, is cut into four sides. Where the curves run into each other without corners (a rim in two or three pieces, cut where a seam crosses it), the four sides are as nearly equal as the curves' ends allow: a round hole is filled the same wherever its rim was cut.tangent: True (default): where the curves are edges of sheets, the patch meets each sheet tangentially along its edge; then every curve must be such an edge, and the sheets must meet each other tangentially where the edges meet (a hole in one smooth sheet, a corner between three rounds). False runs the patch through the curves only, and so do the edges around a planar face or a sketch's region (the patch would cover that face).
Four sides make a Coons patch, of one face (through curves only, it is bilinear: straight across between opposite sides, in the middle the sum of both). Five sides and more make an N-sided fill of one face per side, sewn, meeting in the middle (tangent to the sheets only to about 1.4 degrees: the kernel's N-sided fill). Three sides make an N-sided fill of three faces through curves only; tangent to sheets, a Coons patch whose fourth side shrinks to a point at one corner (a pole there: thickening such a patch fails). Three curves without corners between them make four sides instead.
Returns
The patch, a sheet. Its normal follows the sheets it is tangent to; through curves only,
it follows the right-hand rule around the loop in the direction of the first curve given.
Sew it to the sheets with stitch (stitch(sheet, patch)).
Raises
ValueError: The curves do not close into one loop (the message names the gap), or some curves are edges of sheets and others not whiletangentis True.ModelingError: The patch misses its curves, meets a sheet at an angle, or folds back over the sheets.
network
network(u, v)
A surface through a network of curves: u curves that each cross every v curve.
Args
u: Two or more curves running one way, in any order and direction (splines, arcs, edges; a wire is joined into one curve).v: Two or more curves running across them: each crosses everyucurve once. The outer curves of each set bound the surface: every curve ends on them.
The curves are made to cross at common parameters first (a Gordon surface needs that: the kernel's own missed its curves by 4e-2 on a 10 mm patch otherwise), and the surface is measured against the curves as given.
Returns
A sheet of one face through every curve. Its normal is the first u curve's direction
crossed with the first v curve's, where they cross.
Raises
ValueError: Curves that do not cross (within 1e-4 of the network's size), that cross out of order, or that run on past the outer curves of the other set.ModelingError: The surface misses a curve by more than 1e-4 of the network's size (a very uneven network: curves of more even spacing, or more of them, help).
Sheet metal
Bend
Bend(angle, radius, thickness, k_factor, length, axis=None, line=None, direction=None)
One bend of a sheet metal part.
angle in degrees, radius the inside radius, length the bend's extent along its
axis. From bends, axis is the axis of the bend's cylinders. In a
FlatPattern, line is the bend line (the middle of the bend's strip, at z = 0)
and direction "up" or "down": where the sheet beyond the line folds to, seen from
above (+Z).
allowance(property): The bend allowance (the width of the bend's strip in the flat).
FlatPattern
FlatPattern(part, outline, bends, thickness, k_factor)
The unfolded part, laid on the XY plane: its bottom face at z = 0, the top at z = thickness, the longer side of the smallest rectangle around it along X and its bounding box starting at the origin.
outline is the cut contour (outer boundary and holes) as a sketch at z = 0; bends
carry the bend lines (at z = 0) with angle, radius, direction, K-factor and allowance.
k_factor is the K-factor of every bend, or None where the bends have different ones
(each Bend has its own).
bend_lines(property): The bend lines (middle of each bend's strip), at z = 0.size(property): Size of the blank: (length along X, width along Y, thickness), measured on its edges.
fold
fold(part, line, angle, *, radius, k_factor=0.44, fixed=None, partial=False)
Fold a sheet along a line.
Args
part: A sheet: a solid of constant thickness (a plate, or a part bent before).line: The bend line, anAxisor a straightEdgelying on the top or bottom face of the sheet. It is the middle of the bend: the strip of the bend allowance's width centered on it becomes the bend.angle: Bend angle in degrees, up to 180. A positive angle folds the sheet towards the side the face with the line faces (that face ends up inside the bend); a negative angle folds it the other way.radius: Inside bend radius.k_factor: Position of the neutral fiber, 0 (inside) to 1 (outside). The part keeps it with the bend:unfoldandflat_patterntake it by default.fixed: A point (or a face, edge or vertex) on the side of the line that stays in place; by default the side that reaches farther from the line stays.partial: Bend only along the segmentline(an Edge), not across the whole sheet. The strip next to the segment must be cut free from the rest of the sheet (relief cuts).
Returns
The bent part: the bend faces are exact cylinders of radius and radius + thickness.
flange
flange(part, edge, length, *, angle=90.0, radius, k_factor=0.44)
Add a flange along a straight edge of a sheet.
The sheet is extended beyond the edge and bent there: the bend starts at the edge (the sheet
keeps its size), its inside radius is radius.
Args
part: A sheet (a plate, or a part with bends or flanges).edge: A straight edge where a top or bottom face of the sheet meets a side face (an outer edge, such asplate.edges().filter_by(Y).top().right()).length: Outside length of the flange: from the virtual sharp, where the outside faces of the sheet and the flange meet, to the flange's end. For 90 degrees it is the flange's height over the outside face of the sheet.angle: Bend angle in degrees, below 180. A positive angle folds the flange towards the side the face with the edge faces, a negative one the other way.radius: Inside bend radius.k_factor: Position of the neutral fiber, 0 (inside) to 1 (outside). The part keeps it with the bend, asfolddoes.
unfold
unfold(part, *, k_factor=None, fixed=None)
Unfold a sheet metal part: every bend becomes flat again.
The face fixed (default: the largest planar face) stays where it is; the rest of the
sheet unfolds into its plane. With the K-factor the part was bent with, the result is the
blank it was bent from: by default each bend takes the K-factor fold or
flange made it with (else :data:K_FACTOR, 0.44, as for an imported part).
k_factor gives other ones: one number for every bend, a function (radius, thickness, angle) -> k, a mapping from inside radius to K-factor ({1: 0.33, 6: 0.45}), (r / t, k) pairs to interpolate (a shop's table), or "din6935" (see :data:KFactor). For the
flat pattern on the XY plane, with outline and bend lines, use flat_pattern.
Rolled parts (one bend, no flat sheet: a ring segment), bends at a free end of the sheet (a
curl) and bends over 180 degrees unroll at the neutral radius radius + k_factor * thickness; a rolled part about the middle of its bend (fixed is refused there).
flat_pattern
flat_pattern(part, *, k_factor=None, fixed=None)
The flat pattern of a sheet metal part, laid on the XY plane (see FlatPattern).
k_factor as for unfold: by default each bend's own (from fold and
flange), else :data:K_FACTOR.
The part is unfolded with fixed (default: the largest planar face) staying in place; that
face is the bottom of the flat (z = 0) and bends are "up" when the far side of the sheet
folds towards +Z. The longer side of the smallest rectangle around the blank runs along X, and
the bounding box starts at the origin.
bend_allowance
bend_allowance(angle, *, radius, thickness, k_factor=0.44)
Length of the flat strip that a bend takes: radians(angle) * (radius + k_factor * thickness).
angle is the bend angle in degrees (90 for an L, up to below 360 for a rolled part),
radius the inside radius.
bend_deduction
bend_deduction(angle, *, radius, thickness, k_factor=0.44)
What a bend takes off the sum of the outside leg lengths: 2 * (radius + thickness) * tan(angle / 2) - bend_allowance. The outside lengths run to the virtual sharp, where the
outer faces of the two legs meet (below 180 degrees).
developed_length
developed_length(*legs, angle=90.0, radius, thickness, k_factor=0.44)
Length of the flat blank for a strip bent into legs.
The legs are outside lengths: from the free end, or from the virtual sharp where the outer
faces of two legs meet, to the next virtual sharp (the dimensions on a drawing of the part).
angle is the angle of every bend, or one angle per bend (len(legs) - 1 of them).
The result is sum(legs) - sum(bend deductions).
Simplifying
remove_fillets
remove_fillets(part, faces=None, *, max_radius=None, partial=False)
See Part.remove_fillets.
remove_faces
remove_faces(part, faces, *, partial=False)
See Part.remove_faces.
Molding
parting_line
parting_line(part, direction)
See Part.parting_line.
Meshes
Mesh
Mesh(vertices, triangles, normals=None, _poly=None)
An indexed triangle mesh.
Attributes
vertices:(n, 3)float array of positions.triangles:(m, 3)int array of vertex indices (counterclockwise seen from outside).normals: optional(m, 3, 3)corner normals (one per triangle corner), used for shading crisp CAD edges.
A mesh is its arrays: the kernel's mesh it came from is freed once they are copied out, and
mesh Booleans build one from the arrays when they need it. dispose frees what a mesh
still holds in the kernel at once. The arrays can be changed in place
(m.vertices += (10, 0, 0)); translate, rotate, mirror,
scale and moved return moved copies, as for shapes.
Meshes of scans and STL files: section and slices cut them, decimate
thins them out, fill_holes and repaired close them, mass_properties
measures what they enclose and to_part makes a faceted part of them.
area(property): The total area of the triangles.bbox(): The box along the axes around the mesh's points; ValueError for an empty mesh.center(): The middle of the bounding box (centroidis the center of mass).centroid(property): The center of mass of the volume a closed mesh encloses (uniform density); seedecimate(fraction=None, *, triangles=None, tolerance=None, feature_angle=30.0): A mesh with fewer triangles, as near to this one as the kernel's quadric decimation (SmPolyDecimate) keeps it: it collapses the edges whose removal changes the shape least first, keeps a closed mesh closed and keeps the border of an open one.dispose(): Free the kernel's copy of the mesh now, if it holds one (an internal tessellation can keep it). The arrays stay, and the mesh stays usable: a mesh Boolean builds the kernel's mesh from them again.export(path, **kwargs): Write the mesh to a file; the format follows the extension (seesmlibpy.export).fill_holes(): A copy with every hole closed: each border of edges that only one triangle has, which closes on itself, is filled with triangles (the kernel's triangulation of the polygon, also of one that is not flat). The triangles of the mesh stay as they are; the new ones face as the triangles beside them do. Seerepaired, which also merges points that lie on each other and turns triangles that face the wrong way first.is_closed(): True if every edge of the mesh is shared by exactly two triangles (a watertight mesh).mass_properties(density=1.0): Mass, center of mass and inertia tensor of the volume a closed mesh encloses, for a uniformdensity(asPart.mass_properties, aMassProperties).mirror(plane=Plane.XZ): A mirrored copy (reflection inplane, a plane or a planar face; by default the XZ plane, which flips Y). The triangles keep facing outward.moved(location): A copy placed bylocation.raycast(origin, direction=None): Where a ray meets the mesh's triangles, nearest first (Hit: point, distance from the start, the triangle's normal and its indextriangle). AsPart.raycast, on the triangles instead of the exact faces.raycast_many(origins, directions): The first hit of each of many rays, one per ray (HitorNone), notraycastmany times (which gives every hit of a ray): for each origin, theHitthatraycastgives first (the point, the distance, the triangle's normal and its indextriangle),Nonewhere the ray misses.repaired(): A repaired copy and what was done: points that lie on each other (to 1e-9 of the largest coordinate) are merged, triangles left without an area and repeated ones are left out, triangles are turned to face the way their neighbours face (a closed piece outward), and holes are filled (asfill_holes).rotate(axis=Axis.Z, angle=0.0): A copy rotated byangledegrees aboutaxis.scale(factor, center=(0, 0, 0)): A scaled copy.factoris a number or per-axis factors(sx, sy, sz), none of them zero (ValueError).section(plane=Plane.XY): Where the plane cuts the mesh: polylines (wires of straight edges) through the points where its triangles cross the plane, chained into loops, the longest first.slices(step, axis=Axis.Z): Sections (section) acrossaxis,stepapart: the mesh cut into layers of thicknessstepfrom its lowest point along the axis up, each cut in its middle (atstep / 2,3 * step / 2, ... above the lowest point; the contours of a printer's layers). Layers whose plane cuts nothing are left out.to_part(max_faces=5000): A faceted part of a closed mesh: a planar face for each triangle, where neighbouring triangles that lie in one plane (the faces of a CAD part's mesh) make one face. Exact Booleans with other parts, sections and STEP files work on it; its faces stay flat (no fillets of curved faces).translate(x=0.0, y=0.0, z=0.0): A copy moved by(x, y, z).triangle_normals(property): The normal (length 1) of every triangle, an (n, 3) array; it follows the right-hand rulevolume(property): Enclosed volume (meaningful for closed meshes).
tessellate
tessellate(shape, tolerance=None, angle=15.0, *, max_edge=None)
Triangulate a shape.
Args
shape: A part, sketch, shell or face. A face's mesh faces the way the face does in its body's mesh (out of a part).tolerance: Maximum distance between mesh and exact surface. Default: 0.1 % of the bounding box diagonal.angle: Maximum angle (degrees) between neighbouring triangle normals on curved faces.max_edge: The longest edge a triangle may have (default: no limit): evenly sized triangles for simulation meshes, deformation or sampling, where the tolerance alone leaves a flat face two long triangles. A plate 100 long at tolerance 0.1 gets triangles 100 long;max_edge=10keeps them under 13 (the kernel splits by about that length).
The kernel cuts each face into a grid whose lines it places by the curves along the face's borders. A face that is straight in one direction and twisted along it (the sides of a twisted bar, a ruled loft between different curves, the walls of a thickened free-form sheet) gets no lines across, so a body with such a face is divided by halving its faces until every part is flat within the tolerance: more triangles, but within the tolerance. So is a body with a free-form face whose surface the grid misses (a bump between its lines). On spheres, tori, cones and cylinders, edges whose middle is off the face by more than the tolerance are split onto it (the grid's slivers near the poles of a sphere). Other bodies get the grid's triangles.
With max_edge every body gets the grid (the halving cannot take a longest edge): a body
with a twisted face whose grid triangles are then off by more than twice the tolerance gets a
RuntimeWarning saying how far (a smaller max_edge brings them nearer).
Files
export
export(shapes, path, **kwargs)
Write shapes to path; the format follows the file extension.
export_step
export_step(shapes, path, *, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' = 'mm', name=None, assembly=False)
Exact B-rep export to STEP AP214. Names and colors of parts are kept.
The bodies go into one product called name (default: the file's name), or, with
assembly=True, each into a product of its own, named as the body, in an assembly
called name: other CAD systems then list the parts by name. A body listed more than
once is written once and used at each place.
Edges and wires are written as wireframe curves, vertices and Vectors as points, Planes as
coordinate systems (supplemental geometry), each unnamed; smlibpy.StepCurve,
smlibpy.StepPoint and smlibpy.StepFrame give them names and colors, and
a smlibpy.StepModel (from smlibpy.read_step) is written whole.
smlibpy.read_step reads them back.
export_stl
export_stl(shapes, path, *, tolerance=None, angle=15.0, ascii=False, max_edge=None)
Triangle mesh export (binary unless ascii). tolerance is the maximum deviation,
max_edge the longest edge a triangle may have (see tessellate).
export_glb
export_glb(shapes, path, *, tolerance=None, angle=15.0, edges=True, edge_color='#1f2328', max_edge=None)
Binary glTF export with colors, names and (optionally) the B-rep edges as lines.
glTF is Y-up and measured in meters; the model is written Z-up in millimeters as
modeled, under a root node that turns it upright and scales it by 0.001, so viewers
show it at its real size. Triangles are indexed: each distinct corner (a point with its
normal) is written once. max_edge is the longest edge a triangle may have.
export_gltf
export_gltf(shapes, path, *, tolerance=None, angle=15.0, edges=True, edge_color='#1f2328', max_edge=None)
glTF export with the buffer embedded as a data URI (in meters, like export_glb); the
keywords of export_glb.
export_obj
export_obj(shapes, path, *, tolerance=None, angle=15.0, max_edge=None)
Wavefront OBJ export (one object per part), with the mesh's normals: each corner names
its normal (f v//vn), so edges stay sharp where the faces meet at an angle and curved
faces shade smooth. max_edge is the longest edge a triangle may have.
save
save(shapes, path, *, ascii=True)
Write shapes to SMLib's native files (exact): one body to an .smb file, or bodies and
curves with their names and colors to an .smp part file.
.smb holds one body without name or color. .smp (any other extension writes .smb)
is the kernel's part container: any number of parts, sheets, sketches and faces, each with its
name and color (and a sheet metal part with the K-factors of its bends), and edges and wires as
curves (see to_smp). Reading either back gives
the same geometry; B-spline faces that are exactly planes, cylinders, cones, spheres or surfaces
of revolution come back as those (to_nurbs() does not survive). ascii=False writes the
binary form (bit-exact, about 40 % of the size).
load
load(path)
Read a file, picking the format from the extension: STEP (.step, .stp), IGES
(.igs, .iges), USD (.usda), OpenCASCADE (.brep) and SMLib (.smb,
.smp) give exact parts, DXF (.dxf) a Sketch of the drawing's outlines, STL a
Mesh.
A STEP or IGES file with one body gives that part, one with several a ShapeList. A
native file comes back as a Part when its body encloses a volume (a merged part with
its cells too, and a broken solid, whose is_valid() is False), as a Shell when it
does not; a part file (.smp) with its names, colors and curves (see from_smp). A
body that also holds wire edges, points or faces outside its solid comes with a warning.
import_stl
import_stl(path)
Read an STL file (binary or ASCII) as a mesh.
to_step
to_step(shapes, *, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' = 'mm', name=None, assembly=False)
The text of a STEP AP214 file of the shapes (see export_step). Without a file the
product is called "part" unless name says otherwise.
The text is ASCII (names in other characters are encoded as ISO 10303-21 says); write it with
open(path, "w") or send it as it is: from_step(to_step(part)) reads it back.
to_stl
to_stl(shapes, *, tolerance=None, angle=15.0, ascii=False, max_edge=None)
The bytes of an STL file of the shapes' triangles (binary unless ascii, then the
file's ASCII text as bytes). tolerance is the maximum deviation and max_edge the
longest edge a triangle may have, as in export_stl.
from_stl
from_stl(data)
A mesh from the contents of an STL file (binary or ASCII): its bytes, or the text of an ASCII file.
to_obj
to_obj(shapes, *, tolerance=None, angle=15.0, max_edge=None)
The text of a Wavefront OBJ file of the shapes (one object per part), as
export_obj writes it.
to_glb
to_glb(shapes, *, tolerance=None, angle=15.0, edges=True, edge_color='#1f2328', max_edge=None)
The bytes of a binary glTF (GLB) file of the shapes, with colors, names and (optionally)
the B-rep edges as lines, as export_glb writes it (Z-up in millimeters under a root
node that turns it upright and scales it to meters).
to_gltf
to_gltf(shapes, *, tolerance=None, angle=15.0, edges=True, edge_color='#1f2328', max_edge=None)
The JSON text of a glTF file of the shapes with the buffer embedded as a data URI (in
meters, like to_glb); the keywords of to_glb.
to_smb
to_smb(shapes, *, ascii=True)
The contents of an SMLib native .smb file of one body (exact; ASCII unless ascii is
False), as save writes it.
from_smb
from_smb(data)
The body of an SMLib native .smb file's contents: a Part when it encloses a
volume (a merged part with its cells too, and a broken solid, whose is_valid() is False), a
Shell when it does not.
to_smp
to_smp(shapes, *, ascii=True)
The contents of an SMLib part file (.smp) of the shapes, as save writes it.
A part file is the kernel's own container: any number of exact bodies (parts with their cells,
sheets, sketches and faces as sheets), each with its name and color, and curves (an edge as one,
a wire as its edges). from_smp and load give them back in the same order, with
their names and colors, a wire as a Wire. A sheet metal part keeps the K-factor each
bend was folded with (smlibpy.fold, smlibpy.flange), so that it unfolds as
it was folded; .smb and STEP files do not hold them (pass k_factor= to unfold for a
part read from those). ASCII unless ascii is False; the binary form is bit-exact, the ASCII
form keeps the geometry to 16 decimals.
from_smp
from_smp(data)
The bodies and curves of an SMLib part file's contents (.smp, ASCII or binary): a single
shape when it holds one, otherwise a ShapeList. Bodies come back as Part
(one that encloses a volume) or Shell, named and colored as written, curves as
Edge and Wire; a file of another SMLib program gives its loose surfaces as
sheets of one face each.
import_step
import_step(path, *, heal=True, strict=False)
Read the solids and surfaces of a STEP file (AP203, AP214, AP242 B-rep data).
Returns a single smlibpy.Part (or smlibpy.Shell) when the file
holds one body, otherwise a smlibpy.ShapeList of them. Lengths are converted
to millimeters; assembly placements are applied; names and colors are kept. heal
repairs bodies that come out invalid (valid ones are left alone): the
kernel's healer, then stitching where faces do not share their edges, each with a warning
when it changed the body or could not repair it.
A body that cannot be read (an entity smlibpy does not read, one the kernel cannot build)
is left out with a RuntimeWarning that names it, its entity and the reason; the other
bodies are read. strict=True raises ModelingError for it instead. A file none of
whose bodies can be read raises.
from_step
from_step(data, *, heal=True, strict=False)
Read the solids and surfaces of STEP file contents (the text, or the bytes of the file):
import_step for contents in memory, such as an upload or the text of
smlibpy.to_step.
Returns a single smlibpy.Part (or smlibpy.Shell) when the contents hold
one body, otherwise a smlibpy.ShapeList of them; heal and strict as for
import_step.
read_step
read_step(path, *, heal=True, strict=False)
Read everything a STEP file holds that smlibpy can use: its bodies, and the coordinate systems, curves and points that belong to no body.
The bodies are those of import_step, as a smlibpy.ShapeList also when
there is one. Coordinate systems are the placements of supplemental geometry (as NX,
CATIA and tool catalogs write MCS, PCS or CSW) and the named placements of
shape representations; curves and points are the wireframe geometry (contours such as a
tool's cutting edge line, curve sets, reference points). Each carries its name and the
product it belongs to, at its place in the assembly, in millimeters. Items on hidden
layers are left out. A file with no bodies gives an empty bodies. A body that cannot
be read is left out with a warning and listed in skipped (strict=True raises
instead), as import_step does.
from_step_model
from_step_model(data, *, heal=True, strict=False)
Everything STEP file contents hold that smlibpy can use (the text, or the bytes of the
file): read_step for contents in memory, such as an upload.
StepModel
StepModel(bodies, frames=<factory>, curves=<factory>, points=<factory>, skipped=<factory>)
Everything read_step reads from a STEP file: the bodies (what
import_step returns, always as a list), and the coordinate systems, curves and
points that belong to no body. skipped says which bodies could not be read, and why
("body 'b' (#99): curve type CLOTHOID (#203), which is not supported").
frame(name, product=None): The coordinate system callednameas asmlibpy.Plane. Where several have that name (each part of a tool assembly has its ownMCS),productpicks the one of the product whose name is or begins with it.
StepFrame
StepFrame(name, plane, product='', color=None)
A coordinate system of a STEP file (a named AXIS2_PLACEMENT_3D) at its place in
the assembly. product names the part or assembly it belongs to.
location(property): The placement that moves the world origin onto this coordinate system.
StepCurve
StepCurve(name, shape, product='', color=None)
A curve of a STEP file that belongs to no body (wireframe geometry, contours), at its
place in the assembly: an smlibpy.Edge, or a smlibpy.Wire for a
composite curve.
StepPoint
StepPoint(name, point, product='', color=None)
A point of a STEP file that belongs to no body, at its place in the assembly.
import_iges
import_iges(path, *, heal=True, strict=False)
Read the solids and surfaces of an IGES file (.igs, .iges; IGES 5.3, ASCII).
Returns a single smlibpy.Part (or smlibpy.Shell) when the file holds one
body, otherwise a smlibpy.ShapeList of them, in millimeters whatever unit the file
uses, named and colored as the file has them.
Solids (manifold solid B-rep objects, entity 186) come in as STEP bodies do: each face on
its exact surface, each edge on its exact curve, the faces sharing their edges. Trimmed and
bounded surfaces (144, 143), the way most CAD systems write IGES, share nothing: each becomes
a face, the faces are stitched where their edges meet, and each set of faces that closes up
becomes a part, the others sheets. heal repairs solids that come out invalid, as
import_step does.
Something that cannot be read (an entity smlibpy does not read, one the kernel cannot build)
is left out with a RuntimeWarning that names it and the reason; strict=True raises
ModelingError instead. A file none of whose bodies can be read raises.
from_iges
from_iges(data, *, heal=True, strict=False)
Read the solids and surfaces of IGES file contents (the text, or the bytes of the file):
import_iges for contents in memory; heal and strict as there.
import_dxf
import_dxf(path, *, layers=None, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' | 'ft' | None = None, tolerance=None)
Read the outlines of a DXF drawing as a sketch.
Lines, arcs, circles, ellipses, polylines (bulges become exact arcs), splines (exact NURBS) and inserted blocks are joined end to end into closed loops. Loops nest by the even-odd rule: a loop inside a loop is a hole, a loop inside a hole an island. The result keeps the drawing's coordinates, converted to millimeters.
Args
path: An ASCII DXF file.layers: Read only these layers (names in any letter case).unit: The unit of the drawing ("mm","cm","m","um","inch","ft"), instead of the file's$INSUNITS. A file without a unit is read as mm.tolerance: Ends closer than this (mm) are joined. Default: 1e-7 of the drawing's size.
Raises
ModelingError: Curves that do not close into loops (with their ends and layers), or outlines that branch.
from_dxf
from_dxf(data, *, layers=None, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' | 'ft' | None = None, tolerance=None)
import_dxf of a drawing in memory: the text of a DXF file, or its bytes (an upload).
import_dxf_wires
import_dxf_wires(path, *, layers=None, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' | 'ft' | None = None, tolerance=None)
Every chain of curves of a DXF drawing as a smlibpy.Wire, open or closed.
The curves are read and joined like in import_dxf; chains also stop where three or
more curve ends meet. Closed chains come first, then open ones, each in drawing order.
from_dxf_wires
from_dxf_wires(data, *, layers=None, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' | 'ft' | None = None, tolerance=None)
import_dxf_wires of a drawing in memory: the text of a DXF file, or its bytes.
export_dxf
export_dxf(shapes, path, *, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' | 'ft' = 'mm', plane=None, curves: 'exact' | 'arcs' = 'exact', tolerance=0.01)
Write sketches, faces, wires and edges to a DXF drawing (AutoCAD 2000, AC1015).
Every curve is written exactly: LINE, ARC, CIRCLE, ELLIPSE, or SPLINE with the kernel's
control points, knots and weights. Circular B-splines (the edges of sections) are written as
ARC and CIRCLE, straight ones as LINE. A shape's name becomes its layer. The views of
drawing_views go on the layers VISIBLE and HIDDEN, the hidden lines dashed (the
linetype DASHED: 3 mm dashes, 1.5 mm gaps).
Args
shapes: ASketch,Face,Wire,Edge,DrawingViewor a list of them.path: The file to write.unit: Unit of the file:"mm"(default),"cm","m","um","inch"or"ft". The model (in mm) is converted to it and$INSUNITSsays so.plane: The plane of the drawing; the shapes are written in its coordinates and must lie in planes parallel to it. Default: the world XY plane when the shapes are parallel to it, otherwise the plane of the first sketch (a section inPlane.XZis drawn in that plane's coordinates).curves:"exact"(default) writes splines and ellipses as SPLINE and ELLIPSE;"arcs"writes them as LINE and ARC withintolerance(Edge.to_arcs), for CNC, laser and plasma software that reads only lines and arcs.tolerance: Forcurves="arcs": the largest distance between a curve and its lines and arcs, in millimeters (the model's unit).
to_dxf
to_dxf(shapes, *, unit: 'mm' | 'cm' | 'm' | 'um' | 'inch' | 'in' | 'ft' = 'mm', plane=None, curves: 'exact' | 'arcs' = 'exact', tolerance=0.01)
The text of a DXF drawing (AutoCAD 2000, AC1015) of sketches, faces, wires and edges, as
export_dxf writes it; unit, plane, curves and tolerance as there.
export_usd
export_usd(shapes, path, *, mesh=True, tolerance=None, angle=15.0, materials=False, max_edge=None)
Write parts, sheets and meshes to a USD file (.usda, or .usd as text).
Each body becomes a BrepArray prim under /World, its exact B-rep with its name and
color, and a Mesh prim of it (<name>_mesh), which is what USD viewers draw. The stage
is in millimeters (metersPerUnit = 0.001) with Z up.
Args
shapes: Parts, sheets, faces and meshes (or lists of them). Meshes becomeMeshprims. An empty body (no faces, edges or points) raisesValueError; edges, wires and vertices raiseTypeError(write curves withexport_step).mesh: Write theMeshprim of each body;tolerance,angleandmax_edgeas intessellate.Falsewrites the exact B-reps alone, for usd-brep and Omniverse, which drawBrepArrayprims themselves and would show each body twice.materials: Also give each color aMaterial(aUsdPreviewSurfaceof that color under/World/Looks) bound to the prims of that color, which Omniverse and other renderers use where they leavedisplayColoraside.import_usdreads such bindings back.
to_usd
to_usd(shapes, *, mesh=True, tolerance=None, angle=15.0, materials=False, max_edge=None)
The text of a USD file (.usda) of parts, sheets and meshes, as export_usd writes
it; the keywords as there.
import_usd
import_usd(path, *, heal=False, units=None, placement=True, check=True, strict=False)
Read the bodies of the BrepArray prims of a USD text file (.usda, .usd).
Returns a single smlibpy.Part (or smlibpy.Shell for a body that encloses
no volume) when the file holds one body, otherwise a smlibpy.ShapeList of them,
named and colored as their prims (a body whose prim's name another prim has too is named by
its prim's path). A body's color is that of the material bound to it (the diffuseColor of
the UsdPreviewSurface its material has, through a GeomSubset of bodies, the prim or a prim
above it), or else its prim's displayColor.
The file is read as USD composes it: its subLayers and the files its prims reference
(references, payload) are read too, relative to the file that names them (text USD
only); prims that are abstract (class), inactive (active = false) or only over
hold no bodies. A reference that cannot be read is named in a warning.
Args
heal: Run the kernel's import healer on the bodies.units: The stage's unit,"mm","cm","m","um"or"inch", in place of itsmetersPerUnit.Nonetakes the stage'smetersPerUnit; a stage that has none is taken as millimeters (USD itself takes centimeters then). Lengths come out in millimeters.placement: Place the bodies as the stage does: the transforms (xformOp) of their prims and of the prims above them, and a stage whoseupAxisis"Y"turned to Z up.Falseleaves each body where its prim has it.check: Check each body with the kernel before anything measures it (bodies smlibpy wrote are not checked): a body whose faces, edges and vertices leave gaps of more than 1e-3 of its size cannot be read; smaller gaps give a warning.strict: Raise for the first body that cannot be read.False(as forsmlibpy.import_stepandsmlibpy.import_iges) leaves such bodies out, with aRuntimeWarningfor each that says which and why, and returns the others (as usd-brep'sallow_partial); a file none of whose bodies can be read raisesModelingErrorthen.
A body cannot be read where its BrepArray is malformed (with strict=True a
ValueError that says what is wrong, in which body, face or edge, with the rule of
usd-brep's validator it breaks), where the check refuses it (ValueError), or where the
kernel cannot build it (a KernelError that names it: body 0 of the BrepArray "/World/ball" could not be built). A solid that also holds wire edges, points or faces
outside it (which the schema allows) comes with a RuntimeWarning that names them: such a
Part is not valid.
Edges come back with the curves they had: lines, circles and ellipses that export_usd
wrote as such, and B-spline edges that are lines or circular arcs exactly (usd-brep and
Omniverse write every edge as a B-spline) as lines and circles.
from_usd
from_usd(data, *, heal=False, units=None, placement=True, check=True, strict=False, resolve=None)
The bodies of the BrepArray prims of USD text in memory (.usda: the text, or the bytes
of the file), as import_usd reads a file; the keywords as there.
The layers the text names (subLayers, references, payload) come from
resolve(asset, from_), which gives the text (or bytes) of a layer, or None if it has none:
asset as written, from_ the name of the layer that names it ("" for the text given; a
relative asset is taken from the directory of from_). Without it such layers are not read,
and a warning names them.
export_brep
export_brep(shapes, path)
Write parts, sheets and faces to an OpenCASCADE .brep file (ASCII, as OpenCASCADE's
BRepTools::Write writes it), which build123d (import_brep), CadQuery
(importBrep), FreeCAD and OpenCASCADE itself read.
The file holds one shape: the solid or shell of a single body, or a compound of the bodies
(a part with several solids gives one solid each, a sheet its shell; a sheet whose faces
share no edge, a shell per connected set). Faces keep their exact surfaces (planes,
cylinders, cones, spheres, tori and B-splines; surfaces of revolution and extrusions are
written as the B-splines they are), edges their curves (lines, circles, ellipses, B-splines),
and every edge gets its curves in the parameters of its faces, as OpenCASCADE requires.
Names and colors are not written: the format has no place for them (export_step keeps
them).
Raises ValueError for a body without faces, TypeError for meshes, curves and points,
and smlibpy.KernelError where a body cannot be converted (an edge that lies farther
from its face than 1e-3 of the body's size, a face whose boundary does not close).
to_brep
to_brep(shapes)
The text of an OpenCASCADE .brep file of parts and sheets, as export_brep
writes it: BRepTools::Read and from_brep read it back.
import_brep
import_brep(path, *, heal=False, check=True, strict=False)
Read an OpenCASCADE .brep file (ASCII from BRepTools::Write, binary from
BinTools::Write), as build123d (export_brep), CadQuery (exportBrep), FreeCAD and
OpenCASCADE write it.
Returns a smlibpy.Part for each solid of the file's shape and a
smlibpy.Shell for each shell or face that is no solid's (a single shape when there
is one, otherwise a smlibpy.ShapeList in the order of the file's compound), placed
as the file places them and in its units (millimeters for the tools above). Faces and edges
keep their exact geometry: planes, cylinders, cones, spheres, tori and B-splines come back as
those; surfaces of extrusion and revolution, Bezier surfaces and offset geometry as B-splines.
Args
heal: Run the kernel's import healer on the bodies.check: Check each body with the kernel before anything measures it: one whose faces, edges and vertices leave gaps of more than 1e-3 of its size raisesValueError, smaller gaps give a warning.strict: RaiseModelingErrorwhere a solid, shell or face of the file cannot be read.False(as forsmlibpy.import_step,smlibpy.import_igesandsmlibpy.import_usd) leaves it out with aRuntimeWarningand returns the others.
Curves and points outside faces (wires, edges and vertices of the compound) are not read: a
RuntimeWarning names how many. A file that is not a .brep file, or whose shape holds
no faces, raises ValueError; one the kernel cannot build, smlibpy.KernelError.
from_brep
from_brep(data, *, heal=False, check=True, strict=False)
The bodies of an OpenCASCADE .brep file's contents (the text of an ASCII file, or the
bytes of either kind), as import_brep reads a file; the keywords as there.
Drawings
DrawingView
DrawingView(name, direction, visible, hidden)
One view of a drawing (see drawing_views).
Attributes
-
name:"front","back","top","bottom","left"or"right". -
direction: Where the view looks from: the direction from the part towards the viewer. -
visible: The visible lines, standalone edges in the drawing's plane (world XY). -
hidden: The hidden lines (drawn dashed), likewise. -
bbox(): The box around the view's lines. -
count(value): Return number of occurrences of value. -
index(value, start=0, stop=9223372036854775807): Return first index of value.
drawing_views
drawing_views(part, views=('front', 'top', 'left'), *, projection: 'first-angle' | 'third-angle' = 'first-angle', hidden=True, tangent_edges=False, gap=None)
The views of a part for a 2D drawing, laid out in the world XY plane.
Args
part: A part (or a shell), or a list of them (an assembly): drawn together, each body hiding the lines of the others behind it (bodies that overlap are not cut where they meet).views: The views, by where they look from:"front"(from -Y; the drawing's x is the model's X, its y the model's Z),"back"(from +Y),"top"(from +Z: X and Y),"bottom"(from -Z),"left"(from -X: -Y and Z) and"right"(from +X: Y and Z).projection:"first-angle"(ISO: the top view below the front view, the left view to its right) or"third-angle"(ASME: the top view above it, the left view to its left). The back view goes at the far right.hidden: Draw the hidden lines (DrawingView.hidden, dashed in DXF and SVG);Falseleaves them empty.tangent_edges: Draw the edges between faces that meet tangentially (fillet tangent lines).gap: Space between the views. Default: a fifth of the part's largest extent.
The views of the front row share its height (the model's Z), the views of its column the
front view's x (the model's X). Write them with export_dxf (layers VISIBLE and
HIDDEN, the hidden lines dashed) or export_svg.
export_svg
export_svg(shapes, path, *, margin=None, stroke=None)
Write to_svg of the shapes to a file.
to_svg
to_svg(shapes, *, margin=None, stroke=None)
An SVG drawing of drawing views (dashed hidden lines), edges, wires and the edges of faces and sketches, seen from +Z (their x and y; the SVG's y runs down). Lines and circular arcs are exact, other curves polylines. Lengths are in millimeters: the drawing prints at its true size.
Args
shapes:DrawingView,Edge,Wire,Face,Sketchor a list of them.margin: Space around the lines. Default: 5 % of the drawing's size.stroke: Width of the visible lines (the hidden ones are 0.7 of it, dashed). Default: 0.35 mm, or 1/500 of the drawing's size where that is smaller.
Viewer
show
show(*shapes, title='smlibpy', path=None, open_browser=True, tolerance=None, angle=12.0, edges=True)
Show shapes (parts, sketches, faces, edges, wires, meshes, lists) in a 3D viewer.
In Jupyter the viewer is displayed inline; elsewhere an HTML file is written (to
path or a temporary file) and opened in the default browser. Returns the path,
or the IPython display object in a notebook.
render
render(*shapes, path=None, view='iso', size=(800, 600), edges=True, background='white', tolerance=None, zoom=1.0, look_at=None, frame=None, supersample=2, colors: 'native' | 'distinct' = 'native', lines=False, drawing=False, sheet=False, section=None, cap=True, highlight=None, highlight_at=None, markers=None, annotate=False, xray=False, xray_alpha=0.42, zebra=False, curvature=None)
Render shapes to a PNG image.
The options combine: a sectioned drawing with highlights and markers is fine.
Args
shapes: Parts, sketches, shells, faces, edges, wires, meshes, or lists of them. Edges, wires, and sketches shown together with solids, are drawn on top of everything at their place in space. A read STEP file (read_step) draws its bodies and curves, and marks its coordinate systems and named points.path: Also write the PNG to this file.view: The camera, orthographic, Z up:- a name:
"iso"(default; a true isometric view from front, right and above),"front","back","left","right","top","bottom"; -{"azimuth": a, "elevation": e}in degrees: azimuth 0 looks from the front, 90 from the right (+X); elevation 90 from above."iso"is azimuth 45, elevation 35.264;"right"is azimuth 90; -{"direction": (x, y, z), "up": (x, y, z)}: the direction the camera looks in (from the camera towards the model);updefaults to Z; - a tuple(x, y, z): the direction from the model towards the camera; -"sheet": the same asdrawing="first-angle". Views are never mirrored. size: Width and height in pixels.edges: Draw the edges of faces in the shaded view (hidden edges stay hidden).background: Background color.tolerance: Tessellation tolerance; default 0.1 % of each body's size.zoom: Factor on the scale that fits the shapes (2 shows half as much).look_at: A point that lands in the middle of the picture.frame: The frame of an earlier render of the same view and size (itsPicture.frame, or the picture itself): scale and middle stay the same, so pictures of a changed model compare pixel by pixel (diff_images). Overrideszoomandlook_at.supersample: Render at this many times the size and average down (1 to 4); 2 gives smooth edges. Very large pictures get a lower factor (16 million subpixels at most).colors:"native": each shape's own color, or a palette color by its position;"distinct": a palette color per body, also per solid of a part.lines: Line style instead of shading: no fill, visible edges and silhouettes solid, hidden ones dashed. Applies to the single view and every panel of a sheet.drawing: A technical drawing: front, top and side view in line style, aligned at one scale, and a shaded iso view in the free corner.Trueor"first-angle"(ISO 5456-2 method E): the top view below the front view, the view from the left to its right."third-angle"(method A): the top view above the front view, the view from the right to its right.{"projection": ..., "side": "left" | "right", "iso": bool}picks the side view or leaves the corner empty.sheet: Several shaded views in one picture:True(top, iso, front, right), a list of 4 views (2 x 2) or of 2 views side by side. Named ortho views share one scale; the others fit themselves.drawingwins oversheet.section: Cut at a plane and leave out what is on the positive side of its normal: aPlane, a planar face,(origin, normal)or{"origin", "normal", "cap"}. The picture keeps the framing of the whole model.cap: Fill the cut faces of closed bodies, hatched at 45 degrees (neighbouring bodies alternate the direction); bores and pockets stay open.Falseleaves the cut open and shows the inside walls shaded darker.highlight: Shapes drawn in signal colors: faces and bodies orange, edges red. Faces, edges, wires, parts, vertices or selections (part.edges().concave()).highlight_at: Points; the face closest to each point is highlighted.markers: Crosshairs with labels, drawn on top: points(x, y, z),(point, label), or{"position", "label", "color"}.annotate: Measurement overlay: the size of the bounding box ("60 X 54 X 34"), the axes as seen in the view (an axis pointing into the screen is left out) and a scale bar of a round length.xray: Translucent bodies: hidden faces shine through, edges stay opaque.xray_alpha: Opacity of each face in the x-ray view (0 to 1).zebra: Zebra stripes: the reflection of parallel light lines on the shaded surfaces, from the exact surface normals. Stripes break where surfaces meet with a gap or an edge (G0), kink where they meet tangentially (G1, a circular fillet) and run smoothly across curvature-continuous joints (G2).True, or{"stripes": 16, "width": 0.5, "direction": "vertical"}: the number of black stripes around the light, the black share of each, and the direction of the light lines ("vertical"or"horizontal"on the screen, or a world direction). Surfaces that curve along the light lines show none; turn the direction for them.curvature: A curvature map of the exact surfaces:"mean","gaussian","max"or"min"(the principal curvatures). Blue is concave, white flat, red convex (a sphere of radius R has 1/R everywhere); a legend gives the range in 1/mm (1/mm^2 for Gaussian).{"kind": "mean", "range": 0.2}(or(lo, hi)) fixes the range; by default it spans the values on the shapes.
Returns
A Picture: the PNG file contents as bytes, with .pixels and .frame.
diff_images
diff_images(a, b, tolerance=0)
Compare two pictures of the same size pixel by pixel.
Meaningful for two renders of the same view with a pinned frame (frame= of the
first): without it, a changed model is fitted anew and every pixel moves.
Args
a: A picture fromrender, PNG bytes, a PNG file path, or an(h, w, 3)uint8array.b: The picture to compare with, in any of the same forms.tolerance: Largest difference per color channel (0 to 255) that still counts as equal.
Returns
An ImageDiff: the number, share and bounding box of the changed pixels, and a
picture of the difference (changed pixels red on a faded gray of b).
Picture
Picture(data, pixels=None, frame=None)
A render: the PNG file contents (it is the bytes of the file) and what the render
knows about itself.
Attributes
-
pixels:(height, width, 3)uint8array of the picture. -
frame: The frame of a single view,{"scale", "mid_x", "mid_y"}: output pixels per model unit, and the projected point in the middle of the picture. Pass it asframe=to a later render of the same view and size to get pictures that compare pixel by pixel.Nonefor sheets and drawings. -
capitalize(): B.capitalize() -> copy of B -
center(width, fillchar=b' '): Return a centered string of length width. -
count: Return the number of non-overlapping occurrences of subsection 'sub' in bytes B[start:end]. -
decode(encoding='utf-8', errors='strict'): Decode the bytes using the codec registered for encoding. -
endswith: Return True if the bytes ends with the specified suffix, False otherwise. -
expandtabs(tabsize=8): Return a copy where all tab characters are expanded using spaces. -
find: Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. -
fromhex(string): Create a bytes object from a string of hexadecimal numbers. -
height(property): -
hex: Create a string of hexadecimal numbers from a bytes object. -
index: Return the lowest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. -
isalnum(): B.isalnum() -> bool -
isalpha(): B.isalpha() -> bool -
isascii(): B.isascii() -> bool -
isdigit(): B.isdigit() -> bool -
islower(): B.islower() -> bool -
isspace(): B.isspace() -> bool -
istitle(): B.istitle() -> bool -
isupper(): B.isupper() -> bool -
join(iterable_of_bytes): Concatenate any number of bytes objects. -
ljust(width, fillchar=b' '): Return a left-justified string of length width. -
lower(): B.lower() -> copy of B -
lstrip(bytes=None): Strip leading bytes contained in the argument. -
maketrans(frm, to): Return a translation table usable for the bytes or bytearray translate method. -
partition(sep): Partition the bytes into three parts using the given separator. -
removeprefix(prefix): Return a bytes object with the given prefix string removed if present. -
removesuffix(suffix): Return a bytes object with the given suffix string removed if present. -
replace(old, new, count=-1): Return a copy with all occurrences of substring old replaced by new. -
rfind: Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. -
rindex: Return the highest index in B where subsection 'sub' is found, such that 'sub' is contained within B[start,end]. -
rjust(width, fillchar=b' '): Return a right-justified string of length width. -
rpartition(sep): Partition the bytes into three parts using the given separator. -
rsplit(sep=None, maxsplit=-1): Return a list of the sections in the bytes, using sep as the delimiter. -
rstrip(bytes=None): Strip trailing bytes contained in the argument. -
save(path): Write the PNG file. -
split(sep=None, maxsplit=-1): Return a list of the sections in the bytes, using sep as the delimiter. -
splitlines(keepends=False): Return a list of the lines in the bytes, breaking at line boundaries. -
startswith: Return True if the bytes starts with the specified prefix, False otherwise. -
strip(bytes=None): Strip leading and trailing bytes contained in the argument. -
swapcase(): B.swapcase() -> copy of B -
title(): B.title() -> copy of B -
translate(table, delete=b''): Return a copy with each character mapped by the given translation table. -
upper(): B.upper() -> copy of B -
width(property): -
zfill(width): Pad a numeric string with zeros on the left, to fill a field of the given width.
ImageDiff
ImageDiff(changed, total, fraction, bbox, picture)
The result of diff_images.
Attributes
-
changed: Number of pixels that differ. -
total: Number of pixels. -
fraction:changed / total. -
bbox:(x0, y0, x1, y1)of the changed pixels (inclusive), orNone. -
picture: APictureof the difference: changed pixels red on a faded gray of the second picture. -
save(path): Write the picture of the difference as a PNG file.
html_page
html_page(*shapes, title='smlibpy', tolerance=None, angle=12.0, edges=True, view=(1.0, -1.25, 0.75), margin=1.1)
A self-contained HTML page showing the shapes.
view is the direction from the model towards the camera (Z up).
Errors
ModelingError
ModelingError
A modeling operation cannot be done (for example a fillet radius that does not fit).
add_note(note): Add a note to the exceptionwith_traceback(tb): Set self.traceback to tb and return self.
KernelError
KernelError(operation, detail, status=None, hint=None)
An SMLib operation failed.
operation names the smlibpy call, status the kernel status code
(e.g. SM_ERR_INVALID_INPUT) and hint a suggestion when one is known.
trace says where the kernel gave up: the failures it reported during the call, oldest
first, at most the last 48, as "SM_ERR at SmFilletExecutive.cpp:1603 (DoFillet)". It
ends with the chain from the deepest function that failed to the kernel's API function;
what comes before are errors the kernel recovered from. Empty where the error did not come
from a kernel function. For bug reports: the sites change with the kernel.
add_note(note): Add a note to the exceptionwith_traceback(tb): Set self.traceback to tb and return self.