Example #1
0
def doritosMagic(mesh, joint, jointBase, parent=None):
    # magic of doritos connection
    skinCluster = skin.getSkinCluster(mesh)
    if not skinCluster:
        if pm.objExists('static_jnt') is not True:
            static_jnt = primitive.addJoint(parent,
                                            "static_jnt",
                                            m=datatypes.Matrix(),
                                            vis=True)
        static_jnt = pm.PyNode("static_jnt")

        # apply initial skincluster
        skinCluster = pm.skinCluster(static_jnt,
                                     mesh,
                                     tsb=True,
                                     nw=2,
                                     n='%s_skinCluster' % mesh.name())
    try:
        # we try to add the joint to the skin cluster. Will fail if is already
        # in the skin cluster
        pm.skinCluster(skinCluster, e=True, ai=joint, lw=True, wt=0)
    except Exception:
        pm.displayInfo("The Joint: %s  is already in the %s." %
                       (joint.name(), skinCluster.name()))
        pass
    cn = joint.listConnections(p=True, type="skinCluster")
    for x in cn:
        if x.type() == "matrix":
            if x.name().split(".")[0] == skinCluster.name():
                # We force to avoid errors in case the joint is already
                # connected
                pm.connectAttr(jointBase + ".worldInverseMatrix[0]",
                               skinCluster + ".bindPreMatrix[" +
                               str(x.index()) + "]",
                               f=True)
Example #2
0
    def build(self, no_subdiv=False, num_ctrl=None, degree=3, create_ctrl=True, constraint=False, rot_fol=True, *args,
              **kwargs):
        super(Ribbon, self).build(create_grp_anm=create_ctrl, *args, **kwargs)
        if num_ctrl is not None:
            self.num_ctrl = num_ctrl

        nomenclature_rig = self.get_nomenclature_rig()

        # Create the plane and align it with the selected bones
        plane_tran = next(
            (input for input in self.input if libPymel.isinstance_of_shape(input, pymel.nodetypes.NurbsSurface)), None)
        if plane_tran is None:
            plane_name = nomenclature_rig.resolve("ribbonPlane")
            if no_subdiv:  # We don't want any subdivision in the plane, so use only 2 bones to create it
                no_subdiv_degree = 2
                if degree < 2:
                    no_subdiv_degree = degree
                plane_tran = libRigging.create_nurbs_plane_from_joints([self.chain_jnt[0], self.chain_jnt[-1]],
                                                                       degree=no_subdiv_degree, width=self.width)
            else:
                plane_tran = libRigging.create_nurbs_plane_from_joints(self.chain_jnt, degree=degree, width=self.width)
            plane_tran.rename(plane_name)
            plane_tran.setParent(self.grp_rig)
        self._ribbon_shape = plane_tran.getShape()

        # Create the follicule needed for the system on the skinned bones
        self.attach_to_plane(rot_fol)
        # TODO : Support aim constraint for bones instead of follicle rotation?

        follicles_grp = pymel.createNode("transform")
        follicle_grp_name = nomenclature_rig.resolve("follicleGrp")
        follicles_grp.rename(follicle_grp_name)
        follicles_grp.setParent(self.grp_rig)
        for n in self._follicles:
            n.setParent(follicles_grp)

        # Create the joints that will drive the ribbon.
        # TODO: Support other shapes than straight lines...
        self._ribbon_jnts = libRigging.create_chain_between_objects(
            self.chain_jnt.start, self.chain_jnt.end, self.num_ctrl, parented=False)

        # Group all the joints
        ribbon_chain_grp_name = nomenclature_rig.resolve('ribbonChainGrp')
        self.ribbon_chain_grp = pymel.createNode('transform', name=ribbon_chain_grp_name, parent=self.grp_rig)
        align_chain = True if len(self.chain_jnt) == len(self._ribbon_jnts) else False
        for i, jnt in enumerate(self._ribbon_jnts):
            # Align the ribbon joints with the real joint to have a better rotation ctrl
            ribbon_jnt_name = nomenclature_rig.resolve('ribbonJnt{0:02d}'.format(i))
            jnt.rename(ribbon_jnt_name)
            jnt.setParent(self.ribbon_chain_grp)
            if align_chain:
                matrix = self.chain_jnt[i].getMatrix(worldSpace=True)
                jnt.setMatrix(matrix, worldSpace=True)

        # TODO - Improve skinning smoothing by setting manually the skin...
        pymel.skinCluster(list(self._ribbon_jnts), plane_tran, dr=1.0, mi=2.0, omi=True)
        try:
            libSkinning.assign_weights_from_segments(self._ribbon_shape, self._ribbon_jnts, dropoff=1.0)
        except ZeroDivisionError, e:
            pass
Example #3
0
def createIKSpline( jntList ):
    pymelLogger.debug('Starting: createIKSpline()...') 
    # Make IK Spline
    ikHandleTorso = pm.ikHandle( startJoint=jntList[0], endEffector=jntList[-1], solver = 'ikSplineSolver', numSpans = 4, name = jntList[-1]+'_'+Names.suffixes['ikhandle'])
    # we should probably rename the object created to know names ......    
    # CAREFULL // inherits Transform OFF, to avoid double transformation when grouped later on
    pm.setAttr(ikHandleTorso[2] + '.inheritsTransform', 0)
    
    # Duplicate last and first joint to use as Drivers of the spine Ik curve
    print jntList
    drvStart = pm.duplicate(jntList[0], parentOnly=True, name = Names.prefixes['driver']+'_'+ jntList[0] +'_'+Names.suffixes['start'])
    drvEnd = pm.duplicate(jntList[-1], parentOnly=True, name = Names.prefixes['driver']+'_'+ jntList[-1] +'_'+Names.suffixes['end'])
    pm.parent(drvEnd, w=1)
    
    # Make radius bigger
    pm.joint(drvStart, edit = True, radius = 1)
    pm.joint(drvEnd, edit = True, radius = 1)
    
    # Skin hip/shldr jnt's to back curve
    pm.skinCluster(drvStart,drvEnd,ikHandleTorso[2],dr=4)
    
    # return nedded elements
    rList = [ikHandleTorso, drvStart, drvEnd ]
    
    pymelLogger.debug('End: createIKSpline()...') 
    return rList
Example #4
0
def create_bind_proxy(jnt):
    if jnt.getChildren():
        name=jnt.name() + "_bindProxy"
         
        distance = jnt.getChildren()[0].translateX.get()
        if not pm.objExists(name):
            proxy = pm.polyCylinder(r=0.25, h=0.5, sx=12, sy=4, sz=4, ax=[1,0,0], rcp=1, cuv=0, ch=0, name=name)[0]
            pm.xform(proxy, piv=[-0.5, 0, 0])
             
            pm.parent(proxy, 'bind_proxy')
             
            pm.delete(pm.parentConstraint(jnt, proxy, mo=False))
            proxy.scale.set(distance, distance, distance)
             
            try:
                jnt.addAttr('iterations', at='long', min=1, max=5, dv=3, k=True)
                jnt.addAttr('bind_proxy', at='message')
            except:
                pass            
                 
        else:
            proxy = pm.PyNode(name)

        
        pm.skinCluster( jnt, proxy, tsb=True)
        proxy.message >> jnt.bind_proxy            
Example #5
0
	def spine_init ( self, size=5.0, limbName='spine', mode='biped', numOfJnts=4 , *args ):
		
		self.spine_initJnts=[]
		self.tmpCrv = None
		
		try:# if in UI mode, get number of joints from UI
			size = pm.floatSliderGrp( self.spineSizeF, q=True, value=True)
			limbName = pm.textField( self.limbNameTF, q=True, text=True)
			selectedMode = pm.radioCollection( self.characterModeRC, q=True, select=True)
			mode = pm.radioButton( selectedMode, q=True, label=True ).lower()
			numOfJnts = pm.intSliderGrp( self.numOfInitJntsIS, q=True, value=True)
		except:
			pass

		curveCVs=[]
		curveCVsCount=[]
		for i in range(numOfJnts):
			pm.select (clear=True)

			if mode=='biped':
				jntPos = ( 0, size+(size*1.0/(numOfJnts-1)*i), 0 )
			elif mode=='quadruped':
				jntPos = ( 0, size, (size*1.0/(numOfJnts-1)*i)-size/2.0 )
			else:
				pm.error('ehm_tools...Spine: mode arg accepts "biped" or "quadruped" only!')

			self.spine_initJnts.append(  pm.joint ( p = jntPos , name = "%s_%s_initJnt"%(limbName,i+1) )  )
			curveCVs.append( jntPos )
			curveCVsCount.append( i )

		self.tmpCrv = pm.curve( d=1, p=curveCVs , k=curveCVsCount )
		self.tmpCrv.getShape().template.set(True)
		pm.skinCluster( self.spine_initJnts,self.tmpCrv)	
    def skinSrf(self):
        self.createDrvJnt()

        skinCls = \
        pm.skinCluster(self.srf, self.drvJntList, tsb=1, ih=1, skinMethod=0, maximumInfluences=1, dropoffRate=10.0)[0]
        crvSkinCls = \
        pm.skinCluster(self.ikCrv, self.drvJntList, tsb=1, ih=1, skinMethod=0, maximumInfluences=1, dropoffRate=10.0)[0]
        for i in range(len(self.drvJntList)):
            if i == 0:
                pm.skinPercent(skinCls.name(),
                               self.srf.name() + '.cv[0:1][0:3]',
                               tv=[(self.drvJntList[i], 1)])
                pm.skinPercent(crvSkinCls.name(),
                               self.ikCrv.name() + '.cv[0:1]',
                               tv=[(self.drvJntList[i], 1)])
            elif i > 0 and i < self.numJnt - 1:
                pm.skinPercent(skinCls.name(),
                               self.srf.name() + '.cv[' + str(i + 1) +
                               '][0:3]',
                               tv=[(self.drvJntList[i], 1)])
                pm.skinPercent(crvSkinCls.name(),
                               self.ikCrv.name() + '.cv[' + str(i + 1) + ']',
                               tv=[(self.drvJntList[i], 1)])
            elif i == self.numJnt - 1:
                pm.skinPercent(skinCls.name(),
                               self.srf.name() + '.cv[' + str(i + 1) + ':' +
                               str(i + 2) + '][0:3]',
                               tv=[(self.drvJntList[i], 1)])
                pm.skinPercent(crvSkinCls.name(),
                               self.ikCrv.name() + '.cv[' + str(i + 1) + ':' +
                               str(i + 2) + ']',
                               tv=[(self.drvJntList[i], 1)])
