0
$\begingroup$

I have two operators I want to run in sequence when I click on a button. The first operator changes object mode to edit mode. The second operator subdivides the mesh ten times.

bpy.ops.object.editmode_toggle() bpy.ops.mesh.subdivide(number_cuts=10, smoothness=0, ngon=True, quadcorner='STRAIGHT_CUT', fractal=0, fractal_along_normal=0, seed=0)

In python, how do I limit the subdivide operator to run once. That is, when it runs and the mesh is subdivided 10 times, you can't subdivide again when you click the button again. Kindly assist.

$\endgroup$
2
  • 1
    $\begingroup$ you need to add a state variable that initializes to False. If it's False, run the op and immediately set it to True. If it's True don't run the op. There are a lot of ways to save the state, and the right one depends on how you've set up your script. $\endgroup$ Jan 3, 2022 at 3:31
  • $\begingroup$ Thanks. Let me give it a try. $\endgroup$
    – 3vanse
    Jan 4, 2022 at 1:00

1 Answer 1

2
$\begingroup$

Add a custom IntProperty to each mesh type (https://docs.blender.org/api/current/bpy.types.Mesh.html?highlight=mesh#bpy.types.Mesh) and store the level of subdivisions per execution. This way you can set a maximum of cuts or read the current levels to add even more cuts whenever you like. Run the operator, press f3 and type Custom Subdiv Mesh Operator.

import bpy
import bmesh
from bpy.props import IntProperty


class SimpleOperator(bpy.types.Operator):
    """Tooltip"""
    bl_idname = "mesh.custom_subdiv"
    bl_label = "Custom Subdiv Mesh Operator"
    bl_options = {'REGISTER', 'UNDO'}
    
    subd_levels: IntProperty(default=10, options={'HIDDEN', 'SKIP_SAVE'})
    
    @classmethod
    def poll(cls, context):
        return context.active_object.type=='MESH' and context.mode=='OBJECT'

    def execute(self, context):
        ob = context.object
        me = ob.data
        
        if me.subdiv_prop >= self.subd_levels:
            self.report({'INFO'}, "Maximum reached")
            return {'FINISHED'}
        else:
            bm = bmesh.new()
            bm.from_mesh(me)
            bmesh.ops.subdivide_edges(bm, edges=bm.edges, cuts=self.subd_levels, use_grid_fill=True)
            bm.to_mesh(me)
            me.update()
            self.report({'INFO'}, "{} levels applied".format(self.subd_levels))
            me.subdiv_prop =+ self.subd_levels
            return {'FINISHED'}
        
        
def register():
    bpy.utils.register_class(SimpleOperator)
    bpy.types.Mesh.subdiv_prop = IntProperty(default=0)

def unregister():
    bpy.utils.unregister_class(SimpleOperator)
    del bpy.types.Mesh.subdiv_prop


if __name__ == "__main__":
    register()

    # test call
    #bpy.ops.mesh.custom_subdiv('INVOKE_DEFAULT')

How to subdivide mesh with Python?

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .