示例#1
0
    def createPV(self, ikHandle):
        '''
        Create a Locator in a correct plane to usa as Pole Vector
        :param ikHandle: select an ikHandle
        :return: grupped locator
        '''

        ikHandle_name = ikHandle.name()
        selJoints = ikHandle.getJointList()
        pm.select(selJoints[-1])
        pm.pickWalk(d='down')
        newJoints = pm.ls(sl=True)
        selJoints.append(newJoints[0])

        # Create a locator and group it twice
        poleVector_locator = pm.spaceLocator(n=ikHandle_name + '_PV' + '_LOC')
        poleVector_group = pm.group(poleVector_locator,
                                    n=ikHandle_name + '_PV' + '_LOC' + '_GRP')

        # Point constrain it between the three joints
        pointConstraint = pm.pointConstraint(selJoints, poleVector_group)
        pm.delete(pointConstraint)

        # Create an aim constraint for the locator to aim at the middle joint
        aimConstraint = pm.aimConstraint(selJoints[1], poleVector_group)
        pm.delete(aimConstraint)

        ##Snap grupLocator to middle joint
        # snap = pm.pointConstraint( selJoints[1], poleVector_group, skip=('y','z'))

        return poleVector_group
示例#2
0
    def getSelectedCamera(self):
        sel = pm.ls(sl=1)

        # NOTE 当前的 modelEditor
        cur_mp = None
        for mp in pm.getPanel(type="modelPanel"):
            if pm.modelEditor(mp, q=1, av=1):
                cur_mp = mp
                break

        # NOTE 获取摄像机节点
        pm.pickWalk(d="down")
        cam_list = pm.ls(sl=1, ca=1)

        # NOTE 获取选择的摄像机 没有 则获取当前视窗的摄像机
        cam = cam_list[0].getParent() if cam_list else pm.modelEditor(
            cur_mp, q=1, cam=1)

        for i in range(self.Cam_Combo.count()):
            text = self.Cam_Combo.itemText(i)
            if text == str(cam):
                self.Cam_Combo.setCurrentIndex(i)
                break

        pm.select(sel)
示例#3
0
def getMAT(*args):
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1)
    for i in sel:
        shadingGroup = pm.listConnections(i, type='shadingEngine')
        if shadingGroup:
            i.mtoa_constant_mMat.set(shadingGroup[0].split('SG')[0])
示例#4
0
def pickWalkHairCtrl(d='right', add=False):
    '''Pick Walk and hide Controls'''
    sel = pm.selected()
    hairInfoAll = selHair(returnInfo=True)
    pm.setToolTo(pm.context.manipMoveContext())
    if not hairInfoAll:
        return
    ToggleHairCtrlVis(state='hide')
    if d == 'up':
        pm.select([h[0][0] for h in hairInfoAll])
        selHair()
        for o in pm.selected():
            o.show()
    elif d == 'down':
        pm.select([h[0][0] for h in hairInfoAll])
        selHair(selectTip=True)
        for o in pm.selected():
            o.show()
    else:
        ctrlGroups = [h[1] for h in hairInfoAll]
        for ob in sel:
            ctrls = ctrlGroups[sel.index(ob)].listRelatives(
                type=pm.nt.Transform)
            if ctrls.count(ob):
                for c in ctrls:
                    c.show()
                pm.select(ob, add=1)
            else:
                selHair(selectTip=True)
                if d == 'left':
                    pm.pickWalk(d='right')
                for c in ctrls:
                    c.show()
        pm.pickWalk(d=d)
示例#5
0
def addColorAttr(colorField):
    attrName = colorField.getText().split(' ')
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1, long=1)
    for m in sel:
        for i in attrName:
            if pm.attributeQuery("mtoa_constant_" + i, node=m, exists=True):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(m,
                           ln="mtoa_constant_" + i,
                           nn=i,
                           uac=1,
                           at="float3")
                pm.addAttr(m,
                           ln="red_" + i,
                           at="float",
                           p="mtoa_constant_" + i)
                pm.addAttr(m,
                           ln="grn_" + i,
                           at="float",
                           p="mtoa_constant_" + i)
                pm.addAttr(m,
                           ln="blu_" + i,
                           at="float",
                           p="mtoa_constant_" + i)
示例#6
0
def addColorAttr(*args):
    colorAttrName = pm.textFieldGrp('colorText', q=True, text=True).split(' ')
    pm.pickWalk(d="down")
    selected = pm.ls(sl=1, long=1)
    for member in selected:
        for i in colorAttrName:
            if pm.attributeQuery("mtoa_constant_" + i,
                                 node=member,
                                 exists=True):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(member,
                           ln="mtoa_constant_" + i,
                           nn=i,
                           uac=1,
                           at="float3")
                pm.addAttr(member,
                           ln="red_" + i,
                           at="float",
                           p="mtoa_constant_" + i)
                pm.addAttr(member,
                           ln="grn_" + i,
                           at="float",
                           p="mtoa_constant_" + i)
                pm.addAttr(member,
                           ln="blu_" + i,
                           at="float",
                           p="mtoa_constant_" + i)
                pm.setAttr(member + ".mtoa_constant_" + i, randCol())
                randCol
 def edgeFlow(self):
     oldSel = pm.ls(sl = 1)
     pm.select(pm.ls(o=1, sl=1))
     selected = pm.ls(sl = 1)
     pm.delete(selected, constructionHistory = 1)
     pm.select(cl = 1)
     for s in selected:
         rootEdges = pm.ls(    self.root(s)    , fl = 1)
         tipEdges =  pm.ls(    self.tip(s)    , fl = 1)
         ############length edgeloops of the card
         myEdges = pm.ls(pm.polySelect(s, ebp = [    rootEdges[0].index(), tipEdges[0].index()    ],ass = True ), fl = 1)
         side1Edges = [x for x in myEdges if x not in rootEdges and x not in tipEdges]
         borderEdges = [x for x in pm.ls(s.e, fl = 1) if x.isOnBoundary()]
         pm.select(tipEdges)
         for x in range(len(side1Edges)*2):
             if x != borderEdges and x!= rootEdges and x!= tipEdges:
                 pm.polyEditEdgeFlow(adjustEdgeFlow=1, constructionHistory=0)
                 pm.pickWalk(type = 'edgeloop', direction = 'left')
         if self.lenCheckBox.getValue() == 1:
             pm.select(side1Edges)
             for x in range(    len(rootEdges)*2    ):
                 pm.polyEditEdgeFlow(adjustEdgeFlow=1, constructionHistory=0)
                 pm.pickWalk(type = 'edgeloop', direction = 'left')
             
     pm.select(oldSel)    
