Skip to content

Instances

Instances(points=None, models=None, model_index=None, attr_from=None, **attributes)

Bases: Geometry

Instance container for duplicating geometries.

Instances manages a set of instance transforms (positions, optional scale and rotation) and a list of source models (meshes and/or curves). It can realize instances into concrete geometries or directly create Blender objects.

Attributes:

Name Type Description
points [Point][Point]

Per-instance attributes (e.g., position, optional rotation, scale, model_index, plus any user fields).

models list[[Geometry][Geometry]]

List of source models to instance (e.g., Mesh, Curve).

low_resols list[dict]

Optional Level-of-Detail (LOD) entries, each as {"dist": float, "models": list[Geometry]}.

Notes
  • Each instance chooses its model via points.model_index.

Create a new instance set.

Initializes the per-instance point domain and captures model geometries.

Parameters:

Name Type Description Default
points array-like of shape (N, 3) or None

Instance locations appended as points.position.

None
models Geometry or sequence of Geometry or None

Model(s) to instance. If None, starts empty.

None
model_index int or array-like of int or None

Model index per instance (broadcast rules apply).

None
attr_from Geometry or None

Source geometry from which to join attribute schemas.

None
**attributes

Additional per-instance attributes to append (e.g., rotation, scale).

{}
Notes

bounding_box property

bounding_box

Axis-aligned bounding box of the point positions.

Returns:

Type Description
tuple of numpy.ndarray

(min_xyz, max_xyz). If empty, returns two zero vectors.

bounding_box_dims property

bounding_box_dims

Extents of the axis-aligned bounding box.

Returns:

Type Description
numpy.ndarray of shape (3,)

max_xyz - min_xyz.

max_size property

max_size

Maximum dimension of the bounding box.

Returns:

Type Description
float

max(bounding_box_dims).

add_low_resol

add_low_resol(dist, models)

Register a Level-of-Detail (LOD) set.

Associates a view distance threshold with a list of low-res models (same length and order as self.models).

Parameters:

Name Type Description Default
dist float

Distance threshold at which this LOD should be used.

required
models Geometry or sequence of Geometry

One low-res model per source model.

required

Raises:

Type Description
ValueError

If the number of LOD models does not match len(self.models).

Returns:

Type Description
None

add_materials

add_materials(materials)

Append material name(s) to the geometry.

Parameters:

Name Type Description Default
materials str or sequence of str

One name or a sequence of names to append.

required

Returns:

Type Description
None
Notes

This method does not deduplicate names; duplicates may be appended.

apply_scale

apply_scale(scale, pivot=None)

Scale points (convenience wrapper).

See: transformation

Parameters:

Name Type Description Default
scale ndarray

Per-point or broadcastable scales.

required
pivot ndarray

Optional pivot(s) for scaling.

None

Returns:

Type Description
Geometry

self.

check

check(title='Instances Check', halt=True)

Validate model indices against the models list.

Ensures that max(points.model_index) < len(models).

Parameters:

Name Type Description Default
title str

Prefix for diagnostic messages.

"Instances Check"
halt bool

If True, raise on failure; otherwise print and return False.

True

Returns:

Type Description
bool

True if valid (or no instances), False when invalid and halt=False.

Raises:

Type Description
AssertionError

If a model index is out of range and halt=True.

clear_geometry

clear_geometry()

Clear all instances (keeps attribute schemas and models).

Returns:

Type Description
None

compute_attribute_on_domain

compute_attribute_on_domain(domain_from, attr, domain_to)

Transfer an attribute from one domain to another.

Performs a domain mapping (e.g., points → faces) using the appropriate domain operator, and returns the computed array on the target domain.

Parameters:

Name Type Description Default
domain_from str

Source domain name (e.g., "points", "faces", "edges", "corners", "splines").

required
attr str or ndarray

Source attribute to transfer. If a string, it is looked up on the source domain; if an array, it must match the source domain length.

required
domain_to str

Target domain name.

required

Returns:

Type Description
ndarray

Attribute values on the target domain. If domain_from == domain_to, returns attr unchanged.

Raises:

Type Description
AttributeError

If either domain_from or domain_to is not a valid domain of this geometry.

Exception

If the requested mapping is not implemented.

Notes

Implemented mappings include: - points → faces: [Point.compute_attribute_on_faces][npblender.Point.compute_attribute_on_faces] - points → edges: [Point.compute_attribute_on_edges][npblender.Point.compute_attribute_on_edges] - points → corners: [Point.compute_attribute_on_corners][npblender.Point.compute_attribute_on_corners] - points → splines: [Point.compute_attribute_on_splines][npblender.Point.compute_attribute_on_splines] - faces → points: Face.compute_attribute_on_points - edges → points: Edge.compute_attribute_on_points - corners → points: Corner.compute_attribute_on_points

compute_low_resols

compute_low_resols(start_scale=0.1, scale=0.8, detail=1.0)

