예제 #1
0
    def CreateMulipleBlendShapes(self, BSDefinition, prefix, BSGroups, blendShapeNode=None, objectPrefix=""):
        self.FaceBlendShapeDic = None
        if BSDefinition[BSGroups]["Type"] == "blendShapeDefinition":
            print "blendShapeNode%s" % blendShapeNode
            if blendShapeNode == None:

                BSNodeArray = mel.eval(
                    '''source RMDeformers.mel;\nstring $BSNode[]=GetDeformer("'''
                    + objectPrefix
                    + BSDefinition[BSGroups]["baseMesh"]
                    + """","blendShape");"""
                )
                if len(BSNodeArray) == 0:
                    print "No blendshape Found on %s" % BSDefinition[BSGroups]["baseMesh"]
                    BSName = BSGroups + objectPrefix + "BS"
                    # blendShapeOriginalGeo = cmds.duplicate(prefix + BSDefinition[BSGroups]['baseMesh'], name = self.NameConv.RMGetAShortName(BSDefinition[BSGroups]['baseMesh']) + BSGroups)
                    Side = self.getSideFromPrefix(prefix)
                    # blendShapeOriginalGeo = self.NameConv.RMRenameNameInFormat( blendShapeOriginalGeo, System = "faceRig",Side = Side)
                    # cmds.blendShape(blendShapeOriginalGeo, name = BSName)
                    cmds.blendShape(BSDefinition[BSGroups]["baseMesh"], name=BSName)
                    BSName = self.NameConv.RMRenameNameInFormat(BSName, System="faceRig", Side=Side)
                else:
                    BSName = BSNodeArray[0]
            else:
                BSName = blendShapeNode
            for eachControl in BSDefinition[BSGroups]["order"]:
                self.CreateBlendShapesByControl(
                    BSName, eachControl, BSDefinition[BSGroups], prefix, objectPrefix=objectPrefix
                )
        return self.FaceBlendShapeDic
예제 #2
0
 def heyWitch_addTargetMesh(self, basePass, tgtMshLabelTextFld):
     spawnMesh = basePass.mesh_spawn_name
     baseMesh = basePass.burn_group_label
     targetMeshName = "tgtMsh_" + tgtMshLabelTextFld
     cmds.duplicate(spawnMesh, name=targetMeshName)
     self.helper.heyWitch_blankSlate(targetMeshName)
     # outliner group
     cmds.select(clear=True)
     cmds.parent(targetMeshName, (baseMesh + '_tgt_grp'))
     ###CHECK IF BLEND NODE EXISTS FIRST!
     if cmds.objExists(baseMesh + "_blndNde"):
         tgtNo = len(cmds.listConnections(baseMesh + "_blndNde.it[0].iti")) + 1
         cmds.blendShape((baseMesh + "_blndNde"), edit=True, t=(baseMesh, tgtNo, targetMeshName, 1))
     else:
         cmds.blendShape(targetMeshName, baseMesh, n=(baseMesh + "_blndNde"))
     cmds.setAttr(baseMesh + "_blndNde." + targetMeshName, 1)
     targetMesh = TargetMesh()
     targetMesh.mesh_spawn_name = spawnMesh
     targetMesh.burn_group_label = baseMesh
     targetMesh.vert_vals = basePass.vert_vals
     targetMesh.target_mesh_label = str(targetMeshName)
     self.global_work_space['targetStorage'][targetMeshName] = targetMesh
     tree_layout = self.global_work_space['miscData']['switch_layouts']['msw_tree_layout']
     cmds.treeView(tree_layout, edit=True,
                   addItem=(targetMeshName, targetMesh.burn_group_label), cs=True)
     cmds.treeView(tree_layout, edit=True, selectItem=(targetMeshName, True))
     self.helper.heyWitch_grabMesh(targetMeshName, targetMesh, self.global_work_space)
예제 #3
0
def create(mesh, in_out='in', blend_shape_node=None):
    
    cmds.select(mesh, r=True)
    duplicate_object = cmds.duplicate(n=mesh + '_' + in_out + '_bs')[0]

    if in_out == 'in':
        shape_order = [duplicate_object, mesh]
    else:
        shape_order = [mesh, duplicate_object]
        
    if (blend_shape_node is None) or (in_out == 'out'):
        cmds.select(shape_order[0], shape_order[1], r=True)
        blend_shape_node = cmds.blendShape(n=shape_order[0] + '_passthrough', w=[0,1])[0]
        
    else:
        blend_shape_index = len(cmds.getAttr(blend_shape_node + '.weight')[0]) + 2
        cmds.select(shape_order[0], shape_order[1], r=True)
        name = '{0}_passthrough_{1}'.format(shape_order[0], blend_shape_index)
        cmds.blendShape(blend_shape_node, e=True, t=[shape_order[1], blend_shape_index, shape_order[0], 1])
        cmds.setAttr(blend_shape_node + '.' + shape_order[0], 1)

    
    cmds.select(duplicate_object, r=True)
    
    return blend_shape_node
예제 #4
0
    def Action_Apply(self):
        maya_cmds.undoInfo(openChunk=True)
        try:
            items = self.window.Text_Items.toPlainText().strip().split('\n')
            objects = list(
                set([items[i].split('.')[0] for i in xrange(len(items))]))

            amount = self.window.Int_Amount.value()
            iterations = self.window.Int_Iterations.value()
            blend = self.window.Float_Blend.value() * -1.0

            for i in xrange(len(objects)):
                for _ in xrange(iterations):
                    duplicate = maya_cmds.duplicate(objects[i],
                                                    returnRootsOnly=True)
                    maya_cmds.polyAverageVertex([
                        item.replace(objects[i], duplicate[0])
                        for item in items if objects[i] in item
                    ],
                                                caching=True,
                                                iterations=amount)
                    maya_cmds.blendShape(duplicate,
                                         objects[i],
                                         envelope=blend,
                                         weight=[0, 1.0])
                    maya_cmds.delete(duplicate)
        except Exception as e:
            print >> stderr, str(e)
        maya_cmds.undoInfo(closeChunk=True)
예제 #5
0
def lol():
    '''
	What is the purpose of this ?
	'''
    import maya.cmds as mc

    sel = mc.ls(sl=True)
    shapes = sel[0]
    targets = sel[1]

    shapes = mc.listRelatives(shapes, c=True)
    targets = mc.listRelatives(targets, c=True)

    for shape in shapes:
        get_name = shape.split('__')
        get_name = get_name[1]

        print(shape)
        for target in targets:

            if target == get_name:

                mc.blendShape(shape, target, n='temp_bs')
                mc.delete(target, ch=True)

            else:
                pass
예제 #6
0
def addTargetInbetween(blendShape,inbetweenGeo,baseGeo,inbetweenTarget,inbetweenWeight):
	'''
	Add blendShape target inbetween shape at the specified weight value.
	@param blendShape: Name of blendShape to add inbetween target to
	@type blendShape: str
	@param inbetweenGeo: BlendShape inbetween target geometry
	@type inbetweenGeo: str
	@param baseGeo: BlendShape base geometry to add inbetween to
	@type baseGeo: str
	@param inbetweenTarget: BlendShape target to add inbetween to.
	@type inbetweenTarget: str
	@param inbetweenWeight: BlendShape target weight to add inbetween to.
	@type inbetweenWeight: float
	'''
	# Check blendShape
	if not isBlendShape(blendShape):
		raise Exception('Object "'+blendShape+'" is not a valid blendShape node!')
	
	# Check inbetween target geometry
	if not mc.objExists(inbetweenGeo):
		raise Exception('Inbetween target geometry "'+inbetweenGeo+'" does not exist!')
	
	# Get target index
	targetIndex = getTargetIndex(blendShape,inbetweenTarget)
	
	# Add inbetween
	mc.blendShape(blendShape,e=True,ib=True,t=[baseGeo,targetIndex,inbetweenGeo,inbetweenWeight])
예제 #7
0
def makeBlendshapes():
    sel = cmds.ls(sl=True)  #select head geo
    baseBlend = cmds.duplicate(
        sel[0], n="head_base_blend")  #duplicate out head for blend base
    channels = [
        "translateX", "translateY", "translateZ", "rotateX", "rotateY",
        "rotateZ", "scaleX", "scaleY", "scaleZ"
    ]  #list of locked channels
    for c in channels:  #loop through locked channels
        cmds.setAttr("%s.%s" % (baseBlend[0], c),
                     l=False)  #unlock all channels
    bsGrp = cmds.group(em=True, n="blendShapes")  #make blandshape group
    cmds.parent(baseBlend[0], bsGrp)  #parent blendShape base to group
    shapes = [
        "mouth", "eyebrow", "eyeLid", "cheek", "cheekbone", "nose", "lipCurl"
    ]  #list of blendshapes
    for i, s in enumerate(shapes):  #loop through blendshape list
        newShape = cmds.duplicate(baseBlend[0], n="head_%s_blend" %
                                  s)[0]  #make blendshape targets
        if i == 0:  #first loop
            blendShape = cmds.blendShape(
                newShape, baseBlend[0],
                w=(i, 1))[0]  #make blendshape node and connect first target
        else:  #remaining loop
            cmds.blendShape(blendShape,
                            edit=True,
                            t=(baseBlend[0], i, newShape, 1.0),
                            w=(i, 1))  #connect remaining blendshapes
    cmds.blendShape(baseBlend[0], sel, foc=True,
                    w=(0, 1))  #connect to original object
예제 #8
0
def removeTarget(blendShape, target, baseGeo):
    """
    Remove the specified blendShape target
    @param blendShape: Name of blendShape to remove target from
    @type blendShape: str
    @param target: BlendShape target to remove
    @type target: str
    @param baseGeo: BlendShape base geometry name
    @type baseGeo: str
    """
    # Check blendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape + '" is not a valid blendShape node!')

    # Check target
    if not hasTarget(blendShape, target):
        raise Exception('BlendShape "' + blendShape + '" has no target "' + target + '"!')

    # Get target index
    targetIndex = getTargetIndex(blendShape, target)

    # Connect null duplicate
    targetGeo = getTargetGeo(blendShape, target, baseGeo)
    if not targetGeo:
        cmds.setAttr(blendShape + '.envelope', 0.0)
        targetGeo = cmds.duplicate(baseGeo)[0]
        cmds.setAttr(blendShape + '.envelope', 1.0)
        connectToTarget(blendShape, targetGeo, target, baseGeo, 1.0, force=True)

    # Remove target
    cmds.blendShape(blendShape, e=True, rm=True, t=[baseGeo, targetIndex, targetGeo, 1.0])
