I've been trying to get started with Blender's Python console. So far, I've managed to create vertices and edges without any trouble, but I've encountered an error that search engines aren't getting me anything for, save for the source code that generated it, which is a bit too dense for my knowledge of computer graphics. The below is my code:
import bpy
tgt_name = "MeshName"
x, y, z = 0.0, 0.0, 100.0
def add_vertex(coords):
mesh.vertices.add(1)
mesh.vertices[-1].co = coords
return len(mesh.vertices)-1
def edge(v1, v2):
mesh.edges.add(1)
mesh.edges[-1].vertices = [v1, v2]
def face(v):
mesh.polygons.add(1)
print(v)
mesh.polygons[-1].vertices = v
Selection
tgt_obj = bpy.data.objects.get(tgt_name)
bpy.context.view_layer.objects.active = tgt_obj
tgt_obj.select_set(True)
mesh = tgt_obj.data
Required to add vertices
bpy.ops.object.mode_set(mode='OBJECT')
Create a new vertex at the specified coordinates
v1 = add_vertex((x, y, z))
v2 = add_vertex((x, y+100, z))
v3 = add_vertex((x+110, y+20, z+50))
#edge(v1, v2)
face([v3, v2, v1])
Restore to standard settings
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_mode(type='VERT')
The error, as noted in the title, is:
BM_mesh_bm_from_me: Warning! Bad face in mesh <> at index <>!, skipping
Does anyone have an idea of what could be causing this error? Additionally, if my code contains any issues aside from that, it'd help to point them out so that I don't make similar missteps in the future.
As additional context, this script is intended to be run on an existing mesh - my ultimate goal, here, is to create a script that can be called to generate complex shapes quickly so that I can integrate them into a model. I'm experienced with Python itself, but fairly new to Blender.
Update: Here is code to build a new mesh, from scratch, for anyone looking - it's what I ended up going with. H/T Harry McKenzie.
import bpy
faces = []
verts = []
def vert(x, y, z):
verts.append((x, y, z))
return len(verts)-1
def face(verts):
faces.append(verts)
name = "Generated"
Create a new mesh
mesh = bpy.data.meshes.new(name)
obj = bpy.data.objects.new(name, mesh)
bpy.data.collections['Collection'].objects.link(obj)
bpy.context.view_layer.objects.active = obj
Code for constructing the mesh
x, y, z = 0.0, 0.0, 100.0
v1 = vert(x, y, z)
v2 = vert(x, y+100, z)
v3 = vert(x+110, y+20, z+50)
face((v1,v2,v3))
Finalize new mesh
mesh.from_pydata(verts, [], faces)
mesh.update(calc_edges=True)
mesh.validate(verbose=True)
```
mesh.from_pydata(coords, edges, faces)or usingbmesh. are you open to any method as long as it can construct a mesh via python? Here's the proper way to construct a mesh. – Harry McKenzie Jul 31 '23 at 08:26