示例#8
0
def txShow(
):  # GET TEXTURE FROM CUSTOM ATTR AND ASIGN MATERIAL TO OBJ WITH TEXTURE
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1)  # get shapes of selection
    for i in sel:
        if getTXShape(i):  # Check, if attribute has value
            texturePath, textureName = getTXShape(
                i)  # get texture name with path, texture name
            if textureName:  # Check, if attribute has value
                if pm.objExists('PREV_' + textureName):
                    pm.sets(('PREV_' + str(textureName) + 'SG'),
                            forceElement=i)
                else:
                    previewShader = pm.shadingNode('lambert',
                                                   asShader=True,
                                                   n='PREV_' + textureName)
                    previewIF = pm.shadingNode('file',
                                               asTexture=True,
                                               n='PREV_IF_' + textureName)
                    previewSG = pm.sets(renderable=True,
                                        noSurfaceShader=True,
                                        empty=True,
                                        n=previewShader + 'SG')
                    previewIF.fileTextureName.set('sourceimages/' +
                                                  str(texturePath))
                    previewIF.outColor >> previewShader.color
                    previewShader.outColor >> previewSG.surfaceShader
                    pm.sets(previewSG, forceElement=i)
示例#9
0
def getMAT(*args):
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1)
    for i in sel:
        shadingGroup = pm.listConnections(i ,type='shadingEngine')
        if shadingGroup:
            i.mtoa_constant_mMat.set(shadingGroup[0].split('SG')[0])
示例#10
0
    def getJointDistance(self, ikHandle):
        '''
        Return the lenght of ikHandle
        :param ikHandle: select an ikHandle
        :return: Return the lenght og ikHandle
        '''

        # Put all three joints in a variable based on a selected ikHandle
        selJoints = ikHandle.getJointList()
        pm.select(selJoints[-1])
        pm.pickWalk(d='down')
        newJoints = pm.ls(sl=True)
        selJoints.append(newJoints[0])
        loc0 = pm.spaceLocator()
        loc1 = pm.spaceLocator()
        constraint0 = pm.pointConstraint(selJoints[0], loc0)
        constraint1 = pm.pointConstraint(selJoints[2], loc1)

        def ctr_dist(objA, objB):
            Ax, Ay, Az = objA.getTranslation(space="world")
            Bx, By, Bz = objB.getTranslation(space="world")
            return ((Ax - Bx)**2 + (Ay - By)**2 + (Az - Bz)**2)**0.5

        distance = ctr_dist(loc0, loc1)
        pm.delete(constraint0, constraint1, loc0, loc1)
        return distance
示例#11
0
def pickWalkAdd( direction ):
    """Pick walk that adds pickwalk selected items to current selection"""
    selected = pm.ls( selection=True )
    pm.pickWalk( direction=direction )
    pm.select( selected, add=True )

    selected = pm.ls( selection=True )

    print '// Result: %s //' % ' '.join( [str(x) for x in selected] )
示例#12
0
def delColorAttr(colorField):
    attrName = colorField.getText().split(' ')
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1, long=1)
    for m in sel:
        for i in attrName:
            if pm.attributeQuery("mtoa_constant_" + i, node=m, exists=True):
                pm.deleteAttr(m + '.mtoa_constant_' + i)
            else:
                print 'attribute ' + i + ' not exist!'
示例#13
0
def addStringAttr(stringField):
    attrName = stringField.getText().split(' ')
    pm.pickWalk( d = "down" ) # select SHAPES of selected objects
    sel = pm.ls(sl=1 , long = 1)
    for m in sel:
        for i in attrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = m, exists = True ):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(m, ln = "mtoa_constant_" + i, nn = i, dt = 'string')
示例#14
0
def delColorAttr(colorField):
    attrName = colorField.getText().split(' ')
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1,long=1)
    for m in sel:
        for i in attrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = m, exists = True ):
                pm.deleteAttr(m + '.mtoa_constant_' + i)
            else:
                print 'attribute ' + i + ' not exist!'
示例#15
0
def delBoolAttr(*args):
    floatAttrName = pm.textFieldGrp( 'boolText', q = True, text = True ).split(' ')
    pm.pickWalk( d = "down" )
    selected = pm.ls(sl=1,long=1)
    for member in selected:
        for i in floatAttrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = member, exists = True ):
                pm.deleteAttr(member + '.mtoa_constant_' + i)
            else:
                print 'attribute ' + i + ' not exist!'
示例#16
0
def addBoolAttr(*args):
    stringAttrName = pm.textFieldGrp( 'boolText', q = True, text = True ).split(' ')
    pm.pickWalk( d = "down" )
    selected = pm.ls(sl=1,long=1)
    for member in selected:
        for i in stringAttrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = member, exists = True ):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(member, ln = "mtoa_constant_" + i, nn = i, at = 'bool')
示例#17
0
def addFloatAttr(*args):
    floatAttrName = pm.textFieldGrp( 'floatText', q = True, text = True ).split(' ')
    pm.pickWalk( d = "down" )
    selected = pm.ls(sl=1,long=1)
    for member in selected:
        for i in floatAttrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = member, exists = True ):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(member, ln = "mtoa_constant_" + i, nn = i,hasMaxValue=False,hasMinValue=False, dv =1.0,smn=0, smx=9)
示例#18
0
def addStringAttr(stringField):
    attrName = stringField.getText().split(' ')
    pm.pickWalk(d="down")  # select SHAPES of selected objects
    sel = pm.ls(sl=1, long=1)
    for m in sel:
        for i in attrName:
            if pm.attributeQuery("mtoa_constant_" + i, node=m, exists=True):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(m, ln="mtoa_constant_" + i, nn=i, dt='string')
示例#19
0
def boundingBox():
    pm.pickWalk(d ='down')
    sel = pm.ls(sl = 1, shapes = 1, selection = 1)
    if (sel[0].overrideEnabled.get() == 0):
        for i in sel:
            i.overrideEnabled.set(1) 
            i.overrideLevelOfDetail.set(1)
    else:
        for i in sel:
            i.overrideEnabled.set(0) 
            i.overrideLevelOfDetail.set(0)
示例#20
0
def boundingBox():
    pm.pickWalk(d='down')
    sel = pm.ls(sl=1, shapes=1, selection=1)
    if (sel[0].overrideEnabled.get() == 0):
        for i in sel:
            i.overrideEnabled.set(1)
            i.overrideLevelOfDetail.set(1)
    else:
        for i in sel:
            i.overrideEnabled.set(0)
            i.overrideLevelOfDetail.set(0)
示例#21
0
def addMTOAAttr():
    pm.pickWalk( d = "down" )# get shapes of selection
    sel = pm.ls( sl=1 )
    for i in sel:
        if len(i.split('_Prx')) == 1: # EXCLUDE PROXY OBJECT FROM ADD ATTR
            for n in attrList:
                if pm.attributeQuery( "mtoa_constant_" + n, node = i, exists = True ):
                    print 'Attribute ' + n + ' exist!'
                else:
                    pm.addAttr(i, ln = "mtoa_constant_" + n, nn = n, dt = 'string')
        else:
            print 'No attr for proxy'        
示例#22
0
def copyMTOAAttr(): # COPY ATTRIBUTES FROM LAST SELECTED OBJECTS
    pm.pickWalk( d = "down" ) # get shapes of selection 
    tagert = pm.ls( sl=1 ) 
    source = tagert.pop(-1)
    for m in attrList: # for each MTOA attribute
        attrLong = source + '.mtoa_constant_' + m
        for i in tagert: # copy value for each object
            attrValue = pm.getAttr(attrLong)
            if not pm.attributeQuery( "mtoa_constant_" + m, node = i, exists = True ):
                pm.addAttr(i, ln = "mtoa_constant_" + m, nn = m, dt = 'string')
            if not attrValue == None:
                pm.setAttr(i + ".mtoa_constant_" + m, attrValue ,type = 'string')
