1

I am trying to subdivide and finally add a Shrink Wrap modifier to an object using python.

Below is the object SUBDIVIDE code.

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')

Where do I add the Shrink Wrap code bpy.ops.object.modifier_add(type='SHRINKWRAP') so they can be executed simultaneously?

Gorgious
  • 30,723
  • 2
  • 44
  • 101
3vanse
  • 95
  • 6

1 Answers1

3

Use the low-level function to add modifiers which allows for direct property access: https://docs.blender.org/api/current/bpy.types.ObjectModifiers.html#bpy.types.ObjectModifiers.new

import bpy

C = bpy.context

Get the object

obj = C.scene.objects['Cube']

Add the modifier using the low level function

shrink_mod = obj.modifiers.new(name="Shrinkie", type='SHRINKWRAP') shrink_mod.offset = 0.01 shrink_mod.target = C.scene.objects['Sphere']

How to add modifiers using python script and set parameters?


If you want to make it work along with my code from your other question How to limit number of times an operator can run in python, add the following lines to the operator:

        # Add the modifier using the low level function
        shrink_mod = context.object.modifiers.new(name="Shrinkie", type='SHRINKWRAP')
        shrink_mod.offset = 0.01
        shrink_mod.target = context.scene.objects['Sphere']
pyCod3R
  • 1,926
  • 4
  • 15