Example #7
0
    def extras(self):
        """Add additional features or functionality"""
        self.wagonFront.ctrl.srt.paramU.set(24)
        self.wagonFrontMid.ctrl.srt.paramU.set(16.6)
        self.wagonMid.ctrl.srt.paramU.set(12)
        self.wagonBackMid.ctrl.srt.paramU.set(7.4)
        self.wagonBack.ctrl.srt.paramU.set(0)

        self.wagonFront.ctrl.srt.paramV.set(50)
        self.wagonFrontMid.ctrl.srt.paramV.set(50)
        self.wagonMid.ctrl.srt.paramV.set(50)
        self.wagonBackMid.ctrl.srt.paramV.set(50)
        self.wagonBack.ctrl.srt.paramV.set(50)

        # setup skinweights
        if not cmds.objExists('balgenSkincluster'):
            pm.skinCluster(self.back.jnt_base,
                           self.mid.jnt_base,
                           'Lint_41_Wagen1_Teile_Balgen',
                           tsb=True,
                           n='balgenSkincluster')
            pm.setAttr('Lint_41_Wagen1_Teile_Balgen.inheritsTransform', 0)
        if not cmds.objExists('balgenSkincluster2'):
            pm.skinCluster(self.mid.jnt_base,
                           self.front.jnt_base,
                           'Lint_41_Wagen1_Teile_Balgen_geo',
                           tsb=True,
                           n='balgenSkincluster2')
            pm.setAttr('Lint_41_Wagen1_Teile_Balgen_geo.inheritsTransform', 0)
Example #8
0
def GuideCrv ( startGuider=None , endGuider=None ):

	if startGuider==None or endGuider==None:
		startGuider,endGuider = pm.ls(sl=True)
	
	pm.select(clear=True)
	
	startJnt = pm.joint ( n = startGuider.name()+"_guideCrvJnt")
	pm.parent (startJnt , startGuider)
	startJnt.translate.set (0,0,0)
	startJnt.visibility.set (0)
	pm.setAttr ( startJnt.visibility , lock=True  )
	
	
	endJnt = pm.joint (  n = endGuider.name()+"_guideCrvJnt" )
	pm.parent (endJnt , endGuider)
	endJnt.translate.set (0,0,0)
	endJnt.visibility.set (0)
	pm.setAttr ( endJnt.visibility , lock=True  )
	
	startJntPos = pm.xform ( startJnt , q=True , ws=True , t=True)
	endJntPos = pm.xform ( endJnt , q=True , ws=True , t=True)
	
	guideCrv = pm.curve ( degree=1 , p = (startJntPos ,endJntPos) , k=(1,2)  )
	
	pm.rename ( guideCrv , startGuider.name()+"_guideCrv")
	
	pm.skinCluster ( guideCrv , startJnt , endJnt  )
	
	guideCrv.inheritsTransform.set(0)
	guideCrv.template.set(1)
	
	pm.select(clear=True)
	
	return guideCrv
Example #9
0
def GuideCrv(startGuider=None, endGuider=None):

    if startGuider == None or endGuider == None:
        startGuider, endGuider = pm.ls(sl=True)

    pm.select(clear=True)

    startJnt = pm.joint(n=startGuider.name() + "_guideCrvJnt")
    pm.parent(startJnt, startGuider)
    startJnt.translate.set(0, 0, 0)
    startJnt.visibility.set(0)
    pm.setAttr(startJnt.visibility, lock=True)

    endJnt = pm.joint(n=endGuider.name() + "_guideCrvJnt")
    pm.parent(endJnt, endGuider)
    endJnt.translate.set(0, 0, 0)
    endJnt.visibility.set(0)
    pm.setAttr(endJnt.visibility, lock=True)

    startJntPos = pm.xform(startJnt, q=True, ws=True, t=True)
    endJntPos = pm.xform(endJnt, q=True, ws=True, t=True)

    guideCrv = pm.curve(degree=1, p=(startJntPos, endJntPos), k=(1, 2))

    pm.rename(guideCrv, startGuider.name() + "_guideCrv")

    pm.skinCluster(guideCrv, startJnt, endJnt)

    guideCrv.inheritsTransform.set(0)
    guideCrv.template.set(1)

    pm.select(clear=True)

    return guideCrv
Example #10
0
def reset_skin(oColl):
    #TODO: Test and make sure oColl can be transforms or shapes.
    # first, check for shapes vs. transforms. Let the user pick any mix
    #gatherShapes = [x.getParent() for x in oColl if type(x) == pm.nodetypes.Mesh]
    #gatherTransforms = [x for x in oColl if type(x) == pm.nodetypes.Transform if x.getShape()]
    #firstFilter = gatherTransforms + gatherShapes
    #geoFilter = [x for x in firstFilter if type(x.getShape()) == pm.nodetypes.Mesh]

    oldSel = pm.selected()
    for eachGeo in oColl:
        skinInputs = eachGeo.getShape().listHistory(interestLevel=1,
                                                    type='skinCluster')
        # filters out the bug where if a geo has a lattice which is skinned,
        # you get the lattice influences back instead.
        correctSkins = [
            skin for skin in skinInputs if eachGeo.name() in
            [sk.getTransform().name() for sk in skin.getGeometry()]
        ]
        for oSkin in correctSkins:
            skinJointList = pm.listConnections(oSkin.matrix, t='joint')
            bindPose = pm.listConnections(skinJointList[0].name(),
                                          d=True,
                                          s=False,
                                          t='dagPose')
            if bindPose:
                if not (pm.referenceQuery(bindPose[0], inr=True)):
                    pm.delete(bindPose[0])
            sourceGeo = pm.skinCluster(oSkin, q=True, g=True)[0]
            pm.skinCluster(oSkin, e=True, ubk=True)
            pm.skinCluster(skinJointList, sourceGeo, ibp=True, tsb=True)
    pm.select(oldSel)
Example #11
0
def batchCovert():
	sels = pm.selected()
	if sels:
		for sel in sels:
			if sel.getShape().type() == 'mesh':
				originNode = sel
				originShapeNodes = originNode.getShapes()
				pm.select(cl=True)
				if originShapeNodes:
					originShapeNode = originShapeNodes[0]
					historyNodes = originShapeNode.listHistory()
					if historyNodes:
						influenceJoints = []
						for node in historyNodes:
							if node.type() == 'joint':
								influenceJoints.append(node)
						tempNode = pm.duplicate(originNode,name=originNode+'_temp')[0]
						pm.setAttr(tempNode+'.visibility',0)
						pm.select(influenceJoints,r=True)
						pm.select(tempNode,add=True)
						pm.skinCluster(name=tempNode.name()+'_skinCluster',toSelectedBones=True,maximumInfluences=5,dropoffRate=4)
						pm.copySkinWeights(originNode,tempNode,noMirror=True,surfaceAssociation='closestPoint',influenceAssociation='closestJoint',normalize=True)
						pm.deltaMushToSkinCluster(source=originShapeNode.name(),target=tempNode.getShape().name())
						pm.copySkinWeights(tempNode,originNode,noMirror=True,surfaceAssociation='closestPoint',influenceAssociation='closestJoint')
						pm.delete(tempNode)
	else:
		pm.displayWarning('Please select polygon object!')
Example #12
0
 def add_joint_to_skin(self, joint, skin):
     pm.skinCluster(skin,
                    edit=True,
                    addInfluence=joint,
                    weight=0,
                    lockWeights=True)
     pm.setAttr("%s.liw" % joint, False)
Example #13
0
def mirror_eyeCurve_weights():
    """
    mirror LT_eye_aimAt_crv_0 to RT_eye_aimAt_crv_0
    """
    lf_crv = nt.Transform(u"LT_eye_aimAt_crv_0")
    rt_crv = nt.Transform(u"RT_eye_aimAt_crv_0")
    lf_skn = pm.PyNode(mel.findRelatedSkinCluster(lf_crv))
    rt_skn = pm.PyNode(mel.findRelatedSkinCluster(rt_crv))

    def setEyeJointsLabels(joints):
        for jnt in joints:
            ### change the label

            label = "_".join(jnt.name().split("_")[1:3])
            # label = '_'.join(jnt.name().split('_')[1:4])
            jnt.attr("type").set("Other")
            jnt.otherType.set(label)

    lf_infs = pm.skinCluster(lf_crv, q=True, inf=True)
    setEyeJointsLabels(lf_infs)

    rt_infs = pm.skinCluster(rt_crv, q=True, inf=True)
    setEyeJointsLabels(rt_infs)

    lf_crv.sx.setLocked(False)
    lf_crv.sx.set(-1)

    pm.copySkinWeights(ss=lf_skn, ds=rt_skn, sa="closestPoint", ia="label", nm=True)

    lf_crv.sx.set(1)
def initCycleTweakBase(outMesh, baseMesh, rotMesh, transMesh, staticJnt=None):
    """Initialice the cycle tweak setup structure

    Args:
        outMesh (Mesh): The output mesh after the tweak deformation
        baseMesh (Mesh): The base mesh for the cycle tweak.
        rotMesh (Mesh): The mesh that will support the rotation
                transformations for the cycle tweak
        transMesh (Mesh): The mesh that will support the translation and
                scale transformations for the cycle tweak
        staticJnt (None or joint, optional): The static joint for the
                static vertex.
    """
    blendShapes.connectWithBlendshape(rotMesh, baseMesh)
    blendShapes.connectWithBlendshape(transMesh, rotMesh)
    blendShapes.connectWithBlendshape(outMesh, transMesh)

    # Init skinClusters
    pm.skinCluster(staticJnt,
                   rotMesh,
                   tsb=True,
                   nw=2,
                   n='%s_skinCluster' % rotMesh.name())
    pm.skinCluster(staticJnt,
                   transMesh,
                   tsb=True,
                   nw=2,
                   n='%s_skinCluster' % transMesh.name())
Example #15
0
def bind(skin_dict):
    unbind(skin_dict)
    for model,binds in skin_dict.iteritems():
        print model
        if RIGID in binds:
            for joint_,meshes in binds[RIGID].iteritems():
                joint_ = "%s%s" % (joint_,bind_post)
                meshes_named = []
                for mesh in meshes:
                    meshes_named.append("%s%s" % (model,mesh))
                try:
                    pm.bindSkin(joint_,meshes_named, toSelectedBones=True,
                            doNotDescend=True)
                except Exception as e:
                    print 'Rigid Bind:',e
                #print joint_, meshes_named
        if SMOOTH in binds:
            for mesh, joints in binds[SMOOTH].iteritems():
                #mesh = "%s%s" % (model,mesh)
                joints_named = []
                for joint_ in joints:
                    joints_named.append('%s%s' % (joint_,bind_post))
                try:
                    print 'mesh',mesh
                    #mesh = pm.select(mesh)
                    #print 'pmmesh',mesh
                    pm.skinCluster(
                            mesh,
                            joints_named,
                            toSelectedBones=True, 
                            #maximumInfluences=len(joints_named))
                            maximumInfluences=2,
                            frontOfChain=False)
                except Exception as e:
                    print 'Smooth Bind:',e