예제 #9
0
def snapShapeToNeutral(source, target):
    '''
	Take a mesh, and find the closest location on the target head, and snap to that
	Then set up a blendShape so the artist can "paint" in the snapping behavior
	'''
    # Make a duplicate of the source and snap it to the target
    snapShape = cmds.duplicate(source, name='snp')
    cmds.transferAttributes(
        target,
        snapShape,
        transferPositions=1,
        sampleSpace=1,  # 0=World, 1=Local, 3=UV
        searchMethod=0,  # 0=Along Normal, 1=Closest Location
    )

    # Then delete history
    cmds.delete(snapShape, constructionHistory=True)
    cmds.hide(snapShape)

    # Blend the source to the snappedShape
    bs = cmds.blendShape(snapShape, source)[0]
    cmds.blendShape(bs, edit=True, weight=((0, 1)))

    # But set the weights back to 0.0 for painting
    numVerts = cmds.polyEvaluate(source, vertex=1)
    setter = '{0}.inputTarget[0].inputTargetGroup[0].targetWeights[0:{1}]'.format(
        bs, numVerts - 1)
    weights = [0.0] * numVerts
    cmds.setAttr(setter, *weights, size=numVerts)
예제 #10
0
    def on_btn_FixSkinBsEnd_clicked(self, clicked=None):
        if clicked == None:return

        selectIndexes = self.listView_attributeList.selectedIndexes()
        if len(selectIndexes) == 0:return
        selectAttr = self.__AttributeModel.data(selectIndexes[0], QtCore.Qt.DisplayRole)
        if not uiTool.warning('BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'%selectAttr):return

        openCloseDeformer(self.__baseModel, 0, ('skinCluster'))
        newSculpModel = cvShapeInverterCmds.invert(self.__baseModel, self.__sculpmodel, self.progressBar)
        mc.delete(newSculpModel, ch=True)
        openCloseDeformer(self.__baseModel, 1, ('skinCluster'))

        if mc.objExists(selectAttr):
            mc.blendShape(newSculpModel, selectAttr, w=((0, 1)))
            mc.delete(selectAttr, ch=True)
            mc.delete(newSculpModel)
        else:
            shape = mc.listRelatives(newSculpModel, s=True, path=True)[0]

            weightID = self.__AttributeDT2.get(selectAttr, None)
            TGTattr  = self.__IGTAttributeDT.get(weightID, None)
            mc.connectAttr('%s.worldMesh[0]'%shape, '%s.%s'%(self.__blendShape, TGTattr), f=True)

            mc.rename(newSculpModel, selectAttr)
        mc.delete(self.__sculpmodel)
        mc.delete(self.__tempmodel)
예제 #11
0
파일: mdc.py 프로젝트: ivanzotov/mdc
def prepare(setname="cache_set", groupname="cache_group", prefix="cache_"):
    selection = cmds.ls(sl=True, l=True)
    
    if len(selection) == 0:
        cmds.warning("Please select objects!")
        return
        
    cmds.duplicate()
    dup = cmds.ls(sl=True, l=True)
    
    if cmds.objExists(groupname):
        cmds.parent(dup, groupname)
    else:
        cmds.group(w=True, n=groupname)
    
    cmds.select(groupname)
    dup = get_shapes()
    add_to_set_of_shapes(setname, dup)
    
    i = 0
    for obj in dup:
        cmds.blendShape([selection[i], obj], w=(0, 1),o="world", foc=True)
        objects = []
        objects.append(obj)
        addattr(objects, prefix+str(i))
        i=i+1
예제 #12
0
    def transferEnforce(self, *a):
        source = cmds.textField('tf_agrDJ', q=1, text=1)
        target = cmds.textField('tf_agrJT', q=1, text=1)
        bs = cmds.textField('tf_agrN', q=1, text=1)
        ignNum = cmds.intField('if_agrIV', q=1, value=1)
        su = ['', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
              'k']  # suffix

        ct = int(round(cmds.currentTime(query=1)))
        pdac = cmds.polyDuplicateAndConnect(source, renameChildren=1)[0]
        tn = source.split(':')[-1] + '_' + str(ct)
        for s in su:
            if cmds.objExists(tn + s) == 0:
                tn = tn + s
                break
        cmds.rename(pdac, tn)

        if bs == '':
            bs = cmds.blendShape(tn, target)[0]
            cmds.textField('tf_agrN', e=1, text=bs)
        else:
            #wc = cmds.blendShape(bs,q=1,weightCount=1)
            bsAttr = cmds.aliasAttr(bs, q=1)
            il = []
            il = [
                int(re.findall('\d+', bsAttr[i])[0])
                for i in range(1, len(bsAttr), 2)
            ]
            cmds.blendShape(bs, e=1, target=(target, max(il) + 1, tn, 1.0))

        cmds.setKeyframe(bs + '.' + tn, v=1, t=ct)
        cmds.setKeyframe(bs + '.' + tn, v=0, t=ct - ignNum)
        cmds.setKeyframe(bs + '.' + tn, v=0, t=ct + ignNum)
        cmds.select(tn, replace=1)
예제 #13
0
    def on_btn_FixSkinBsEnd_clicked(self, clicked=None):
        if clicked == None: return

        selectIndexes = self.listView_attributeList.selectedIndexes()
        if len(selectIndexes) == 0: return
        selectAttr = self.__AttributeModel.data(selectIndexes[0],
                                                QtCore.Qt.DisplayRole)
        if not uiTool.warning(
                'BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'
                % selectAttr):
            return

        openCloseDeformer(self.__baseModel, 0, ('skinCluster'))
        newSculpModel = cvShapeInverterCmds.invert(self.__baseModel,
                                                   self.__sculpmodel,
                                                   self.progressBar)
        mc.delete(newSculpModel, ch=True)
        openCloseDeformer(self.__baseModel, 1, ('skinCluster'))

        if mc.objExists(selectAttr):
            mc.blendShape(newSculpModel, selectAttr, w=((0, 1)))
            mc.delete(selectAttr, ch=True)
            mc.delete(newSculpModel)
        else:
            shape = mc.listRelatives(newSculpModel, s=True, path=True)[0]

            weightID = self.__AttributeDT2.get(selectAttr, None)
            TGTattr = self.__IGTAttributeDT.get(weightID, None)
            mc.connectAttr('%s.worldMesh[0]' % shape,
                           '%s.%s' % (self.__blendShape, TGTattr),
                           f=True)

            mc.rename(newSculpModel, selectAttr)
        mc.delete(self.__sculpmodel)
        mc.delete(self.__tempmodel)
예제 #14
0
def cntLod02ToLod03(*args):
    selLs = cmds.ls(sl=True, dag=True, g=True, ni=True)
    lod02ShpLs = selLs if selLs else cmds.ls(
        'lod02_GRP', dag=True, g=True, ni=True)

    for shp in lod02ShpLs:
        lod02Geo = cmds.listRelatives(shp, p=True)[0]
        lod03Geo = lod02Geo.split('lod02_')[-1]

        if cmds.objExists(lod03Geo):
            lod03DefLs = tak_lib.getAllDef(lod03Geo)
        else:
            OpenMaya.MGlobal.displayWarning(
                '"%s" is not exists that matching with "%s". Skip this' %
                (lod03Geo, lod02Geo))
            continue

        if not lod03DefLs:
            try:
                cmds.blendShape(lod02Geo,
                                lod03Geo,
                                frontOfChain=True,
                                w=[0, 1])
            except:
                OpenMaya.MGlobal.displayWarning(
                    '"%s" has different topology compare to "%s". Connect using wrap'
                    % (lod02Geo, lod03Geo))
                cmds.select(lod03Geo, lod02Geo)
                cmds.CreateWrap()
def LoadDelta(Args):

    global adress    
    # Open dialog window to choose directory to load delta        
    folder = cmds.fileDialog2( cap='Choose directory to load Delta', fm=3, dialogStyle=1 )
    adress = folder[0]+"\\"
    pathList_cleared = []    
    targetBlendDict = {}
    named_targetBlendDict = {}
    print "Loading Delta :)"
    # Getting .bsp files from choosen folder
    pathList = os.listdir( adress )
    if len(pathList) == 0:
        print "Folder is empty"
    for element in pathList:
        if '.bsp' in element:
            pathList_cleared.append( element )
        else:
            print 'wrong type - ', element
    pathList = pathList_cleared
    
    headObj = cmds.ls( sl=True )
    object_qnty_check(headObj)
    headObject = headObj[0]
    
    step = 25
    for i in range( len(pathList) ):
        start_time = timeit.default_timer()
        named_targetBlendDict.clear()
        path_name = open( adress+pathList[i],'r' )
        DeltaDict = pickle.load( path_name )
        targetBlendDict.clear()
        new_name = pathList[i].split('.')[0]
        cmds.duplicate( headObj[0], n=headObject+'_' + new_name )
        cmds.select( headObject+'_'+new_name )
        cmds.move( step, 0, 0 )
        step += 25
        for key in compOpacities:
            weight = compOpacities.get(key)
            x =  baseVertDict[key][0] + (DeltaDict[key][0] * weight)
            y =  baseVertDict[key][1] + (DeltaDict[key][1] * weight)
            z =  baseVertDict[key][2] + (DeltaDict[key][2] * weight)
            targetBlendDict[key] = [x, y, z]
        copy_headObj = cmds.ls( sl=True )
        for head in copy_headObj:
            for i in targetBlendDict:
                 named_targetBlendDict[head+'.vtx' + str(i)] = targetBlendDict[i]
        for head in copy_headObj:
           for vert, value in named_targetBlendDict.iteritems():
               cmds.xform( vert, t=value )
        print "Loading time - ", head, ( timeit.default_timer() - start_time )
    cmds.softSelect( sse=1 )
    names = cmds.listAttr( "blendShape1", m=True, k=True )[1:]
    fullNames = []
    for i in names:
    	fullNames.append( headObj[0] + '_' + i )
    cmds.blendShape( fullNames, headObj )
    cmds.delete( fullNames )

    return adress