Auto-compute a LOD pyramid from current models.

Uses a camera model to estimate view distances for a target on-screen scale. For meshes, generates simplified copies; for curves, converts to curve views.

Parameters:

Name Type Description Default
start_scale float

Initial relative on-screen scale.

0.1
scale float

Multiplicative factor between consecutive LOD levels (clipped to 0.01–0.99).

0.8
detail float

Detail factor forwarded to simplification (mesh-dependent).

1.0

Returns:

Type Description
None
Notes
  • Up to 10 levels are created, stopping when the max vertex count drops to ≤ 8.
  • Each level is recorded via add_low_resol.

from_dict classmethod

from_dict(d)

Deserialize an Instances object produced by to_dict.

Parameters:

Name Type Description Default
d dict

Serialized payload with keys "points", "models", "low_resols".

required

Returns:

Type Description
Instances

New instance with points, models and LODs reconstructed.

get_cubic_envelop

get_cubic_envelop()

Return a cube mesh that encloses the geometry’s bounding box.

Uses the bounding box dimensions to build a cube via Mesh.cube, forwarding this geometry’s materials if present.

Returns:

Type Description
Mesh

A cube mesh sized to the bounding box.

get_material_index

get_material_index(mat_name)

Return the index of a material name, creating it if needed.

Parameters:

Name Type Description Default
mat_name str

Material name to look up or append.

required

Returns:

Type Description
int

Index of mat_name in self.materials.

Notes

If mat_name is not present, it is appended to self.materials and the new index is returned.

get_points_selection

get_points_selection()

Selection of points relevant to operations.

Returns slice(None) in the base class (all points). Subclasses (e.g., curves) may override to select only referenced points.

Returns:

Type Description
slice

slice(None) by default.

join

join(*others)

Concatenate other instance sets into this one.

Appends models and per-instance points; newly appended model_index values are offset by the previous model count.

Parameters:

Name Type Description Default
*others Instances

Other Instances objects to append.

()

Returns:

Type Description
Instances

self, for chaining.

Raises:

Type Description
AttributeError

If any argument is not an Instances.

join_attributes

join_attributes(other, **kwargs)

Merge attribute schemas from another geometry.

For each domain listed in self.domain_names and also present in other, copies (joins) the attribute definitions (names, dtypes, metadata) from other into this geometry's domains. Use keyword flags to include/exclude domains by name (e.g., faces=False).

Parameters:

Name Type Description Default
other Geometry or None

Source geometry. If None, does nothing and returns self.

required
**kwargs

Per-domain boolean switches to filter which domains to join.

{}

Returns:

Type Description
Geometry

self, for chaining.

Examples:

mesh.join_attributes(other_mesh, faces=False)
curve.join_attributes(mesh)  # only common domains are merged

load_models staticmethod

load_models(*specs)

Load multiple geometries from collections, objects, or instances.

Accepts mixed inputs such as Blender collections, Blender objects, lists/ tuples of either, or already-instantiated Mesh/Curve. Returns a flat list of geometries discovered or constructed.

This method is mainly intended to be used by Instances to load its models.

Parameters:

Name Type Description Default
*specs

Collections, objects, lists/tuples, or Mesh/Curve instances.

()

Returns:

Type Description
list

List of geometries (Mesh/Curve).

Raises:

Type Description
ValueError

If a spec cannot be resolved to a geometry.

load_object staticmethod

load_object(name)

Load a Blender object and return a Mesh or a Curve.

Resolves name to a Blender object, inspects its data type, and returns a matching geometry by calling the subclass' from_object.

Parameters:

Name Type Description Default
name str or Object

Object name or object instance.

required

Returns:

Type Description
Mesh or Curve or None

A Mesh or a Curve, or None if the object is not found.

Raises:

Type Description
Exception

If the object exists but is neither a bpy.types.Mesh nor bpy.types.Curve.

Examples:

geo = Geometry.load_object("MyObject")
if geo is not None:
    print(type(geo).__name__)

models_to_object

models_to_object(name='Models')

Dump all models (and their LODs) into a single Blender mesh object.

Places each source model along +X with its LOD stack above it along +Z, then creates a single object with flat shading.

Parameters:

Name Type Description Default
name str

Object name.

"Models"

Returns:

Type Description
Object

The created object.

Examples:

obj = insts.models_to_object("AllModelsPreview")

multiply

multiply(count, in_place=True)

Duplicate the instance set count times.

Parameters:

Name Type Description Default
count int

Number of copies to create.

required
in_place bool

If True, expand this instance; otherwise return a new expanded copy.

True

Returns:

Type Description
Instances or None

self (in place) or a new Instances; None if count == 0.

Raises:

Type Description
(TypeError, ValueError)

If count cannot be converted to int.

object

object(index=0, readonly=True, **kwargs)

Temporary access to a Blender Object built from this geometry.