Example #16
0
def finalize_boxes():
    # collect weights
    boxes = collect_proxy_boxes()
    jnts = [box.getParent() for box in boxes]
    weights = []
    for i, box in enumerate(boxes):
        weights.extend([i] * len(box.vtx))

    # mergeboxes
    polyUnite = pymel.createNode('polyUnite')
    itt = 0
    for box in boxes:
        for shape in box.getShapes():
            pymel.connectAttr(shape.worldMatrix, polyUnite.inputMat[itt])
            pymel.connectAttr(shape.outMesh, polyUnite.inputPoly[itt])
            itt += 1
    outputMesh = pymel.createNode('mesh')
    pymel.connectAttr(polyUnite.output, outputMesh.inMesh)
    #pymel.delete(boxes)

    # set skin weights
    pymel.skinCluster(jnts, outputMesh.getParent(), toSelectedBones=True)
    skinCluster = next((hist for hist in outputMesh.listHistory() if isinstance(hist, pymel.nodetypes.SkinCluster)), None)
    for vtx, inf in zip(iter(outputMesh.vtx), weights):
        skinCluster.setWeights(vtx, [inf], [1])
Example #17
0
def wrap_createScalableWrap(driver, tgts, scale_obj, parent=None):
	'''Only used on skinned driver meshes, creates a wrap that scales
	Args:
		driver (pm.nt.Transform): wrap driver
		tgts ([pm.nt.Transform]): list of objects to wrap
		scale_obj (pm.nt.Transform): The object that it gets its scaling from
		parent (pm.nt.Transform): If not set, uses scaleParent as parent, otherwise
								  That's the new parent
	Returns ([pm.nt.wrap]): list of wrap deformers that were created
	Usage: 
		wrap_createScalableWrap(pm.ls(sl=True)[0],[pm.ls(sl=True)[1]], pm.PyNode('global_CTRL'))
	'''
	wrap = createWrap(driver, tgts, 0, 50, 2, True, True, 0)
	#Create the wrap scale group
	scaleGrp = 'wrapScale_GRP'
	if pm.objExists(scaleGrp):
		scaleGrp = pm.PyNode(scaleGrp)
	else:
		scaleGrp = pm.group(em=True, n=scaleGrp)
	#Create a scale joint for the base object
	scaleJnt = pm.joint(n=driver+'_WRAPSCALE_JNT')
	scaleJnt.setParent(scaleGrp)
	#skin it
	pm.skinCluster(scaleJnt, wrap['driver'][1], tsb=True, n=driver.name()+'wrap_SKINCLSTR')
	#parent the joint under the scale parent
	if parent:
		scaleGrp.setParent( parent )
	else:
		scaleGrp.setParent( scale_obj )
	#scale the transform of the targets
	for tgt in tgts:
		pm.scaleConstraint(scale_obj, tgt, mo=True)
	return wrap
Example #18
0
def sphere_generator(source_sphrs, source_verts, gen_bones, settings):
    spheres = []
    for i in range(len(source_sphrs)):
        sphere = source_sphrs[i]
        core_vert = source_verts[sphere.vertex]
        coords = [core_vert.x, core_vert.y, core_vert.z]

        poly_transform, poly_sphere = pm.polySphere(
            name="Sphere" + str(i),
            r=sphere.size * WORLD_SCALE,
            sx=settings.sphere_resolution,
            sy=settings.sphere_resolution)
        poly_transform.translate.set(coords)
        poly_transform.rotate.set([90, 0, 0])
        poly_shape = poly_transform.getShape()

        if settings.use_palette:
            sg = "paletteSG" + str(sphere.colour)
            pm.sets(sg, edit=True, forceElement=poly_transform)

        pm.polySoftEdge(a=180)
        if settings.use_rigging:
            pm.skinCluster(gen_bones[core_vert.bone], poly_shape, tsb=True)

        spheres.append(poly_shape)
    return spheres
Example #19
0
    def attachCurveToCtrls(self, num, mainAxis):
        """Excellent way to control a curve without
		the control objects floating away from the curve itself, 
		the way clustering CVs would. Create num amount of ctrls,
		evenly spaced along the curve, then JOINTS right on top of them.
		parentConstrain joints to ctrls, and SKIN curve to joints.
		TWISTING not included."""
        jnts = []
        for i in range(num):
            pmc.select(cl=True)
            ctrl = self.ctrls[i]
            jnt = pmc.joint(n=ctrl.name().replace(self.rigData["control"],
                                                  self.rigData["skinJoint"]))
            pmc.parentConstraint(ctrl, jnt, mo=False)
            # disconnect after constrain so that it is synchronized initially
            #pmc.Attribute(jnt+".rotate"+mainAxis).disconnect()
            jnts.append(jnt)

        jntGrp = pmc.group(jnts,
                           n=self.rigData["root"] +
                           self.rigData["skinJointGroup"])
        jntGrp.setParent(self.rigGrp)
        # skin curve to joints - how to do it so that
        # the influences are smooth and even?
        # iterate through every CV, weight based on distance
        # from joint? Just trust it works okay?
        pmc.skinCluster(jnts, self.curve, maximumInfluences=2)
Example #20
0
def make_joints_for_cards(cards=None, head_jnt=None, numCVs=5, w=2):
    """
    Create a joint chain at the averaged position of each ring for the given hair cards.
    This joint chain can then be driven by FK controls which can themselves blend into
    riding along an nHair via motionPath. 
    FOR NOW, JUST DO JOINTS << MAKE JOINTS DYNAMIC THOUGH. TO TEST HOW IT LOOKS.
    Maybe rotate since that goes better with FK controls which are probably better for hair.
    """
    if not cards:
        cards = pmc.selected()
        if not head_jnt:
            head_jnt = cards.pop()

    # max influences = 1, to only head_jnt (not children)
    merged_cards = pmc.polyUnite(cards, muv=True)[0]
    sc = pmc.skinCluster(head_jnt, merged_cards, mi=1, tsb=True)
    j = head_jnt
    pmc.select(cl=True)
    for n in range(numCVs):
        # starting point is length step by width steps, step is total verts per card
        if n:
            pmc.skinCluster(sc, e=True, addInfluence=j, wt=0)
        verts = [
            v for i in range(w)
            for v in merged_cards.vtx[n * w + i::numCVs * w]
        ]
        pmc.skinPercent(sc, verts, transformValue=(j, 1.0))
        avg_pos = sum(v.getPosition() for v in verts) / len(verts)
        j = pmc.joint(p=avg_pos, n="hairCurve{:02d}_bind".format(n + 1))
        j.radius.set(.05)

    # merging objects & skinclusters is be one easy step
    return merged_cards
    def removeUnusedInfluence(self, skinClusterNode):
        allInfs = pm.skinCluster(skinClusterNode, q=True, inf=True)
        goodInfs = pm.skinCluster(skinClusterNode, q=True, wi=True)
        badInfs = list(set(allInfs).difference(set(goodInfs)))
        if len(badInfs):
            pm.progressWindow(title='',
                              progress=0,
                              status='Remove Unused Influence...',
                              isInterruptable=True,
                              maxValue=len(badInfs))
            nodeState = skinClusterNode.nodeState.get()
            lockState = skinClusterNode.nodeState.get(lock=True)

            skinClusterNode.nodeState.set(1)
            skinClusterNode.nodeState.set(lock=False)

            amount = 0
            for badInf in badInfs:
                if pm.progressWindow(query=True, isCancelled=True):
                    break
                skinClusterNode.removeInfluence(badInf)
                amount += 1
                pm.progressWindow(e=True, progress=amount)
            pm.progressWindow(endProgress=1)
            skinClusterNode.nodeState.set(nodeState)
            skinClusterNode.nodeState.set(lock=lockState)
Example #22
0
    def checkTwoSkin(cls, skin_from, skin_to):

        """
        !@Brief Check two skin. If skin_to is different of skin_from delete it and apply new skin
        with same influences of skin_from.

        :type skin_from: pymel.core.nodetypes.SkinCluster
        :param skin_from: Skin reference for check
        :type skin_to: pymel.core.nodetypes.SkinCluster
        :param skin_to: Skin you want to check

        :rtype: pymel.core.nodetypes.SkinCluster
        :return: SkinCluster checked
        """

        #   Get influences
        influences_ref = pmc.skinCluster(skin_from, query=True, influence=True)
        influences_check = pmc.skinCluster(skin_to, query=True, influence=True)

        #   If is same return check skinCluster
        if influences_check == influences_ref:
            return skin_to

        #   If is not same apply new skin
        skin_check_geo = pmc.skinCluster(skin_to, query=True, geometry=True)
        pmc.delete(skin_to)

        for geo in skin_check_geo:
            skin_to = cls.skinFromOther(skin_from, geo)

        return skin_to
Example #23
0
def skinCopy(sourceMesh=None, targetMesh=None, *args):
    if not sourceMesh or not targetMesh:
        if len(pm.selected()) >=2:
            sourceMesh = pm.selected()[-1]
            targetMeshes = pm.selected()[:-1]
        else:
            pm.displayWarning("Please select target mesh/meshes and source mesh with skinCluster.")
            return
    else:
        targetMeshes = [targetMesh]

        #we check this here, because if not need to check when we work base on selection.
        if isinstance(sourceMesh, basestring):
            sourceMesh = pm.PyNode(sourceMesh)

    for targetMesh in targetMeshes:
        if  isinstance(targetMesh, basestring):
            sourceMesh = pm.PyNode(targetMesh)

        ss = getSkinCluster(sourceMesh)

        if ss:
            oDef = pm.skinCluster(sourceMesh, query=True, influence=True)
            skinCluster = pm.skinCluster(oDef, targetMesh, tsb=True, nw=2, n=targetMesh.name() + "_SkinCluster")
            pm.copySkinWeights( ss=ss.stripNamespace(), ds=skinCluster.name(), noMirror=True, ia="oneToOne", sm=True, nr=True)
        else:
            pm.displayError("Source Mesh :" + sourceMesh.name() + " Don't have skinCluster")
	def attachCurveToCtrls(self, num, mainAxis):
		"""Excellent way to control a curve without
		the control objects floating away from the curve itself, 
		the way clustering CVs would. Create num amount of ctrls,
		evenly spaced along the curve, then JOINTS right on top of them.
		parentConstrain joints to ctrls, and SKIN curve to joints.
		TWISTING not included."""
		jnts = []
		for i in range(num):
			pmc.select(cl=True)
			ctrl = self.ctrls[i]
			jnt = pmc.joint(n=ctrl.name().replace(self.rigData["control"],
												self.rigData["skinJoint"]))
			pmc.parentConstraint(ctrl, jnt, mo=False)
			# disconnect after constrain so that it is synchronized initially
			#pmc.Attribute(jnt+".rotate"+mainAxis).disconnect()
			jnts.append(jnt)

		jntGrp = pmc.group(jnts, 
					n=self.rigData["root"]+self.rigData["skinJointGroup"])
		jntGrp.setParent(self.rigGrp)
		# skin curve to joints - how to do it so that
		# the influences are smooth and even?
		# iterate through every CV, weight based on distance
		# from joint? Just trust it works okay?
		pmc.skinCluster(jnts, self.curve, maximumInfluences=2)