예제 #16
0
    def on_btn_FixBsBsEnd_clicked(self, clicked=None):
        if clicked == None:return

        #-
        selectIndexes = self.listView_attributeList.selectedIndexes()
        if len(selectIndexes) == 0:return
        selectAttr = self.__AttributeModel.data(selectIndexes[0], QtCore.Qt.DisplayRole)

        if not uiTool.warning('BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'%selectAttr):return

        #- dup model
        openCloseDeformer(self.__baseModel, 0)
        midModel = mc.duplicate(self.__baseModel, n=nameTool.compileMayaObjectName('%s_mid'%self.__baseModel.split(':')[-1]))[0]
        openCloseDeformer(self.__baseModel, 1)

        #- add blendShape
        mc.blendShape(self.__sculpmodel, self.__baseModel, midModel, w=((0, 1), (1, -1)))
        mc.delete(midModel, ch=True)


        if mc.objExists(selectAttr):
            mc.blendShape(midModel, selectAttr, w=((0, 1)))
            mc.delete(selectAttr, ch=True)
            mc.delete(midModel)
        else:
            shape = mc.listRelatives(midModel, s=True, path=True)[0]

            weightID = self.__AttributeDT2.get(selectAttr, None)
            TGTattr  = self.__IGTAttributeDT.get(weightID, None)
            mc.connectAttr('%s.worldMesh[0]'%shape, '%s.%s'%(self.__blendShape, TGTattr), f=True)

            mc.rename(midModel, selectAttr)
        mc.delete(self.__sculpmodel)
        mc.delete(self.__tempmodel)
예제 #17
0
파일: BSM.py 프로젝트: jonntd/mla_marTool
    def create_in_between(self):
        """
        Create a new in between
        """

        # --- Open history chunk
        mc.undoInfo(openChunk=True)
        try:
            # --- Get datas from ui
            datas = self.get_ui_datas()
            # --- Get in between value, base, index, and new_target
            in_between_value = self.inbetween_value.value()
            base = self.get_blendshape_base()
            index = self.get_target_index(datas[1][0])
            new_target = mc.ls(sl=True, transforms=True)[0]
            weight = self.get_target_from_weight(datas[1][0])

            # --- Create the new in between
            if self.blendshapes_datas[datas[0]]['type'] == 'DPK_bcs':
                # --- Get the index of the selected weight
                get_weight_index = mel.eval('DPK_bcs -query -gw -called "%s" "%s" ' % (weight, datas[0]))
                # --- Get the index of the weight pos
                get_wp_index = mel.eval('DPK_bcs -query -gwp -w %s "%s" ' % (get_weight_index, datas[0]))
                # --- Create the new weightPos
                index = mel.eval('DPK_bcs -e -wPosGrp %s -createWPos -wPosPosition %s "%s"'
                                 % (get_wp_index[0], in_between_value, datas[0]))
                # --- Create a new dataPoint at the created weight using new_target
                mel.eval('DPK_bcs -e -createDataPoint -name "%s" -dataPointPosition %s -go "%s" "%s"'
                         % (new_target, index, new_target, datas[0]))
            else:
                mc.blendShape(datas[0], e=True, inBetween=True, target=(base, index, new_target, in_between_value))
        finally:
            mc.undoInfo(closeChunk=True)
예제 #18
0
def TryLoadExternalBaseMeshBodyMorph():
    with mayaUtils.DebugTimer('TryLoadExternalBaseMeshBodyMorph'):
        mainMesh = mayaUtils.FindMeshByWildcard('Genesis8Female*',
                                                checkForMatWithName='Torso')

        if mainMesh is None:
            print 'Error! Can`t find body(Torso) mesh'
            return
        #Mesh unskinned on this stage so we can safely delete all history
        cmds.delete(mainMesh, constructionHistory=True)

        bodyMorphFile = os.path.join(env.GetIntermediateFullPath(),
                                     env.PROCESSED_BASE_MESH_NAME + '.obj')
        bodyMorphExist = os.path.exists(bodyMorphFile)
        print 'Body morph file: {} Exist: {}'.format(bodyMorphFile,
                                                     bodyMorphExist)
        if not bodyMorphExist:
            print 'ABORTED: no body morph file found'
            return

        morphMesh = cmds.file(bodyMorphFile, i=True, returnNewNodes=True)[0]
        morphMesh = cmds.rename(morphMesh, 'BodyMorph')
        cmds.xform(morphMesh, absolute=True, translation=[0, 0, 100])

        bs = cmds.blendShape([morphMesh, mainMesh])
        cmds.blendShape(bs, edit=True, weight=[0, 1.0])

        cmds.delete(mainMesh, constructionHistory=True)
        cmds.delete(morphMesh)
예제 #19
0
def shapeExtract_weights(baseGeo,
                         targetGeo,
                         weightList,
                         deleteHistory=True,
                         name=''):
    '''
	Extract a portioin of a blendShape target based on a list of vertex weight value
	@param baseGeo: Base geometry shape
	@type baseGeo: str
	@param targetGeo: Target geometry shape
	@type targetGeo: str
	@param weightList: Weight list to apply to extracted shape blendShape weights
	@type weightList: list
	@param deleteHistory: Delete blendShape history
	@type deleteHistory: bool
	@param name: Name for extracted shape
	@type name: str
	'''
    # =========
    # - Check -
    # =========

    # Check base geo
    if not mc.objExists(baseGeo):
        raise Exception('Base geometry "' + baseGeo + '" does not exist!')

    # Check target geo
    if not mc.objExists(targetGeo):
        raise Exception('Target geometry "' + targetGeo + '" does not exist!')

    # =================
    # - Extract Shape -
    # =================

    # Determine blendShape geometry
    if name and mc.objExists(name):
        blendGeo = name
        m_blendShape = mc.blendShape(baseGeo, blendGeo)[0]
        m_blendAlias = mc.listAttr(m_blendShape + '.w', m=True)[0]
        mc.setAttr(m_blendShape + '.' + m_blendAlias, 1.0)
        mc.delete(blendGeo, ch=True)
    else:
        blendGeo = mc.duplicate(baseGeo, n=blendGeo)[0]

    # Create blendShape to target
    blendShape = mc.blendShape(targetGeo, blendGeo)[0]
    mc.setAttr(blendShape + '.' + targetGeo, 1)

    # Set belndShape target weights
    glTools.utils.blendShape.setTargetWeights(blendShape, targetGeo,
                                              weightList, blendGeo)

    # Delete history on duplicated geometry
    if deleteHistory: mc.delete(blendGeo, constructionHistory=True)

    # =================
    # - Return Result -
    # =================

    return blendGeo
예제 #20
0
파일: faceUI.py 프로젝트: yazici/fromGod
def FC_addNewObj():
    slObj = rig.ls(sl=True)
    if slObj:
        for obj in slObj:
            newObj = rig.duplicate(obj, rr=True, n=obj + '_Skin_Mesh')[0]
            rig.blendShape(obj, newObj, w=(0, 1), n=obj + '_Mesh_BS')

            JNTS = [
                jnt + '_JNT' for jnt in rig.listConnections(
                    'Face_Scale_Grp.signA', s=False, d=True)
            ]
            SkinClus = rig.skinCluster(JNTS,
                                       newObj,
                                       n=obj + '_BlendShape_SKIN')[0]
            infs = rig.skinCluster(SkinClus, q=True, inf=True)
            for i, inf in enumerate(infs):
                MirrorGRP = inf.replace('_M_JNT', '_M_Mirror_GRP')
                rig.connectAttr(MirrorGRP + '.worldInverseMatrix[0]',
                                SkinClus + '.bindPreMatrix[' + str(i) + ']')


#           重新命名眼睫毛名字
            ModiObj = rig.rename(obj, obj + '_Skin')
            rig.rename(newObj, obj)
            rig.parent(ModiObj, 'Face_Deformers_Grp')
예제 #21
0
def splitShapeSetup():

    # create 3 splitOutput meshes that will be painted
    # start with creating the splitters
    selection = cmds.ls(sl=True)
    meshList = selection[:-1]
    base = selection[-1]
    
    splitters = []
    blends = []
    meshes = ["A", "B", "C"]
    inputMeshList = meshList

    # first target plays an important role, this is the one we're going to default turn on and align to in tx
    first = meshList[0]
    for i, letter in enumerate(meshes):
        # create splitters
        split = "{0}_split{1}".format(base, letter)
        cmds.duplicate(base, n=split)
        cmds.delete(cmds.parentConstraint(first, split))
        # how far to move the dup
        dist = (int(i) + 1) * 10
        cmds.move(dist, 0, 0, split, r=True)

        blend = "{0}_BSHP".format(split)
        cmds.select(split)
        cmds.blendShape(n=blend)
        splitters.append(split)
        blends.append(blend)


    # add blends and set them too yada yada
    blendDrivers = []
    blendDrivers = blendDrivers + meshList
    for i, split in enumerate(splitters):

        # connections?
        cmds.select(blendDrivers)
        cmds.select(split, tgl=True)
        mel.eval("performBlendShapeAdd 0;")
        blendDrivers.append(split)

        # if a splitter, set to -1
        for s in splitters:
            splitBshp = "{0}.{1}".format(blends[i], s)
            if cmds.objExists(splitBshp):
                cmds.setAttr(splitBshp, -1)

    # Turn on the first. Just as a default
    for blend in blends:
        cmds.setAttr("{0}.{1}".format(blend, first), 1)

        # connect all meshList input shapes to each other
        for i, target in enumerate(inputMeshList):
            print inputMeshList
            if blend != blends[0]:
                cmds.connectAttr(
                    "{0}.{1}".format(blends[0], target),
                    "{0}.{1}".format(blend, target)
                )
