← Blender.Today
  • Published 9 Jul 2021

Creating a blender mesh directly from numpy data?

(I wrote a stackoverflow question on the same issue, but did not receive any answer, so I'm trying my luck here.)

Is it possible to create a Blender mesh directly from efficient numpy arrays without needing to go through (the slow and space wasting) POD python types? Here is a script that illustrate what I mean. I need to call .tolist() on my numpy data to make the script work. Is there another more efficient API?

Looking at the bpy_types.py it uses the C-API binding bpy_rna.c:foreach_getset() which does support the python buffer protocol, so it looks like in theory it should be possible, but how?

# Create a mesh from numpy arrays. Can you do this without tolist()?
import bpy
import numpy as np

verts = np.array([
  (1, 1, 1),
  (-1, 1, -1),
  (-1, -1, 1),
  (1, -1, -1),
], dtype=np.float32)

faces = np.array([[0, 1, 2], [0, 2, 3], [0, 3, 1], [2, 1, 3]],
                 dtype=int)

mesh = bpy.data.meshes.new('TetraMesh')   
obj = bpy.data.objects.new('Tetra', mesh) 

# Must call tolist() to pass to from_pydata()!
mesh.from_pydata(verts.tolist(),[],faces.tolist())   
mesh.update(calc_edges=True)              # Update mesh with new data
bpy.context.collection.objects.link(obj)  # Link to scene

dovgrobgeld
9 Jul 2021