Example #25
0
def mirror_eyeCurve_weights():
    '''
    mirror LT_eye_aimAt_crv_0 to RT_eye_aimAt_crv_0
    '''
    lf_crv = nt.Transform(u'LT_eye_aimAt_crv_0')
    rt_crv = nt.Transform(u'RT_eye_aimAt_crv_0')
    lf_skn = pm.PyNode(mel.findRelatedSkinCluster(lf_crv))
    rt_skn = pm.PyNode(mel.findRelatedSkinCluster(rt_crv))

    def setEyeJointsLabels(joints):
        for jnt in joints:
            ### change the label

            label = '_'.join(jnt.name().split('_')[1:3])
            #label = '_'.join(jnt.name().split('_')[1:4])
            jnt.attr('type').set('Other')
            jnt.otherType.set(label)

    lf_infs = pm.skinCluster(lf_crv, q=True, inf=True)
    setEyeJointsLabels(lf_infs)

    rt_infs = pm.skinCluster(rt_crv, q=True, inf=True)
    setEyeJointsLabels(rt_infs)

    lf_crv.sx.setLocked(False)
    lf_crv.sx.set(-1)

    pm.copySkinWeights(ss=lf_skn,
                       ds=rt_skn,
                       sa='closestPoint',
                       ia='label',
                       nm=True)

    lf_crv.sx.set(1)
Example #26
0
def copyBind(source, destination, sa='closestPoint', ia='closestJoint'):
    """
    Bind and Copy skincluster to destination GEO
    :param source: mesh str
    :param destination: mesh str
    :return: 
    """
    # Get Shape and skin from Object
    skinCluster = findRelatedSkinCluster(source)
    if skinCluster:
        skin = skinCluster
    else:
        print 'Missing source SkinCluster'

    # Get joint influence of the skin
    influnces = skin.getInfluence(q=True)  # influences is joint

    # Bind destination Mesh
    # pm.select(influnces[0])
    # pm.select(destination, add=True)
    # mel.eval('SmoothBindSkin;')
    pm.skinCluster(influnces[0], destination, dr=4.0)

    # copy skin wheights form source
    pm.select(source)
    pm.select(destination, add=True)
    pm.copySkinWeights(noMirror=True, surfaceAssociation=sa, influenceAssociation=ia)
    pm.select(cl=True)
Example #27
0
def bindCurve(crv=None):
    '''
    Creates a joint for each cv in the supplied or selected curve
    performs a smooth bind on the curve to the joints
    returns a list of the newly created joints

    '''
    # Validation of args
    if not crv:
        if len(pmc.selected()) == 1:
            crv = pmc.selected()[0]
        else:
            return 'bindCurve: Please supply or select a nurbs curve'

    jointList = []

    cvs = crv.getCVs(space='world')

    for cv in range(len(cvs)):
        pmc.select(None)
        j = pmc.joint(p=cvs[cv], name='%s_%s_JNT' % (crv, cv + 1))
        jointList.append(j)

    pmc.skinCluster(jointList, crv, tsb=1, name='%s_SKN' % crv)

    return jointList
Example #28
0
    def unbind(self, meshes=None, bind_pose=True):
        """
        Unbinds the skin clusters from the given meshes (will use selection or all meshes in scene if None).
        Stores skin cluster weights in a temp file to be rebound with the rebind method.

        Args:
            meshes (list): Meshes to unbind.

            bind_pose (boolean): If True will move joints back to the bind pose before unbinding.

        Returns:
            (dictionary): All the info gathered  from unbinding joints.
        """
        # reset info
        self.info = {}
        scene_path = pm.sceneName()
        scene_name = os.path.splitext(
            scene_path.name)[0] + '_' if scene_path else ''
        meshes = myu.validateSelect(meshes, find='mesh', parent=True)
        pcu.validateDirectory(self.directory)

        for mesh in meshes:
            # get the skin of the mesh, if it doesnt exist then we don't need to store skin weights
            mesh_name = mesh.nodeName()
            skin = mesh.listHistory(type='skinCluster')

            if not skin:
                continue

            # get the info we need to rebind the mesh: skin name, max influences, and joints influencing mesh
            # stored as string in case object gets deleted and renamed after unbinding
            skin = skin[0].nodeName()
            max_influences = pm.skinCluster(mesh, q=True, mi=True)
            joints = [
                joint.nodeName()
                for joint in pm.skinCluster(skin, q=True, influence=True)
            ]

            if bind_pose:
                returnToBindPose(joints)

            # select mesh, export skin weights, and detach skin using MEL because pm.bindSkin(delete=True) has errors.
            pm.select(mesh)
            deformer_name = scene_name + mesh_name + '.xml'
            path = pm.deformerWeights(deformer_name,
                                      export=True,
                                      deformer=skin,
                                      path=self.directory)
            pm.mel.eval('doDetachSkin "2" { "1","1" }')

            self.info[mesh_name] = {
                'skin': skin,
                'max_influences': max_influences,
                'joints': joints,
                'path': path
            }

        pm.select(meshes)
        return self.info
Example #29
0
def applySkin(ns_prefix, skindata_path):
    mesh_name = '{}Geo:Mesh'.format(ns_prefix)

    # Bind skin
    pm.skinCluster('Root_M', mesh_name, skinMethod=1)

    # Load weights
    applyNgSkin(skindata_path, pm.ls(mesh_name)[0])
Example #30
0
    def build(self, no_subdiv=False, num_ctrl = None, degree=3, create_ctrl=True, constraint=False, rot_fol=True, *args, **kwargs):
        super(Ribbon, self).build(create_grp_anm=create_ctrl, *args, **kwargs)
        if num_ctrl is not None:
            self.num_ctrl = num_ctrl

        nomenclature_rig = self.get_nomenclature_rig()

        # Create the plane and align it with the selected bones
        plane_tran = next((input for input in self.input if libPymel.isinstance_of_shape(input, pymel.nodetypes.NurbsSurface)), None)
        if plane_tran is None:
            plane_name = nomenclature_rig.resolve("ribbonPlane")
            if no_subdiv:  # We don't want any subdivision in the plane, so use only 2 bones to create it
                no_subdiv_degree = 2
                if degree < 2:
                    no_subdiv_degree = degree
                plane_tran = libRigging.create_nurbs_plane_from_joints([self.chain_jnt[0], self.chain_jnt[-1]],
                                                                       degree=no_subdiv_degree, width=self.width)
            else:
                plane_tran = libRigging.create_nurbs_plane_from_joints(self.chain_jnt, degree=degree, width=self.width)
            plane_tran.rename(plane_name)
            plane_tran.setParent(self.grp_rig)
        self._ribbon_shape = plane_tran.getShape()

        # Create the follicule needed for the system on the skinned bones
        self.attach_to_plane(rot_fol)
        # TODO : Support aim constraint for bones instead of follicle rotation?

        follicles_grp = pymel.createNode("transform")
        follicle_grp_name = nomenclature_rig.resolve("follicleGrp")
        follicles_grp.rename(follicle_grp_name)
        follicles_grp.setParent(self.grp_rig)
        for n in self._follicles:
            n.setParent(follicles_grp)

        # Create the joints that will drive the ribbon.
        # TODO: Support other shapes than straight lines...
        self._ribbon_jnts = libRigging.create_chain_between_objects(
            self.chain_jnt.start, self.chain_jnt.end, self.num_ctrl, parented=False)

        # Group all the joints
        ribbon_chain_grp_name = nomenclature_rig.resolve('ribbonChainGrp')
        self.ribbon_chain_grp = pymel.createNode('transform', name=ribbon_chain_grp_name, parent=self.grp_rig)
        align_chain = True if len(self.chain_jnt) == len(self._ribbon_jnts) else False
        for i, jnt in enumerate(self._ribbon_jnts):
            # Align the ribbon joints with the real joint to have a better rotation ctrl
            ribbon_jnt_name = nomenclature_rig.resolve('ribbonJnt{0:02d}'.format(i))
            jnt.rename(ribbon_jnt_name)
            jnt.setParent(self.ribbon_chain_grp)
            if align_chain:
                matrix = self.chain_jnt[i].getMatrix(worldSpace=True)
                jnt.setMatrix(matrix, worldSpace=True)

        # TODO - Improve skinning smoothing by setting manually the skin...
        pymel.skinCluster(list(self._ribbon_jnts), plane_tran, dr=1.0, mi=2.0, omi=True)
        try:
            libSkinning.assign_weights_from_segments(self._ribbon_shape, self._ribbon_jnts, dropoff=1.0)
        except ZeroDivisionError, e:
            pass
Example #31
0
def ResetSkin(_oObj):
    oSkinCluster = GetSkinCluster(_oObj)
    if oSkinCluster == None:
        pm.warning("Can't find skinCluster in {0}".format(_oObj))
    else:
        aJoints = oSkinCluster.influenceObjects()
        pm.delete(pm.ls('bindPose*'))
        pm.skinCluster(oSkinCluster, edit=True, unbindKeepHistory=True)
        pm.skinCluster(aJoints, _oObj, toSelectedBones=True)