예제 #22
0
 def doBlendShape(self):
     dupObjectName = cmds.textField('Face_Control_Object_Name',
                                    q=True,
                                    tx=True)
     cmds.select(dupObjectName)
     cmds.select(object, add=True)
     cmds.blendShape(name=dupObjectName + 'BlendShape')
예제 #23
0
    def __remove_blendshapes(self):
        #--- this method removes the blendShape nodes
        #--- remove blendShape connection
        cmds.blendShape(self.mesh_bsp,
                        edit=True,
                        topologyCheck=False,
                        remove=True,
                        target=((self.mesh, self.target_index,
                                 self.mesh_result, 1),
                                (self.mesh, self.target_index, self.mesh, 1)))
        #--- remove the sculpt mesh
        cmds.delete(self.mesh_sculpt)
        #--- remove the negative mesh
        cmds.delete(self.mesh_negative)
        #--- remove the result mesh
        cmds.delete(self.mesh_result)

        #--- delete the sculpt group
        if not cmds.listRelatives(self.sf_sculpt, allDescendents=True):
            cmds.delete(self.sf_sculpt)
        #--- delete the negative group
        if not cmds.listRelatives(self.sf_negative, allDescendents=True):
            cmds.delete(self.sf_negative)
        #--- delete the result group
        if not cmds.listRelatives(self.sf_result, allDescendents=True):
            cmds.delete(self.sf_result)

        #--- delete the bsp grp
        if not cmds.listRelatives(self.sf_bsp_grp, allDescendents=True):
            cmds.delete(self.sf_bsp_grp)
        #--- delete the blendShapes grp
        if not cmds.listRelatives(self.sf_blendshapes, allDescendents=True):
            cmds.delete(self.sf_blendshapes)
예제 #24
0
 def createCopyAndBlendShape(
     self,
     obj,
     descrip='_FORDEFORMER',
     suf='_NBS'
 ):  #crea el duplicado y luego lo adiere al original mediante un blendshape
     if not cmds.objExists(str(obj) + descrip):
         if self.existNode(
                 obj,
                 'skinCluster'):  #Solo si tiene un skin hace el bindPose
             #Coloco el objeto a copiar en el origen
             bindPose = cmds.dagPose(str(obj), q=True, bindPose=True)[0]
             cmds.dagPose(bindPose, restore=True)
         #Duplica el objeto para trabajarlo
         copy = cmds.duplicate(obj, n=obj + descrip)[0]
         nbs = str(obj) + suf
         #Crea blendshape si no existe lo agrega
         if cmds.objExists(str(obj) + suf):
             try:
                 waithBsh = cmds.blendShape(obj + suf, q=True, wc=True)
                 nbs = cmds.blendShape(
                     obj + suf,
                     edit=True,
                     target=[obj, waithBsh + 1,
                             str(copy), 1.0])[0]
             except:
                 pass
         else:
             nbs = cmds.blendShape([copy, obj], n=obj + suf)[0]
         return copy, nbs
     else:
         cmds.warning('Ya existe el deformador ' + obj + descrip)
예제 #25
0
def makeCopies(default_blendshape, target_mesh):
    
    target_mesh_copy = cmds.duplicate(target_mesh, n='{}_COPY'.format(target_mesh), 
                                      returnRootsOnly=True)
                                          
    cmds.transferAttributes(default_blendshape, target_mesh,
                            transferPositions=1,
                            transferNormals=0,
                            transferUVs=2,
                            transferColors=2,
                            sampleSpace=3,
                            sourceUvSpace=utils.getCurrentUV(default_blendshape),
                            targetUvSpace=utils.getCurrentUV(target_mesh),
                            searchMethod=3,
                            flipUVs=0,
                            colorBorders=1)
                            
    target_mesh_final = cmds.duplicate(target_mesh, n='{}_FINAL'.format(target_mesh), 
                                      returnRootsOnly=True)
                                      
    create_blendshape = cmds.blendShape(target_mesh, target_mesh_copy, target_mesh_final, 
                    automatic=True, name='{}_BS'.format(default_blendshape))

    cmds.blendShape('{}.{}'.format(create_blendshape[0], 
                    target_mesh), edit=True, 
                    w=[(0, 1.0), (1, 1.0)])
                    
    cmds.delete(target_mesh_copy)
    
    # returns the mesh that will serve as a dummy to create new duplicates from
    return target_mesh_final
예제 #26
0
파일: sf_tool.py 프로젝트: jonntd/Public
    def __remove_blendshapes(self):
        #--- this method removes the blendShape nodes
        #--- remove blendShape connection
        cmds.blendShape(self.mesh_bsp, 
                        edit = True, 
                        topologyCheck = False, 
                        remove = True, 
                        target = ((self.mesh, self.target_index, self.mesh_result, 1),
                                  (self.mesh, self.target_index, self.mesh, 1)))
        #--- remove the sculpt mesh
        cmds.delete(self.mesh_sculpt)
        #--- remove the negative mesh
        cmds.delete(self.mesh_negative)
        #--- remove the result mesh
        cmds.delete(self.mesh_result)

        #--- delete the sculpt group
        if not cmds.listRelatives(self.sf_sculpt, allDescendents = True):
            cmds.delete(self.sf_sculpt)
        #--- delete the negative group
        if not cmds.listRelatives(self.sf_negative, allDescendents = True):
            cmds.delete(self.sf_negative)
        #--- delete the result group
        if not cmds.listRelatives(self.sf_result, allDescendents = True):
            cmds.delete(self.sf_result)

        #--- delete the bsp grp
        if not cmds.listRelatives(self.sf_bsp_grp, allDescendents = True):
            cmds.delete(self.sf_bsp_grp)
        #--- delete the blendShapes grp
        if not cmds.listRelatives(self.sf_blendshapes, allDescendents = True):
            cmds.delete(self.sf_blendshapes)
예제 #27
0
def mBS():
    oText = mc.textField('original', q=True, tx=True)
    rText = mc.textField('replace', q=True, tx=True)

    sel = mc.ls(sl=True)
    print(sel)
    mc.duplicate(sel[0], n='revBlend')
    mc.duplicate(sel[0], n='genBlend')
    mc.blendShape(sel[1], 'revBlend', n='tempBlend')

    mc.setAttr('revBlend.sx', -1)

    mc.select('genBlend', 'revBlend')
    mm.eval('CreateWrap')

    mc.setAttr('tempBlend.' + sel[1], 1)
    newBlend = sel[1].replace(oText, rText)
    mc.duplicate('genBlend', n=newBlend)
    mc.delete('genBlend', 'revBlend', 'revBlendBase')
    oX = mc.getAttr(sel[1] + '.tx')
    oY = mc.getAttr(sel[1] + '.ty')
    oZ = mc.getAttr(sel[1] + '.tz')

    mc.setAttr(newBlend + '.tx', oX + 40)
    mc.setAttr(newBlend + '.ty')
    mc.setAttr(newBlend + '.tz')
예제 #28
0
def removeTarget(blendShape,target,baseGeo):
	'''
	Remove the specified blendShape target
	@param blendShape: Name of blendShape to remove target from
	@type blendShape: str
	@param target: BlendShape target to remove
	@type target: str
	@param baseGeo: BlendShape base geometry name
	@type baseGeo: str
	'''
	# Check blendShape
	if not isBlendShape(blendShape):
		raise Exception('Object "'+blendShape+'" is not a valid blendShape node!')

	# Check target
	if not hasTarget(blendShape,target):
		raise Exception('BlendShape "'+blendShape+'" has no target "'+target+'"!')

	# Get target index
	targetIndex = getTargetIndex(blendShape,target)

	# Connect null duplicate
	targetGeo = getTargetGeo(blendShape,target,baseGeo)
	if not targetGeo:
		mc.setAttr(blendShape+'.envelope',0.0)
		targetGeo = mc.duplicate(baseGeo)[0]
		mc.setAttr(blendShape+'.envelope',1.0)
		connectToTarget(blendShape,targetGeo,target,baseGeo,1.0,force=True)

	# Remove target
	mc.blendShape(blendShape,e=True,rm=True,t=[baseGeo,targetIndex,targetGeo,1.0])
예제 #29
0
def removeTarget(blendShape, target, baseGeometry):
    '''
	Remove the specified blendShape target
	@param blendShape: Name of blendShape to remove target from
	@type blendShape: str
	@param target: BlendShape target to remove
	@type target: str
	@param baseGeometry: BlendShape base geometry name
	@type baseGeometry: str
	'''
    # Check blendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape +
                        '" is not a valid blendShape node!')

    # Get target index
    targetIndex = getTargetIndex(blendShape, target)

    # Connect null duplicate
    mc.setAttr(blendShape + '.envelope', 0.0)
    dup = mc.duplicate(baseGeometry)
    mc.setAttr(blendShape + '.envelope', 1.0)
    connectToTarget(blendShape, dup[0], target, baseGeometry, 1.0, force=True)

    # Remove target
    mc.blendShape(blendShape,
                  e=True,
                  rm=True,
                  t=[baseGeometry, targetIndex, dup[0], 1.0])

    # Delete duplicate geometry
    mc.delete(dup)