示例#23
0
def addBoolAttr(*args):
    stringAttrName = pm.textFieldGrp('boolText', q=True, text=True).split(' ')
    pm.pickWalk(d="down")
    selected = pm.ls(sl=1, long=1)
    for member in selected:
        for i in stringAttrName:
            if pm.attributeQuery("mtoa_constant_" + i,
                                 node=member,
                                 exists=True):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(member, ln="mtoa_constant_" + i, nn=i, at='bool')
示例#24
0
def setSBD(value):
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1)
    for i in sel:
        if value == 'off':
            mayaSmoothOff(i)
        elif value == 0:
            i.aiSubdivType.set(0)
        else:
            mayaSmoothOff(i)
            i.aiSubdivType.set(1)
            i.aiSubdivIterations.set(value)
示例#25
0
def delBoolAttr(*args):
    floatAttrName = pm.textFieldGrp('boolText', q=True, text=True).split(' ')
    pm.pickWalk(d="down")
    selected = pm.ls(sl=1, long=1)
    for member in selected:
        for i in floatAttrName:
            if pm.attributeQuery("mtoa_constant_" + i,
                                 node=member,
                                 exists=True):
                pm.deleteAttr(member + '.mtoa_constant_' + i)
            else:
                print 'attribute ' + i + ' not exist!'
示例#26
0
 def pickWalk(direction=("StringPin", "left", {"ValueList": ["up", "down", "left", "right", "in", "out"]}),
              bRecurse=("BoolPin", False),
              typ=("StringPin", "nodes", {
                  "ValueList": ["nodes", "instances", "edgeloop", "edgering", "faceloop", "keys", "latticepoints",
                                "motiontrailpoints"]})):
     """The pickWalk command allows you to quickly change the selection list relative to the nodes that are
     currently selected. It is called pickWalk, because it walks from one selection list to another by unselecting
     what's currently selected, and selecting nodes that are in the specified direction from the currently
     selected list.\n\nIf you specify objects on the command line, the pickWalk command will walk from those
     objects instead of the selected list. If the -type flag is instances, then the left and right direction will
     walk to the previous or next instance of the same selected dag node. """
     pm.pickWalk(d=direction, r=bRecurse, type=typ)
示例#27
0
def setSBD(value):
    pm.pickWalk( d = "down" )
    sel = pm.ls( sl=1 )
    for i in sel:
        if value == 'off':
            mayaSmoothOff(i)
        elif value == 0:
            i.aiSubdivType.set(0)
        else: 
            mayaSmoothOff(i)
            i.aiSubdivType.set(1)
            i.aiSubdivIterations.set(value)  
示例#28
0
def addColorAttr(colorField):
    attrName = colorField.getText().split(' ')
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1,long=1)
    for m in sel:
        for i in attrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = m, exists = True ):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(m, ln = "mtoa_constant_" + i, nn = i , uac = 1, at ="float3" )
                pm.addAttr(m, ln = "red_" + i, at = "float", p = "mtoa_constant_" + i )
                pm.addAttr(m, ln = "grn_" + i, at = "float", p = "mtoa_constant_" + i )
                pm.addAttr(m, ln = "blu_" + i, at = "float", p = "mtoa_constant_" + i )            
示例#29
0
def setAttrColor(colorSetField, colorValField):
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1, long=1)
    for i in sel:
        if colorValField.getText() == 'R':
            print i + '.mtoa_constant_' + colorSetField.getText()
            pm.setAttr(i + '.mtoa_constant_' + colorSetField.getText(), R)
        elif colorValField.getText() == 'G':
            pm.setAttr(i + '.mtoa_constant_' + colorSetField.getText(), G)
        elif colorValField.getText() == 'B':
            pm.setAttr(i + '.mtoa_constant_' + colorSetField.getText(), B)
        else:
            pm.warning('Set one of R, G, B colors!')
示例#30
0
def setAttrColor(colorSetField , colorValField):
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1,long=1)
    for i in sel:
        if colorValField.getText() == 'R':
            print i + '.mtoa_constant_' + colorSetField.getText()
            pm.setAttr( i + '.mtoa_constant_' + colorSetField.getText(), R)
        elif colorValField.getText() == 'G':
            pm.setAttr( i + '.mtoa_constant_' + colorSetField.getText(), G)
        elif colorValField.getText() == 'B':
            pm.setAttr( i + '.mtoa_constant_' + colorSetField.getText(), B)
        else:
            pm.warning( 'Set one of R, G, B colors!' )
示例#31
0
def copyMTOAAttr():  # COPY ATTRIBUTES FROM LAST SELECTED OBJECTS
    pm.pickWalk(d="down")  # get shapes of selection
    tagert = pm.ls(sl=1)
    source = tagert.pop(-1)
    for m in attrList:  # for each MTOA attribute
        attrLong = source + '.mtoa_constant_' + m
        for i in tagert:  # copy value for each object
            attrValue = pm.getAttr(attrLong)
            if not pm.attributeQuery("mtoa_constant_" + m, node=i,
                                     exists=True):
                pm.addAttr(i, ln="mtoa_constant_" + m, nn=m, dt='string')
            if not attrValue == None:
                pm.setAttr(i + ".mtoa_constant_" + m, attrValue, type='string')
示例#32
0
def addMTOAAttr():
    pm.pickWalk(d="down")  # get shapes of selection
    sel = pm.ls(sl=1)
    for i in sel:
        if len(i.split('_Prx')) == 1:  # EXCLUDE PROXY OBJECT FROM ADD ATTR
            for n in attrList:
                if pm.attributeQuery("mtoa_constant_" + n, node=i,
                                     exists=True):
                    print 'Attribute ' + n + ' exist!'
                else:
                    pm.addAttr(i, ln="mtoa_constant_" + n, nn=n, dt='string')
        else:
            print 'No attr for proxy'