Creates a transient object (named "BPBL Temp {index}" unless index is a string), selects and activates it, yields it for editing, then cleans up. If readonly=True, the edited object is captured back into self.

This method can be used to set and apply a modifier (see exemple below).

Parameters:

Name Type Description Default
index int or str

Index or name used to label the temporary object.

0
readonly bool

If False, re-capture the possibly edited object back into this geometry.

True
kwargs dict

Keyword arguments passed to self.to_object.

{}

Yields:

Type Description
Object

The temporary Blender object built from self.

Examples:

plane = Mesh.Grid()
with plane.object(readonly=False) as obj:
    mod = obj.modifiers.new("Solidify", 'SOLIDIFY')
    mod.thickness = .1
    bpy.ops.object.modifier_apply(modifier=mod.name)

# plane is now solidifed

realize

realize(camera_culling=False)

Realize instances into concrete geometries.

Duplicates each model for its selected instances, applies per-instance transform (translation, optional rotation/scale), and accumulates results into a Mesh and/or a Curve. With camera_culling=True, hidden instances are skipped and LODs may be used.

Parameters:

Name Type Description Default
camera_culling bool or object

If truthy, perform visibility tests and LOD selection using a camera.

False

Returns:

Type Description
dict

A dictionary with keys: - "mesh" : a Mesh or None - "curve": a Curve or None

Raises:

Type Description
TypeError

If a model type is not supported (neither Mesh nor Curve).

Examples:

insts = Instances(points=np.random.randn(100, 3), models=[Mesh.cube(), Curve.circle()])
geos = insts.realize(camera_culling=True)
if geos["mesh"] is not None:
    geos["mesh"].to_object("InstancedMesh")

rotate

rotate(rotation, pivot=None)

Rotate points (convenience wrapper).

See: transformation

Parameters:

Name Type Description Default
rotation ndarray or Rotation - like

Rotation(s) to apply as R @ v.

required
pivot ndarray

Optional pivot(s) for rotation.

None

Returns:

Type Description
Geometry

self.

to_dict

to_dict()

Serialize the instances to a plain dictionary.

Returns:

Type Description
dict

Keys: - "geometry" = "Instances" - "points" : point-domain payload - "models" : list of serialized models - "low_resols" : list of serialized LOD levels

to_object

to_object(name, profile=None, caps=True, use_radius=True, shade_smooth=True, camera_culling=False)

Create Blender object(s) from realized instances.

Realizes instances, converts curves to mesh when a profile is provided (or when culling requires meshing), and creates one or two Blender objects.

Parameters:

Name Type Description Default
name str

Base name for created objects.

required
profile Curve or None

Profile to sweep along curve outputs (see Curve.to_mesh).

None
caps bool

Close ends when sweeping.

True
use_radius bool

Use per-point radius when sweeping.

True
shade_smooth bool

Smooth shading for the mesh object.

True
camera_culling bool

If True, perform visibility tests and LOD selection.

False

Returns:

Type Description
dict

Possibly contains: - "mesh" : the created mesh object (with optional “ - (M)” suffix) - "curve": the created curve object (with “ - (C)” suffix if both exist)

transform

transform(transformation)

Apply a rotation matrix or batch of matrices.

See: transformation

Parameters:

Name Type Description Default
transformation ndarray

Rotation matrix or batch of rotation matrices.

required

Returns:

Type Description
Geometry

self.

transformation

transformation(rotation=None, scale=None, translation=None, pivot=None)

Apply rotation/scale/translation (with optional per-packet broadcasting).

Operates in-place on points.position and, when present, Bezier handles (points.handle_left, points.handle_right). Shapes can represent packets of points: broadcasting rules are handled by [Point._get_shape_for_operation][npblender.Point._get_shape_for_operation].

Parameters:

Name Type Description Default
rotation ndarray or Rotation - like

Rotation matrix/matrices applied as R @ v. Shape may broadcast over points (see notes).

None
scale ndarray

Per-axis scaling. Shape may broadcast over points.

None
translation ndarray

Per-point translation. Shape may broadcast over points.

None
pivot ndarray

Pivot(s) subtracted before, and added after, the rotation/scale; same broadcasting rules as scale/translation.

None

Returns:

Type Description
Geometry

self, for chaining.

Notes
  • If handles exist, they are transformed consistently with positions.

Examples:

# 12 cubes laid out randomly with per-instance transforms
cubes = Mesh.cube(size=1).multiply(12)
T = np.random.uniform(-1, 1, (12, 3))
S = np.random.uniform(0.5, 2.0, (12, 3))
R = Rotation.from_euler(np.random.uniform(0, 2*np.pi, (12, 3)))
cubes.transformation(rotation=R, scale=S, translation=T)

translate

translate(translation)

Translate points (convenience wrapper).

See: transformation

Parameters:

Name Type Description Default
translation ndarray

Per-point or broadcastable translation vectors.

required

Returns:

Type Description
Geometry

self.