예제 #30
0
def eyebalRder(pfx):
    """pfx Rendre Anim
    lr L_ R_
    """
    sls = mc.ls(sl=True)
    size = len(sls)
    if size==0:
        print "No geo selected!"
        return
    #gusLR
    lr = "L" if re.search("L$",sls[0])!=None else "R"
    nameLs = ["RigToSSS_Eye%s%s"%(pfx,lr),"SSSToFinal_Eye%s%s"%(pfx,lr)]
    sufxs = ["_SSS","_Final"]
    origin = ["world","local"]
    blsGeos = sls[:]
    for idx,name in enumerate(nameLs):
        sss_grp = mc.createNode( "transform",name="%s_grp"%nameLs[idx] )
        for n,geo in enumerate(sls):
            dup = mc.duplicate( geo )
            clds = mc.listRelatives(dup[0],c=True,type="transform",f=True)
            if len(clds)>1:
                mc.delete( clds )
            newObj = mc.rename( dup[0],"%s%s"%(geo,sufxs[idx]) )
            #print "geo,newObj",geo,newObj
            mc.parent(newObj,sss_grp)
            blsGeos.append(newObj)
    idxs = [0]
    for n in range( size,size*3,size ):
        idxs.append( n )
    for mi in range(size):
        for n in range( len(idxs)-1 ):
            ma = idxs[n]+mi
            mb = idxs[n+1]+mi
            shapeMa = mc.listRelatives(blsGeos[ma],c=True,type="mesh",f=True)
            mc.blendShape( shapeMa[0],blsGeos[mb],o=origin[n],name="%s_bls"%nameLs[n],weight=[0,1] )
예제 #31
0
    def on_btn_FixBsEnd_clicked(self, clicked=None):
        if clicked == None: return

        #-
        selectIndexes = self.listView_attributeList.selectedIndexes()
        if len(selectIndexes) == 0: return

        selectAttr = self.__AttributeModel.data(selectIndexes[0],
                                                QtCore.Qt.DisplayRole)
        #-
        if not uiTool.warning(
                'BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'
                % selectAttr):
            return

        if mc.objExists(selectAttr):
            mc.blendShape(self.__sculpmodel, selectAttr, w=((0, 1)))
            mc.delete(selectAttr, ch=True)
            mc.delete(self.__sculpmodel)

        else:
            shape = mc.listRelatives(self.__sculpmodel, s=True, path=True)[0]

            weightID = self.__AttributeDT2.get(selectAttr, None)
            TGTattr = self.__IGTAttributeDT.get(weightID, None)
            mc.connectAttr('%s.worldMesh[0]' % shape,
                           '%s.%s' % (self.__blendShape, TGTattr),
                           f=True)
            mc.rename(self.__sculpmodel, selectAttr)

        mc.delete(self.__tempmodel)
예제 #32
0
    def on_btn_FixBsEnd_clicked(self, clicked=None):
        if clicked == None:return

        #-
        selectIndexes = self.listView_attributeList.selectedIndexes()
        if len(selectIndexes) == 0:return

        selectAttr = self.__AttributeModel.data(selectIndexes[0], QtCore.Qt.DisplayRole)
        #-
        if not uiTool.warning('BlendShape\'s shape on attribute "%s" will be changed,\nand it can\'t to undo, \ncontinue? ?'%selectAttr):return


        if mc.objExists(selectAttr):
            mc.blendShape(self.__sculpmodel, selectAttr, w=((0, 1)))
            mc.delete(selectAttr, ch=True)
            mc.delete(self.__sculpmodel)

        else:
            shape = mc.listRelatives(self.__sculpmodel, s=True, path=True)[0]

            weightID = self.__AttributeDT2.get(selectAttr, None)
            TGTattr  = self.__IGTAttributeDT.get(weightID, None)
            mc.connectAttr('%s.worldMesh[0]'%shape, '%s.%s'%(self.__blendShape, TGTattr), f=True)
            mc.rename(self.__sculpmodel, selectAttr)

        mc.delete(self.__tempmodel)
예제 #33
0
def removeTarget(blendShape,target,baseGeometry):
	'''
	Remove the specified blendShape target
	@param blendShape: Name of blendShape to remove target from
	@type blendShape: str
	@param target: BlendShape target to remove
	@type target: str
	@param baseGeometry: BlendShape base geometry name
	@type baseGeometry: str
	'''
	# Check blendShape
	if not isBlendShape(blendShape):
		raise Exception('Object "'+blendShape+'" is not a valid blendShape node!')
	
	# Get target index
	targetIndex = getTargetIndex(blendShape,target)
	
	# Connect null duplicate
	mc.setAttr(blendShape+'.envelope',0.0)
	dup = mc.duplicate(baseGeometry)
	mc.setAttr(blendShape+'.envelope',1.0)
	connectToTarget(blendShape,dup[0],target,baseGeometry,1.0,force=True)
	
	# Remove target
	mc.blendShape(blendShape,e=True,rm=True,t=[baseGeometry,targetIndex,dup[0],1.0])
	
	# Delete duplicate geometry
	mc.delete(dup)
예제 #34
0
파일: BSM.py 프로젝트: jonntd/mla_marTool
    def remove_blendshape_target(self):
        """
        Add blendShape target(s) to the specified blendShape node (see ui).
        """

        # --- Open history chunk
        mc.undoInfo(openChunk=True)
        try:
            # --- Get datas from ui
            datas = self.get_ui_datas()

            for target in datas[1]:
                if mc.objExists(target) is False or self.blendshapes_datas[datas[0]]['type'] == 'DPK_bcs':
                    self.extract_blendshape_target(target, delete=True)
                else:
                    # --- Get index
                    index = self.get_target_index(target)
                    # --- Get base
                    base = self.get_blendshape_base()
                    # --- Remove it
                    mc.blendShape(datas[0], edit=True, remove=True, target=(base, index, target, 1.0))

                self.refresh_ui()
        finally:
            mc.undoInfo(closeChunk=True)
예제 #35
0
def add_target_shape(mesh_name="",
                     target_mesh="",
                     target_name="",
                     target_value=1.0):
    """
    adds a target blend shape shape to this mesh.
    :param mesh_name: <str> the mesh name to attach blend shape to.
    :param target_mesh: <str> the target mesh.
    :param target_name: <str> the blendShape target attribute name.
    :param target_value: <float>
    :return: <str> blendShape name, attribute target.
    """
    blend_node = get_connected_blendshape_nodes(mesh_name)
    if not blend_node:
        blend_node = create_blend_shape(mesh_name,
                                        deform_order='before',
                                        origin='local')
    if blend_node:
        blend_node = blend_node[0]
    target_index = len(get_blendshape_targets(blend_node)) + 1
    if target_name:
        if not cmds.objExists(target_name):
            cmds.rename(target_mesh, target_name)
    cmds.blendShape(blend_node,
                    edit=True,
                    t=(mesh_name, target_index, target_name, target_value))
    return blend_node
    def CreateMirrorShape(self,base_shape,sculpt_shape):
        if base_shape and sculpt_shape:
            if "L_" in sculpt_shape and "left" not in sculpt_shape and "right" not in sculpt_shape:
                newShape="R_{0}".format(sculpt_shape.split('L_')[1])
                print sculpt_shape,newShape
            elif "R_" in sculpt_shape and "left" not in sculpt_shape and "right" not in sculpt_shape:
                newShape="L_{0}".format(sculpt_shape.split('R_')[1])
                print sculpt_shape,newShape
            elif "L_" in sculpt_shape and "left" in sculpt_shape and "right" not in sculpt_shape:
                newShape="R_{0}right{1}".format(sculpt_shape.split('L_')[1].split('left')[0],sculpt_shape.split('L_')[1].split('left')[1])
                print sculpt_shape,newShape
            elif "L_" in sculpt_shape and "left" not in sculpt_shape and "right" in sculpt_shape:
                newShape="R_{0}left{1}".format(sculpt_shape.split('L_')[1].split('right')[0],sculpt_shape.split('L_')[1].split('right')[1])
                print sculpt_shape,newShape
            elif "R_" in sculpt_shape and "left" in sculpt_shape and "right" not in sculpt_shape:
                newShape="L_{0}right{1}".format(sculpt_shape.split('R_')[1].split('left')[0],sculpt_shape.split('R_')[1].split('left')[1])
                print sculpt_shape,newShape
            elif "R_" in sculpt_shape and "left" not in sculpt_shape and "right" in sculpt_shape:
                newShape="L_{0}left{1}".format(sculpt_shape.split('R_')[1].split('right')[0],sculpt_shape.split('R_')[1].split('right')[1])
                print sculpt_shape,newShape
            elif "M_" in sculpt_shape and "left" not in sculpt_shape and "right" in sculpt_shape:
                newShape="{0}left{1}".format(sculpt_shape.split('right')[0],sculpt_shape.split('right')[1])
                print sculpt_shape,newShape
            elif "M_" in sculpt_shape and "left" in sculpt_shape and "right" not in sculpt_shape:
                newShape="{0}right{1}".format(sculpt_shape.split('left')[0],sculpt_shape.split('left')[1])
                print sculpt_shape,newShape
            else:
                newShape="Mirrored_{0}".format(sculpt_shape)
                print sculpt_shape,newShape
            
            #Create Wrap and Negative shape
            cmds.duplicate(base_shape, name="baseWrap")
            cmds.duplicate(base_shape, name="baseScaleNeg")
            
            #Flip Scale  
            cmds.setAttr("baseScaleNeg.scaleX", -1)

            #Blend Sculped shape to flipped shape
            cmds.blendShape(sculpt_shape, 'baseScaleNeg', name='TempBlend')
            
            #Create Wrap between wrap shape and Neg Shape
            cmds.select(cl=True)
            cmds.select('baseWrap')
            cmds.select('baseScaleNeg', add=True)
            cmds.CreateWrap()
            cmds.select(cl=True)
            
            cmds.setAttr("wrap1.exclusiveBind", 1)

            #Now turn on our Negated blendShpe
            cmds.setAttr("TempBlend."+sculpt_shape, 1)

            #Duplicate Wrapped shape for final result
            new_shape = cmds.duplicate('baseWrap', name=newShape)
            if cmds.listRelatives(new_shape,p=True):
                cmds.parent(new_shape,w=True)
            
            #Clean up setup
            cmds.delete('baseWrap', 'baseScaleNeg')
예제 #37
0
def addDummyToMasterBlendshape(master,dummy):
	"""
	Adds the template blendshape with the corrective substraction
	to the master blendshape.
	"""
	blendshape_node = getBlendshapesFromMaster(master)[0]
	weight_count = getBlendshapeWeightCount(master)
	blendShape(master, e=True, t=[master, weight_count+1,dummy,1])