示例#33
0
	def startLeg ( self , side ):
		print 'ehm_leg........................startLeg'
		self.side               =     side

		if self.side == "R" :
			pm.select ( clear = True )
			self.upLegInitJnt =     pm.joint ( p = ( -2     ,  self.legSize*7 , 0)                     , name = "leg_upLegInitJnt" )
			self.kneeInitJnt =      pm.joint ( p = ( -2     ,  self.legSize*4 , 0)                     , name = "leg_kneeInitJnt" )
			self.ankleInitJnt =      pm.joint ( p = ( -2     ,  self.legSize*1 , 0)                     , name = "leg_ankleInitJnt" )
			self.heelInitJnt =   pm.joint ( p = ( -2     , 0 , self.legSize*-1 )                    , name = "leg_heelInitJnt" )
			self.toeInitJnt =   pm.joint ( p = ( -2     , 0 , self.legSize* 2 )                     , name = "leg_toeInitJnt" )
			self.toeEndInitJnt =   pm.joint ( p = ( -2     , 0, self.legSize*4 )                      , name = "leg_toeEndInitJnt" )
			pm.pickWalk ( d = "up")
			self.outPivInitJnt =   pm.joint ( p = (  -(2 - self.legSize)  , 0, self.legSize*2 )                       , name = "leg_outPivInitJnt" )
			pm.pickWalk ( d = "up")
			self.inPivInitJnt =   pm.joint ( p = ( -(2 + self.legSize)  , 0 , self.legSize*2)        , name = "leg_inPivInitJnt" )
			pm.select ( clear=True )

		else :
			pm.select ( clear = True )
			self.upLegInitJnt =     pm.joint ( p = ( 2     ,  self.legSize*7 , 0)                     , name = "leg_upLegInitJnt" )
			self.kneeInitJnt =      pm.joint ( p = ( 2     ,  self.legSize*4 , 0)                     , name = "leg_kneeInitJnt" )
			self.ankleInitJnt =      pm.joint ( p = ( 2     ,  self.legSize*1 , 0)                     , name = "leg_ankleInitJnt" )
			self.heelInitJnt =   pm.joint ( p = ( 2     , 0 , self.legSize*-1 )                    , name = "leg_heelInitJnt" )
			self.toeInitJnt =   pm.joint ( p = ( 2     , 0 , self.legSize* 2 )                     , name = "leg_toeInitJnt" )
			self.toeEndInitJnt =   pm.joint ( p = ( 2     , 0, self.legSize*4 )                      , name = "leg_toeEndInitJnt" )
			pm.pickWalk ( d = "up")
			self.outPivInitJnt =   pm.joint ( p = (  2 - self.legSize  , 0, self.legSize*2 )                       , name = "leg_outPivInitJnt" )
			pm.pickWalk ( d = "up")
			self.inPivInitJnt =   pm.joint ( p = (  2 + self.legSize  , 0 , self.legSize*2)        , name = "leg_inPivInitJnt" )
			pm.select ( clear=True )

			
		return self.upLegInitJnt
示例#34
0
def addColorAttr(*args):
    colorAttrName = pm.textFieldGrp( 'colorText', q = True, text = True ).split(' ')
    pm.pickWalk( d = "down" )
    selected = pm.ls(sl=1,long=1)
    for member in selected:
        for i in colorAttrName:
            if pm.attributeQuery( "mtoa_constant_" + i, node = member, exists = True ):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(member, ln = "mtoa_constant_" + i, nn = i , uac = 1, at ="float3" )
                pm.addAttr(member, ln = "red_" + i, at = "float", p = "mtoa_constant_" + i )
                pm.addAttr(member, ln = "grn_" + i, at = "float", p = "mtoa_constant_" + i )
                pm.addAttr(member, ln = "blu_" + i, at = "float", p = "mtoa_constant_" + i )
                pm.setAttr(member +".mtoa_constant_" + i, randCol())
                randCol
示例#35
0
    def do_check_other(self):

        self.hitface_list = []
        self.listWidget_ID.clear()
        self.textEdit_Pos.clear()

        curr = time.time()

        sellist = [mesh for mesh in pm.ls(pm.pickWalk(d="down"), type="mesh")]

        if len(sellist) >= 2:

            for i in range(len(sellist)):
                for j in range(i + 1, len(sellist)):
                    f = self.find_intersection_other(sellist[i], sellist[j])

                    self.hitface_list += f
                    if f != None:
                        self.hitface_list += self.find_intersection_other(sellist[j], sellist[i])  # 两个对象都需要

            centerpos = [0, 1, 2]
            for face in self.hitface_list:

                self.listWidget_ID.addItem(str(face))

                pos = pm.xform(face, q=1, ws=1, t=1)
                for i in range(3):
                    centerpos[i] = (pos[i] + pos[i + 3] + pos[i + 6] + pos[i + 9]) / 4  # 求面中心点位置
                self.textEdit_Pos.append(str(centerpos))

            pm.select(self.hitface_list)
            self.lineEdit_time.setText(str(time.time() - curr))
示例#36
0
def txShow(): # GET TEXTURE FROM CUSTOM ATTR AND ASIGN MATERIAL TO OBJ WITH TEXTURE 
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1) # get shapes of selection 
    for i in sel:
        if getTXShape(i): # Check, if attribute has value
            texturePath, textureName  = getTXShape(i) # get texture name with path, texture name
            if textureName: # Check, if attribute has value
                if pm.objExists ('PREV_' + textureName):
                    pm.sets(('PREV_' + str(textureName) + 'SG'), forceElement = i)
                else:
                    previewShader = pm.shadingNode ('lambert', asShader = True, n = 'PREV_' + textureName) 
                    previewIF = pm.shadingNode ('file',asTexture = True, n = 'PREV_IF_' + textureName)
                    previewSG = pm.sets (renderable = True, noSurfaceShader = True, empty = True, n = previewShader  + 'SG')
                    previewIF.fileTextureName.set('sourceimages/' + str(texturePath))
                    previewIF.outColor >> previewShader.color
                    previewShader.outColor >> previewSG.surfaceShader
                    pm.sets(previewSG, forceElement = i) 
示例#37
0
def txGet(attr, ext): # GET TEXTURE FROM MATERIAL AND ASIGN TO CUSTOM ATTR
    pm.pickWalk( d = "down" ) # get shapes of selection
    sel = pm.ls( sl=1 ) 
    for i in sel: 
        if not pm.attributeQuery(attr, ex = 1, node = i): # check if attribute exists
            for n in attrList: # add  mtoa custom attributes to ASS
                pm.addAttr(i , ln = "mtoa_constant_" + n, nn = n, dt = 'string')
        texture = getColor(i, attr)
        if texture: # Check, if attribute has value
            if not os.path.exists(texture.replace(ext,'.tx')): # check if there is TX TEXTURE exists
                txWarning = pm.confirmDialog( title='Warning', message = 'There is NO TX texture for' + str(i) + '!' , button=['Cancel' , 'Get anyway'], cancelButton='OK' )
                if txWarning == 'Cancel':
                    sys.exit('Convert to TX textures for' + str(i))
            if texture: # SET custom attribute with TEXTURE NAME
                texture = texture.split('sourceimages/')[1].replace(ext,'.tx') 
                i.attr(attr).set(texture)
            else:
                pm.warning('There is NO TEXTURE asigned for ' + str(i))
示例#38
0
def distanceNode(*args):
    global distT, distS
    '''
	Create the distance node
	'''
    dist_node = pm.createNode('distanceDimShape')
    print('Distance Node:', dist_node)
    pm.pickWalk(d='up')
    selection = pm.ls(sl=1, dag=1)
    distT = selection[0]
    distS = selection[1]
    print('Dist Transform:', distT)
    print('Dist Shape:', distS)
    '''
	Rename the node
	'''
    node_name = boneT.replace('bone', 'dist')
    distT.rename(node_name)
示例#39
0
def do_pickrun_motion(direction):
    '''Try to pickrun in a given direction. Otherwise, pickWalk.

    Args:
        direction (str):
            The direction to walk. Options are: ("up", "down", "left", "right").

    '''
    try:
        node = pm.selected()[-1]
    except IndexError:
        pm.pickWalk(direction=direction)
        return

    new_node = MayaBehaviorControl.do_motion(direction, node)
    if not new_node:
        # Pickrun failed for some reason so lets pickWalk, instead
        pm.pickWalk(direction=direction)
