Docs · Scripting
Script examples
Short, tested Python scripts for the Script Editor. Each one is a complete starting point for your own tools.
These scripts ship with the editor: open Windows › Script Editor, then Help › Script Examples, and they appear read-only in the Examples folder. Copy one into a new tab (or use Save As) to change it. Each one runs in the browser and in the Windows app.
Scene report: list every object with its type and size
Makes a box and a ball first, so it runs in an empty scene, then reads the scene back.
import toolbox3d as tb
tb.scene.set_editor("model")
with tb.undo.group("Two shapes"):
tb.ops.create.cube(name="Box", width=1.0, height=0.5, depth=0.8)
tb.ops.create.sphere(name="Ball")
objects = tb.scene.objects()
print(f"{len(objects)} objects in the {tb.scene.editor()} editor")
for obj in objects:
line = f" {obj.path:<12} {obj.type:<6}"
if obj.mesh:
size = obj.bbox.size
line += f" {obj.mesh.vertex_count:>5} verts {size.x:.2f} x {size.y:.2f} x {size.z:.2f} m"
print(line)Build a fence: ten posts and two rails, as one undo step
Change COUNT and SPACING to taste.
import toolbox3d as tb
COUNT = 10
SPACING = 0.5 # scene units between posts
tb.scene.set_editor("model")
with tb.undo.group("Build fence"):
parts = []
for i in range(COUNT):
post = tb.ops.create.cube(name=f"Post{i + 1}", width=0.08, height=1.0, depth=0.08).created[0]
post.transform.position = (i * SPACING, 0.5, 0)
parts.append(post)
length = (COUNT - 1) * SPACING
for n, y in enumerate((0.35, 0.8)):
rail = tb.ops.create.cube(name=f"Rail{n + 1}", width=length, height=0.06, depth=0.04).created[0]
rail.transform.position = (length / 2, y, 0)
parts.append(rail)
tb.ops.scene.group(name="Fence", nodes=parts)
tb.ui.message(f"Fence with {COUNT} posts built", level="success")Scatter rocks: copies of a rock on a grid, each with a random turn
Makes its own rock first, so it runs in an empty scene. The random seed makes the result repeatable.
import random
import toolbox3d as tb
ROWS, COLUMNS, GAP = 3, 4, 1.5
random.seed(7)
tb.scene.set_editor("model")
with tb.undo.group("Scatter rocks"):
source = tb.ops.create.sphere(name="Rock").created[0]
for r in range(ROWS):
for c in range(COLUMNS):
if r == 0 and c == 0:
continue # the original stays where it is
copy = source.duplicate()
copy.transform.position = source.transform.position + (c * GAP, 0, r * GAP)
copy.transform.rotation_euler = (0, random.uniform(0, 360), 0)
print(f"{ROWS * COLUMNS - 1} copies of {source.name}")Rough sphere: move every vertex of a sphere a little at random with numpy
Makes its own sphere first, so it runs in an empty scene. One operation and one undo step, however many vertices the mesh has.
import numpy as np
import toolbox3d as tb
AMOUNT = 0.02 # scene units
tb.scene.set_editor("model")
with tb.undo.group("Rough sphere"):
obj = tb.ops.create.sphere(name="Rough").created[0]
rng = np.random.default_rng(1)
positions = obj.mesh.positions()
positions += rng.normal(0.0, AMOUNT, positions.shape).astype(np.float32)
obj.mesh.set_positions(positions)
print(f"moved {len(positions)} vertices of {obj.name}")Colored cubes: five cubes, each with its own colored material
Makes its own cubes first, so it runs in an empty scene.
import colorsys
import toolbox3d as tb
COUNT = 5
tb.scene.set_editor("model")
with tb.undo.group("Colored cubes"):
for i in range(COUNT):
cube = tb.ops.create.cube(name=f"Cube{i + 1}", width=0.5, height=0.5, depth=0.5).created[0]
cube.transform.position = (i * 0.7, 0.25, 0)
r, g, b = colorsys.hsv_to_rgb(i / COUNT, 0.6, 0.9)
mat = tb.scene.materials.new(f"Color{i + 1}", base_color=(r, g, b, 1.0), roughness=0.5)
mat.assign(cube)
print(f"{COUNT} cubes, each with its own material")Crate stacker: a small tool written as a class
Builds a pyramid of crates (one undo step) and reports what it made. Shows how to organise a bigger script: settings in __init__, one method per step, a report at the end.
import toolbox3d as tb
class CrateStacker:
"""Stacks cube crates into a pyramid."""
def __init__(self, levels=4, size=0.5, gap=0.05):
self.levels = levels
self.size = size
self.gap = gap
self.crates = []
def crate(self, level, column):
"""One crate at a pyramid level and column."""
step = self.size + self.gap
x = (column - (self.levels - level - 1) / 2) * step
y = self.size / 2 + level * self.size
crate = tb.ops.create.cube(name=f"Crate_{level}_{column}", width=self.size,
height=self.size, depth=self.size).created[0]
crate.transform.position = (x, y, 0)
self.crates.append(crate)
def build(self):
"""Every level, bottom to top, as one undo step."""
tb.scene.set_editor("model")
with tb.undo.group("Stack crates"):
for level in range(self.levels):
for column in range(self.levels - level):
self.crate(level, column)
tb.ops.scene.group(name="Crates", nodes=self.crates)
return self
def report(self):
top = max(c.bbox.max.y for c in self.crates)
print(f"{len(self.crates)} crates, {top:.2f} units tall")
CrateStacker(levels=4).build().report()Select by name: make six pillars, then select every other one
Shows how to find objects by name and change the selection from a script.
import toolbox3d as tb
tb.scene.set_editor("model")
with tb.undo.group("Pillars"):
for i in range(6):
pillar = tb.ops.create.cylinder(name=f"Pillar{i + 1}").created[0]
pillar.transform.position = (i * 1.2, 0.5, 0)
even = [tb.scene.get(f"Pillar{i}") for i in (2, 4, 6)]
tb.scene.selection.set(even)
print("selected:", ", ".join(obj.name for obj in tb.scene.selection.objects))Posts along a path: a rounded running track with a post every metre
Uses the curve helpers in tb.math: a stadium-shaped path, resampled to even spacing, with each post turned to face along the track. Runs in an empty scene, as one undo step.
import math
import toolbox3d as tb
LENGTH, WIDTH, SPACING = 8.0, 4.0, 1.0
path = tb.math.stadium_path(length=LENGTH, width=WIDTH, plane="xz")
perimeter = sum(abs(b - a) for a, b in zip(path, path[1:] + path[:1]))
samples = tb.math.arc_length_resample(path + path[:1], max(4, int(perimeter / SPACING)))
frames = tb.math.compute_frames(samples, initial_up=(0, 1, 0))
tb.scene.set_editor("model")
with tb.undo.group("Track posts"):
posts = []
for i, frame in enumerate(frames[:-1]):
post = tb.ops.create.cube(name=f"Post{i + 1}", width=0.1, height=0.8, depth=0.3).created[0]
p = frame["position"]
post.transform.position = (p.x, 0.4, p.z)
t = frame["tangent"]
post.transform.rotation_euler = (0, math.degrees(math.atan2(t.x, t.z)), 0)
posts.append(post)
tb.ops.scene.group(name="Track", nodes=posts)
print(f"{len(posts)} posts around a {perimeter:.1f} m track")Rusty metal: layer a rust material over steel, masked by edge wear
Material layers stack whole materials. Makes its own ball and both materials, so it runs in an empty scene, as one undo step.
import toolbox3d as tb
tb.scene.set_editor("model")
with tb.undo.group("Rusty ball"):
ball = tb.ops.create.sphere(name="Ball").created[0]
steel = tb.scene.materials.new("Steel", base_color=(0.6, 0.62, 0.65, 1.0), metallic=1.0, roughness=0.3)
rust = tb.scene.materials.new("Rust", base_color=(0.45, 0.18, 0.06, 1.0), roughness=0.9)
steel.assign(ball)
layer = tb.ops.material.layers.add(material=steel.name, source=rust.name, opacity=0.8,
mask={"kind": "edgeWear"})["layer"]
stack = tb.ops.material.layers.list(material=steel.name)
for row in stack["layers"]:
print(f"{steel.name} + {row['name']} layer, mask: {row['mask']['kind']}")Texture a crate: create an image texture and plug it into a material's color
Makes its own crate, texture and material, so it runs in an empty scene, as one undo step. Swap the color for image data (base64 PNG) to use a real picture.
import toolbox3d as tb
tb.scene.set_editor("model")
with tb.undo.group("Textured crate"):
crate = tb.ops.create.cube(name="Crate").created[0]
wood = tb.scene.materials.new("Wood", roughness=0.7)
wood.assign(crate)
texture = tb.ops.texture.create(name="Wood Color", width=256, height=256,
color=(0.55, 0.35, 0.2, 1.0))["texture"]
tb.ops.material.bind_texture(material=wood.name, channel="baseColor", texture=texture)
print(f"{crate.name} uses {wood.name} with a 256 x 256 color texture")Bouncing ball: key a ball's height so it drops, bounces and settles
Makes its own ball and clip, so it runs in an empty scene. Each key is one call to tb.ops.animation.set_key; scrub the timeline in the Animation editor to see it move.
import toolbox3d as tb
HEIGHTS = [2.0, 0.5, 1.2, 0.5, 0.8, 0.5, 0.5] # the ball rests at its radius, 0.5
STEP = 6 # frames between keys
tb.scene.set_editor("model")
ball = tb.ops.create.sphere(name="Ball").created[0]
tb.scene.set_editor("animation", decisions="recommended")
clip = tb.ops.animation.create_clip(name="Bounce", duration=(len(HEIGHTS) - 1) * STEP / 30, fps=30)
with tb.undo.group("Bounce keys"):
for i, height in enumerate(HEIGHTS):
tb.ops.animation.set_key(clip="Bounce", target=ball.name, channel="translateY",
value=height, frame=i * STEP)
print(f"{len(HEIGHTS)} keys on {ball.name}'s height over {(len(HEIGHTS) - 1) * STEP} frames")