Bmesh data

24 Ⅷ 2013

One of the downsides of BMesh is that it lives next to the old Blender Python API. This means that… before you use BMesh data in a script you need to retrieve it, and after you are done… you have to put it back in your mesh object.

You convert from the old mesh to BMesh to use the BMesh functions… then you convert back to the old style Mesh once you are done. Right now I’m using two small functions for that, and every time I want to use BMesh for something I use these… like this…

import bpy, bmesh

# Get the bmesh data from the current mesh object
def get_bmesh():

	# Get the active mesh
	ob = bpy.context.active_object
	me = ob.data

	# Get a BMesh representation
	if ob.mode == 'OBJECT':
		bm = bmesh.new()
		bm.from_mesh(me)   # fill it in from a Mesh
	else:
		bm = bmesh.from_edit_mesh(me) # Fill it from edit mode mesh

	return bm

# Put the bmesh data back into the current mesh object
def put_bmesh(bm):

	# Get the active mesh
	ob = bpy.context.active_object
	me = ob.data

	# Flush selection
	bm.select_flush_mode() 

	# Finish up, write the bmesh back to the mesh
	if ob.mode == 'OBJECT':
		bm.to_mesh(me)
		bm.free()
	else:
		bmesh.update_edit_mesh(me, True)
		
# Here is an example where I use the functions to retrieve the bmesh and select all faces
bm = get_bmesh()

for f in bm.faces:
	# Remember to use select_set() because f.select doesn't flush nice!
	f.select_set(True)

put_bmesh(bm)