示例#40
0
def addFloatAttr(*args):
    floatAttrName = pm.textFieldGrp('floatText', q=True, text=True).split(' ')
    pm.pickWalk(d="down")
    selected = pm.ls(sl=1, long=1)
    for member in selected:
        for i in floatAttrName:
            if pm.attributeQuery("mtoa_constant_" + i,
                                 node=member,
                                 exists=True):
                print 'attribute ' + i + ' already exist!'
            else:
                pm.addAttr(member,
                           ln="mtoa_constant_" + i,
                           nn=i,
                           hasMaxValue=False,
                           hasMinValue=False,
                           dv=1.0,
                           smn=0,
                           smx=9)
示例#41
0
def main(thersold = 0.01):
        
    # NOTE 选择模型
    pm.pickWalk(d="down")
    for sel in pm.ls(sl=1,type="mesh"):
        bbox = pm.exactWorldBoundingBox(sel)
        x = (bbox[0] + bbox[3])/2
        y = (bbox[1] + bbox[4])/2
        z = (bbox[2] + bbox[5])/2
        pt = OpenMaya.MPoint(x, y, z)
        
        node = sel.node()
        itr = OpenMaya.MItMeshVertex(node.__apimdagpath__())

        l_dict = {}
        c_dict = {}
        r_dict = {}
        while not itr.isDone():
            pt_pos = itr.position(OpenMaya.MSpace.kWorld)
            pt_idx = itr.index()
            pt_x = pt_pos.x
            if pt_x - x > 0 :
                l_dict[pt_idx] = pt_pos
            elif abs(pt_x - x) < thersold:
                c_dict[pt_idx] = pt_pos
            else:
                r_dict[pt_idx] = pt_pos
            itr.next()
        
        match_dict = {}
        for l_idx,l_pos in l_dict.items():
            l_len = (pt - l_pos).length()
            l_len_x = abs(l_pos.x - x)
            for r_idx,r_pos in r_dict.items():
                r_len = (pt - r_pos).length()
                r_len_x = abs(r_pos.x - x)
                if abs(l_len - r_len) < thersold and abs(l_len_x - r_len_x) < thersold :
                    match_dict[l_idx] = r_idx
                    break
        
        for l,r in match_dict.items():
            l_pos = sel.vtx[l].getPosition()
            sel.vtx[r].setPosition(dt.Point(-l_pos.x , l_pos.y , l_pos.z))
示例#42
0
def main():

    mesh_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh")
    if not mesh_list:
        return

    csv_path = r"C:\Users\timmyliang\Desktop\file_test\2020-12-1\head.csv"
    pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0)

    with open(csv_path, "r") as f:
        reader = csv.DictReader(f)
        data_list = {
            int(row[" IDX"]): (
                float(row[" COLOR.x"]),
                float(row[" COLOR.y"]),
                float(row[" COLOR.z"]),
                float(row[" COLOR.w"]),
            )
            for row in reader
        }

    mesh = mesh_list[0]
    mfn = mesh.__apimfn__()
    itr = OpenMaya.MItMeshFaceVertex(mesh.__apimobject__())

    face_list = OpenMaya.MIntArray()
    vertex_list = OpenMaya.MIntArray()
    colors = OpenMaya.MColorArray()

    index = -1
    total = len(mesh.vtxFace)
    pm.progressWindow(title=u"设置顶点色", status=u"设置顶点色...", progress=0.0)
    while not itr.isDone():
        index += 1
        pm.progressWindow(e=1, progress=index / total * 100)
        vert_id = itr.vertId()
        face_id = itr.faceId()
        vertex_list.append(vert_id)
        face_list.append(face_id)

        color = data_list.get(vert_id)
        if not color:
            colors.append(OpenMaya.MColor(0, 0, 0))
            itr.next()
            continue
        r, g, b,a = color
        
        colors.append(OpenMaya.MColor(r, g, b))

        itr.next()

    mfn.setFaceVertexColors(colors, face_list, vertex_list)
    pm.progressWindow(ep=1)
示例#43
0
 def getMeshList(self):
     # TODO 定义模型组名称
     mesh_list = pm.ls("MODEL", ni=1, dag=1, type="mesh")
     # NOTE 获取选择的模型
     mesh_list = mesh_list if mesh_list else pm.ls(
         pm.pickWalk(d="down"), ni=1, dag=1, type="mesh")
     # NOTE 获取根目录下的模型
     mesh_list = mesh_list if mesh_list else [
         mesh for mesh in pm.ls(assemblies=1)
         if type(mesh.getShape()) is nt.Mesh
     ]
     return mesh_list
示例#44
0
def createDOF():  # Create DOF setup for CAMERA
    i = pm.ls(sl=1, type='transform')
    if i:
        if pm.nodeType(i[0].getShape()) == 'camera':
            pm.pickWalk(d="down")  # get shapes of selection
            dist = pm.createNode('distanceDimShape')
            dist.getParent().rename('DISTANCE')
            loc = pm.spaceLocator(n='FOCUS')
            loc.scale.set(100, 100, 100)
            print i
            i[0].tx >> dist.startPointX
            i[0].ty >> dist.startPointY
            i[0].tz >> dist.startPointZ
            loc.tx >> dist.endPointX
            loc.ty >> dist.endPointY
            loc.tz >> dist.endPointZ
            dist.distance >> i[0].aiFocusDistance
            print '<<  Created DOF for {}  >>'.format(i[0])
        else:
            print 'SELECT CAMERA!'
    else:
        print 'SELECT CAMERA TRANSFORM!'
示例#45
0
def createDOF(): # Create DOF setup for CAMERA
    i = pm.ls(sl = 1, type = 'transform')
    if i:
        if pm.nodeType(i[0].getShape()) == 'camera':
            pm.pickWalk( d = "down" )# get shapes of selection
            dist = pm.createNode('distanceDimShape')
            dist.getParent().rename('DISTANCE')
            loc = pm.spaceLocator( n = 'FOCUS' )
            loc.scale.set( 100,100,100 )
            print i
            i[0].tx >> dist.startPointX
            i[0].ty >> dist.startPointY
            i[0].tz >> dist.startPointZ
            loc.tx >> dist.endPointX
            loc.ty >> dist.endPointY
            loc.tz >> dist.endPointZ
            dist.distance >> i[0].aiFocusDistance
            print '<<  Created DOF for {}  >>'.format(i[0])
        else:
            print 'SELECT CAMERA!'
    else:
        print 'SELECT CAMERA TRANSFORM!'
示例#46
0
def pickWalk(direction, additive=False):

    if not cmds.ls(selection=True, dagObjects=True):
        strandInfoDict = ka_geometry.getStrandInfoDict(
            checkSelectionMatches=True)

        # are we additively selecting strands?
        if additive:  # ------------------------------------------------------------------------------------------
            ka_geometry.strandWalk(direction,
                                   strandInfoDict=strandInfoDict,
                                   additive=True)

        else:
            ka_geometry.strandWalk(direction, strandInfoDict=strandInfoDict)

    # Dag pick walk
    else:

        if additive:
            selection.extend(pymel.pickWalk(direction=direction))
            cmds.select(selection)

        else:
            pymel.pickWalk(direction=direction)
