def create_deltaMush(bindGeo, iterations = [5, 10, 20, 30, 40]): smoothGeo = pm.duplicate( bindGeo, rr=True, ic=True, name=bindGeo.name() + "_smooth") [0] smoothGeo.addAttr("envelope", at='long', min=0, max=1, dv=1, k=True) smoothGeo.addAttr("partitions", at='message') deltaGeo = pm.duplicate( bindGeo, rr=True, ic=False, name="BS_" + bindGeo.name() + "_delta") [0] pm.select(deltaGeo, smoothGeo) pm.mel.eval("CreateWrap") smoothNodes = [] smoothNodeSets = [] for i in range(0, len(iterations)): smoothNode = pm.deformer([smoothGeo], type='smooth')[0] smoothNode.iterations.set(iterations[i]) smoothGeo.envelope >> smoothNode.envelope smoothNodes.append(smoothNode) smoothNodeSet = smoothNode.message.listConnections()[0] smoothNodeSet.clear() smoothNodeSets.append(smoothNodeSet) for smoothNodeSet in smoothNodeSets: smoothNodeSet.clear() partition = pm.partition(smoothNodeSets) partition.message >> smoothGeo.partitions skinCls = bindGeo.getShape().listConnections(type='skinCluster')[0] joints = skinCls.getInfluence() assign_iteration_set(joints, bindGeo, skinCls, deltaGeo)
def aw_muscleShrinkWrap(source, meshes): '''Attaches muscle objects to the source then targets and makes them conform to its shape Args: source (pm.PyNode): source object to get shape from targets (pm.PyNode): target objects to conform Returns (pm.nt.CMuscleSystem): muscle object that is created Usage: aw_muscleShrinkWrap(pm.ls(sl=True)[0], pm.ls(sl=True)[1:]) ''' #convert target to muscle pm.select(source, r=True) eval('cMuscle_makeMuscle(0)') #apply muscle skin deformer to source pm.select(meshes, r=True) eval('cMuscle_makeMuscleSystem(1)') #connect the two systems pm.select([source,meshes], r=True) eval('cMuscle_connectToSystem()') #get the system: pm.select(meshes, r=True) systems = eval('cMuscle_getSelectedDeformers("cMuscleSystem")') for system in systems: system=pm.PyNode(system) deformeds = pm.deformer(system, q=True, geometry=True) #print 'setting weights for muscle system: %s'%system #print deformeds #system.shrinkWrap.set(1) system.enableSliding.set(1) for deformed in deformeds: deformedVerts = pm.polyListComponentConversion(deformed,tv=True)
def gear_curveslide2_op(outcrv, incrv, position=0, maxstretch=1, maxsquash=1, softness=0): """Apply a sn_curveslide2_op operator Arguments: outcrv (NurbsCurve): Out Curve. incrv (NurbsCurve): In Curve. position (float): Default position value (from 0 to 1). maxstretch (float): Default maxstretch value (from 1 to infinite). maxsquash (float): Default maxsquash value (from 0 to 1). softness (float): Default softness value (from 0 to 1). Returns: pyNode: The newly created operator. """ pm.select(outcrv) node = pm.deformer(type="mgear_slideCurve2")[0] pm.connectAttr(incrv + ".local", node + ".master_crv") pm.connectAttr(incrv + ".worldMatrix", node + ".master_mat") pm.setAttr(node + ".master_length", pm.arclen(incrv)) pm.setAttr(node + ".slave_length", pm.arclen(incrv)) pm.setAttr(node + ".position", 0) pm.setAttr(node + ".maxstretch", 1) pm.setAttr(node + ".maxsquash", 1) pm.setAttr(node + ".softness", 0) return node
def cMuscle_setupSystemforRelative(ms): shapes = pm.deformer(ms, q=True, geometry=True) if shapes: shape = shapes[0] rels = cMuscle_getDeformers('cMuscleRelative', shape) if len(rels) >= 1: rel = rels[0] else: rels = pm.deformer(shape, type='cMuscleRelative', frontOfChain=True) skins = cMuscle_getDeformers('skinCluster', shape) rel.point.connect(ms.relativePoint) ms.relativeSticky.set(1) msg = mel.eval('uiRes("m_cMuscle.kSetupMuscleSystemForRelativeStickyDeformation")') pm.format(msg, stringArg=ms.name()) print msg return rel
def deformerSwap(master): sel = pm.ls(sl=True) master = sel[0] deformers=[] deformer_types=[pm.nt.NonLinear] for connection in master.getShape().listConnections(): for deformer_type in deformer_types: if isinstance(connection,deformer_type): deformers.append(connection) print deformers for obj in sel[1:]: for deformer in deformers: print obj.getShape().listConnections() if not deformer in obj.getShape().listConnections(): try: pm.deformer(deformer, e=True, g=obj) except: pm.warning('something was up with the deformer %s for obj %s' % (deformer, obj)) #deformerSwap(pm.PyNode('engine_L_cap2L'))
def shrinkWrapDeformer(wrappedObj, wrapperObj): """ Apply ShrinkWrap Deformer on selected mesh :param wrappedObjs: str :param wrapperObj: str :return: deformer node """ shrinkWrapNode = pm.deformer(wrappedObj, type='shrinkWrap')[0] pm.PyNode(wrapperObj).worldMesh[0] >> shrinkWrapNode.targetGeom shrinkWrapNode.closestIfNoIntersection.set(True) return shrinkWrapNode
def ContactDeformer(): sel = pm.ls(sl=True) if len(sel) is 2: collider = sel[0] target = sel[1] collidershape = pm.listRelatives(collider, s=True)[0] collisiondeformer = pm.deformer(target, type="ContactDeform", n="collisionDeformer")[0] pm.connectAttr(collidershape.worldMesh[0], collisiondeformer.collider, f=True) pm.connectAttr(collider.matrix, collisiondeformer.colliderMatrix, f=True) pm.connectAttr(collider.boundingBoxSize, collisiondeformer.colliderBBoxSize, f=True) else: print("Please select two meshes: first the collider mesh then the mesh that should be deformed.")
def create_deltaMush(bindGeo, iterations=10): smoothGeo = pm.duplicate( bindGeo, rr=True, ic=True, name=bindGeo.name() + "_smooth") [0] deltaGeo = pm.duplicate( bindGeo, rr=True, ic=False, name=bindGeo.name() + "_delta") [0] pm.select(deltaGeo, smoothGeo) pm.mel.eval("CreateWrap") smoothNode = pm.deformer([smoothGeo], type='smoothSimple')[0] smoothNode.iterations.set(iterations) newBaseGeo = pm.duplicate( smoothGeo, rr=True, ic=False, name=bindGeo.name() + "_smoothBase") [0] wrapNode = deltaGeo.inMesh.listConnections()[0] swap_wrap_deformer_base(wrapNode, newBaseGeo)
def cMuscle_prepareRelax(mesh): hist = pm.listHistory(mesh, pdo=True, il=1) muscleSystems = pm.ls(hist, type='cMuscleSystem') muscleSystems = list(set(muscleSystems)) for ms in muscleSystems: deformed = pm.deformer(ms, q=True, geometry=True)[0] if deformed.type() in ['nurbsSurface', 'mesh', 'subdiv']: ms.envelope.set(0) a, size = 0, 0 for attr in ['smoothData.smoothEntry','smoothData.ptToPtEntry','relaxData.relaxSt','relaxData.relaxBd','relaxData.relaxTri']: for index in range(0, ms.attr(attr).get(size=True)-1): pm.removeMultiInstance(ms.attr(attr)[index]) pm.cMuscleRelaxSetup(ms, gen=True) ms.envelope.set(1)
def cMuscleSystemDeformer(obj, relativeSticky=True): """ Apply cMuscleSystem Deformer on selected mesh :param obj: str :return: deformer node """ deformerNode = None if relativeSticky: pm.select(obj) d = mel.eval('cMuscle_makeMuscleSystem(1);') deformerNode = pm.ls(d)[0] else: deformerNode = pm.deformer(obj, type='cMuscleSystem')[0] return deformerNode
def createWrap(driver, tgts, threshold=0, maxDistance=50, inflType=2, exclusiveBind=True, autoWeightThreshold=True, falloffMode=0): ''' Args: driver (pm.nt.Transform): driver object for the wrap tgts [pm.nt.Transform]: List of target objects threshold (float): look in the docs maxDistance (float): look in the docs inflType (int): look in the docs exclusiveBind (boolean): look in the docs autoweightThreshold (boolean): look in the docs falloffMode (int): look in the docs Returns {'wraps':[pm.nt.wrap], 'driver':[pm.nt.Transform, pm.nt.Transform]}: Dictionary with the wrap deformers and the driver/base objects Usage: createWrap(driver, tgts, 0, 50, 2, True, True, 0) ''' wraps=[] base=None #create or use the existing base object driverName = driver.name()+'BASE' if not pm.objExists( driverName ): base = pm.duplicate(driver, rr=True, n=driverName)[0] base.visibility.set(0) else: base = pm.PyNode(driverName) for target in tgts: wrap = pm.deformer(target, type='wrap', n = '%s_WRAP'%driver )[0] wraps.append( wrap ) wrap.weightThreshold.set( threshold ) wrap.maxDistance.set( maxDistance ) wrap.exclusiveBind.set( exclusiveBind ) wrap.autoWeightThreshold.set( autoWeightThreshold ) wrap.falloffMode.set( falloffMode ) wrap.inflType[0].set( inflType ) wrap.dropoff[0].set( 4 ) target.getShape().worldMatrix[0].connect( wrap.geomMatrix, f=True ) base.getShape().worldMesh.connect( wrap.basePoints[0], f=True ) driver.getShape().worldMesh.connect( wrap.driverPoints[0], f=True ) return {'wraps':wraps, 'driver':[driver, base]}
def create_wrap_deformer(influence, deformed, **kwargs): ''' Create a wrap deformer object :param influence: pymel.PyNode influence object :param deformed: pymel.PyNode deformed object :param kwargs: Wrap attribute values ''' pm.select(deformed, replace=True) kwargs.setdefault('weightThreshold', 0.0) kwargs.setdefault('maxDistance', 1.0) kwargs.setdefault('exclusiveBind', False) kwargs.setdefault('autoWeightThreshold', True) kwargs.setdefault('falloffMode', 1) wrap = pm.deformer(type='wrap')[0] for k, v in kwargs.iteritems(): wrap.attr(k).set(v) if not influence.hasAttr('dropoff'): influence.addAttr('dropoff', sn='dr', dv=4, min=0, max=20, k=True) if not influence.hasAttr('smoothness'): influence.addAttr('smoothness', sn='smt', dv=0, min=0, k=True) if not influence.hasAttr('inflType'): influence.addAttr('inflType', sn='ift', at='short', dv=2, min=1, max=2) influence.dropoff.connect(wrap.dropoff[0]) influence.smoothness.connect(wrap.smoothness[0]) influence.inflType.connect(wrap.inflType[0]) influence_shape = influence.getShape(noIntermediate=True) influence_shape.worldMesh.connect(wrap.driverPoints[0]) base = influence.duplicate(name=influence + 'Shape', rc=True)[0] base_shape = base.getShape(noIntermediate=True) base.hide() base_shape.worldMesh.connect(wrap.basePoints[0]) deformed.worldMatrix.connect(wrap.geomMatrix) return wrap, base
def gear_curvecns_op(crv, inputs=[]): """ create mGear curvecns node. Args: crv (nurbsCurve): Nurbs curve. inputs (List of dagNodes): Input object to drive the curve. Should be same number as crv points. Also the order should be the same as the points Returns: pyNode: The curvecns node. """ pm.select(crv) node = pm.deformer(type="mgear_curveCns")[0] for i, item in enumerate(inputs): pm.connectAttr(item + ".worldMatrix", node + ".inputs[%s]" % i) return node
def WrapDeformer(SEL): BaseMod = SEL[0] TargetMod = SEL[1] #for Group selection duplicateData = pm.duplicate(BaseMod, name=BaseMod + 'Base') BaseModShape = BaseMod.getChildren()[0] wrapData = pm.deformer(TargetMod, type='wrap', n=TargetMod + '_wrap') wrapNode = wrapData[0] wrapNode.setAttr('weightThreshold', 0.0) wrapNode.setAttr('maxDistance', 1.0) wrapNode.setAttr('exclusiveBind', False) wrapNode.setAttr('autoWeightThreshold', True) wrapNode.setAttr('falloffMode', 0) TargetMod.worldMatrix[0] >> wrapNode.geomMatrix # add influence base = duplicateData[0] shapes = base.getChildren() baseShape = shapes[0] base.hide() # create dropoff attr if it doesn't exist if not pm.attributeQuery('dropoff', n=BaseMod, exists=True): pm.addAttr(BaseMod, sn='dr', ln='dropoff', dv=4.0, min=0.0, max=20.0) pm.setAttr(BaseMod + '.dr', k=True) # # if type mesh # if pm.nodeType(BaseModShape) == 'mesh': # create smoothness attr if it doesn't exist if not pm.attributeQuery('smoothness', n=BaseMod, exists=True): pm.addAttr(BaseMod, sn='smt', ln='smoothness', dv=0.0, min=0.0) pm.setAttr(BaseMod + '.smt', k=True) # create the inflType attr if it doesn't exist if not pm.attributeQuery('inflType', n=BaseMod, exists=True): pm.addAttr(BaseMod, at='short', sn='ift', ln='inflType', dv=2, min=1, max=2) BaseModShape.worldMesh >> wrapNode.driverPoints[0] baseShape.worldMesh >> wrapNode.basePoints[0] BaseMod.inflType >> wrapNode.inflType[0] BaseMod.smoothness >> wrapNode.smoothness[0] BaseMod.dropoff >> wrapNode.dropoff[0]
def move_skin(source, target): source_shape = get_deform_shape(source) source_dp = get_dag_path(source_shape.longName()) source_skin = get_skin_cluster(source) source_mfn = get_mfn_skin(source_skin) source_mesh = get_mfn_mesh(get_deform_shape(source)) components = get_complete_components(source_mesh) weights, influence_count = source_mfn.getWeights(source_dp, components) pm.select(cl=True) target_skin = pm.deformer(target, type='skinCluster', n='MERGED__' + source_skin.name())[0] ## copy over input values / connections bind_inputs = [(x.inputs(plugs=True)[0] if x.isConnected() else None) for x in source_skin.bindPreMatrix] bind_values = [x.get() for x in source_skin.bindPreMatrix] mat_inputs = [(x.inputs(plugs=True)[0] if x.isConnected() else None) for x in source_skin.matrix] mat_values = [x.get() for x in source_skin.matrix] for index, bind_value, mat_value in zip(xrange(influence_count), bind_values, mat_values): target_skin.bindPreMatrix[index].set(bind_value) target_skin.matrix[index].set(mat_value) for index, bind_input, mat_input in zip(xrange(influence_count), bind_inputs, mat_inputs): if bind_input: bind_input >> target_skin.bindPreMatrix[index] if mat_input: mat_input >> target_skin.matrix[index] ## copy over weights target_mfn = get_mfn_skin(target_skin) target_mesh = get_mfn_mesh(get_deform_shape(target)) target_dp = get_dag_path(get_deform_shape(target).longName()) components = get_complete_components(target_mesh) all_indices = om2.MIntArray(range(influence_count)) target_mfn.setWeights(target_dp, components, all_indices, weights)
def create_poseDeformer(name, obj): '''Creates a deformer on an object Args: name (string): the name of the deformer obj (pm.PyNode): the object to apply to Returns (boolean): pm.nt.poseDeformer ''' deformer = pm.deformer( obj, type='poseDeformer', n=name+'_POSD')[0] skinCluster = lib_sc.rig_getConnectedSkinCluster(obj) if skinCluster: influences = lib_sc.rig_getSkinClusterInfluences(skinCluster) i=0 for influence in influences: influence.worldMatrix.connect( deformer.worldMatrix[i] ) i+=1 deformer.avgPoseSepRBF.set(30.0) return deformer else: pm.warning('No skinCluster detected attached to the mesh...not creating deformer %s on obj %s'%(name,obj))
def apply_cage(target_mesh=None, cage_mesh=None): if not target_mesh or not cage_mesh: currently_selected = pm.selected() if len(currently_selected) != 2: warning('Select a target and cage mesh!') return None target_mesh, cage_mesh = currently_selected else: target_mesh = pm.PyNode(target_mesh) cage_mesh = pm.PyNode(cage_mesh) if not pm.pluginInfo('green_cage_deformer', loaded=True, query=True): pm.loadPlugin('green_cage_deformer') pm.select(target_mesh, r=True) cage_deformer = pm.deformer(type='green_cage_deformer')[0] cage_mesh.worldMesh[0] >> cage_deformer.cageMesh return cage_deformer
def cMuscle_makeMuscleSystem(meshes, prompt): if len(meshes) <= 0: pm.warning('No meshes were provided...') return False for mesh in meshes: muscleDeformer = mesh.getShape().listConnections(s=True, d=False, type='cMuscleSystem') if len(muscleDeformer): pm.warning('Already have a muscle deformer on this mesh...') return False muscleDeformer = pm.deformer(mesh, type='cMuscleSystem')[0] pm.PyNode('time1').outTime.connect(muscleDeformer.inTime) path = pm.workspace(q=True, dir=True) + 'muscleCache/' if not os.path.exists(path): os.makedirs(path) muscleDeformer.cachePath.set(path+mesh+'.mus') for attr in ['STICKY','SLIDING','JIGGLE','DISPLACE','FORCE','RELAX','SMOOTH','COLLISION']: muscleDeformer.attr(attr).lock() #relax now cMuscle_prepareRelax(mesh) skins = cMuscle_getDeformers('skinCluster', mesh) if prompt and len(skins) >= 1: labelYes = mel.eval('uiRes("m_cMuscle.kYes")') labelYes = mel.eval('uiRes("m_cMuscle.kNo")') ret = pm.confirmDialog(t=mel.eval('uiRes("m_cMuscle.kSetupForRelativeDeformation")'), m=mel.eval('uiRes("m_cMuscle.kThisMeshAppearsToHaveSkinClusterApplied")'), button = [labelYes, labelNo], defaultButton = labelYes, cancelButton = labelNo, dismissString = labelNo) if ret == labelYes: cMuscle_setupSystemforRelative(muscleDeformer) msg = mel.eval('uiRes("m_cMuscle.kAddedDef")') print msg return muscleDeformer
def wrapIt(self, *args): slMsh = cmds.ls(sl = True) mesh = [] if len(slMsh) >=2: for each in slMsh: cmds.select(each, add=True ) name = each+'_g' importedCombinedMesh = cmds.polyUnite( n=name ) cmds.delete( importedCombinedMesh, ch = True ) mesh.append(name) else: for each in slMsh: cmds.select(each, add=True ) obj = cmds.ls(sl=True) print (obj) name = cmds.rename(obj[0], (each+'_g')) mesh.append(name) bbox = cmds.exactWorldBoundingBox(mesh[0]) x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(mesh[0]) lowRes = mesh[0] + '_proxyGeo' proxymesh = cmds.polySphere(n = lowRes, subdivisionsX = 15, subdivisionsY = 15) print proxymesh xc = (x2 + x1) / 2.0 yc = (y2 + y1) / 2.0 zc = (z2 + z1) / 2.0 xw = x2 - x1 yw = y2 - y1 zw = z2 - z1 cmds.move(xc, yc, zc, proxymesh) cmds.scale(xw, yw, zw, proxymesh) shrinkWrapNode = pm.deformer(proxymesh, type='shrinkWrap')[0] pm.PyNode(name).worldMesh[0] >> shrinkWrapNode.targetGeom shrinkWrapNode.closestIfNoIntersection.set(True) cmds.delete( proxymesh, ch = True ) cmds.select(clear = True) cmds.select(proxymesh[0]) cmds.select(mesh[0], add = True) self.copyPivot(mesh[0], proxymesh) return proxymesh[0]
plugin_fn.registerNode(CarpetRoll.TYPE_NAME, CarpetRoll.TYPE_ID, CarpetRoll.creator, CarpetRoll.initialize, ommpx.MPxNode.kDeformerNode) except: pm.displayError("Failed to register node {0}".format( CarpetRoll.TYPE_NAME)) def uninitializePlugin(plugin): plugin_fn = ommpx.MFnPlugin(plugin) try: plugin_fn.deregisterNode(CarpetRoll.TYPE_ID) except: pm.displayError("Failed to deregister node {0}".format( CarpetRoll.TYPE_NAME)) if __name__ == "__main__": pm.newFile(f=1) plugin_name = "E:/Maya/MayaAPI/Deforner/CarpetRoll.py" if pm.pluginInfo(plugin_name, q=1, loaded=True): pm.unloadPlugin(os.path.basename(plugin_name), f=True) pm.loadPlugin(plugin_name) pplane_transform, pplane_shape = pm.polyPlane() pplane_shape.subdivisionsWidth.set(20) pplane_shape.subdivisionsHeight.set(20) pm.select(pplane_transform) pm.deformer(type="CarpetRoll")
def create_wrap_deformer(influence_mesh, target_mesh, **kwargs): """ Ryan Roberts - Wrap Deformer rr_wrap.py Description: Ryan Robers created a simple function to create a wrap deformer. The wrap deformer needs a little more than the deform command to get working. Michael Clavan I wanted to have the function also return the deformer to the user. So, my contributions are pretty minor. I converted the wrap deformer into a pynode object type pm.nt.Wrap. Scott Clary Converted maya.cmds to pymel code so that we can pass PyNodes into this method. """ influence_shape = influence_mesh.getShape() # create wrap deformer weight_threshold = kwargs.get('weightThreshold', 0.0) max_distance = kwargs.get('maxDistance', 1.0) exclusive_bind = kwargs.get('exclusiveBind', False) auto_weight_threshold = kwargs.get('autoWeightThreshold', True) falloff_mode = kwargs.get('falloffMode', 0) wrap_node = pm.deformer(target_mesh, type='wrap')[0] wrap_node.weightThreshold.set(weight_threshold) wrap_node.maxDistance.set(max_distance) wrap_node.exclusiveBind.set(exclusive_bind) wrap_node.autoWeightThreshold.set(auto_weight_threshold) wrap_node.falloffMode.set(falloff_mode) target_mesh = target_mesh.getShape() target_mesh.worldMatrix[0].connect(wrap_node.geomMatrix) # add influence base = pm.duplicate(influence_mesh, name='{0}Base'.format(influence_mesh))[0] base_shape = base.getShape() base_shape.visibility.set(False) def safe_add_attr(node, long_name, keyable=True, **kwargies): try: # if the attribute already exists, do nothing otherwise create it node.attr(long_name).exists() except AttributeError: node.addAttr(long_name, **kwargies) if keyable: node.attr(long_name).set(keyable=True) # create dropoff attr if it doesn't exist safe_add_attr(influence_mesh, 'dropoff', shortName='dr', defaultValue=4.0, min=0.0, max=20.0) # if type mesh if isinstance(influence_shape, pm.nt.Mesh): # create smoothness attr if it doesn't exist safe_add_attr(influence_mesh, 'smoothness', shortName='smt', defaultValue=0.0, min=0.0) # create the inflType attr if it doesn't exist safe_add_attr(influence_mesh, 'inflType', keyable=False, shortName='ift', attributeType='short', defaultValue=2, min=1, max=2) influence_shape.worldMesh.connect(wrap_node.driverPoints[0]) base_shape.worldMesh.connect(wrap_node.basePoints[0]) influence_mesh.inflType.connect(wrap_node.inflType[0]) influence_mesh.smoothness.connect(wrap_node.smoothness[0]) if isinstance(influence_shape, pm.nt.NurbsCurve) or isinstance( influence_shape, pm.nt.NurbsSurface): # create the wrapSamples attr if it doesn't exist safe_add_attr(influence_mesh, 'wrapSamples', shortName='wsm', attributeType='short', defaultValue=10, min=1) influence_shape.ws.connect(wrap_node.driverPoints[0]) base_shape.ws.connect(wrap_node.basePoints[0]) influence_mesh.wsm.connect(wrap_node.nurbsSamples[0]) influence_mesh.dropoff.connect(wrap_node.dropoff[0]) return wrap_node, base_shape
def wrap_create(*args,**kwargs): ''' Args: *args [source (pm.nt.Transform), target (pm.nt.Transform)]: source and target objects Returns [pm.nt.Deformer, pm.nt.Transform]: resulting wrap deformer Usage: wrap_create(pm.ls(sl=True)[0],pm.ls(sl=True)[1]) ''' influence, surface = args[0], args[1] influenceShape = influence.listRelatives(shapes=True)[0] surfaceShape = pm.listRelatives(surface,shapes=True)[0] #create wrap deformer weightThreshold = kwargs.get('weightThreshold',0.0) maxDistance = kwargs.get('maxDistance',1.0) exclusiveBind = kwargs.get('exclusiveBind',False) autoWeightThreshold = kwargs.get('autoWeightThreshold',True) falloffMode = kwargs.get('falloffMode',0) attr_sets = [weightThreshold, maxDistance, exclusiveBind, autoWeightThreshold, falloffMode] wrapData = pm.deformer(surface, type='wrap') wrapNode = wrapData[0] pm.setAttr(wrapNode+'.weightThreshold',weightThreshold) pm.setAttr(wrapNode+'.maxDistance',maxDistance) pm.setAttr(wrapNode+'.exclusiveBind',exclusiveBind) pm.setAttr(wrapNode+'.autoWeightThreshold',autoWeightThreshold) pm.setAttr(wrapNode+'.falloffMode',falloffMode) pm.connectAttr(surface+'.worldMatrix[0]',wrapNode+'.geomMatrix') #add influence base = pm.duplicate(influence,name=influence+'Base')[0] baseShape = base.listRelatives(shapes=True)[0] baseShape.visibility.set(0) #create dropoff attr if it doesn't exist if not pm.attributeQuery('dropoff',n=influence,exists=True): pm.addAttr( influence, sn='dr', ln='dropoff', dv=4.0, min=0.0, max=20.0 ) pm.setAttr( influence+'.dr', k=True ) #if type mesh if pm.nodeType(influenceShape) == 'mesh': #create smoothness attr if it doesn't exist if not pm.attributeQuery('smoothness',n=influence,exists=True): pm.addAttr( influence, sn='smt', ln='smoothness', dv=0.0, min=0.0 ) pm.setAttr( influence+'.smt', k=True ) #create the inflType attr if it doesn't exist if not pm.attributeQuery('inflType',n=influence,exists=True): pm.addAttr( influence, at='short', sn='ift', ln='inflType', dv=2, min=1, max=2 ) pm.connectAttr(influenceShape+'.worldMesh',wrapNode+'.driverPoints[0]') pm.connectAttr(baseShape+'.worldMesh',wrapNode+'.basePoints[0]') pm.connectAttr(influence+'.inflType',wrapNode+'.inflType[0]') pm.connectAttr(influence+'.smoothness',wrapNode+'.smoothness[0]') #if type nurbsCurve or nurbsSurface if pm.nodeType(influenceShape) == 'nurbsCurve' or pm.nodeType(influenceShape) == 'nurbsSurface': #create the wrapSamples attr if it doesn't exist if not pm.attributeQuery('wrapSamples',n=influence,exists=True): pm.addAttr( influence, at='short', sn='wsm', ln='wrapSamples', dv=10, min=1 ) pm.setAttr( influence+'.wsm', k=True ) pm.connectAttr(influenceShape+'.ws',wrapNode+'.driverPoints[0]') pm.connectAttr(baseShape+'.ws',wrapNode+'.basePoints[0]') pm.connectAttr(influence+'.wsm',wrapNode+'.nurbsSamples[0]') pm.connectAttr(influence+'.dropoff',wrapNode+'.dropoff[0]') return [wrapNode, base]
import pymel.core as pymel pymel.mel.eval('CreateWrap;') pymel.deformer('pSphere2',type='wrap') src = pymel.PyNode('src') if not pymel.attributeQuery('influence', n=src, exists=True): src.addAttr('influence', keyable=True, defaultValue=2) if not pymel.attributeQuery('smoothness', n=src, exists=True): src.addAttr('smoothness', keyable=True, defaultValue=0) if not pymel.attributeQuery('dropoff', n=src, exists=True): src.addAttr('dropoff', keyable=True, defaultValue=0)
def connectAlembic(alembicFile, roots, namespace=':'): """Connects alembic cache to an hierarchy # TODO: Currently blend shape is used and the process is messy and not reliable """ # Read archive and find all deformed geometry meshTransforms = [] excludeFilter = [] for g in alembic_utils.listArchive(Abc.IArchive(str(alembicFile)), AbcGeom.IPolyMesh): tName = g.getParent().getName().split(':')[-1] gName = g.getName().split(':')[-1] # Determine what to import from alembic based on shape name and is deformations present if g.getSchema().isConstant() and not gName == tName + 'ShapeDeformed': excludeFilter.append(g.getParent().getFullName() + '/') else: meshTransforms.extend( pm.ls(namespace + ':' + tName, transforms=True)) excludeFilter = ' '.join(excludeFilter) # Do alembic cache import with namespaceContext(namespace): # NOTE: Unlock reference transforms attributes if locked # as alembic will automatically create connections for transforms in hierarchy below for c in roots + pm.listRelatives( roots, allDescendents=True, typ='transform'): for a in 'tx|ty|tz|sx|sy|sz|rx|ry|rz'.split('|'): getattr(c, a).__apimplug__().setLocked(False) pm.mel.AbcImport( str(preparePath(alembicFile).replace('\\', '/')), ct=[r.longName() for r in roots], excludeFilterObjects=excludeFilter, # HACK: Create deformed geometry to make out # poly plug evaluate its data as there is a bug crt=True) # Connect alembic cache with blendShape on to target geometry for t in meshTransforms: if len(t.getShapes()) == 1: logger.warn('Failed to connect cache for {} ' 'there is not deformed shape'.format(t.longName())) continue destinationMeshPlug = t.getShape().inMesh deformedShape = t.getShapes()[1] if deformedShape.inMesh.listConnections(p=1): sourceMeshPlug = deformedShape.inMesh.listConnections(p=1)[0] else: sourceMeshPlug = deformedShape.outMesh deformedShape.intermediateObject.set(1) for sp, dp in deformedShape.outputs(p=1, c=1): if dp.node().nodeType() == 'shadingEngine': sp.disconnect(dp) try: blendShape = pm.deformer(destinationMeshPlug.node(), type='blendShape', before=True)[0] pm.connectAttr( sourceMeshPlug, blendShape.inputTarget[0]. inputTargetGroup[0].inputTargetItem[6000].inputGeomTarget) blendShape.weight[0].set(1) except Exception as e: logger.debug( 'Failed to connect cache for {} exception: {}'.format( t.longName(), traceback.format_exc())) pass # NOTE: Force refresh # TODO: Can pm.refresh be used? pm.currentTime(pm.playbackOptions(q=True, animationStartTime=True) + 1) pm.currentTime(pm.playbackOptions(q=True, animationStartTime=True) - 1) alembicNodes = pm.ls(regex=re.escape(namespace) + ':.+', typ='AlembicNode') # Geometry Cache is not static if alembicNodes: # NOTE: Delete shapes created by alembic # as we connected outMeshData directly in too blend shape for i in alembicNodes[0].outPolyMesh.getArrayIndices(): pm.delete( pm.listConnections(alembicNodes[0].outPolyMesh[i], shapes=True, t='mesh')) return alembicNodes
def generateLODS(self): x = self.ui.selectedGeo_groupBox.title() x = (x.replace('Selected Mesh: ', '')) fullPath = str(cmds.ls(x, long=True)[0]) if fullPath: print fullPath obSl = fullPath if len(obSl) == 0: cmds.confirmDialog( title='Error:', message='No objects selected for polygon reduction') else: print('\n') cmds.select(obSl) lods = [] LOD01_Val = [] LOD02_Val = [] LOD03_Val = [] currentIndex = self.whatTab() print currentIndex if currentIndex == 0: LOD1_Number = int(self.ui.LOD1_num.text()) LOD2_Number = int(self.ui.LOD2_num.text()) LOD3_Number = int(self.ui.LOD3_num.text()) LOD3_Number = int(self.ui.LOD3_num.text()) LOD01_Val.append(LOD1_Number) LOD02_Val.append(LOD2_Number) LOD03_Val.append(LOD3_Number) else: LOD01_Percent = self.ui.LOD1_horizontalSlider.value() LOD02_Percent = self.ui.LOD2_horizontalSlider.value() LOD03_Percent = self.ui.LOD3_horizontalSlider.value() currentMeshPolyGonCount = cmds.polyEvaluate(f=True) print currentMeshPolyGonCount LOD01_PolyPercent = (LOD01_Percent * currentMeshPolyGonCount) / 100 LOD02_PolyPercent = (LOD02_Percent * currentMeshPolyGonCount) / 100 LOD03_PolyPercent = (LOD03_Percent * currentMeshPolyGonCount) / 100 LOD01_Val.append(LOD01_PolyPercent) LOD02_Val.append(LOD02_PolyPercent) LOD03_Val.append(LOD03_PolyPercent) LOD0_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD0')) lods.append(LOD0_LOD) #print LOD01_Val,LOD02_Val,LOD03_Val if self.ui.LOD1_chkBox.isChecked(): LOD1_Num = LOD01_Val[0] LOD1_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD1')) self.genFunction(LOD1_LOD, LOD1_Num) lods.append(LOD1_LOD) print('"__LOD1"__LOD__generated__Successfully :~- ' + str(LOD1_LOD)) if self.ui.LOD2_chkBox.isChecked(): LOD2_Num = LOD02_Val[0] LOD2_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD2')) self.genFunction(LOD2_LOD, LOD2_Num) lods.append(LOD2_LOD) print('"__LOD2"__LOD__generated__Successfully :~- ' + str(LOD2_LOD)) if self.ui.LOD3_chkBox.isChecked(): LOD3_Num = LOD03_Val[0] LOD3_LOD = cmds.duplicate(obSl, name=(obSl + '__LOD3')) self.genFunction(LOD3_LOD, LOD3_Num) lods.append(LOD3_LOD) print('"__LOD3"__LOD__generated__Successfully :~- ' + str(LOD3_LOD)) if self.ui.WRAP_chkBox.isChecked(): WRAP_Num = str(self.ui.wrap_comboBox.currentText()) print WRAP_Num LOD5_LOD = cmds.CreatePolygonSoccerBall(n=obSl + '__LOD4') newMesh = cmds.rename(LOD5_LOD, (obSl + '__LOD4')) if WRAP_Num == '180': cmds.polySmooth(newMesh, divisions=1) if WRAP_Num == '720': cmds.polySmooth(newMesh, divisions=2) if WRAP_Num == '2880': cmds.polySmooth(newMesh, divisions=3) cmds.delete(newMesh, ch=True) bbox = cmds.exactWorldBoundingBox(obSl) x1, y1, z1, x2, y2, z2 = cmds.exactWorldBoundingBox(obSl) xc = (x2 + x1) / 2.0 yc = (y2 + y1) / 2.0 zc = (z2 + z1) / 2.0 xw = x2 - x1 yw = y2 - y1 zw = z2 - z1 cmds.move(xc, yc, zc, newMesh) cmds.scale(xw, yw, zw, newMesh) shrinkWrapNode = pm.deformer(newMesh, type='shrinkWrap')[0] pm.PyNode(obSl).worldMesh[0] >> shrinkWrapNode.targetGeom shrinkWrapNode.closestIfNoIntersection.set(True) cmds.delete(newMesh, ch=True) cmds.select(clear=True) cmds.select(newMesh) cmds.select(obSl, add=True) self.copyPivot() lods.append(newMesh) if self.ui.BBOX_chkBox.isChecked(): print('make a bounding box') cmds.select(obSl) box = self.MakeCube() newmeshBox = cmds.rename(box, (obSl + '__LOD5')) lods.append(newmeshBox) cmds.select(obSl) cmds.select(newmeshBox, add=True) self.copyPivot() cmds.select(clear=True) if lods == []: pass else: grp = (obSl + '__LOD_grp') if cmds.objExists(grp): pass else: lod_grp = cmds.group(n=grp, em=True) print grp for lod in lods: print lod cmds.parent(lod, grp) print('\n') cmds.inViewMessage(amg="LOD generated successfully", pos="botCenter", fade=True) print('Done') else: cmds.confirmDialog( title='Error:', message='No objects selected for polygon reduction')
#create root_j_manip root_j_manip = pm.circle(r = 1.3, nr = (0.0,1.0,0.0), n = 'root_j_manip', ch = False)[0] pm.select(cl = True) root_j_manip_grp = pm.group(root_j_manip, n = 'root_j_manip_grp') pm.select(cl = True) #constrain j to manip pm.parentConstraint(root_j_manip, root_j_grp , mo = True) pm.scaleConstraint(root_j_manip, root_j_grp , mo = True) pm.select(cl = True) #Create Deformer pm.select(sphereTrans, r = True) rbRollNode = pm.deformer(type = 'RbRoll')[0] pm.setAttr(rbRollNode.radius, 1.0) pm.select(cl = True) #create skincluster skincluster = pm.skinCluster( root_j, sphereTrans, foc = False) pm.select(cl = True) #create frameCache nodes frameCacheX = pm.createNode('frameCache') pm.select(cl = True) pm.rename(frameCacheX, 'frameCacheX') pm.select(cl = True) frameCacheZ = pm.createNode('frameCache') pm.select(cl = True)
def wrapDeformer(_HiRez=pm.selected(), _LoRez=pm.selected()): """ Custom wrapDeformer Select target - HiRez first, then the source - LoRez @param Hirez: Target which will receive the wrap : str or selection @param Lorez: Source : str of selection ## EXTERIOR CLASS BUILD #------------------------ import adb_utils.Script__WrapDeformer as adbWrap reload(adbWrap) #or from adb_utils.Script__WrapDeformer import wrapDeformer """ ## Define Variable type if isinstance(_HiRez, str) and isinstance(_LoRez, str): print('a') HiRez = _HiRez LoRez = _LoRez elif len(_HiRez) == 2: print('b') HiRez = _HiRez[0] LoRez = _LoRez[1] else: print('c') HiRez = _HiRez LoRez = _LoRez ## get Orig node orig_node = adb.getShapeOrig(LoRez) if orig_node == None: cls = pm.cluster(LoRez) pm.delete(cls) orig_node = adb.getShapeOrig(LoRez) # raise RuntimeError("No 'Orig' Node for: {}".format(LoRez)) ## Wrap Node creation pm.select(HiRez, r=True) pm.select(LoRez, add=True) wrapData = pm.deformer(HiRez, name='{}_{}'.format(HiRez, 'wrap'), type='wrap')[0] pm.PyNode(wrapData).maxDistance.set(1) pm.PyNode(wrapData).autoWeightThreshold.set(1) pm.PyNode(wrapData).exclusiveBind.set(0) pm.PyNode(wrapData).falloffMode.set(0) ## add custom attribute on LoRez mesh if adb.attrExist(LoRez, 'dropoff'): pass else: LoRez_node = adbAttr.NodeAttr([LoRez]) LoRez_node.addAttr('dropoff', 4) LoRez_node.addAttr('smoothness', 0) LoRez_node.addAttr('inflType', 2) ## Connections (pm.PyNode(LoRez).getShape() ).worldMesh[0] >> pm.PyNode(wrapData).driverPoints[0] (pm.PyNode(HiRez).getShape() ).worldMatrix[0] >> pm.PyNode(wrapData).geomMatrix pm.PyNode(LoRez).dropoff >> pm.PyNode(wrapData).dropoff[0] pm.PyNode(LoRez).inflType >> pm.PyNode(wrapData).inflType[0] pm.PyNode(LoRez).smoothness >> pm.PyNode(wrapData).smoothness[0] pm.PyNode(orig_node).worldMesh[0] >> pm.PyNode(wrapData).basePoints[0] ## Clean Up) pm.PyNode(LoRez).v.set(0) sys.stdout.write('custom wrap deformer created \n') return wrapData # wrapDeformer()
import pymel.core as pm import os MAYA_APP_DIR = mel.eval('getenv ("MAYA_APP_DIR")') pluginName = "dsAttractDeformer" pm.newFile(f=1) try: pm.unloadPlugin(pluginName) except: pass pm.loadPlugin( os.path.join( MAYA_APP_DIR, "scripts\dsNodes\dsAttractDeformer\plugins\{0}.py".format(pluginName))) pm.openFile(os.path.join( MAYA_APP_DIR, "scripts\dsNodes\dsAttractDeformer\\tests\\dsAttractDeformerTest.ma"), f=1) #### TEST #### dsAttractDeformer = pm.deformer("pTorus1", typ="dsAttract")[0] pm.connectAttr("sticky_CRVShape.local", dsAttractDeformer + ".inputShape") pm.connectAttr("sticky_CRV.worldMatrix[0]", dsAttractDeformer + ".inputMatrix")