Example #32
0
    def splineIK_controls(self, *args):
        """ Build splineIK Controls
        Args:
            None
        Returns (None)
        """
        jnt_prefix = self.jntNameFeild.getText()
        midJnt = self.model.numCVs / 2
        
        #Create and place joints
        baseJoint = pm.joint( p = self.model.crvCVs[0].getPosition(), n = self.jntNameFeild.getText() + '_base_JNT')
        pm.select(clear = True)
        midJoint = pm.joint( p = self.model.crvCVs[midJnt].getPosition(), n = self.jntNameFeild.getText() + '_mid_JNT')
        pm.select(clear = True)
        endJoint = pm.joint( p = self.model.crvCVs[-1].getPosition(), n = self.jntNameFeild.getText() + '_end_JNT')
        pm.select(clear = True)                                              

        #Create CTRL curves
        pm.circle(c = (0, 0, 0), nr = (0, 1, 0), sw = 360, r = 1, d = 3, ut = False, tol = 3.80125e-10, s = 8, ch = False, n = self.jntNameFeild.getText() + '_base_CTRL')
        pm.select(self.jntNameFeild.getText() + '_base_CTRL', r=True)
        pm.select(self.jntNameFeild.getText() + '_base_JNT', add=True)
        nPos.set_newPosition()
        pm.select(self.jntNameFeild.getText() + '_base_CTRL', r=True)
        offSetGRP.add_offset_grps()
        conGRP.add_con_grps()
        pm.select(clear = True)
        
        pm.circle(c = (0, 0, 0), nr = (0, 1, 0), sw = 360, r = 1, d = 3, ut = False, tol = 3.80125e-10, s = 8, ch = False, n = self.jntNameFeild.getText() + '_mid_CTRL')
        pm.select(self.jntNameFeild.getText() + '_mid_CTRL', r=True)
        pm.select(self.jntNameFeild.getText() + '_mid_JNT', add=True)
        nPos.set_newPosition()
        pm.select(self.jntNameFeild.getText() + '_mid_CTRL', r=True)
        offSetGRP.add_offset_grps()
        conGRP.add_con_grps()
        pm.select(clear = True)
        
        pm.circle(c = (0, 0, 0), nr = (0, 1, 0), sw = 360, r = 1, d = 3, ut = False, tol = 3.80125e-10, s = 8, ch = False, n = self.jntNameFeild.getText() + '_end_CTRL')
        pm.select(self.jntNameFeild.getText() + '_end_CTRL', r=True)
        pm.select(self.jntNameFeild.getText() + '_end_JNT', add=True)
        nPos.set_newPosition()
        pm.select(self.jntNameFeild.getText() + '_end_CTRL', r=True)
        offSetGRP.add_offset_grps()
        conGRP.add_con_grps()
        pm.select(clear = True)
        
        #Skin jnt's to crv
        pm.select(self.jntNameFeild.getText() + '_base_JNT', r=True)
        pm.select(self.jntNameFeild.getText() + '_mid_JNT', add=True) 
        pm.select(self.jntNameFeild.getText() + '_end_JNT', add=True)       
        pm.select(self.jntNameFeild.getText() + '_CRV', add=True) 
        pm.skinCluster(n=self.jntNameFeild.getText() + '_smoothSkin', mi=3, sm=0, nw=2)

        #Constrain joints to ctrl grps
        pm.parentConstraint( self.jntNameFeild.getText() + '_base_CTRLCon_GRP', self.jntNameFeild.getText() + '_base_JNT')
        pm.parentConstraint( self.jntNameFeild.getText() + '_mid_CTRLCon_GRP', self.jntNameFeild.getText() + '_mid_JNT')
        pm.parentConstraint( self.jntNameFeild.getText() + '_end_CTRLCon_GRP', self.jntNameFeild.getText() + '_end_JNT')
        pm.select(clear = True)
Example #33
0
def addMissingJoints(obj, joints):
    '''
    Adds the given joints to the mesh if they aren't already influencing without affecting the current skinning.
    '''
    boundJoints = skinCluster(obj, q=True, inf=True)

    missing = [PyNode(j) for j in joints if j not in boundJoints]

    skinCluster(obj, e=True, addInfluence=missing, weight=0)
Example #34
0
def create_bind_proxy(jnt):
    if jnt.getChildren():
        name=jnt.name() + "_bindProxy"
         
        distance = jnt.getChildren()[0].translateX.get()
        if not pm.objExists(name):
            proxy = pm.polyCylinder(r=0.25, h=0.5, sx=12, sy=4, sz=4, ax=[1,0,0], rcp=1, cuv=0, ch=0, name=name)[0]
            pm.xform(proxy, piv=[-0.5, 0, 0])
             
            pm.parent(proxy, 'bind_proxy')
             
            pm.delete(pm.parentConstraint(jnt, proxy, mo=False))
            proxy.scale.set(distance, distance, distance)
             
            try:
                jnt.addAttr('iterations', at='long', min=1, max=5, dv=3, k=True)
                jnt.addAttr('bind_proxy', at='message')
            except:
                pass            
                 
        else:
            proxy = pm.PyNode(name)

        
        pm.skinCluster( jnt, proxy, tsb=True)
        proxy.message >> jnt.bind_proxy           
#===============================================================================
#     if not joint.getChildren(): #not end joints
#         return
# 
#     if not joint.hasAttr('bind_proxy'): 
#         joint.addAttr('bind_proxy', at='message')
#     
#     name = joint.name() + "_bindProxy"
#      
#     distance = joint.getChildren()[0].translateX.get()
#     if not pm.objExists(name):
#         proxy = pm.polyCylinder(r=0.25, h=0.5, sx=12, sy=4, sz=4, ax=[1,0,0], rcp=1, cuv=0, ch=0, name=name)[0]
#         pm.xform(proxy, piv=[-0.5, 0, 0])
#          
#         pm.delete(pm.parentConstraint(joint, proxy, mo=False))
#         proxy.scale.set(distance, distance, distance)
#         
#     else:
#         proxy = pm.PyNode(name)
#          
#     pm.skinCluster( joint, proxy, tsb=True)
#     
#     proxy.sy.setLocked(False)
#     proxy.sy.set_nonKeyable(True)
#     proxy.sz.setLocked(False)
#     proxy.sz.set_nonKeyable(True)
#     
#     proxy.message >> joint.bind_proxy
#         
#===============================================================================
    return proxy    
Example #35
0
 def addInfluence(self, influence):
     ''' Adds an influence to a skin cluster
     Args:
         influence (pm.nt.Joint): influence to be added to skinCluster
     Returns:
         (boolean): True if success
     '''
     pm.skinCluster(self.skinCluster, edit=True,  ug=True, dr=4, ps=0, ns=10, lw=True, wt=0, ai=influence)
     return True
Example #36
0
    def build(self, rig, num_subdiv = 5, num_ctrl = None, degree=1, create_ctrl=True, constraint=False, rot_fol=False, *args, **kwargs):
        super(Ribbon, self).build(rig, create_grp_anm=create_ctrl, *args, **kwargs)
        if num_ctrl is not None:
            self.num_ctrl = num_ctrl

        nomenclature_anm = self.get_nomenclature_anm(rig)
        nomenclature_rig = self.get_nomenclature_rig(rig)

        #Create the plane and align it with the selected bones
        plane_tran = next((input for input in self.input if libPymel.isinstance_of_shape(input, pymel.nodetypes.NurbsSurface)), None)
        if plane_tran is None:
            plane_name = nomenclature_rig.resolve("ribbonPlane")
            plane_tran = libRigging.create_nurbs_plane_from_joints(self.chain_jnt, degree=degree, width=self.width)
            plane_tran.rename(plane_name)
            plane_tran.setParent(self.grp_rig)
        self._ribbon_shape = plane_tran.getShape()

        # TODO: Remove usage of djRivet
        #Create the follicule needed for the system on the skinned bones
        for i, jnt in enumerate(self.chain_jnt):
            pymel.select(jnt, plane_tran)
            mel.eval("djRivet")
            #TODO : Support aim constraint for bones instead of follicle rotation?

        # Apply the skin on the plane and rename follicle from djRivet
        dj_rivet_grp = pymel.PyNode("djRivetX")
        follicle_grp_name = nomenclature_rig.resolve("follicle_grp")
        dj_rivet_grp.rename(follicle_grp_name)
        dj_rivet_grp.setParent(self.grp_rig)
        self._follicles = dj_rivet_grp.getChildren()
        for n in self._follicles:
            fol_name = nomenclature_rig.resolve("fol")
            n.rename(fol_name)

        # Create the joints that will drive the ribbon.
        # TODO: Support other shapes than straight lines...
        # TODO: Support ctrl hold/fetch when building/unbuilding.
        self._ribbon_jnts = libRigging.create_chain_between_objects(
            self.chain_jnt.start, self.chain_jnt.end, self.num_ctrl, parented=False)

        # Group all the joints
        ribbon_chain_grp_name = nomenclature_rig.resolve('ribbonChain' + "_grp")
        ribbon_chain_grp = pymel.createNode('transform', name=ribbon_chain_grp_name, parent=self.grp_rig)
        align_chain = True if len(self.chain_jnt) == len(self._ribbon_jnts) else False
        for i, jnt in enumerate(self._ribbon_jnts):
            #Align the ribbon joints with the real joint to have a better rotation ctrl
            if align_chain:
                matrix = self.chain_jnt[i].getMatrix(worldSpace=True)
                jnt.setMatrix(matrix, worldSpace=True)
            jnt.setParent(ribbon_chain_grp)

        #TODO - Improve skinning smoothing by setting manully the skin...
        pymel.skinCluster(list(self._ribbon_jnts), plane_tran, dr=1.0, mi=2.0, omi=True)
        try:
            libSkinning.assign_weights_from_segments(self._ribbon_shape, self._ribbon_jnts, dropoff=1.0)
        except ZeroDivisionError, e:
            pass
 def bindToMesh(self, *args):
     mesh = pm.textField(self.loadCurves2, q = True, text = True)
     jntLst = facialAnimations.allJoints
     print jntLst
     pm.select(pm.ls(sl = True))
     pm.select(jntLst, add = True)
     pm.select(mesh, add = True)
     #pm.bindSkin(mesh, jntLst)
     pm.skinCluster()    