示例#47
0
def txGet(attr, ext):  # GET TEXTURE FROM MATERIAL AND ASIGN TO CUSTOM ATTR
    pm.pickWalk(d="down")  # get shapes of selection
    sel = pm.ls(sl=1)
    for i in sel:
        if not pm.attributeQuery(attr, ex=1,
                                 node=i):  # check if attribute exists
            for n in attrList:  # add  mtoa custom attributes to ASS
                pm.addAttr(i, ln="mtoa_constant_" + n, nn=n, dt='string')
        texture = getColor(i, attr)
        if texture:  # Check, if attribute has value
            if not os.path.exists(texture.replace(
                    ext, '.tx')):  # check if there is TX TEXTURE exists
                txWarning = pm.confirmDialog(
                    title='Warning',
                    message='There is NO TX texture for' + str(i) + '!',
                    button=['Cancel', 'Get anyway'],
                    cancelButton='OK')
                if txWarning == 'Cancel':
                    sys.exit('Convert to TX textures for' + str(i))
            if texture:  # SET custom attribute with TEXTURE NAME
                texture = texture.split('sourceimages/')[1].replace(ext, '.tx')
                i.attr(attr).set(texture)
            else:
                pm.warning('There is NO TEXTURE asigned for ' + str(i))
示例#48
0
文件: pickwalk.py 项目: loichuss/maya
def pickWalkRight():
    sels = pmc.ls(sl=True)
    pmc.select(clear=True)
    futurSel = []
    for sel in sels:
        if sel.hasAttr('pgRt') or sel.hasAttr('pgUp'):
            try:
                futurSel.append(sel.pgRt.outputs()[0])
            except:
                futurSel.append(sel)
        else:
            pmc.select(sel)
            futurSel.extend(pmc.pickWalk(d='right'))
    
    if futurSel:    
        pmc.select(futurSel, replace=True)
示例#49
0
def setAttrString(stringSetField , stringValField):
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1,long=1)
    for i in sel:
       pm.setAttr( i + '.mtoa_constant_' + stringSetField.getText(), stringValField.getText())
示例#50
0
def main():
    sel_list = pm.ls(pm.pickWalk(d="down"), ni=1, type="mesh")
    if not sel_list:
        QtWidgets.QMessageBox.warning(None, u"警告", u"请选择一个模型")
        return
    sel = sel_list[0]
    # pm.undoInfo(ock=1)

    num_list, total = sel.getUvShellsIds()
    shell_dict = {num: i for i, num in enumerate(num_list)}
    border_dict = defaultdict(dict)
    uv_dict = {}

    for i, uv in shell_dict.items():
        pm.select(sel.map[uv])
        pm.polySelectConstraint(uv=1, bo=0, m=2)
        uv_list = pm.ls(pm.polySelectConstraint(uv=0, rs=1), fl=1)
        face_list = pm.polyListComponentConversion(fuv=1, tf=1)
        border_list = pm.ls(pm.polyListComponentConversion(fuv=1, te=1, bo=1),
                            fl=1)
        _border_list = [e.index() for e in border_list]

        edge_dict = {
            edge: {
                face.getUVIndex(j): face.getUV(j)
                for j in range(face.polygonVertexCount())
            }
            for face in pm.ls(face_list, fl=1) for edge in face.getEdges()
            if edge in _border_list
        }

        border_dict = {}
        border_uvs = pm.polyListComponentConversion(border_list, fe=1, tuv=1)
        border_uvs = [uv for uv in pm.ls(border_uvs, fl=1) if uv in uv_list]
        for uv in border_uvs:
            edges = pm.polyListComponentConversion(uv, fuv=1, te=1)
            edges = [e for e in pm.ls(edges, fl=1) if e in border_list]
            uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1)
            uvs = [
                _uv for _uv in pm.ls(uvs, fl=1)
                if _uv != uv and _uv in border_uvs
            ]
            border_dict[uv] = uvs

        print(border_dict)
        break
        # print(json.dumps(edge_dict))

    return

    # TODO 遍历 polygon 找 UV 对应关系

    dag_path = sel.__apimdagpath__()
    itr = OpenMaya.MItMeshPolygon(dag_path)

    util = OpenMaya.MScriptUtil()

    edge_dict = defaultdict(list)
    while not itr.isDone():
        face_idx = itr.index()

        uv = {}
        for i in range(itr.polygonVertexCount()):
            idx_ptr = util.asIntPtr()
            u_ptr = util.asFloatPtr()
            v_ptr = util.asFloatPtr()
            itr.getUVIndex(i, idx_ptr, u_ptr, v_ptr)
            idx = util.getInt(idx_ptr)
            u = util.getFloat(u_ptr)
            v = util.getFloat(v_ptr)
            uv[idx] = (u, v)

        edges = OpenMaya.MIntArray()
        itr.getEdges(edges)
        for i in range(edges.length()):
            edge = edges[i]
            edge_dict[edge].append({"uv": uv, "face_idx": face_idx})

        itr.next()

    edge_list = []
    for edge_idx, data in edge_dict.items():
        print(len(data))
        if len(data) == 1:
            edge_list.append(edge_idx)
    print(edge_list)
    # print(json.dumps(edge_dict))

    return

    pm.progressWindow(title=u"获取 uv border",
                      status=u"获取模型 uv border...",
                      progress=0.0)
    for i, uv in shell_dict.items():
        pm.progressWindow(e=1, progress=i / total * 100)
        # NOTES(timmyliang) 如果 uv 不在 0,1 象限则跳过
        x, y = sel.getUV(uv)

        if not 0 < x < 1 or not 0 < y < 1:
            continue

        pm.select(sel.map[uv])
        pm.polySelectConstraint(uv=1, bo=0, m=2)
        uv_list = pm.polySelectConstraint(t=0x0010, uv=0, bo=1, m=2, rs=1)
        uv_list = [_uv.currentItemIndex() for _uv in pm.ls(uv_list, fl=1)]
        pos_list = {uv: sel.getUV(uv) for uv in uv_list}
        x = sum([pos[0] for pos in pos_list.values()]) / len(pos_list)
        y = sum([pos[1] for pos in pos_list.values()]) / len(pos_list)
        uv_dict.update(pos_list)
        borders = pm.polyListComponentConversion(fuv=1, te=1, bo=1)
        borders = pm.ls(borders, fl=1)
        for uv in uv_list:
            edges = pm.polyListComponentConversion(sel.map[uv], fuv=1, te=1)
            edges = [e for e in pm.ls(edges, fl=1) if e in borders]
            uvs = pm.polyListComponentConversion(edges, fe=1, tuv=1)
            uvs = [_uv.currentItemIndex() for _uv in pm.ls(uvs, fl=1)]
            uvs = [_uv for _uv in uvs if _uv != uv and _uv in uv_list]
            border_dict[uv] = {"uvs": uvs, "center": (x, y)}

    pm.progressWindow(ep=1)
    pm.polySelectConstraint(uv=0, bo=0, rs=1)

    distant = 0.01

    for uv, data in border_dict.items():
        uvs = data.get("uvs", [])
        if len(uvs) <= 1:
            continue
        uv1, uv2 = uvs
        x, y = data.get("center")
        center = dt.Vector(x, y)

        pos = dt.Vector(*uv_dict[uv])
        pos1 = dt.Vector(*uv_dict[uv1])
        pos2 = dt.Vector(*uv_dict[uv2])
        vec1 = pos - pos1
        vec2 = pos2 - pos

        x, y = get_pt(pos, pos1, pos2, vec1, vec2, distant)
        pt = dt.Vector(x, y)
        vec = pos - pt
        line = pos - center
        # NOTE reverse
        if vec.dot(line) > 0:
            x, y = get_pt(pos, pos1, pos2, vec1, vec2, distant, True)
        sel.setUV(uv, x, y)

    face_list = pm.polyUVOverlap(sel.faces, oc=True)
    pm.undoInfo(cck=1)
