Is there a simple way of triangulating all faces in a mesh in the python API? I am already aware of that you can do it in blender by selecting an object in edit mode and pressing ctrl+T, but I need to do so in a python script.
Thank you in advance!
You could use the bmesh.ops.triangulate
See TextEditor > Templates > Python > Bmesh simple edit mode for some of the boilerplate.
For any mesh in object mode.
# This example assumes we have a mesh in object mode.
import bpy
import bmesh
def triangulate_object(obj):
me = obj.data
# Get a BMesh representation
bm = bmesh.new()
bm.from_mesh(me)
bmesh.ops.triangulate(bm, faces=bm.faces[:])
# V2.79 : bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method=0, ngon_method=0)
# Finish up, write the bmesh back to the mesh
bm.to_mesh(me)
bm.free()
# Get the active object (could be any mesh object)
triangulate_object(bpy.context.active_object)
For any mesh in edit mode.
# This example assumes we have a mesh object in edit-mode
import bpy
import bmesh
def triangulate_edit_object(obj):
me = obj.data
# Get a BMesh representation
bm = bmesh.from_edit_mesh(me)
bmesh.ops.triangulate(bm, faces=bm.faces[:])
# V2.79 : bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method=0, ngon_method=0)
# Show the updates in the viewport
# and recalculate n-gon tessellation.
bmesh.update_edit_mesh(me, True)
# Get the edit mesh
triangulate_edit_object(bpy.context.edit_object)
bmesh.ops.triangulate(bm, faces=bm.faces[:], quad_method='BEAUTY', ngon_method='BEAUTY')
to make above work.
$\endgroup$
bmesh.ops
as mentioned by WDC and bpy.ops
as seen mousing over UI.
$\endgroup$
Commented
Mar 9, 2021 at 6:49