Example #38
0
    def transfer_deformer_weights(self, geo_source, geo_target=None, deformer_source=None, deformer_target=None,
                                  surface_association="closestPoint"):
        """
        Copies the weight map of a deformer of an object to the deformer of another object.
        :param geo_source: Source Shape
        :param geo_target: Target Shape
        :param deformer_source: Source Deformer
        :param deformer_target: Target Deformer
        :param surface_association: Surface Association. Valid values: closestPoint, rayCast, or closestComponent.
        """
        assert geo_source and deformer_source and deformer_target, \
            "select a source and target geometry and then the source and target deformers"

        previous_selection = pm.selected()

        if not geo_target:
            geo_target = geo_source

        self.progress_bar_init()
        self.progress_bar_next()

        deformer_source_weights = deformer_source.weightList[0].weights.get()

        self.progress_bar_next()
        tmp_source = pm.duplicate(geo_source)[0]
        tmp_target = pm.duplicate(geo_target)[0]
        tmp_source.v.set(True)
        tmp_target.v.set(True)

        self.progress_bar_next()
        pm.select(clear=True)
        l_jnt = list()
        l_jnt.append(pm.joint(n="jnt_tmpA_01", p=[0, 0, 0]))
        l_jnt.append(pm.joint(n="jnt_tmpA_02", p=[0, 1, 0]))
        skin_source = pm.skinCluster(l_jnt, tmp_source, nw=1)
        skin_target = pm.skinCluster(l_jnt, tmp_target, nw=1)

        self.progress_bar_next()
        skin_source.setNormalizeWeights(0)
        pm.skinPercent(skin_source, tmp_source, nrm=False, prw=100)
        skin_source.setNormalizeWeights(True)
        [pm.setAttr('{}.wl[{}].w[{}]'.format(skin_source, i, 0), value) for i, value in enumerate(deformer_source_weights)]
        [pm.setAttr('{}.wl[{}].w[{}]'.format(skin_source, i, 1), 1.0 - value) for i, value in enumerate(deformer_source_weights)]

        self.progress_bar_next()
        pm.copySkinWeights(ss=skin_source, ds=skin_target, nm=True, sa=surface_association)

        self.progress_bar_next()
        deformer_target_weights = [v for v in skin_target.getWeights(tmp_target, 0)]
        [deformer_target.weightList[0].weights[i].set(val) for i, val in enumerate(deformer_target_weights)]

        self.progress_bar_next()
        pm.delete([tmp_source, tmp_target, l_jnt])
        pm.select(previous_selection)

        self.progress_bar_next()
        self.progress_bar_ends(message="Finished successfully!")
Example #39
0
    def addShadowPlane(self):
        print 'Creating the shadow plane'
        shadowPlane = pm.polyPlane(n='shadowPlane',
                                   w=10,
                                   h=10,
                                   sx=1,
                                   sy=1,
                                   ax=(0, 1, 0),
                                   cuv=2,
                                   ch=0)
        shadowJoint = pm.joint(n='shadowJoint')
        pm.skinCluster(shadowJoint, shadowPlane)

        root = pm.ls("Root", type='joint')[0]
        pm.parent(shadowJoint, root)

        # rig the plane
        hips = pm.ls("Hips", type='joint')[0]
        leftFoot = pm.ls("LeftFoot", type='joint')[0]
        rightFoot = pm.ls("RightFoot", type='joint')[0]

        pm.pointConstraint(hips, shadowJoint, mo=0, skip='y')
        pm.pointConstraint(leftFoot, shadowJoint, mo=0, skip='y')
        pm.pointConstraint(rightFoot, shadowJoint, mo=0, skip='y')

        # default T pose Y value for the hips will be stored as reference
        # pm.addAttr(hips, ln = 'startY',t = 'double')
        hipsY = hips.getTranslation(space='world').y
        # pm.setAttr(hips.name() + '.startY',hipsY)

        shadowPlaneRV = pm.createNode('remapValue', n='shadowPlane_RV')
        shadowPlaneRV.imx.set(hipsY * 2.0)
        shadowPlaneRV.outputMin.set(2.0)
        shadowPlaneRV.outputMax.set(0)

        hips.translateY.connect(shadowPlaneRV.inputValue)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleX)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleY)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleZ)

        shadowPlaneCgfx = self.importCgfxShader()
        shadowPlaneCgfx.rename('shadowPlane_cgfx')
        shadowPlaneSg = pm.listConnections('%s.outColor' % shadowPlaneCgfx)[0]
        shadowPlaneSg.rename('shadowPlane_cgfxSG')

        shadowPlaneTxt = pm.shadingNode('file',
                                        asTexture=1,
                                        name='shadowPlane_file')

        shadowPlaneTxt.fileTextureName.set(
            'sourceimages\\groundshadow_diffusecolor.tga')
        shadowPlaneTxt.outColor.connect(shadowPlaneCgfx.diffuseMapSampler)

        pm.select(shadowPlane)
        pm.mel.eval('sets -e -forceElement ' + shadowPlaneSg)

        print 'Shadow plane created!!'
Example #40
0
def assignWeight(geo, wdata, skinc=None, jnt=None, pos=None):

    comp = "vtx"
    if geo.type() == "nurbsCurve":
        comp = "cv"
    mesh = None
    if pm.PyNode(geo).type() != "transform":
        mesh = geo
        geo = geo.getParent()

    #TODO: find center of wlist
    if not pos:
        pos = [0, 0, 0]

    if not jnt:
        print " Z"
        pm.select(cl=1)
        jnt = pm.joint(p=pos)
        jnt_grp = pm.group(jnt, em=1, n=str(jnt) + "_grp")
        jnt_grp.setTranslation(pos)
        jnt.setParent(jnt_grp)
    if not skinc:
        print " Y"

        skinc = getSkinc(geo)
    if not skinc:
        print " X"

        # insert base jnt
        pm.select(cl=1)
        basejnt = pm.joint(n=(str(geo) + "_baseJnt"))
        # check cons TODO: reconnect all constraint types
        ls_constrs = pm.parentConstraint(geo, q=1, n=1)
        if ls_constrs:
            transfer_constraint(geo, basejnt)
        skinc = pm.skinCluster(geo, basejnt)
        print "  New skincluster: {0}".format(skinc)

    print "_:", geo, skinc
    # add infl
    pm.skinCluster(skinc, e=1, ai=jnt, lw=1, wt=0)
    print "_:", jnt
    #########
    """
    for v, w in vtxs_data1.items():
        print "__:", v, w
        pm.skinPercent(snc, v, tv=[str(jnt), w])
    """
    for i, w in wdata.items():
        #print "__:", i, w
        print i, w
        pm.skinPercent(skinc, geo.__getattr__(comp)[i], tv=[str(jnt), w])

    return jnt
Example #41
0
def jntChainToPoly( JntRoots, ch=False, smoothBind=True ):
    '''
    조인트 체인들에 메쉬를 붙여줌.
    C:/Program Files/Autodesk/MayaBonusTools2013/scripts/bt_makeJointsDynamicUI.mel 참고할것
    '''
    curveList = []
    for root in JntRoots:
        root  = pm.PyNode(root)
        chain = root.getChildren( allDescendents=True, type='joint' )
        chain.reverse()
        chain.insert(0,root)
        curveList.append( jntToCrv( chain, degree=1, ep=False) )

    loftedSurface, loft = pm.loft( curveList, ch=1, u=1, c=0, ar=1, d=1, ss=1, rn=0, po=1, rsn=True )
    nurbsTessellate = pm.PyNode( loft.outputSurface.outputs()[0] )

    nurbsTessellate.polygonType.set(1)   # 0.Triangle, 1.Quads
    nurbsTessellate.setAttr('format', 2) # 0.Count, 1.Fit, 2.General, 3.CVs
    nurbsTessellate.uType.set(3)         # 1.Per Surf # of Isofarms in 3D, 2.Per Surf # of Isofarms, 3.Per Span # of Isofarms
    nurbsTessellate.vType.set(3)         # 1.Per Surf # of Isofarms in 3D, 2.Per Surf # of Isofarms, 3.Per Span # of Isofarms
    nurbsTessellate.uNumber.set(1)
    nurbsTessellate.vNumber.set(1)

	#polyNormalizeUV -normalizeType 1 -preserveAspectRatio off ;
    if not ch:
        pm.delete( loftedSurface, ch=True )
        pm.delete( curveList )

    if smoothBind:
        pm.select( JntRoots, hi=True )
        JNTs = pm.selected( type='joint')
        pm.skinCluster( JNTs, loftedSurface,
            toSelectedBones   = True,
            bindMethod        = 0,   # 0 - Closest distance between a joint and a point of the geometry.
                                     # 1 - Closest distance between a joint, considering the skeleton hierarchy, and a point of the geometry.
                                     # 2 - Surface heat map diffusion

            skinMethod        = 0,   # 0 - classical linear skinning (default).
                                     # 1 - dual quaternion (volume preserving),
                                     # 2 - a weighted blend between the two

            normalizeWeights  = 1,   # 0 - none,
                                     # 1 - interactive,
                                     # 2 - post (default)
            maximumInfluences = 1,
            dropoffRate       = 4,
            removeUnusedInfluence = False,
            )

        for jnt in JNTs:
            vtx = getClosestVertexOnMesh( loftedSurface, jnt.getTranslation( ws=True ) )
            setWeight( [vtx], jnt)

    return loftedSurface
Example #42
0
def skin_chain_to_tube(obj, jnts):
    # skin, and calculate average dropoff rate
    distances = [j.t.get().length() for j in jnts[1:]]
    dropoff = 1.0 / (sum(distances) / len(distances))
    # closest in hierarchy, neighbors weight dist
    pmc.skinCluster(jnts[0],
                    obj,
                    bindMethod=1,
                    maximumInfluences=3,
                    weightDistribution=1,
                    dropoffRate=dropoff)
def loadWeights(weightsPath):

    files = [
        f for f in os.listdir(weightsPath)
        if os.path.isfile(os.path.join(weightsPath, f))
        and 'faceWeights.json' in f
    ]

    for f in files:
        mesh = None
        try:
            mesh = pmc.PyNode(f.split('_faceWeights.json')[0])
        except:
            continue
        skin = getSkin(mesh)

        if not skin:
            print 'no skin cluster found on %s' % node.name()
            continue
        #pmc.setAttr('%s.maxInfluences' % skin, 4)
        pmc.setAttr('%s.maintainMaxInfluences' % skin, 0)
        pmc.setAttr('%s.weightDistribution' % skin, 1)

        # Get list of joints from weights file
        weights = None
        with open(os.path.join(weightsPath, f), 'r') as jsonFile:
            weights = json.load(jsonFile)

        # Make sure joints from weights file are added to skinCluster
        joints = None
        try:
            joints = [
                pmc.PyNode(j) for j in weights['joints'] if not j == 'null_jnt'
            ]
            print joints
        except:
            raise RuntimeError(
                'Some joints specified in the weights file not found in scene: %s'
                % weights['joints'])
        try:
            pmc.skinCluster(skin, ai=joints, lw=1, wt=0, e=1)
        except:
            print 'joints are already in %s: %s' % (skin, joints)

        # Apply weights
        for v in weights.keys():
            if v == 'joints':
                continue
            keys = [key for key in weights[v].keys() if key != 'null_jnt']
            values = [weights[v][key] for key in keys]
            pmc.skinPercent(skin,
                            '%s.vtx[%s]' % (mesh, v),
                            transformValue=list(zip(keys, values)))