示例#51
0
def setAttrString(stringSetField, stringValField):
    pm.pickWalk(d="down")
    sel = pm.ls(sl=1, long=1)
    for i in sel:
        pm.setAttr(i + '.mtoa_constant_' + stringSetField.getText(),
                   stringValField.getText())
示例#52
0
	def bipedLimb_init( self, BipedLimbSize=10, mode='arm', side='L', *args  ):

		self.BipedLimbInitJnts = []
		
		try:# if in UI mode, get number of joints from UI
			BipedLimbSize = pm.floatSliderGrp( self.BipedLimbSizeF, q=True, value=True)
			selectedMode = pm.radioCollection( self.limbModeRC, q=True, select=True)
			mode = pm.radioButton( selectedMode, q=True, label=True ).lower()
		
		except:
			pass
		
		if mode == 'arm':
			pm.select( clear = True )
			self.BipedLimbInitJnts.append( pm.joint ( p = ( BipedLimbSize * 3 / 14.0     , BipedLimbSize*13 / 14.0 , 0) , name = "%s_uparm_initJnt"%side ) )
			
			self.BipedLimbInitJnts.append( pm.joint ( p = ( BipedLimbSize * 7 / 14.0      , BipedLimbSize*13 / 14.0 , 0) , name = "%s_elbow_initJnt"%side ) )
			pm.joint( self.BipedLimbInitJnts[0], e=True, zso=True, oj='xyz', sao='yup')
			
			self.BipedLimbInitJnts.append( pm.joint ( p = ( BipedLimbSize * 11 / 14.0     , BipedLimbSize*13 / 14.0 , 0) , name = "%s_hand_initJnt"%side ) )
			pm.joint( self.BipedLimbInitJnts[1], e=True, zso=True, oj='xyz', sao='yup')
			
			self.BipedLimbInitJnts.append( pm.joint ( p = ( BipedLimbSize * 12 / 14.0     , BipedLimbSize*13 / 14.0 , 0) , name = "%s_handEnd_initJnt"%side ) )
			pm.joint( self.BipedLimbInitJnts[2], e=True, zso=True, oj='xyz', sao='yup')
			
			pm.select ( clear=True )


		elif mode == 'leg':
			pm.select( clear = True )

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*2/7.0, BipedLimbSize*7/7.0, 0), name = "L_initUplegJnt") )

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*2/7.0, BipedLimbSize*4/7.0, 0), name = "L_initKneeJnt") )
			pm.joint( self.BipedLimbInitJnts[0], e=True, zso=True, oj='xzy', sao='xup' )

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*2/7.0, BipedLimbSize*1/7.0, 0), name = "L_initAnkleJnt") )
			pm.joint( self.BipedLimbInitJnts[1], e=True, zso=True, oj='xzy', sao='xup')

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*2/7.0,0,BipedLimbSize*-1/7.0), name = "L_initHeelJnt") )
			pm.joint( self.BipedLimbInitJnts[2], e=True, zso=True, oj='xzy', sao='xup')

			pm.pickWalk( d='up' )

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize* 2/7.0, BipedLimbSize*0.5/7.0, BipedLimbSize*1/7.0), name = "L_initBallJnt") )
			pm.joint( self.BipedLimbInitJnts[3], e=True, zso=True, oj='xzy', sao='xup')

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*2/7.0,0,BipedLimbSize*2/7.0), name = "L_initToeEndJnt") )
			pm.joint( self.BipedLimbInitJnts[4], e=True, zso=True, oj='xzy', sao='xup')

			pm.pickWalk( d='up' )

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*2.5/7.0,0,BipedLimbSize*1/7.0), name = "L_initOutFootJnt") )
			pm.joint( self.BipedLimbInitJnts[4], e=True, zso=True, oj='xzy', sao='xup')

			pm.pickWalk( d='up' )

			self.BipedLimbInitJnts.append( pm.joint(p=(BipedLimbSize*1.5/7.0,0,BipedLimbSize*1/7.0), name = "L_initInFootJnt") )
			pm.joint( self.BipedLimbInitJnts[4], e=True, zso=True, oj='xzy', sao='xup')

			pm.select ( clear=True )
示例#53
0
def setAttrFloat(floatSetField , floatValField):
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1,long=1)
    for i in sel:
       pm.setAttr( i + '.mtoa_constant_' + floatSetField.getText(), float(floatValField.getText()))