예제 #38
0
def extractDeltas(original, sculpted, rest):
    '''
	Get the difference between the original and the sculpted meshes
	Then apply that difference to the rest
	'''
    extractedDeltas = cmds.duplicate(rest, name="extractedDeltas")[0]
    deltaBlends = cmds.blendShape(sculpted, original, extractedDeltas)
    cmds.blendShape(deltaBlends, edit=True, weight=((0, 1), (1, -1)))
def set_BS_to_0():
    names = cmds.listAttr( "blendShape1", m=True, k=True )[1:] # List of blendshape attributes (without envelope)
    keyAttr = []
    nullAttr = ()
    for k in range( len(names) ):
        nullAttr = ( k, 0 )
        keyAttr.append( nullAttr )
    cmds.blendShape( 'blendShape1', edit=True, w=keyAttr )
예제 #40
0
def connectToTarget(blendShape,geometry,target,baseGeometry,weight=1.0,force=False):
	'''
	Connect a new target geometry to a specified blendShape target
	@param blendShape: Name of blendShape to connect geometry target to
	@type blendShape: str
	@param geometry: Geometry to connect to blendShape target
	@type geometry: str
	@param target: BlendShape target name to connect geometry to
	@type target: str
	@param baseGeometry: BlendShape base geometry name
	@type baseGeometry: str
	@param weight: BlendShape target weight value to connect geometry to
	@type weight: float
	'''
	# Check blendShape
	if not isBlendShape(blendShape):
		raise Exception('Object "'+blendShape+'" is not a valid blendShape node!')
	
	# Check target
	if not mc.objExists(blendShape+'.'+target):
		raise Exception('Blendshape "'+blendShape+'" has no target "'+target+'"!')
	
	# Check geometry
	if not mc.objExists(geometry):
		raise Exception('Geometry object "'+geometry+'" does not exist!')
	
	# Get target index
	targetIndex = getTargetIndex(blendShape,target)
	
	# FORCE connection
	if force:
		
		# Get geometry details
		geomIndex = glTools.utils.deformer.getGeomIndex(baseGeometry,blendShape)
		geomShape = mc.listRelatives(geometry,s=True,ni=True)
		if geomShape:
			geomShape = geomShape[0]
			geomType = mc.objectType(geomShape)
		else:
			geomShape = geometry
			geomType = 'none'
		
		# Get geometry type output attribute.
		# Non dict values allow specific node attributes to be connected!!
		geomDict = {'mesh':'.worldMesh[0]','nurbsSurface':'.worldSpace[0]','nurbsCurve':'.worldSpace[0]'}
		if geomDict.has_key(geomType): geomAttr = geomDict[geomType]
		else: geomAttr = ''
		
		# Get weight index
		wtIndex = int(weight*6000)
		
		# Connect geometry to target input
		mc.connectAttr(geomShape+geomAttr,blendShape+'.inputTarget['+str(geomIndex)+'].inputTargetGroup['+str(targetIndex)+'].inputTargetItem['+str(wtIndex)+'].inputGeomTarget',f=True)
		
	else:
		
		# Connect geometry to target input
		mc.blendShape(blendShape,e=True,t=[baseGeometry,targetIndex,geometry,weight])
예제 #41
0
def addTargetInbetween(blendShape,
                       targetGeo,
                       targetName,
                       base='',
                       targetWeight='0.5'):
    '''
	Add a new target inbetween to the specified blendShape target
	@param blendShape: Name of blendShape to remove target from
	@type blendShape: str
	@param targetGeo: New blendShape target inbetween geometry
	@type targetGeo: str
	@param targetName: BlendShape target name to add inbetween target to
	@type targetName: str
	@param base: BlendShape base geometry. If empty, use first connected base geomtry
	@type base: str
	@param targetWeight: BlendShape inbetween target weight value
	@type targetWeight: str
	'''
    # ==========
    # - Checks -
    # ==========

    # BlendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape +
                        '" is not a valid blendShape node!')

    # Target
    if not mc.objExists(targetGeo):
        raise Exception('Target geometry "' + target + '" does not exist!')
    if not hasTarget(blendShape, targetName):
        raise Exception('BlendShape "' + blendShape + '" has no target "' +
                        targetName + '"!')

    # Base
    if base and not mc.objExists(base):
        raise Exception('Base geometry "' + base + '" does not exist!')

    # ========================
    # - Add Target Inbetween -
    # ========================

    # Get Base Geometry
    if not base: base = getBaseGeo(blendShape)[0]

    # Get Target Index
    targetIndex = getTargetIndex(blendShape, targetName)

    # Add Target
    mc.blendShape(blendShape,
                  e=True,
                  t=(base, targetIndex, targetGeo, targetWeight))

    # =================
    # - Return Result -
    # =================

    return (blendShape + '.' + targetName)
예제 #42
0
def animFixShape(fixShape):
	objs=mc.ls(sl=1)
	numVtx=mc.polyEvaluate(objs[1],v=1)
	skinMeshShapes=mc.listRelatives(objs[1],s=1,pa=1)
	skinMeshShapes1=mc.listRelatives(objs[1],s=1,ni=1,pa=1)
	fixMeshShape=mc.listRelatives(objs[0],s=1,ni=1,pa=1)[0]
	inputs=mc.listHistory(objs[1])
	for i in skinMeshShapes:
		if not i in skinMeshShapes1:
			intermediateShape=i
			break
	BSNode=None
	for n in inputs:
		if 'animFixBS' in n and mc.nodeType(n)=='blendShape':
			BSNode=n
	if not BSNode:
	    BSNode=mc.blendShape(objs[1],parallel=1,n='animFixBS')[0]
	if not mc.objExists('animFixCtrl'):
		createCtrl()
		
	mc.addAttr('animFixCtrl',ln=fixShape,at='double',min=0,max=1,dv=0,k=1)
	weightAttrs=mc.listAttr(BSNode+'.weight',m=1)
	weightListNum=0
	if weightAttrs:
	    weightListNum=len(weightAttrs)
	beforeFixMesh=mc.duplicate(objs[1],n='beforeFixMesh')[0]
	buildBSMesh=mc.duplicate(objs[1],n='buildBlendShapeMesh')[0]
	mc.hide(buildBSMesh)
	buildBSMeshShapes=mc.listRelatives(buildBSMesh,s=1,pa=1)
	buildBSMeshShapes1=mc.listRelatives(buildBSMesh,s=1,ni=1,pa=1)
	for i in buildBSMeshShapes:
		if not i in buildBSMeshShapes1:
			buildBSMeshShape=i
			break
	mc.setAttr(buildBSMeshShape+'.intermediateObject',0)
	mc.delete(buildBSMeshShapes1)
	
	buildBSNode=mc.blendShape(beforeFixMesh,objs[0],buildBSMesh,foc=1,w=[(0,-1),(1,1)],n='buildFixBs')[0]
	
	mc.blendShape(BSNode,e=1,t=[objs[1],weightListNum,buildBSMesh,1])
	
	BSTargets=mc.listAttr(BSNode+'.weight',m=1)
	mc.connectAttr('animFixCtrl.'+fixShape,BSNode+'.'+BSTargets[-1])
	
	'''for i in range(0,numVtx):
		ipos=mc.xform(intermediateShape+'.vtx[%d]'%i,q=1,os=1,t=1)
		tPos=mc.xform(objs[0]+'.vtx[%d]'%i,q=1,os=1,t=1)
		bPos=mc.xform(objs[1]+'.vtx[%d]'%i,q=1,os=1,t=1)
		mc.xform(objs[0]+'.vtx[%d]'%i,os=1,t=[(ipos[0]+tPos[0]-bPos[0]),(ipos[1]+tPos[1]-bPos[1]),(ipos[2]+tPos[2]-bPos[2])])'''
	mc.delete(beforeFixMesh)
	#mc.deleteUI('animFixWin')
	mc.setAttr('animFixCtrl.'+fixShape,1)
	if not mc.objExists('targetShapesGrp'):
	    targetGrp=mc.group(em=1,n='targetShapesGrp')
	    mc.parent(targetGrp,'animFixGrp')
	shapeTmpGrp=mc.group(buildBSMesh,objs[0],n=fixShape+'_TmpGrp')
	mc.parent(shapeTmpGrp,'targetShapesGrp')
예제 #43
0
def buildExpressionRig(char):
    """
    Build main generic expression driver rig from imported components.
    @param char: The character to build expression rig for
    @type char: str
    """
    # ---------------------------
    # - Define constant strings -
    # ---------------------------

    face_mesh = 'face_mesh'
    face_expressionDelta_mesh = 'face_expressionDelta_mesh'
    shapeAdd_blendShape = 'shapeAdd_blendShape'
    targetToSwitchOff = 'shapes_face_mesh'

    base_prefs_null = 'base_prefs_null'
    base_prefs_attr = 'expressionShape'

    # ---------------------
    # - Import Components -
    # ---------------------

    # Expression Sculpts
    glTools.utils.dnpublish.importExpressionSculpts(char)

    # Expression Regions Deltas
    print('IMPORTING: ' + char.upper() + ' Expression Deltas')
    expressionDeltaPath = '/jobs/JCOM/ldev_' + char.lower() + '/rig/scenes/face/expressionIntegrate/expression/' + char.upper() + '_FACE_expressionDelta.mb'
    cmds.file(expressionDeltaPath, i=True, type='mayaBinary', rpr="_", options='v=0', pr=False)

    # Measurements
    print('IMPORTING: ' + char.upper() + ' Face Measurements')
    measurementPath = '/jobs/JCOM/ldev_' + char.lower() + '/rig/scenes/face/expressionIntegrate/measure/' + char.upper() + '_FACE_measure.mb'
    cmds.file(measurementPath, i=True, type='mayaBinary', rpr="_", options='v=0', pr=False)

    # ------------------------------------------
    # - Connect To Expression Delta BlendShape -
    # ------------------------------------------

    nextTargetIndex = glTools.utils.blendShape.nextAvailableTargetIndex(shapeAdd_blendShape)
    cmds.blendShape(shapeAdd_blendShape, e=True, t=(face_mesh, nextTargetIndex, face_expressionDelta_mesh, 1.0))
    cmds.setAttr(shapeAdd_blendShape + '.face_expressionDelta_mesh', 1)
    if cmds.objExists(shapeAdd_blendShape + '.' + targetToSwitchOff):
        cmds.setAttr(shapeAdd_blendShape + '.' + targetToSwitchOff, 0)

    face_mesh_grp = cmds.listRelatives(face_mesh, p=True)[0]
    cmds.parent(face_expressionDelta_mesh, face_mesh_grp)
    cmds.setAttr(face_expressionDelta_mesh + '.v', 0)

    # ----------------------------
    # - Add Detail Switch to Rig -
    # ----------------------------

    cmds.addAttr(base_prefs_null, ln=base_prefs_attr, dv=1.0, min=0.0, max=1.0)
    cmds.setAttr(base_prefs_null + '.' + base_prefs_attr, 1, e=True, cb=True)
    cmds.connectAttr(base_prefs_null + '.' + base_prefs_attr, shapeAdd_blendShape + '.' + face_expressionDelta_mesh,
                   f=True)