Example #44
0
def move_weights(src=None, trg=None, skcls=None):
    """Move weights from one influence to antoher"""
    ls_skcls = pm.ls(skcls)
    if not (src and trg and skcls):
        lssl = pm.selected()
        if not (src and trg):
            jnts = pm.ls(lssl, type="joint")
            if not jnts:
                print ">_<  No joints selected"
                return
            if not src:
                src = jnts[0]
                if not trg:
                    if len(jnts) < 2:
                        print ">_<  Not enough joints are selected"
                        return
                    trg = jnts[1]
            else:
                trg = jnts[0]
        if not skcls:
            other = list(set(lssl) - set(jnts))
            if not other:
                # print ">_<  You need to add binded geometry(ies) to current selection"
                print(
                    "o_O No gometries are found, " +
                    "i will try get all common skin nodes from given influences"
                )
            else:
                skcls = pm.ls(pm.listHistory(other), type="skinCluster")
                if not skcls:
                    print ">_<  Try to select \"BINDED\" or skinned geometry(ies), gl xD"
                    return
    print "src/trg: {0} >> {1}".format(src, trg)

    if not skcls:
        ls_src_skcl_plgs = set(src.wm.outputs(p=1, type="skinCluster"))
        src_skcls = set(x.node() for x in ls_src_skcl_plgs)
        ls_trg_skcl_plgs = set(trg.wm.outputs(p=1, type="skinCluster"))
        trg_skcls = set(x.node() for x in ls_trg_skcl_plgs)
        skcls = list(src_skcls.intersection(trg_skcls))
        if not skcls:
            print ">_< Given influences have no sharing skinCluster nodes"
            return
    for skcl in skcls:
        # check if influences are not binded to skin cluster node
        if skcl not in src.wm.outputs(type="skinCluster"):
            print ">_< {} is not linked to {}".format(src, skcl)
            return
        if skcl not in trg.wm.outputs(type="skinCluster"):
            print("O_o {} is not linked to {}, but wait... " +
                  "i will bind it for you ^_^").format(trg, skcl)
            pm.skinCluster(skcl, e=1, ai=trg, wt=0)
        do_move_weights(src, trg, skcl)
Example #45
0
    def rebind(self, mesh_display=pm.warning, joint_display=pm.warning):
        """
        Rebinds meshes with skin clusters based on the date in the stored info class variable.

        Args:
            mesh_display (method): How to display a missing mesh.

            joint_display (method): How to display a missing joint.
        """
        for mesh, info in self.info.items():

            path = info['path']
            if not pm.objExists(mesh):
                mesh_display(mesh + ' does not exist! Will not be rebound')
                os.remove(path)
                continue

            # make sure mesh is unique, and that joints exist
            mesh = pm.PyNode(mesh)
            joints = info['joints']
            joints = [
                pm.PyNode(joint)
                if pm.objExists(joint) else joint_display('Missed ' + joint)
                for joint in joints
            ]

            pm.select(mesh, joints)
            skin_name = info['skin']
            max_influences = info['max_influences']
            pm.skinCluster(tsb=True,
                           fnw=True,
                           mi=max_influences,
                           name=skin_name,
                           omi=True)

            directory = os.path.dirname(path)
            deformer_name = os.path.basename(path)
            pm.deformerWeights(deformer_name,
                               im=True,
                               m='index',
                               df=skin_name,
                               e=True,
                               p=directory)
            os.remove(path)
            print('# Imported deformer weights from ' + path + ' to ' +
                  mesh.nodeName())

        # select meshes to end it all
        pm.select(self.info.keys())

        if not os.listdir(self.directory):
            os.rmdir(self.directory)
Example #46
0
        def bdCreateFKChain(self):
                fkRootObj = pm.duplicate(self.rootObj)[0]
                fkRootObj.rename(self.rootObj.name() + '_FK')
                
                fkChain = fkRootObj.listRelatives(type='joint', ad=True, f=True)
                #fkChain.append(fkRootObj)
                fkChain.reverse()

                for jnt in fkChain:
                        jnt.rename(jnt.name() + '_FK')
                
                pm.skinCluster(fkRootObj,self.dynCrv)
                return fkRootObj
Example #47
0
 def skinSrf(self):
     self.createDrvJnt()
     
     skinCls = pm.skinCluster( self.srf,self.drvJntList, tsb=1, ih=1, skinMethod = 0, maximumInfluences = 1, dropoffRate = 10.0 )[0]
     crvSkinCls = pm.skinCluster( self.ikCrv,self.drvJntList, tsb=1, ih=1, skinMethod = 0, maximumInfluences = 1, dropoffRate = 10.0 )[0]
     for i in range(len(self.drvJntList)):
         if i == 0:
             pm.skinPercent(skinCls.name(),self.srf.name() + '.cv[0:1][0:3]',tv=[(self.drvJntList[i],1)])
             pm.skinPercent(crvSkinCls.name(),self.ikCrv.name() + '.cv[0:1]',tv=[(self.drvJntList[i],1)])
         elif i > 0 and i < self.numJnt-1:
             pm.skinPercent(skinCls.name(),self.srf.name() + '.cv[' + str(i+1) + '][0:3]',tv=[(self.drvJntList[i],1)])
             pm.skinPercent(crvSkinCls.name(),self.ikCrv.name() + '.cv[' + str(i+1) + ']',tv=[(self.drvJntList[i],1)])
         elif i == self.numJnt-1:
             pm.skinPercent(skinCls.name(),self.srf.name() + '.cv[' + str(i+1) + ':' + str(i+2) + '][0:3]',tv=[(self.drvJntList[i],1)])
             pm.skinPercent(crvSkinCls.name(),self.ikCrv.name() + '.cv[' + str(i+1) + ':' + str(i+2) + ']',tv=[(self.drvJntList[i],1)])
Example #48
0
 def skinConnect_globalPlane(self, *args):
     """ 
     Args:
         None
     Returns (None)
     Usage:
     """
     base_name = '%s_flexiPlane' % self.flexiPlaneNameField.getText()
     surface = '%s_SURF' % base_name
     surfaceSkinJNT = '%s_surfSkin_JNT' % base_name
     main_CTRLCon = '%s_main_CTRLCon_GRP' % base_name
     
     pm.joint( p = (0, 0, 0), a = True, n = surfaceSkinJNT )
     pm.parentConstraint( main_CTRLCon, surfaceSkinJNT )
     pm.skinCluster( surfaceSkinJNT, surface, bm = 0, sm = 0, nw = 1, wd = 0, mi = 1, omi = 1, dr = 4.0 )
Example #49
0
    def addShadowPlane(self):
        print 'Creating the shadow plane'
        shadowPlane = pm.polyPlane( n='shadowPlane', w=10 , h=10, sx=1, sy= 1, ax=( 0, 1, 0),cuv = 2, ch = 0)
        shadowJoint = pm.joint(n='shadowJoint')
        pm.skinCluster(shadowJoint,shadowPlane)

        root = pm.ls("Root",type='joint')[0]
        pm.parent(shadowJoint,root)


        #rig the plane
        hips = pm.ls("Hips",type='joint')[0]
        leftFoot = pm.ls("LeftFoot",type='joint')[0]
        rightFoot = pm.ls("RightFoot",type='joint')[0]

        pm.pointConstraint(hips,shadowJoint,mo=0,skip='y')
        pm.pointConstraint(leftFoot,shadowJoint,mo=0,skip='y')
        pm.pointConstraint(rightFoot,shadowJoint,mo=0,skip='y')

        #default T pose Y value for the hips will be stored as reference
        #pm.addAttr(hips, ln = 'startY',t = 'double')
        hipsY = hips.getTranslation(space='world').y
        #pm.setAttr(hips.name() + '.startY',hipsY)

        shadowPlaneRV = pm.createNode('remapValue', n ='shadowPlane_RV')
        shadowPlaneRV.imx.set(hipsY * 2.0)
        shadowPlaneRV.outputMin.set(2.0)
        shadowPlaneRV.outputMax.set(0)

        hips.translateY.connect(shadowPlaneRV.inputValue)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleX)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleY)
        shadowPlaneRV.outValue.connect(shadowJoint.scaleZ)

        shadowPlaneCgfx = self.importCgfxShader()
        shadowPlaneCgfx.rename('shadowPlane_cgfx')
        shadowPlaneSg = pm.listConnections('%s.outColor'%shadowPlaneCgfx)[0]
        shadowPlaneSg.rename('shadowPlane_cgfxSG')        

        shadowPlaneTxt = pm.shadingNode('file',asTexture=1,name='shadowPlane_file')

        shadowPlaneTxt.fileTextureName.set('sourceimages\\groundshadow_diffusecolor.tga')
        shadowPlaneTxt.outColor.connect(shadowPlaneCgfx.diffuseMapSampler)

        pm.select(shadowPlane)
        pm.mel.eval('sets -e -forceElement ' + shadowPlaneSg)

        print 'Shadow plane created!!'
Example #50
0
    def __areaSkin(self,*args):

        geo = pm.ls(sl = 1)[0]
        skinCluster = mel.eval('findRelatedSkinCluster ' + geo)
        vertex = pm.polyEvaluate(geo,v = 1)
        joints = pm.skinCluster(skinCluster,q = 1,inf = 1)
        skinList = {}

        for num in range(0,vertex):
            vertex = geo + '.vtx[' + str(num) + ']'
            vertPos = pm.xform(vertex,q = 1,t = 1,ws = 1)
            tempDict = {}
          
            for joint in joints:
                jntPos = pm.xform(joint,q = 1,t = 1,ws = 1)
                dist = math.sqrt(pow(vertPos[0] - jntPos[0],2) + pow(vertPos[1] - jntPos[1],2) + pow(vertPos[2] - jntPos[2],2))
                tempDict.setdefault(joint,dist)
                  
            minDistVal = min(distVal for distVal in tempDict.values())
          
            for joint in tempDict.keys(): 
                if minDistVal == tempDict[joint]:
                    if joint not in skinList:
                        skinList[joint] = []
                    skinList[joint].append(vertex)
                      
        for item in skinList.items():
            joint =  item[0]
            vertex = item[1]
            for vert in vertex:
                pm.skinPercent(skinCluster,vert,transformValue = (joint,1))        