示例#54
0
    def rig_createFkChain(self, topNode=None):
        ''' Create Fk controls and attributes and SH joint chain '''
        # Get the root locators
        rootLocs = pm.listRelatives('HairRig_MainCnt',children=True)[1:]

        # Per chain
        index = 0
        for chainName, numJnts in zip(self.chainNames, self.chainNumJnts):
            # Chain grp
            chainGrp = pm.group(n=chainName+'_hr_fk_grp', parent=topNode, em=True)
            pm.delete(pm.parentConstraint(rootLocs[index],chainGrp,mo=0))

            # Get locator names
            locNames = ['%s_loc%s'%(chainName,num) for num in range(int(numJnts)) if num != 0]
            locNames.insert(0,'%s_rootLoc'%chainName)

            # Get locator positions
            positions = []
            for loc in locNames:
                positions.append(pm.xform(loc,q=1,ws=1,t=1))

            # Draw fk joint chain
            fkJnts = []
            pm.select(chainGrp,replace=True)
            for i in range(len(positions)):
                fkJnts.append(pm.joint(name=chainName+'_hr_fkJnt_%s'%i, p=positions[i])) 
                
            index = index + 1

            # Create Fk controls and attributes
            label = chainName
            control = 'HairRig_MainCnt'
            fkControl = pm.circle( nr=(0, 0, 1), c=(0, 0, 0), ch=False )[0]

            aim = 'Z'
            twist = 'Y'
            up = 'X'

            # Create main attributes on control
            pm.select(control,r=True)
            attList = pm.attributeInfo(control,all=True)

            if(label not in attList):
                try:
                    pm.addAttr(longName=label,k=True)
                    pm.setAttr(control + '.' + label, lock=True)
                except:
                    pass #Attribute already exists

            #Get data for current limb
            startJnt = pm.listRelatives(chainGrp,children=True)[0]
            pm.select(pm.listRelatives(chainGrp,children=True)[0], hi=True)
            endJnt = pm.ls(sl=1)[-1]

            #Get full chain
            chain = []

            #Get the hierarchy of startJnt, then store it until endJnt is found
            try:
                pm.select(startJnt,r=True,hi=True)
                sel = pm.ls(sl=True,fl=True,type='joint')
                tempChain = sel

                for each in tempChain:
                    if each == endJnt:
                        chain.append(each)
                        break
                    else:
                        chain.append(each)
            except:
                pass

            #Store parent of chain
            parent = pm.listRelatives( chain[0], parent=True)

            #Unparent joints
            for each in chain:
                try:
                    pm.parent(each,w=True)
                except:
                    pass

            #Create duplicate joints above orig joints, then store duplicate joint names
            dupJoints = []
            for joint in chain:
                offName = joint + '_off'
                jnt = pm.duplicate(joint,rr=True,po=True,n=offName)
                dupJoints.append(jnt)

            #Rebuild heirarchy
            x = 0
            while x < len(chain):
                pm.parent(chain[x],dupJoints[x])
                if x != 0:
                    pm.parent(dupJoints[x],chain[x-1])
                x = x + 1

            # Add dynamic switch attribute
            pm.addAttr( control, longName=chainName + '_dynamic', k=True, min=0, max=1 )

            #Adding Curl atts on controller
            x= 0 
            while x < len(chain):
                pm.addAttr(control, longName=chainName + '_curl_' + str(x+1),k=True)
                x = x + 1

            #Adding spread atts on controller
            x= 0 
            while x < len(chain):
                pm.addAttr(control, longName=chainName + '_spread_' + str(x+1),k=True)
                x = x + 1

            #Twist
            pm.addAttr(control, longName=chainName + '_Twist',k=True)

            #Connect attributes to dupJoints rotate's ( aim = curl, up = spread )
            x = 0
            pm.connectAttr( control + '.' + chainName + '_Twist' , str(dupJoints[x][0]) + '.rotate' + twist ) 
            while x < len(chain):
                pm.connectAttr( control + '.' + chainName + '_curl_' + str(x+1) , str(dupJoints[x][0]) + '.rotate' + aim )
                pm.connectAttr( control + '.' + chainName + '_spread_' + str(x+1), str(dupJoints[x][0]) + '.rotate' + up )
                x = x + 1

            #Create fk controllers on joints
            #Duplicate FK control, parent it to chain joints, delete left over transform node
            for each in chain:
                #Duplicate control
                tempCnt = pm.duplicate(fkControl)
                #Select the shape
                tempShp = pm.pickWalk(tempCnt,direction='down')
                pm.parent(tempShp,each,r=True,s=True)
                pm.delete(tempCnt)
            
            pm.parent( dupJoints[0], chainGrp )
            pm.delete( fkControl )
            
            pm.parentConstraint( 'HairRig_MainCnt', chainGrp, mo=True )
示例#55
0
    def rig_createDynamicChain(self, topNode=None): # Returns: [DynJoints], [DynControl], Transform(DynTopNode)
        ''' Create dynamic joint chain '''
        # Get the root locators
        rootLocs = pm.listRelatives('HairRig_MainCnt',children=True)[1:]

        # Per chain
        index = 0
        for chainName, numJnts in zip(self.chainNames, self.chainNumJnts):
            index = index + 1
            
            # Chain grp
            chainGrp = pm.group(n=chainName+'_dyn_grp', parent=topNode, em=True)
            pm.delete(pm.parentConstraint(rootLocs[index-1],chainGrp,mo=0))

            # Get locator names
            locNames = ['%s_loc%s'%(chainName,num) for num in range(int(numJnts)) if num != 0]
            locNames.insert(0,'%s_rootLoc'%chainName)

            # Get locator positions
            positions = []
            for loc in locNames:
                positions.append( pm.xform(loc,q=1,ws=1,t=1) )

            # Draw dynamic joint chain
            dynJnts = []
            pm.select(chainGrp,replace=True)
            for i in range(len(positions)):
                dynJnts.append(pm.joint(name=chainName+'_hr_dynJnt_%s'%i, p=positions[i]))
            
            # Draw curve along dynamic chain
            positions = []
            for jnt in dynJnts:
                positions.append(pm.xform(jnt,q=1,ws=1,rp=1))
            crv = pm.curve( name='chain%s_crv'%index, p=positions, d=1 )
            pm.rebuildCurve( crv, s=5 )
            pm.xform( crv, rp=positions[0], ws=True )
            pm.delete( crv, ch=True )
            pm.parent( crv, topNode )
            
            # Create root nurbs plane
            plane = pm.nurbsPlane( name='dynPlane_%s'%index, d=3, u=2, v=2, ax=[0,-1,0] )[0]
            pm.move(plane, float(positions[0][0]), float(positions[0][1]), float(positions[0][2]), a=1)
            pm.parent( plane, chainGrp )
            
            #Get data for current limb
            startJnt = pm.listRelatives( chainGrp, children=True )[0]
            pm.select(pm.listRelatives( chainGrp, children=True )[0], hi=True )
            endJnt = pm.ls(sl=1)[-1]

            # Make curve dynamic
            pm.select( plane, r=True )
            pm.select( crv, add=True )
            pm.mel.eval( 'makeCurvesDynamicHairs %d %d %d' % (1, 0, 1) )
            
            # Get names for hair system
            temp = pm.pickWalk( crv, d='up' )
            hairSystemName = 'hairSystem%s'%index
            dynCrv = pm.listRelatives( '%sOutputCurves'%hairSystemName,  children=True)[0]
            pm.rename(dynCrv,'dynCrv_%s'%index)
            dynCrv = 'dynCrv_%s'%index
            pm.parent( hairSystemName, chainGrp )
            
            # Make ik spline using dynamic curve
            handle, effector = pm.ikHandle( sj=startJnt, ee=endJnt, sol='ikSplineSolver', c=dynCrv, ccv=False )
            pm.parent( handle, chainGrp )
            
            # Clean up
            follicle = pm.listRelatives( crv, parent=True )[0]
            pm.parent( crv, 'HairRig_MainCnt' )
            pm.parent( follicle, chainGrp )
            pm.delete( '%sOutputCurves'%hairSystemName )
            
            pm.setAttr( '%s.visibility'%follicle, 0 )
            pm.setAttr( '%s.visibility'%crv, 0 )
            pm.setAttr( '%s.visibility'%dynCrv, 0 )
            pm.setAttr( '%s.visibility'%handle, 0 )
            pm.setAttr( '%s.visibility'%plane, 0 )
            pm.setAttr( '%s.visibility'%hairSystemName, 0 )
            
            # Create attributes on main control
            
        return dynJnts
示例#56
0
def setMAT(attrField):
    pm.pickWalk( d = "down" )
    sel = pm.ls(sl=1)
    for i in sel:
        i.mtoa_constant_mMat.set(attrField.getText())