예제 #44
0
def shapeExtract_weights(baseGeo,targetGeo,weightList,deleteHistory=True,name=''):
	'''
	Extract a portioin of a blendShape target based on a list of vertex weight value
	@param baseGeo: Base geometry shape
	@type baseGeo: str
	@param targetGeo: Target geometry shape
	@type targetGeo: str
	@param weightList: Weight list to apply to extracted shape blendShape weights
	@type weightList: list
	@param deleteHistory: Delete blendShape history
	@type deleteHistory: bool
	@param name: Name for extracted shape
	@type name: str
	'''
	# =========
	# - Check -
	# =========
	
	# Check base geo
	if not mc.objExists(baseGeo):
		raise Exception('Base geometry "'+baseGeo+'" does not exist!')
		
	# Check target geo
	if not mc.objExists(targetGeo):
		raise Exception('Target geometry "'+targetGeo+'" does not exist!')
	
	# =================
	# - Extract Shape -
	# =================
	
	if not name: name = targetGeo+'_extract'
	
	# Determine blendShape geometry
	if mc.objExists(name):
		blendGeo = name
		m_blendShape = mc.blendShape(baseGeo,blendGeo)[0]
		m_blendAlias = mc.listAttr(m_blendShape+'.w',m=True)[0]
		mc.setAttr(m_blendShape+'.'+m_blendAlias,1.0)
		mc.delete(blendGeo,ch=True)
	else:
		blendGeo = mc.duplicate(baseGeo,n=name)[0]
	
	# Create blendShape to target
	blendShape = mc.blendShape(targetGeo,blendGeo)[0]
	mc.setAttr(blendShape+'.'+targetGeo,1)
	
	# Set belndShape target weights
	glTools.utils.blendShape.setTargetWeights(blendShape,targetGeo,weightList,blendGeo)
	
	# Delete history on duplicated geometry
	if deleteHistory: mc.delete(blendGeo,constructionHistory=True)
		
	# =================
	# - Return Result -
	# =================
	
	return blendGeo
예제 #45
0
def splitShapeSetup():

    # create 3 splitOutput meshes that will be painted
    # start with creating the splitters
    selection = cmds.ls(sl=True)
    meshList = selection[:-1]
    base = selection[-1]

    splitters = []
    blends = []
    meshes = ["A", "B", "C"]
    inputMeshList = meshList

    # first target plays an important role, this is the one we're going to default turn on and align to in tx
    first = meshList[0]
    for i, letter in enumerate(meshes):
        # create splitters
        split = "{0}_split{1}".format(base, letter)
        cmds.duplicate(base, n=split)
        cmds.delete(cmds.parentConstraint(first, split))
        # how far to move the dup
        dist = (int(i) + 1) * 10
        cmds.move(dist, 0, 0, split, r=True)

        blend = "{0}_BSHP".format(split)
        cmds.select(split)
        cmds.blendShape(n=blend)
        splitters.append(split)
        blends.append(blend)

    # add blends and set them too yada yada
    blendDrivers = []
    blendDrivers = blendDrivers + meshList
    for i, split in enumerate(splitters):

        # connections?
        cmds.select(blendDrivers)
        cmds.select(split, tgl=True)
        mel.eval("performBlendShapeAdd 0;")
        blendDrivers.append(split)

        # if a splitter, set to -1
        for s in splitters:
            splitBshp = "{0}.{1}".format(blends[i], s)
            if cmds.objExists(splitBshp):
                cmds.setAttr(splitBshp, -1)

    # Turn on the first. Just as a default
    for blend in blends:
        cmds.setAttr("{0}.{1}".format(blend, first), 1)

        # connect all meshList input shapes to each other
        for i, target in enumerate(inputMeshList):
            print inputMeshList
            if blend != blends[0]:
                cmds.connectAttr("{0}.{1}".format(blends[0], target),
                                 "{0}.{1}".format(blend, target))
예제 #46
0
def createbs(crv, bsname, partname):
    if cmds.objExists(partname) == 0:
        cmds.group(em=1, n=partname)
    else:
        pass
    crv1 = 'crv_' + bsname
    cmds.duplicate(crv, n='crv_' + bsname)
    cmds.parent(crv1, partname)
    cmds.blendShape(crv1, crv, tc=0, ib=0, n='bs_' + partname)
예제 #47
0
파일: cacheFile.py 프로젝트: skarone/PipeL
def createBlendshape( replace = [ 'Rig', 'Final' ]):
	"""create blendshape between RIG and FINAL
	FINAL allways is the render asset"""
	sel = mn.ls( sl = True, s = True, dag = True, ni = True )
	if sel:
		sel = mn.ls( sel[0].name[:sel[0].name.rindex(':')] + ':*', dag = True, ni = True, typ = 'mesh' )
	for r in sel:
		rSha = mn.Node( r.name.replace( replace[0], replace[1] ) )
		blend = mc.blendShape( r.name, rSha.name, o = 'world' )[0]
		mc.blendShape( blend, edit=True, w=[(0, 1)] )
예제 #48
0
def getGeoInputsOld(resultGeo='ZBrush_defualt_group002', correctiveGeo=['breast_Geo', 'pin_Geo'], importList=['pin', 'breast'], *args):
    geoMap = {'ZBrush_defualt_group002': ['breast_Geo', 'pin_Geo'], '__CLASHCLASH___ZBrush_defualt_group002': ['breast_Geo_M', 'pin_Geo_M'], '__CLASHCLASH___ZBrush_defualt_group003': ['breast_Geo_H', 'pin_Geo_H']}

    # Assume that the current open file has been opened from the correct directory and get the base path from that
    path = os.path.dirname(cmds.file(query=True, exn=True))
    # import the face assets, items in list are actual file names
    importFaceAssets(path, importList=importList)

    head = extractShapeNode(resultGeo, False)
    headOrig = extractShapeNode(resultGeo, True)
    # hood = extractShapeNode('breast_Geo', False)
    # chest = extractShapeNode('pin_Geo', False)
    # new
    # Duplicate the head_Geo, this is used and an intermediate from the head_Geo and the blendshapes
    headInter = cmds.duplicate(head, name=head + '_intermediateGeo')[0]
    corr = []
    for geo in correctiveGeo:
        corr.append(extractShapeNode(geo, False))
    corr.append(headInter)
    # new end

    # create the blendShape
    # blendNode = cmds.blendShape(hood, chest, headInter, n='face_blendshape') # old
    blendNode = cmds.blendShape(corr, n='face_blendshape')  # new

    # set the blendNode target weights
    trgCnt = len(cmds.blendShape(blendNode, query=True, t=True))
    for i in range(0, trgCnt, 1):
        cmds.blendShape(blendNode, edit=True, w=(i, 1))
    '''
    # Visibility list
    setVisList = ['chest_Geo', 'hood_Geo', 'hood_root_jnt', 'sculpt_Geo', 'faceUtil_Gp', 'faceJnt_Gp', headInter, 'head_FrGeo', 'Lf_eye_FrGeo', 'Lf_eyeouter_FrGeo',
                  'Lf_eyewater_FrGeo', 'Rt_eye_FrGeo', 'Rt_eyeouter_FrGeo', 'Rt_eyewater_FrGeo', 'tongue_FrGeo']
    setFaceItemsVis(setVisList)
    '''
    # Connect the blendShape to the Orig node
    cmds.connectAttr(blendNode[0] + '.outputGeometry[0]', headOrig + '.inMesh', force=True)
    #
    X = cmds.floatField('atom_srig_conScale', query=True, value=True)
    # clean up geo and joints
    for geo in corr:
        place.cleanUp(geo, Utility=True)
    # floaters
    slave, master = dfrm.floatingControl(name='pin', parent='clavicle_jnt_02_L', joint='pin_jnt', size=X * 6, shape='arrow_ctrl')
    place.cleanUp(slave[0], World=True)
    place.cleanUp(master[0], Ctrl=True)
    slave, master = dfrm.floatingControl(name='breast_L', parent='spine_jnt_06', joint='breast_jnt_L', size=X * 15, shape='arrow_ctrl')
    place.cleanUp(slave[0], World=True)
    place.cleanUp(master[0], Ctrl=True)
    slave, master = dfrm.floatingControl(name='breast_R', parent='spine_jnt_06', joint='breast_jnt_R', size=X * 15, shape='arrowInv_ctrl')
    place.cleanUp(slave[0], World=True)
    place.cleanUp(master[0], Ctrl=True)
예제 #49
0
	def pop( self, targetToRemove ):
		'''pops the given shape name or shape index out of the blendShape node - creating the object in
		the scene, and removing it from the blendShape node'''
		targets = self.targets
		indicies = self.indicies
		if targetToRemove in targets:
			blendIdx = self.getTargetIdx(targetToRemove)
			shape = self.expand(targetToRemove)
			cmd.blendShape(self.name,edit=True,remove=True,target=(self.obj,blendIdx,shape,1.0))

			return shape
		else:
			raise AttributeError("target doesn't exist")