Example #51
0
    def createSkinCluster(self):

        """
        !@Brief Create Skin cluster from class datas.

        :rtype: pymel.core.nodetypes.SkinCLuster
        :return: New skin node
        """

        #   Check
        if not self.SKIN_NODE:
            raise RuntimeError("\n\tNo datas for create skinCluster !!!\n")

        skin_node = pmc.skinCluster(
            self.SHAPE,
            self.INFLUENCES.values(),
            toSelectedBones=True,
            normalizeWeights=1,
            forceNormalizeWeights=False,
            maximumInfluences=self.MAX_INFLUENCES,
            obeyMaxInfluences=self.MAINTAIN_MAX_INFLUENCES,
            skinMethod=self.SKINNING_METHOD,
            useGeometry=self.USE_COMPONENTS,
            name=self.SKIN_NODE,
        )

        return skin_node
	def createSkinclusterAndSplineIk(self):
		
		#Skincluster
		#----------------------------------------------------
		
		pm.select(cl = True)
	
		self.bound_curve_skincluster = pm.skinCluster( self.splineIkBoundJointsList , self.lowResCurveTrans ,tsb=True, n = self.prefix + '_bound_curve_skincluster', rui = False, ih = True)
		
		pm.select(cl = True)
		
		
		
		#Spline Ik
		#----------------------------------------------------
		
		pm.select( cl = True )
		
		#Create spline IK
		self.bound_curve_spline_ik = pm.ikHandle( sj= self.ikSplineJointsList[0] , ee= self.ikSplineJointsList[-1] , roc = True, n = self.prefix + '_ikSplineHandle_bound_curve', c = self.lowResCurveTrans, ccv = False, pcv = False, sol = 'ikSplineSolver' )[0]
		pm.select( cl = True )
		
		#Group Spline_ik
		self.bound_curve_spline_ik_grp = pm.group(self.bound_curve_spline_ik ,  n= self.prefix + '_ikSplineHandle_bound_curve_grp' )
		
		pm.select(cl = True)
Example #53
0
def file_autoSkinner( model_file, joints_file, skin_file ):
	'''takes multiple files, joins them together then skins them
	Args:
		model_file (string): path to the model maya file
		joints_file (string): path to the skeleton maya file
		skin_file (string): path to the skinning info file
	Returns (boolean): True if success
	'''
	#first we import the files
	model_top_nodes = file_importer(model_file)
	joints_top_nodes = file_importer(joints_file)
	joints, models, skinCluster = [], [], None
	#now we parse through for all the meshes and all the joints in each file
	for model_top_node in model_top_nodes:
		models += [transform for transform in model_top_node.listRelatives(ad=True, c=True, type='transform') if transform.getShape() and transform.getShape().type() == 'mesh']
	for joints_top_node in joints_top_nodes:
		joints += joints_top_node.listRelatives(ad=True, c=True, type='joint')
	#remove duplicates
	models, joints = list(tuple( models )), list(tuple( joints ))
	#Now skin every model to all the joints TODO: (this process should be taken over by the weight storing script)
	for model in models:
		try:
			skinCluster = pm.skinCluster(joints, model, ih=True, sm=1, mi=5, dr=4.1, rui=True, tsb=True)
		except:
			print 'model %s is already connected to a skinCluster...skipping'%model.name()
Example #54
0
 def rig_chain(self, chain):
     """
     takes chain and adds joints and a smooth bind to rig it
     
     chain: list of objects 
     """
     pm.select(deselect=True)
     joints = []
     for obj in chain:
         pos = obj.translateX.get(), obj.translateY.get(), obj.translateZ.get()
         jnt = pm.joint(p=pos)
         joints.append(jnt)
         pm.rename(jnt, self.name + "_joint%d" % len(joints))
     linked = pm.polyUnite(chain, ch=0)[0]
     self.name = pm.rename(linked, self.name)
     pm.skinCluster(linked, joints[0])
     return joints
Example #55
0
def bdGetJntFromMesh():
    import pymel.core as pm
    sel = pm.ls(sl=True)[0].getShape()
    skinCls = pm.listConnections('%s.inMesh'%sel)
    print skinCls
    jnts = pm.skinCluster(skinCls,q=True,influence=True)
    names = [str(jnt.name()) for jnt in jnts]
    pm.select([names])    
Example #56
0
 def addIk(self):
     self.createJntChain()
     #create the surface that will be skinned to the joints
     self.createSrf()
     #create the follicles on the surface and also the controllers
     self.createFlcAndCtrl('u', 0)
     #get the joint position on the surface and store it as an attribute
     self.addJntPosAttr()
 
     self.jntGrp = pm.group(name=self.name+'_drv_jnt_grp')
     pm.rotate(self.jntGrp ,0,-90,0,r=1)
     pm.parent(self.jntList[0],self.jntGrp)
 
     pm.parent(self.jntGrp,self.mainGrp)
     self.addMainCtrl()
 
     pm.skinCluster( self.srf,self.jntList, tsb=1, ih=1, skinMethod = 0, maximumInfluences = 1, dropoffRate = 10.0 )        
Example #57
0
    def bdCreateDrvJnt(self,crv1,crv2):
        pm.select(cl=1)
        drv1 = self.startJnt.duplicate(po=1)[0]
        pm.parent(drv1,w=1)
        drv1.rename(self.nameRbn + '_DRV_1_JNT')
        radius = self.startJnt.radius.get()
        drv1.radius.set(radius*1.5)
        pm.parentConstraint(self.startJnt,drv1,mo=0)
        
        drv2 = drv1.duplicate(po=1)[0]
        drv2.rename(self.nameRbn + '_DRV_2_JNT')
        
        drv3 = drv1.duplicate(po=1)[0]
        drv3.rename(self.nameRbn + '_DRV_3_JNT')
        pm.parentConstraint(self.endJnt,drv3,mo=0)

        startPos,endPos = self.bdGetPos(0)
        drv1.setTranslation(startPos)
        drv3.setTranslation(endPos)

        drv2CtrlGrp = self.bdCreateJntCtrl(drv2,0.20)
        pm.pointConstraint(drv1,drv2CtrlGrp,mo=0 )
        pm.pointConstraint(drv3,drv2CtrlGrp,mo=0 )
        aimLocator = pm.spaceLocator(n=drv2CtrlGrp.name().replace('DRV_2_CTRL_GRP','AIM'))
        drv2CtrlGrpPos = drv2CtrlGrp.getTranslation(space='world')
        aimLocator.setPosition(drv2CtrlGrpPos)
        for axis in ['X','Y','Z']:
            aimLocator.attr('localScale'+axis).set(0.1)
        aimLocatorGrp = pm.group(aimLocator,n=aimLocator.name() + '_grp')
        aimLocatorGrp.centerPivots()
        if self.direction == 'hor':
            pm.move(0,0.5,0, aimLocatorGrp, r=1, os=1, wd=1)
        elif self.direction == 'vert':
            pm.move(0,0,0.5, aimLocatorGrp, r=1, os=1, wd=1)
        pm.parentConstraint(self.startJnt,aimLocatorGrp,mo=1)
        print aimLocator.getTranslation(space='world').x
        if aimLocator.getTranslation(space='world').x > 0:
            pm.aimConstraint(drv3,drv2CtrlGrp,mo=1,weight=1,aimVector=[1, 0, 0],upVector = [0, 1, 0],worldUpType="object" , worldUpObject = aimLocator)
        else:
            pm.aimConstraint(drv3,drv2CtrlGrp,mo=1,weight=1,aimVector=[-1, 0, 0],upVector = [0, 1, 0],worldUpType="object" , worldUpObject = aimLocator)
        drvGrp = pm.group([drv1,drv2CtrlGrp,drv3],n=self.nameRbn + '_DRV_GRP')
        crv1Skin = pm.skinCluster(drv1,drv2,drv3,crv1)
        crv1Skin = pm.skinCluster(drv1,drv2,drv3,crv2)
        pm.parent(aimLocatorGrp,drvGrp)
        return drvGrp
def getRelatedSkinCluster(trans):
    shps = trans.listRelatives(s=True, ni=True)
    for sh in shps:
        scs = pm.ls(type='skinCluster')
        for sc in scs:
            mesh = pm.skinCluster(sc, q=True, g=True)
            if mesh[0] == shps[0]:
                relatedSkinCluster = sc
                return relatedSkinCluster
Example #59
0
def rivet_to_surface(objects, surface, replaceStr=None):
	'''Rivets the objects to the target surface's closest vert
	Args:
		objects [pm.PyNode]: objects to rivet
		surface (pm.PyNode): surface to attach them to
		replaceStr (string): the suffix to replace with JNT
	Returns:
		(boolean): True if we're all good in the hood
	Usage:
		rivet_to_surface( pm.ls(sl=True), pm.PyNode('l_hand_GEO') )
	'''
	sel=pm.ls(sl=True)
	bindList=[]
	module_name, module = surface.name()+'_rivet_GRP', None
	try:
		module = module_name
	except:
		module = pm.group(n=module_name, em=True)
	
	for obj in objects:
		pm.select(cl=True)
		name = ''
		
		if replaceStr:
			name_jnt = obj.name().replace(replaceStr, 'JNT')
			name_grp = obj.name().replace(replaceStr, 'GRP')
		else:
			name_jnt = obj.name()+'_JNT'
			name_grp = obj.name()+'_GRP'
			
		joint = pm.joint(p=obj.c.get(), n=name_jnt)
		grp = pm.group(n=name_grp, em=True)
		
		#stupid f*****g point on poly constraint bullshit being broken.
		closestVert = closestVertex( joint, surface ) 
		pm.select(closestVert, grp, r=True)
		eval('doCreatePointOnPolyConstraintArgList 1 { "0","0","0","1","0","0" };')
		#Now setup the proper hierarchy and parent up
		joint.setParent(grp)
		pm.skinCluster(obj, joint, tsb=True)
		grp.setParent(module)
	pm.select(sel, r=True)
	return True
Example #60
-1
def loadSkinning(path):
    with open(path, 'rb') as handle:
        fileData = pickle.load(handle)

    for msh, dataDict in fileData.iteritems():
        mshAndJnts = dataDict.keys()
        mshAndJnts.append(msh)

        skinCls = findSkinCluster(msh)
        if skinCls:
            for eachJnt in mshAndJnts:
                pm.skinCluster(skinCls, edit=True, ai=eachJnt, lw=True)

        else:
            skinCls = pm.skinCluster(mshAndJnts, tsb=True, tst=False)

        skinCls.setNormalizeWeights(0)
        pm.skinPercent(skinCls, msh, nrm=False, prw=100)

        jointDict = {}
        for storedJoint in dataDict:
            try:
                jnt = pm.PyNode(storedJoint)
            except pm.MayaNodeError:
                logger.debug('nao achou jnt: %s' % jnt)
            jointDict[storedJoint] = skinCls.indexForInfluenceObject(jnt)

        for infl in dataDict:
            for vtx in dataDict[infl]:
                pm.setAttr(
                    skinCls.name() + '.weightList[' + str(vtx[0]) +
                    '].weights[' + str(jointDict[infl]) + ']', vtx[1])
        skinCls.setNormalizeWeights(1)
        logger.debug('skin loading ok!')