Skip to content
AlphaToolBox3D is in early alpha: features are incomplete and things can break. Use it at your own risk and keep copies of your files. Report a problem
ToolBox3D

Docs · Scripting

Python API reference

The toolbox3d package as the Script Editor and tbpy load it. Generated from the app itself, so every name and default here matches the editor.

import toolbox3d as tb

ToolBox3D's Python API — the same on the website and in the Windows app.

import toolbox3d as tb
cube = tb.scene.get("Cube")
cube.transform.position = (0, 1, 0)
tb.ops.scene.duplicate(nodes=[cube])
with tb.undo.group("Build fence"):
    ...

tb.ops holds every registered operation (generated from the app's operation registry); tb.scene the document (objects, materials, clips, skeleton, rig); tb.types the handles; tb.events handlers that run when the artist changes the selection, the document or the editor; tb.undo the history; tb.io files (open, import, export, save); tb.ui messages and questions; tb.app where the script runs (tb.app.is_headless under tbpy); tb.math vectors, quaternions, matrices, colors, planes and KD-trees. Errors are tb.ToolBox3DError subclasses.

New to scripting? Start with the scripting guide or the examples.

tb.scene

The document: objects, lookup, selection, sets, materials and the active editor.

import toolbox3d as tb cube = tb.scene.get("Cube") for obj in tb.scene.objects(type="mesh"): print(obj.name, obj.mesh.vertex_count)

tb.scene.objects(type=None)

Every object in outliner order; type="mesh" keeps one kind.

tb.scene.get(name)

The object called name (or with that outliner path).

Raises NotFound when nothing matches and AmbiguousName (listing the ids) when several objects share the name.

tb.scene.by_id(ident)

The object with this stable id (NotFound if it was deleted).

tb.scene.find(name)

Every object called name (possibly none).

tb.scene.create_mesh(name, positions, faces, uvs=None)

Builds a mesh object from arrays in one undo step and returns it.

positions: one (x, y, z) per vertex (a list or numpy (N, 3) array); faces: lists of vertex indices; uvs: optional, one (u, v) per face corner in face order. Runs create.mesh_from_data.

tb.scene.selection

The active editor's selection: tb.scene.selection.objects, .set([...]).

.objects property

Selected objects (active last).

.active property
.mode property

"object", "vertex", "edge", "face", "island" or "cv".

.set(self, objects, mode='replace')

Selects objects; mode is "replace", "add", "remove" or "toggle".

.add(self, objects)
.remove(self, objects)
.clear(self)
.components(self, mesh=None)

The selected components as dense indices, one dict per mesh with a component selection (or only mesh): {"mesh", "name", "vertices", "edges", "faces", "active"}, active being {"kind", "index"} or None: selection.components.

.all(self)

class tb.scene.Set

A set, addressed by name: an Object Set (type "object": objects, joints, controls — sets.*) or a component set stored on its meshes ("vertex", "edge", "face", "island" — mesh.set.*), including each mesh's built-in "Seam Set" and "Hard Edge Set". members are names such as "Cube", "joint:Hips" or "Cube.vtx[0:7]". Sets hold membership only: graded values are the weight maps of the modifier, skin or cloth that uses them.

.name property
.type property
.quick_select property

A Quick Select Set (Object Sets only: also on the sets bar).

.members property

Member names.

.add(self, members=None)

Adds members (default: the selection).

.remove(self, members=None)

Removes members (default: the selection).

.set_members(self, members)

Replaces the members.

.select(self, mode='replace')

Selects the members; mode is "replace", "add", "remove" or "toggle".

.mark_edges(self, as_='seams')

Marks an Edge Set's edges as "seams" or "hardEdges".

.delete(self)

Deletes the set (not its members).

tb.scene.sets

The scene's sets — Object Sets and every mesh's component sets: iterate, tb.scene.sets["Hands"], create(...), union / intersection / difference.

.list(self, type=None, member=None)

Sets as dicts (set, type, member count; component sets also object and builtin, one row per mesh). type keeps one type; member keeps the Object Sets holding that object and the component sets of its mesh.

.get(self, name)

The set called name (an Object Set first); NotFound otherwise.

.create(self, name=None, members=None, type=None, quick_select=False)

Creates a set from members (default: the selection). Component members ("Cube.vtx[0:7]", or selected components) make a component set on their meshes; objects, joints and controls an Object Set (quick_select=True: a Quick Select Set). type ("vertex" … or "object") is needed only for an empty set.

.union(self, sets, name=None)

A new set with the members of any of sets.

.intersection(self, sets, name=None)

A new set with the members common to all sets.

.difference(self, sets, name=None)

A new set with the members of the first of sets in none of the others.

tb.scene.materials

Scene materials: iterate, get(name), new(name, **fields).

.get(self, name)
.new(self, name, **fields)

Creates a material: tb.scene.materials.new("Rust", roughness=0.8) → material.create.

tb.scene.clips

The document's animation clips: iterate, get(name), new(name, duration, fps).

.get(self, name)

The clip called name (or with that id); NotFound if there is none.

.new(self, name, duration=1.0, fps=30.0)

Creates a clip duration seconds long: animation.create_clip (a control-rig clip when the document has a control rig, else a skeleton clip).

tb.scene.skeleton()

The document's skeleton (bones and their rest pose), or None.

tb.scene.rig()

The document's control rig (its modules), or None.

tb.scene.editor()

The active editor: "previewer", "model", "control_rig", "animation" or "texture_paint".

tb.scene.set_editor(name, decisions=None, reconcile=None)

Switches editors (pushing and reconciling like the editor switcher). Edits that must be reconciled into the shared scene first (Changes Detected) are answered by decisions ("recommended": every row's recommended answer; "safe": safe rows only; "ask"; or [{"id": ..., "choice": ...}]) and reconcile ({"skin": "transfer.uv", "clips": "rebake", ...}: one choice per kind of change or exact family), as for tb.io.save; without them Settings ▸ Reconciler decides. Unanswered rows raise NotApplicable whose detail["needsDecision"] lists each row (id, kind, family, summary, choices, recommended, risky), and you stay in the current editor.

Operations switch on their own: calling one another editor owns (tb.ops.create.cube in the Control Rig editor) switches there first, answering safe rows with their recommendation (Result.switched).

tb.scene.preview_editor(name)

The Changes Detected rows switching to editor name would raise now, without switching: a list of {id, kind, family, summary, choices, recommended, risky}.

tb.scene.ray_cast(origin, direction, nodes=None, mesh=None, include_hidden=False, max_distance=None)

The nearest surface hit along a ray, as a dict (node, name, mesh, point, normal, distance, face) or None: scene.ray_cast. Meshes are read as stored, in world space (or mesh's own space).

tb.scene.closest_point(point, nodes=None, mesh=None, include_hidden=False, max_distance=None)

The nearest surface point to point, as a dict like ray_cast's or None: scene.closest_point.

tb.types

Typed handles over the document.

A handle is an id plus a type. Reading a property asks the app for the current state (cached until the document changes); setting a property runs the matching registered operation, so it is validated, undoable and owned exactly like the same edit in the UI.

class tb.types.Result

What an operation returned: value (its JSON result), label (the undo entry), changed, notices, the objects it created / removed, and switched: when another editor owns the operation, the script switched there first ({"from", "to", "answered": [...]}, the Changes Detected rows answered on the way; also printed), else None.

.created property

New objects, in creation order.

.removed property

Names of the objects the operation deleted.

class tb.types.Transform

An object's local transform. Rotation is XYZ Euler in degrees; lengths in scene units.

Setting position, rotation_euler or scale runs scene.set_transform.

.position property
.rotation_euler property
.rotation_quaternion property

(x, y, z, w).

.scale property

class tb.types.Object(_Handle)

A scene object (mesh, curve, solid, group, light, camera, …).

.name property
.path property

Outliner path, e.g. "Rig/Body".

.type property

"mesh", "curve", "solid", "group", …

.parent property
.children property
.visible property
.locked property
.selected property
.transform property
.bbox property

World-space bounds of the object's geometry, or None.

.mesh property

The mesh this object places, or None.

.curve property

The curves this object places, or None.

.solid property

The solid (an authored B-rep body) this object places, or None.

.evaluated_mesh(self)

The geometry after the modifier stack, as the viewport shows it: (positions, faces) with positions a numpy (N, 3) float32 array in object space and faces a list of vertex-index lists. A mesh without modifiers gives its own data; a curve with a Pipe or Fill gives the generated mesh.

.delete(self)

Deletes the object (and its children): scene.delete.

.duplicate(self)

Duplicates the object and returns the copy: scene.duplicate.

class tb.types.Mesh(_Handle)

Mesh data. Bulk data comes as numpy arrays.

.name property
.vertex_count property
.edge_count property
.face_count property
.visible_face_count property

The faces an artist sees: faces joined by hidden splits (a face with a hole) count once.

.hidden_split_count property

The hidden edges that join the pieces of a face with a hole.

.material_slots property
.positions(self)

Vertex positions as a numpy (N, 3) float32 array (a snapshot).

.set_positions(self, positions)

Replaces every vertex position (one operation, one undo step).

.read_data(self, attribute=None, weight_map=None, edge_data=None)

One data layer as a numpy array, one row per element of its domain ((N,) for one value per element, (N, k) otherwise): an attribute by name, a weight map (0 where a vertex is not a member) or edge data ("crease", "bevelWeight", "sharp", "seam", "vertexCrease", "vertexBevelWeight"): mesh.data.read.

.set_topology(self, positions, faces, loose_edges=None)

Replaces the vertices and faces in place, keeping this mesh, its objects and its data layers (carried over by vertex, face, edge and corner); one undo step: mesh.set_topology.

.faces(self)

Faces as a list of vertex-index lists.

.edges(self)

Edges as a numpy (E, 2) array of vertex indices.

.edge_lengths(self)

Length of each edge, (E,).

.edge_midpoints(self)

Middle of each edge, (E, 3).

.face_centroids(self)

Mean of each face's corners, (F, 3).

.face_normals(self)

Unit normals (Newell), (F, 3); degenerate faces give zero.

.face_areas(self)

Area of each face, (F,).

.area property

Total surface area.

.bounds(self)

Local-space bounds of the vertices, or None for an empty mesh.

.nearest(self, point, k=1)

Indices of the k vertices nearest point, nearest first.

.within(self, point, radius)

Indices of the vertices within radius of point.

.is_closed(self)

Every edge borders exactly two faces (watertight).

.is_manifold(self)

No edge borders more than two faces.

.shells(self)

Connected pieces, each a sorted list of vertex indices.

.uvs(self, map=None)

A UV map (default: the active one) as a numpy (corners, 2) array, face corners in face order (the order of faces()).

.set_uvs(self, uvs, map=None, corners=None)

Writes UVs in one undo step: every corner, or only corners (one UV each).

.uv_islands(self, map=None)

UV islands as lists of face indices (faces join where their UVs continue and no seam separates them).

.uv_pins(self, map=None)

The pinned face corners of a UV map.

.vertex(self, index)

Handle of vertex index.

.edge(self, index)

Handle of edge index (the order of edges()).

.face(self, index)

Handle of face index (the order of faces()).

class tb.types.Vertex(_Component)

A vertex: position (settable), neighbors, edges, faces, ring(n).

.position property
.neighbors property
.edges property
.faces property
.is_boundary property
.ring(self, n=1)

Vertices within n edge steps (not this one).

class tb.types.Edge(_Component)

An edge: vertices, faces, length, is_boundary; bevel(), extrude(), mark_seam(), clear_seam().

.vertices property
.faces property
.length property
.is_boundary property
.bevel(self, **params)
.extrude(self, **params)
.mark_seam(self)
.clear_seam(self)

class tb.types.Face(_Component)

A face: vertices, num_verts, normal, area, centroid; extrude(), inset(), poke(), triangulate(), reverse_normals().

.vertices property
.num_verts property
.normal property
.area property
.centroid property
.extrude(self, **params)
.inset(self, **params)
.poke(self, **params)
.triangulate(self, **params)
.reverse_normals(self)

class tb.types.Material(_Handle)

A material.

.name property
.get(self, field)

A material field: "roughness", "base_color", "metallic", …

.base_color property
.roughness property
.metallic property
.set(self, **fields)

Sets material fields in one undo step: mat.set(roughness=0.3, base_color=(1, 0, 0, 1)) → material.set.

.assign(self, *objects, slot=None)

Assigns this material to the meshes of objects: material.assign.

class tb.types.Curve(_Handle)

Curve data (one or more splines) placed by an object. Control points come as numpy arrays in the curve's local space; set_point runs curve.set_point.

.name property
.point_count property
.splines property

The splines in order: each has type, cyclic and positions().

.positions(self)

Every control point as a numpy (N, 3) float32 array, spline by spline.

.set_point(self, index, position)

Moves control point index (as in positions) to position (local space; its handles follow): curve.set_point.

class tb.types.Spline

One spline of a Curve: type ("bezier", "nurbs", "poly", "catmullrom"), cyclic, and its control points.

.type property
.cyclic property
.point_count property
.positions(self)

This spline's control points, a numpy (n, 3) float32 array.

class tb.types.Solid(_Handle)

An authored B-rep body (from OpenSCAD, CAD import, …): read-only metadata. Its display mesh is obj.evaluated_mesh().

.name property
.body_class property

"solid", "sheet", …

.geometry_kind property
.unit property

The unit the body was authored in.

class tb.types.Clip(_Handle)

An animation clip: name (settable), fps, duration (seconds), frames, kind and its curves. Keys are edited with AnimCurve.insert_key and the tb.ops.animation operations.

.name property
.kind property

"skeleton", "control_rig" or "vertex".

.fps property
.duration property
.frames property

The last frame (duration × fps).

.curves property

Every animation curve: target (what it drives), property and its keys.

.curve(self, target, property)

The curve driving property ("translateX", "weight", …) of the bone, control, object or blendshape named target; NotFound if none.

.set_key(self, target, frame, **channels)

Keys channels of the bone, control or object target at frame: clip.set_key("Hips", 12, translate_x=0.4, rotate_y=10) → animation.set_key. A channel given as None keys its current value.

.delete(self)

Deletes the clip: animation.delete_clip.

class tb.types.AnimCurve

One animation curve of a Clip.

.id property
.target property

What the curve drives: {"kind": "bone" | "control" | "object" | "blendshape", "id", "name"}.

.target_name property
.key_count property
.keys(self)

The keys as a numpy (K, 2) float64 array of (frame, value).

.insert_key(self, frame)

Inserts a key at frame without changing the curve's shape: animation.insert_key.

.property property

The animated attribute: "translateX", "rotateY", "weight", …

class tb.types.Bone

One bone of the Skeleton: name, parent and its rest pose relative to the parent (translation, rotation as (x, y, z, w), scale).

.id property
.name property
.parent property
.children property
.translation property
.rotation property

The rest rotation as a quaternion (x, y, z, w).

.scale property

class tb.types.Skeleton

The document's skeleton (a snapshot): bones in order, bone(name), roots.

.name property
.bones property
.roots property
.bone(self, name)

The bone called name; NotFound if there is none.

class tb.types.Rig

The document's control rig (a snapshot): name and its modules (each a dict of id, type, name, side and parent). Rigs are built and edited with the tb.ops.controlrig operations.

.id property
.name property
.modules property

tb.events

Handlers that run when the artist changes something.

import toolbox3d as tb
@tb.events.on("selection_changed")
def report(e):
    print(len(e.selection), "selected")

Events: selection_changed (e.selection: the selected objects), document_changed (an edit or undo step) and editor_changed (e.editor: the editor's name). They fire after the artist's own changes, not a script's, so a handler that edits the scene does not call itself again. Each time, the handlers run as one script run: their edits are one undo step and an error is shown in the Script Editor. Handlers stay until off or until the interpreter restarts; running a script again replaces its handlers instead of adding copies.

tb.events.on(name)

Decorator: fn(event) runs whenever name happens (one of EVENTS).

tb.events.off(name, fn=None)

Removes fn (every handler of name when fn is omitted).

tb.events.handlers(name)

The handlers listening to name, in the order they run.

class tb.events.Event

What happened: name and data (the app's details, also readable as attributes).

.selection property

The selected objects (selection_changed).

tb.math

Value types, linear algebra and pure caller-unit curve math (numpy-friendly).

Vec2 / Vec3 / Vec4 are immutable tuples with arithmetic; anything that takes a vector also takes a plain tuple, list or numpy array of numbers. Quat is (x, y, z, w); Mat3 / Mat4 are row-major and act on column vectors (m @ v, a @ b applies b first). Angles are degrees and Euler orders match the app's rotate orders ("XYZ" is the channel-box default). Color is linear RGBA. Plane, Sphere, BBox and KDTree (nearest-neighbour queries over 2D or 3D points) complete the set. All of it is plain Python: no scene access, no undo steps.

Curve helpers share the app's Rust kernels on native Python and Pyodide. They return data, never scene objects or undo steps. Path/frame requests are bounded to 100000 sample rows; banking smoothing has a ten-million-row work budget. No grid-unit conversion is applied.

class tb.math.Vec3(tuple)

An immutable 3D vector: Vec3(1, 2, 3), v.x, v + w, v * 2, abs(v).

.x property
.y property
.z property
.length property
.normalized(self)
.dot(self, o)
.cross(self, o)
.distance(self, o)

Distance to point o.

.lerp(self, o, t)

The point t of the way from this one to o (t = 0..1).

class tb.math.Vec2(_VecN)

An immutable 2D vector (UVs, screen points): Vec2(u, v), .x, .y.

.x property
.y property
.cross(self, o)

The z of the 3D cross product (signed parallelogram area).

class tb.math.Vec4(_VecN)

An immutable 4D vector (homogeneous points): Vec4(x, y, z, w).

.x property
.y property
.z property
.w property
.xyz property

class tb.math.Quat(tuple)

A rotation quaternion (x, y, z, w), the order Transform.rotation_quaternion returns. a @ b applies b then a; q @ v rotates a vector.

.x property
.y property
.z property
.w property
.identity(cls)
.from_axis_angle(cls, axis, degrees)

Rotation of degrees about axis (right-handed).

.from_euler(cls, degrees, order='XYZ')

Euler angles (x, y, z) in degrees; order as the app's rotate order ("XYZ" composes X @ Y @ Z, so Z applies first, matching the channel box).

.rotation_between(cls, a, b)

The shortest rotation turning direction a onto direction b.

.from_matrix(cls, m)

The rotation of a Mat3 / Mat4 (scale-free upper 3x3).

.rotate(self, v)

v rotated by this quaternion.

.length property
.normalized(self)
.conjugated(self)
.inverted(self)
.dot(self, o)
.to_axis_angle(self)

(axis, degrees); the identity returns the +X axis and 0.

.to_matrix(self)

The 3x3 rotation matrix.

.to_euler(self, order='XYZ')

Euler degrees (x, y, z) for order (each angle in ±180).

tb.math.slerp(a, b, t)

Spherical interpolation from rotation a to b along the shorter arc.

class tb.math.Mat3(_Mat)

A 3x3 matrix (rotation and scale): Mat3() is the identity; m @ v.

.to_quat(self)
.to_euler(self, order='XYZ')

Euler degrees (x, y, z) of the rotation in order (each angle in ±180).

class tb.math.Mat4(_Mat)

A 4x4 transform (row-major, column vectors, translation in the last column).

.from_trs(cls, translation=(0, 0, 0), rotation=None, scale=(1, 1, 1))

Translate @ rotate @ scale, as an object's transform composes. rotation is a Quat (or 4 numbers) or Euler degrees (3 numbers, XYZ).

.translation(cls, offset)
.scaling(cls, factors)
.decompose(self)

(translation, rotation, scale): Vec3, Quat, Vec3. A mirrored matrix returns a negative x scale.

.transform_point(self, p)

p moved by the full transform (projective divide when the last row is not 0 0 0 1).

.transform_vector(self, v)

Direction v rotated and scaled (no translation).

.transform_normal(self, n)

Surface normal n under this transform (inverse transpose), normalized.

class tb.math.Color(tuple)

A linear RGBA color of floats, the space operations and materials use. Color.from_srgb / Color.from_hex convert display (sRGB) values.

.r property
.g property
.b property
.a property
.from_srgb(cls, r, g, b, a=1.0)

From display values 0..1 (what a color picker shows).

.from_hex(cls, text)

From "#rrggbb" or "#rrggbbaa" (sRGB, as web colors are).

.to_srgb(self)

Display values (r, g, b, a) 0..1.

.hex property
.lerp(self, o, t)

class tb.math.BBox

An axis-aligned box: min, max, size, center (scene units).

.from_points(cls, points)
.size property
.center property
.contains(self, p)
.union(self, o)

class tb.math.Sphere

A sphere: center and radius (scene units).

.from_points(cls, points)

A sphere around points centered on their bounding box (not the minimal one).

.contains(self, p)
.distance_to(self, p)

Signed distance from the surface (negative inside).

class tb.math.Plane

An infinite plane normal · p == offset (normal is unit length).

.from_point_normal(cls, point, normal)
.from_points(cls, a, b, c)

The plane through three points (counter-clockwise a, b, c faces the normal).

.distance_to(self, p)

Signed distance: positive on the side the normal points to.

.project(self, p)

The closest point on the plane to p.

.intersect_ray(self, origin, direction)

Where the ray hits the plane, or None when parallel or pointing away.

class tb.math.KDTree

Nearest-neighbour queries over fixed 2D or 3D points (mathutils.kdtree style).

KDTree(points) takes a list or (N, 2) / (N, 3) numpy array. Queries return (co, index, distance) with index into the original points.

.find(self, co)

The nearest point: (co, index, distance), or (None, None, None) when empty.

.find_n(self, co, n)

The n nearest points, nearest first.

.find_range(self, co, radius)

Every point within radius, nearest first.

tb.math.belt_around_circles(circles, *, arc_segments=32, plane='xz')

Convex-center pulley routing in caller units; interior-center circles are ignored.

Circles are {"center": (x,y,z), "radius": r}. Planes: xz, xy, yz. Samples per full circle floor/clamp to at least three. Output has no repeated wrap point.

tb.math.stadium_path(*, length=None, width=None, center=(0, 0, 0), center_a=None, center_b=None, radius=None, segments=32, plane='xz')

Closed stadium: either total length > width > 0, or two cap centers and a radius.

The major axis is the plane's first axis. Caller units are preserved; no repeated wrap point.

tb.math.external_tangent_points(center_a, radius_a, center_b, radius_b, side, *, plane='xz')

External tangent endpoints as point_a/point_b. Nonnegative side chooses +90 degrees.

Concentric or containing circles refuse. The first center supplies the out-of-plane value.

tb.math.catmull_rom(points, samples_per_segment=20, *, closed=False)

Uniform tension-0.5 Catmull-Rom samples: position and global t in [0,1].

Open controls clamp at the ends; closed controls wrap and include a final t=1 wrap sample.

tb.math.compute_frames(points_or_samples, *, closed=False, initial_up=None)

Rotation-minimizing position/tangent/normal/binormal frames, one per input point.

Uses shared double-reflection transport and closed seam correction. initial_up seeds only the first normal; its parallel/zero case uses the stable least-parallel-axis seed.

tb.math.arc_length_resample(points, count, *, closed=False)

Exactly count chord-length-even position/s records. Count must be an integer >=2.

Open endpoints are inclusive; closed uses i/count and excludes a repeated wrap point.

tb.math.orient_to_curve(point, frames, *, mode='tangent', up_axis=(0, 1, 0))

Nearest-frame quaternion aligning local +Z to tangent (or its negative for away).

Modes tangent and tangent-up use up_axis for roll. Ties choose the first frame. Returns quaternion (x,y,z,w), nearest_position, s=sample_index/(count-1), and distance.

tb.math.ribbon_mesh(points_or_frames, width, *, banking=False, closed=False, up=(0, 1, 0), uv_scale=1)

Gravity-aware ribbon arrays: positions (N,3) f32, uvs (N,2) f32, indices (T,3) u32.

Frames need position/tangent; raw points are framed internally. Banking is False, True, or {max_angle:0.28, smoothing_passes:3}; angles use radians. Up defaults to Y. V follows sample index times uv_scale; closed stitches the last row to the first.

tb.undo

Undo history.

A script run is one undo step ("Run script: name.py") and is rolled back if it raises. Inside it, with tb.undo.group("label"): makes a nested step that is rolled back on its own when the block raises (the exception still propagates).

A run that has only read data may control completed Undo/Redo. After its first control, authoring and nested groups require a separate execution. Completed history controls stay applied if a later read raises or the run is stopped. An authoring run's Undo/Redo walks only its own local steps, preserving the outer history boundary. The registered tb.ops.history.undo/redo controls always address completed history and refuse in authoring or nested runs.

tb.undo.group(label)

One undo step for everything done inside the with block (atomic).

tb.undo.undo()

Undo one step; returns whether anything changed.

In a read/control-only run this controls completed history. After an authoring request, it walks only the run's own local steps; it never crosses that boundary.

tb.undo.redo()

Redo one completed or owner-local step under the same rule as undo.

tb.io

Files: open, import, export and save — the same readers and writers as the File menu.

import toolbox3d as tb
tb.io.open("crate.fbx")                       # replaces the document
tb.io.export("crate.glb")                     # format from the extension
tb.io.export("crate.fbx", target_axis="z", pose="animation")
tb.io.save("crate.tb3d")                      # the project

The script reads and writes the files itself (on the website: Pyodide's file system and linked folders), so the same script works in the app, on the website and under tbpy.

tb.io.formats()

Every file format: [{"format": "glb", "capabilities": [...]}, ...].

tb.io.open(path, companions=(), merge_vertices=True, parts=None)

Opens a project or 3D file, replacing the document (File ▸ Open). companions are extra files it references (an OBJ's .mtl, a glTF's .bin and textures). merge_vertices=False keeps the vertices glTF files split at UV seams. A Maya scene (.ma or .mb) or a Blender file (.blend) is converted to ToolBox3D data, so rigs and animation may not work exactly as in the other app; each of its warnings has a conversion of "approximated" or "left out", as the Import dialog's Conversion Report lists them. parts picks what a Maya or Blender file brings in, as the Import dialog does: a dict of model, skeleton, skinning, blendshapes, control_rig, materials and animation (each omitted part stays on), e.g. tb.io.open("hero.ma", parts={"skeleton": False, "skinning": False, "control_rig": False, "animation": False}) for the model alone. Returns the file's import warnings.

tb.io.reopen_last_export(merge_vertices=True)

Opens the file the last scene export wrote (File ▸ Reopen Last Export), replacing the document, to check exactly what the export carried. Returns its import warnings.

tb.io.import_file(path, companions=(), merge_vertices=True)

Adds a 3D file's objects to the scene (the Model editor's Import Model) and returns the new top-level objects. merge_vertices is as for open.

tb.io.reimport_file(path, objects=None, companions=(), merge_vertices=True)

Replaces the geometry of objects with the meshes of a changed file (the Model editor's Reimport Model). Each object keeps its place, name, materials and texture sets. A mesh in the file replaces the object with the same name; a file with one mesh replaces the one object given. objects defaults to the selection, else every object a file mesh names. Returns {"replaced": [Object, ...], "painted_sets": [material id, ...]}: in Texture Paint, tb.ops.texture.paint.provenance.keep_strokes(material=id) moves each painted set's strokes onto the new surface.

tb.io.export(path, format=None, **options)

Exports the scene to path (File ▸ Export 3D File). format defaults to the extension. Options: pose ("bind", "current", "animation"), target_axis ("y", "z"), clips (names), time (seconds, for pose="current") and the format options binary, embed_textures, include_normals, include_uvs, include_colors, bake_materials, bake_size, write_mtl, max_texture_size, allow_material_loss, freeze_transforms (bake each mesh's transform into its points in the file; the scene keeps its transforms); selection=True writes only the selected meshes (File ▸ Export Selection). Edits that must be reconciled into the shared scene first are answered by decisions ("recommended" or [{"id": ..., "choice": ...}]) and reconcile ({"skin": "transfer.uv", "clips": "rebake", ...}: one choice per kind of change or exact family); unanswered rows raise with their ids and choices. Returns the paths written (formats with companion files write them next to path).

tb.io.save(path, decisions=None, reconcile=None)

Saves the project as a .tb3d file at path; decisions and reconcile as for export.

tb.ui

Messages, progress and simple questions to the artist.

prompt and confirm open a dialog in the app and wait for the answer; under tbpy (no window) they raise HostCapability: check tb.app.is_headless first.

tb.ui.message(text, level='info')

Shows text as a notification in the app (level: info, success, warning, error). Under tbpy it is printed to stderr.

tb.ui.show_image(image, name=None)

Shows an image in the Script Editor's output, with a Download button.

image is PNG, JPEG or WebP data (bytes), the path of such a file, or a matplotlib figure (anything with savefig), which is saved as PNG. name is the file name Download offers. Returns {"name", "width", "height"}. Under tbpy a line naming the image is printed to stderr.

tb.ui.progress(done, total, label='')

Shows the run's progress bar above the Script Editor console: done of total steps, label naming the current phase. It clears when the run ends.

Call it as often as you like: updates closer than a tenth of a second apart are skipped (the final step always shows), so a loop pays for at most ten updates a second.

for i, name in enumerate(names):
    tb.ui.progress(i + 1, len(names), "Building posts")

tb.ui.prompt(label, default='', title='Script')

Asks for a line of text: returns what the artist typed, or None when cancelled.

tb.ui.confirm(question, title='Script')

Asks a yes/no question: True for OK, False for Cancel.

tb.app

Where the script runs.

import toolbox3d as tb
if tb.app.is_headless:      # tbpy: no window, no dialogs
    print("batch mode on", tb.app.host)

is_headless is true under tbpy; host is "windows" or "web"; version is the ToolBox3D version.

tb.project

Scripts saved inside the project (the Script Editor's Project Scripts): they travel with the .tb3d on every host. Writing one marks the project unsaved; it is not an undo step.

import toolbox3d as tb
tb.project.scripts.write("tools/fence.py", source)
for name in tb.project.scripts:
    print(name, len(tb.project.scripts.read(name)))
tb.project.scripts.run("tools/fence.py")

tb.project.scripts

The project's scripts by name (fence.py, tools/fence.py or OpenSCAD parts/box.scad).

.names(self)

Every project script, sorted.

.read(self, name)

The script's source (NotFound if there is none).

.write(self, name, text)

Saves text as the script name (created or replaced).

.delete(self, name)
.rename(self, name, to)
.run(self, name, **variables)

Runs the script as __main__ (variables are predefined) and returns its namespace. An OpenSCAD script (.scad) is baked into the scene instead, with variables as its customizer values, and the bake report is returned.

tb.preview

Registered operation previews, shared with the UI and automation callers.

Keep the returned observation and pass it to the next mutation. A stale observation never changes a replacement preview. Accept commits to the script's undo group; an unaccepted preview is cancelled when that group or the run closes. Operation defaults and readiness are available through tb.ops.describe.

tb.preview.start(op, params=None, *, deferred=False)

Open a preview. Deferred requests validate without executing until materialized.

tb.preview.update(observation, params, *, deferred=False)

Replace the full recipe of exactly the observed preview, retaining last good output on refusal.

tb.preview.status()

Bounded status and shown result; raw recipes and private transport handles are omitted.

tb.preview.materialize(observation)

Execute the observed deferred request using its canonical registered operation.

tb.preview.accept(observation)

Accept the exact preview; returns the ordinary operation Accept report.

tb.preview.cancel(observation)

Restore the original asset and selection without recording a step.

tb.errors

Exceptions raised by the ToolBox3D API.

Every failure the app reports carries a stable code, a plain-language message and, where the app knows one, a hint saying how to fix it. detail is the structured part: a dict when the app sends one (a rig build failure gives kind, items (names), fix and the technical reason), else the text the app sent.

class tb.errors.ToolBox3DError(Exception)

Base class of every ToolBox3D error.

class tb.errors.InvalidParams(ToolBox3DError)

A parameter is missing, has the wrong type or is out of range.

class tb.errors.NotApplicable(ToolBox3DError)

The operation cannot run now (wrong selection, busy, unsupported here).

class tb.errors.Ownership(ToolBox3DError)

The active editor does not own the data the operation writes.

class tb.errors.Cancelled(ToolBox3DError)

The script was stopped, or the work was cancelled.

class tb.errors.Stale(ToolBox3DError)

A handle points at something that was deleted, or the document changed under it.

class tb.errors.AmbiguousName(ToolBox3DError)

A name matches more than one item; use an id or a path instead.

class tb.errors.NotFound(ToolBox3DError)

No item matches the name or id.

class tb.errors.HostCapability(ToolBox3DError)

This host (website or Windows app) cannot do what was asked.

tb.ops — operations

1312 registered operations, generated from the app's operation registry. Each domain page lists the Python signature, arguments, defaults and the editors that show the operation. Artists can also browse them by category in the operation reference.

DomainOperationsExamples
tb.ops.animation213Bake Adjust Layer, Set Adjust Effector, Mirror Adjust Offsets
tb.ops.bodyrig12Add Body Rig Chain, Remove Body Rig Chain, Reset Body Rig Chain
tb.ops.controlrig152Add Attribute, Add In-between, Add Offset Control
tb.ops.create22Arch, Boundary Fill, Capsule
tb.ops.curve55Add Point, Cable, Clear Tilt
tb.ops.font2Add Font, List Fonts
tb.ops.garment34Bake Garment, Begin Garment, Add Base Body
tb.ops.history5History Example, History Help, Redo
tb.ops.library3List Library Animations, Retarget Library Animations, Stage Library Animations
tb.ops.limits2Get Transform Limits, Set Transform Limits
tb.ops.material95Assign Material, Assign Faces to Material Slot, Assign Material to Selection
tb.ops.measurement7Measure Angle, Measure Arc Length, Measure Distance
tb.ops.mesh217Add Divisions, Add Divisions to Faces, Support Loops
tb.ops.model3Import Model, Model Mode, Reimport Model
tb.ops.modifier20Add Modifier, Apply Modifier, Apply as Blendshape Target
tb.ops.multires6Apply Base, Clear Detail, Delete Higher
tb.ops.object17Align Objects, Align Axes to Model, Clear Live Surface
tb.ops.openscad3Check OpenSCAD Printability, OpenSCAD Parameters, Bake OpenSCAD
tb.ops.physics27Apply Simulation, Clear Physics Body, Set Physics Body
tb.ops.preferences4Get Preferences, List Preferences, Reset Preferences
tb.ops.project5Delete Project Script, List Project Scripts, Read Project Script
tb.ops.reconciler2Set Reconciler Settings, Reconciler Settings
tb.ops.retopology27Adjust Quad Strip, Quad Draw, Cancel Quad Draw
tb.ops.scene28Add Image Plane, Clear Parent Inverse, Closest Surface Point
tb.ops.sculpt55Sculpt Blendshape Target, Get Sculpt Brush, Sculpt Brushes
tb.ops.selection31Deselect All, Deselect Components, Selected Components
tb.ops.sets14Add to Set, Create Set, Delete Set
tb.ops.skeleton6Add Joint, Orient Joints, Rename Joint
tb.ops.skincluster22Add Skin Layer, Apply Computed Weights, Bind Skin
tb.ops.solid37Analyze Mesh for Solid, Array, Bake Linked Mesh
tb.ops.texture100Create Texture, Export Texture, Release Texture Export
tb.ops.tool8Cancel Interactive Tool, Commit Interactive Tool, Add Tool Input
tb.ops.uv64Align, Average Islands Scale, Reset Unwrap Parts
tb.ops.viewport14Dolly View, Exit Isolate, Frame Viewport