예제 #50
0
def addTargetInbetween(blendShape, targetGeo, targetName, base='', targetWeight='0.5'):
    """
    Add a new target inbetween to the specified blendShape target
    @param blendShape: Name of blendShape to remove target from
    @type blendShape: str
    @param targetGeo: New blendShape target inbetween geometry
    @type targetGeo: str
    @param targetName: BlendShape target name to add inbetween target to
    @type targetName: str
    @param base: BlendShape base geometry. If empty, use first connected base geomtry
    @type base: str
    @param targetWeight: BlendShape inbetween target weight value
    @type targetWeight: str
    """
    # ==========
    # - Checks -
    # ==========

    # BlendShape
    if not isBlendShape(blendShape):
        raise Exception('Object "' + blendShape + '" is not a valid blendShape node!')

    # Target
    if not cmds.objExists(targetGeo):
        raise Exception('Target geometry "' + target + '" does not exist!')
    if not hasTarget(blendShape, targetName):
        raise Exception('BlendShape "' + blendShape + '" has no target "' + targetName + '"!')

    # Base
    if base and not cmds.objExists(base):
        raise Exception('Base geometry "' + base + '" does not exist!')

    # ========================
    # - Add Target Inbetween -
    # ========================

    # Get Base Geometry
    if not base: base = getBaseGeo(blendShape)[0]

    # Get Target Index
    targetIndex = getTargetIndex(blendShape, targetName)

    # Add Target
    cmds.blendShape(blendShape, e=True, t=(base, targetIndex, targetGeo, targetWeight))

    # =================
    # - Return Result -
    # =================

    return (blendShape + '.' + targetName)
예제 #51
0
 def _UI(self,*args):
     target_nodes = cmds.blendShape(blendshape_node[0],q=True,t=True)
     target_weights = cmds.blendShape(blendshape_node[0],q=True,w=True)
     if len(target_nodes)>0:
         w = 300
         if cmds.window('blendshapeWin',exists=True):cmds.deleteUI('blendshapeWin',window=True)
         cmds.window('blendshapeWin',t='BlendShape Editor',w=w,rtf=1,mxb=0,mnb=0,s=0)
         #cmds.columnLayout("mainColumn",p="blendshapeWin",columnAttach=('both', 2), rowSpacing=10, columnWidth=w)
         cmds.rowColumnLayout('mainRowColumn',p='blendshapeWin',numberOfColumns=3, columnWidth=[(1, 100), (2, 150), (3, 50)] )
         for i,tgt in enumerate(target_nodes):
             cmds.text(p='mainRowColumn',l=tgt)
             cmds.floatSlider("{0}FltSld".format(tgt),p='mainRowColumn',v=target_weights[i],max=1,min=0,cc=self.updateTargetValue)
             cmds.button(p='mainRowColumn',l='Edit')
         cmds.showWindow('blendshapeWin')
def createCorrectiveBlendshape(master, blendshape1, blendshape2):
	"""
	Creates the corrective blendshape to be reshaped,  using the master as template.
	"""
	corrective_blendshape_pos = getBlendshapePosFromMaster(master)
	corrective_blendshape = "%s_%s_corrective" % (blendshape1, blendshape2)
	duplicate(master, name=corrective_blendshape)
	if (getBlendshapeWeight(master, blendshape1) == 0) and  (getBlendshapeWeight(master, blendshape2) == 0):
		blendShape(blendshape1, blendshape2,corrective_blendshape)
		setBlendshapeWeight(corrective_blendshape, blendshape1, 1)
		setBlendshapeWeight(corrective_blendshape, blendshape2, 1)
		clearHistory(corrective_blendshape)
	move(corrective_blendshape_pos,0,0, corrective_blendshape)
	return corrective_blendshape
예제 #53
0
파일: plot.py 프로젝트: edeglau/storage
 def CurveShapes(self):
     getSel=self.selection_grab()
     if getSel:
         pass
     else:
         return
     getNames=cmds.ls(sl=1, fl=1)
     if ".e[" not in str(getNames[0]):
         print "selection needs to be continuous edges of two seperate polygon objects: first select one, then continuous edge and then the continuous edge on a seperate poly object that you want to deform it along"
         return
     else:
         pass
     getFirstGrp = getNames[0].split(".")[0]
     getSecondGrp = getNames[-1:][0].split(".")[0]
     if getFirstGrp == getSecondGrp:
         print "Only one poly object has been detected. Select one object and it's continuous edge and then select another object and select it's continuous edge for the first object to align to."
         return
     else:
         pass
     firstList=[(each) for each in getNames if each.split(".")[0]==getFirstGrp]
     secondList=[(each) for each in getNames if each.split(".")[0]==getSecondGrp]
     '''create childfirst curve'''
     cmds.select(firstList)
     cmds.CreateCurveFromPoly()
     getFirstCurve=cmds.ls(sl=1, fl=1)
     '''get cv total of curve'''
     getFirstCurveInfo=cmds.ls(sl=1, fl=1)
     numberCV=str(pm.PyNode(getFirstCurveInfo[0]).numCVs())
     cmds.delete(getFirstCurve[0], ch=1)
     '''wrap child mesh to curve'''
     cmds.select(cmds.ls(getFirstGrp)[0], r=1)
     cmds.wire(w=getFirstCurve[0], gw=0, en=1.000000, ce=0.000000, li=0.000000, dds=[(0, 500)] )
     '''create parent curve'''
     cmds.select(secondList)
     cmds.CreateCurveFromPoly()
     getSecondCurve=cmds.ls(sl=1, fl=1)
     getSecondCurveInfo=cmds.ls(sl=1, fl=1)
     '''rebuilt curve to match first curve built'''
     cmds.rebuildCurve(getSecondCurve[0], getFirstCurve[0], rt=2 )
     getSecondCurve=cmds.ls(sl=1, fl=1)
     getSecondCurveInfo=cmds.ls(sl=1, fl=1)
     cmds.delete(getSecondCurve[0], ch=1)
     '''wrap parent curve to parent mesh'''
     cmds.select(getSecondCurve[0], r=1)
     cmds.select(cmds.ls(getSecondGrp)[0], add=1)
     cmds.CreateWrap()
     '''blend child curve to parent curve'''
     cmds.blendShape(getSecondCurve[0], getFirstCurve[0],w=(0, 1.0))
     return getFirstGrp, getSecondGrp
def _add_blend_shape(blend_shape_node, base, target):
    """
    Add target as a blend shape on base, using the blendShape node blend_shape_node.

    Return the index of the new blend shape.
    """
    # Get the next free blend shape target index.  cmds.blendShape won't do this for us.
    existingIndexes = cmds.getAttr('%s.weight' % blend_shape_node, mi=True) or [-1]
    next_index = max(existingIndexes) + 1

    # Add the inverted shape to the blendShape.
    cmds.blendShape(blend_shape_node, edit=True,  t=(base, next_index, target, 1))

    # Return the target index.
    return next_index
예제 #55
0
	def ApplyBlendShapes(self,BSDefinition):
		for BSGroups in BSDefinition:
			BSName = BSGroups + "BS"
			cmds.duplicate(BSDefinition[BSGroups]['original'], name = BSName + BSGroups)
			blendShapeOriginalGeo = BSName + BSGroups
			blendShapeOriginalGeo = self.NameConv.RMRenameNameInFormat( blendShapeOriginalGeo, System = "rig" )
			cmds.blendShape(blendShapeOriginalGeo, name = BSName)
			BSName = self.NameConv.RMRenameNameInFormat(BSName, System = "rig" )
			NumBS = 0
			for keys in BSDefinition[BSGroups]['attributes']:
				if cmds.objExists(keys):
					cmds.blendShape(BSName,edit=True, target=[blendShapeOriginalGeo,NumBS,keys,1.0])
					self.FaceBlendShapeDic[keys]["index"] = NumBS
					self.FaceBlendShapeDic[keys]["Exists"] = True
					NumBS += 1 
예제 #56
0
def interpolateGeometry(geoList, numGeo, prefix='interpGeo'):
    """
    """
    # Initialize outoput list
    dupGeoList = []

    # Generate base Geo
    baseGeo = cmds.duplicate(geoList[0], n=prefix + '_baseGeo')[0]
    baseTargetList = geoList[1:]
    baseBlendShape = cmds.blendShape(baseTargetList, baseGeo)[0]
    baseBlendAlias = cmds.listAttr(baseBlendShape + '.w', m=True)
    baseBlendCount = len(baseBlendAlias)
    baseBlendWeight = 1.0 / baseBlendCount
    for i in range(baseBlendCount): cmds.setAttr(baseBlendShape + '.' + baseBlendAlias[i], baseBlendWeight)

    # Generate interpolated geometry
    for i in range(numGeo):

        # Duplicate Geo as blended
        intGeo = cmds.duplicate(baseGeo, n=prefix + '#')[0]
        cmds.parent(intGeo, w=True)

        # Blend to source geometry
        intBlendShape = cmds.blendShape(geoList, intGeo)[0]
        intBlendAlias = cmds.listAttr(intBlendShape + '.w', m=True)
        intBlendCount = len(intBlendAlias)

        # Generate blend weights
        wt = []
        wtTotal = 0.0
        for i in range(intBlendCount):
            wt.append(random.random())
            wtTotal += wt[-1]
        for i in range(len(wt)):
            wt[i] /= wtTotal

        # Assign blend weights
        for i in range(intBlendCount):
            cmds.setAttr(intBlendShape + '.' + intBlendAlias[i], wt[i])

        # Append output list
        dupGeoList.append(intGeo)

    # Delete base Geo
    cmds.delete(baseGeo)

    # Return result
    return dupGeoList
예제 #57
0
파일: assign.py 프로젝트: jonntd/mayadev-1
 def __init__(self, targets, base ):
     
     targets.append( base )
     
     self._mainBlendShape = cmds.blendShape( *targets, n= base+'_mainBlendShape' )[0]
     
     cmds.addAttr( self._mainBlendShape, ln='isMainBlendShape', at='bool' )