コード例 #1
0
ファイル: core.py プロジェクト: ordinc/rigbits
def get_info(node):
    """
    Given either the SDK box, or Anim ctl, will find other and return it

    Arguments:
        node (PyNode): either the SDK box or Anim ctl

    Returns:
        list [PyNode(SDK box), PyNode(anim ctl)]
    """
    SDK_node = None
    tweak_node = None

    if pm.attributeQuery("is_SDK", node=node, ex=True):
        SDK_node = node
        for connected in pm.listConnections(node.attr("ctl")):
            if pm.attributeQuery("is_tweak", node=connected, ex=True):
                tweak_node = connected

    if pm.attributeQuery("is_tweak", node=node, ex=True):
        tweak_node = node
        for connected in pm.listConnections(node.attr("sdk")):
            if pm.attributeQuery("is_SDK", node=connected, ex=True):
                SDK_node = connected

    return [SDK_node, tweak_node]
コード例 #2
0
    def update_attrs(self, func, status):

        attrs = self.exp_json[func]["attrs"]

        if status:

            for attr, attrType in attrs.items():

                if not pc.attributeQuery(
                        attr, node=self.nparticle.name(), exists=True):
                    pc.addAttr(self.nparticle.name(), ln=attr, dt=attrType)
                    pc.addAttr(self.nparticle.name(),
                               ln=("%s0" % attr),
                               dt=attrType)

        else:

            for attr, attrType in attrs.items():

                if pc.attributeQuery(attr,
                                     node=self.nparticle.name(),
                                     exists=True):

                    if len(
                            pc.listConnections(
                                "%s.%s" % (str(self.nparticle), attr))) == 0:

                        pc.deleteAttr(self.nparticle.name(), at=attr)
                        pc.deleteAttr(self.nparticle.name(), at=("%s0" % attr))

                    else:

                        pc.warning(
                            "Can't remove Attribute:%s(Function:%s), which is being used."
                            % (attr, func))
コード例 #3
0
def messageConnect(fromNode=None, toNode=None, fromName=None, toName=None, category=None):
    '''
    Creates a message attribute on fromNode and toNode with the names fromName and toName respectively
    Connects the two new attributes
    '''
    # validation
    if not fromNode or not toNode and (len(pmc.selected()) == 2):
        fromNode = pmc.selected()[0]
        toNode = pmc.selected()[1]

    if not fromNode or not toNode:
        return 'Argument Error, messageConnect requires fromNode and toNode as either arguments or 2 selected nodes'

    if not fromName or not toName:
        return 'Argument Error, messageConnect requires fromName and toName arguments for newly created attrs'

    # Add attributes
    if pmc.attributeQuery(fromName, node=fromNode, exists=1):
        print '%s.%s: Attribute exists' % (fromNode, fromName)
    else:
        pmc.addAttr(fromNode, ln=fromName, at='message', category=category)
        print '%s.%s: Attribute created' % (fromNode, fromName)

    if pmc.attributeQuery(toName, node=toNode, exists=1):
        print '%s.%s: Attribute exists' % (toNode, toName)
    else:
        pmc.addAttr(toNode, ln=toName, at='message', category=category)
        print '%s.%s: Attribute created' % (toNode, toName)

    # Connect attributes
    pmc.connectAttr('%s.%s' % (fromNode, fromName), '%s.%s' % (toNode, toName), f=1)
    print '%s.%s connected to %s.%s' % (fromNode, fromName, toNode, toName)
コード例 #4
0
ファイル: gui.py プロジェクト: zakuro9715/mgear
    def inspectSettings(self, *args):

        oSel = pm.selected()
        if oSel:
            root = oSel[0]
        else:
            pm.displayWarning(
                "please select one object from the componenet guide")
            return

        comp_type = False
        guide_root = False
        while root:
            if pm.attributeQuery("comp_type", node=root, ex=True):
                comp_type = root.attr("comp_type").get()
                break
            elif pm.attributeQuery("ismodel", node=root, ex=True):
                guide_root = root
                break
            root = root.getParent()
            pm.select(root)

        if comp_type:
            guide = shifter.importComponentGuide(comp_type)
            gqt.showDialog(guide.componentSettings)

        elif guide_root:
            module_name = "mgear.maya.shifter.guide"
            guide = __import__(module_name, globals(), locals(), ["*"], -1)
            gqt.showDialog(guide.guideSettings)

        else:
            pm.displayError(
                "The selected object is not part of component guide")
コード例 #5
0
ファイル: rigGuiBaseClass.py プロジェクト: clamdragon/SurfRig
 def __init__(self, parent, attr):
     self.base = super(MayaFloatSlider, self)
     self.base.__init__(parent)
     if not pmc.objExists(attr):
         msg = "Maya attribute \"{0}\" not found".format(attr)
         raise(NameError(msg))
     self.mult = 100.0
     self.attr = attr
     self.setValue(pmc.getAttr(attr))
     
     # Find if maya object has min & max
     obj, a = attr.split(".")
     if pmc.attributeQuery(a, node=obj, minExists=True):
         sMin = pmc.attributeQuery(a, node=obj, min=True)[0]
     else:
         sMin = -10.0
     if pmc.attributeQuery(a, node=obj, maxExists=True):
         sMax = pmc.attributeQuery(a, node=obj, max=True)[0]
     else:
         sMax = 10.0
     self.setMinimum(sMin * self.mult)
     self.setMaximum(sMax * self.mult)
     
     self.valueChanged.connect(self.valueChangedConvert)
     self.floatValueChanged.connect(self.mayaAttrUpdate)
コード例 #6
0
    def custom_sets(self, *args):
        self.log.clear()
        self.log.insertText('Create Custom Sets...\n')
        self.log.insertText('\nFind all controls under the groups: \n  "Placer", "rig_arc", and "Face_UI|Panels"\n\nGenerate two sets as result : \n  "ctrlSet" contains all tagged controls\n  "_NON_TAGGED_CURVES" contains all non-tagged controls\n')
                
        ctrlSets = pm.ls("*ctrlSet")
        if not ctrlSets:
            self.controlSet = pm.sets(empty=True, name = "ctrlSet")
        
        grps = [grp for grp in ['Placer', 'rig_arc'] if pm.objExists(grp)]
        pm.select(grps, hi=True)
        all_curve = pm.ls(sl=True, type="nurbsCurve")
        pm.select(clear=True)

        all_ctrl = [ctrl.getParent() for ctrl in all_curve]
        
        if pm.objExists('Panels'):
            pm.select('Panels', hi=True)
            all_facial_curve = pm.ls(sl=True, type="nurbsCurve")
            pm.select(clear=True)
            all_ctrl.extend([curve.getParent() for curve in all_facial_curve if curve.getParent().tz.isLocked()]) 
            #pm.sets(all_ctrl, name="_ALL_CURVES")
        
        no_tags = [ctrl for ctrl in all_ctrl if not pm.attributeQuery ('ClientAnimCtrl', node= ctrl, ex=True)]
        pm.sets(no_tags, name="_NON_TAGGED_CURVES")
        
        tags = [ctrl for ctrl in all_ctrl if pm.attributeQuery ('ClientAnimCtrl', node= ctrl, ex=True)]
        self.controlSet.addMembers(tags)
コード例 #7
0
def createCurveControl(controlObj, controlAttribute, destinationAttribute):
    '''
    Script:     js_createCurveControl.mel
    Author:     Jason Schleifer

    Descr:      This script will create a single curve which can be used to control
                the given attribute on the selected objects.

                For example, if you want to drive the ty attribute on 10 objects with
                a "height" curve on another object, you would select the 10 objects,
                and then enter:

                js_createControlCurve controlObj height ty

                Note: make sure the given object and attribute exists
    '''

    if not pm.objExists(controlObj):
        pm.pm.mel.error(controlObj + " does not exist.  Exiting..\n")

    if not pm.attributeQuery(controlAttribute, node=controlObj, exists=1):
        pm.addAttr(controlObj, ln=controlAttribute, at='double')
        pm.setAttr((controlObj + "." + controlAttribute), k=1)

    # find the selected objects
    objs = pm.ls(sl=1)
    if len(objs) == 0:
        pm.pm.mel.error("Nothing Selected.\n")

    numControls = len(objs)
    # now that we have the objects, we can create the animation curve which will control the attribute
    objAttr = (controlObj + "." + controlAttribute)
    pm.setKeyframe(controlObj, v=0, at=controlAttribute, t=1)
    pm.setKeyframe(controlObj, v=0, at=controlAttribute, t=numControls)
    pm.keyTangent(controlObj, wt=1, at=controlAttribute)
    pm.keyTangent(controlObj, at=controlAttribute, weightLock=False)
    pm.keyTangent(objAttr, a=1, e=1, t=1, outAngle=50)
    pm.keyTangent(objAttr, a=1, e=1, t=numControls, inAngle=-50)
    # next, we'll create frameCache nodes for each object, and attach them to the object's attribute
    for x in range(0, numControls):
        fc = pm.createNode('frameCache')
        # create the frameCache node
        fc = pm.rename(fc, (str(objs[x]) + "_frameCache"))
        # connect the attribute
        pm.connectAttr(objAttr, (str(fc) + ".stream"))
        # set the frame
        pm.setAttr((str(fc) + ".vt"), (x + 1))
        # connect the output
        # check and see if the destination attribute exists.  if not, create it
        if not pm.attributeQuery(destinationAttribute, node=objs[x], exists=1):
            pm.addAttr(objs[x], ln=destinationAttribute, at='double')
            pm.setAttr((str(objs[x]) + "." + destinationAttribute), k=1)

        pm.connectAttr((str(fc) + ".v"),
                       (str(objs[x]) + "." + destinationAttribute),
                       f=1)

    pm.select(objAttr)
コード例 #8
0
def create_attribute_proxy(node, attr):
    """
    Create a proxy for attr on node.  Return the new attribute.
    """
    # Be sure to assign both the long and short name.  Being inconsistent with the
    # original attribute can lead to issues with the CB.
    short_name = pm.attributeQuery(attr.attrName(), node=attr.node(), shortName=True)
    long_name = pm.attributeQuery(attr.attrName(), node=attr.node(), longName=True)
    pm.addAttr(node, ln=long_name, sn=short_name, proxy=attr)
    return node.attr(long_name)
コード例 #9
0
ファイル: gtags.py プロジェクト: Wizard-collab/Wizard
def tagGuerilla(*arg):
    mesh_List = pm.ls(sl=1)
    slectionChild_List = pm.listRelatives(mesh_List, ad=1)
    if mesh_List:
        tagName = tagGuerillaText.getText()
        for mesh in slectionChild_List:
            parentMesh = mesh.getParent()
            if mesh.nodeType() == 'mesh' or mesh.nodeType() == 'camera':
                if pm.iconTextButton(addMoreTagButton, q=1, l=1) == 'off':
                    if pm.attributeQuery('GuerillaTags',
                                         node=parentMesh,
                                         exists=1) == 1:
                        pm.setAttr(parentMesh.GuerillaTags,
                                   tagName,
                                   type="string")

                    elif pm.attributeQuery('GuerillaTags',
                                           node=parentMesh,
                                           exists=1) == 0:
                        pm.addAttr(parentMesh, ln="GuerillaTags", dt="string")

                        pm.setAttr(parentMesh.GuerillaTags,
                                   tagName,
                                   type="string")

                elif pm.iconTextButton(addMoreTagButton, q=1, l=1) == 'on':
                    if pm.attributeQuery('GuerillaTags',
                                         node=parentMesh,
                                         exists=1):
                        currentAttr = parentMesh.name() + '.GuerillaTags'
                        currentTag = pm.getAttr(currentAttr)
                        currentSplit = currentTag.split(',')
                        checker_if_tag_in = 'no'
                        for tag in currentSplit:
                            if tag == tagName:
                                checker_if_tag_in = 'yes'

                        if checker_if_tag_in == 'no':
                            totalName = currentTag + ',' + tagName
                            pm.setAttr(parentMesh.GuerillaTags,
                                       totalName,
                                       type="string")

                    elif pm.attributeQuery('GuerillaTags',
                                           node=parentMesh,
                                           exists=1) == 0:

                        pm.addAttr(parentMesh, ln="GuerillaTags", dt="string")

                        pm.setAttr(parentMesh.GuerillaTags,
                                   tagName,
                                   type="string")

    else:
        pm.warning('Select object to assign Guerilla Tags')
コード例 #10
0
ファイル: assetManager.py プロジェクト: zhmig/AnimationDNA
def checkAttr(*args):
    # CHECK MTOA CUSTOM ATTR
    attrList = ['mColor', 'mMat']  # attributes to check LIST
    list = pm.ls(type='geometryShape')  # select all geo shapes
    setNo = pm.sets(em=1, name='NO_CUSTOM_ATTR'
                    )  # create SET for objecs without custom attributes
    for e in attrList:
        set = pm.sets(em=1,
                      name='EMPTY_' + str(e))  # create SET for blank ATTR
        for i in list:
            if pm.attributeQuery('mtoa_constant_%s' % e, node=i,
                                 ex=1):  # check if attribute exists
                if not i.attr('mtoa_constant_%s' %
                              e).get():  # check if attribute has any value
                    set.add(i)
            else:
                if not len(i.split('_Prx')) == 2:
                    setNo.add(i)
    # CHECK ATTRIBUTES ON TRANSFORMS
    transform = pm.ls(type='transform')  # select all transforms
    setTRS = pm.sets(em=1, name='ATTR_TRANS')
    for i in transform:
        if pm.attributeQuery('mtoa_constant_mMat', node=i,
                             ex=1):  # check if attribute exists
            setTRS.add(i)
    # CHECK BLANK SUBD
    setSBD = pm.sets(em=1, name='NO_SUBDIV')
    listAtrSBD = pm.ls('*.aiSubdivType')
    for i in listAtrSBD:
        if not i.split('.')[0].split(
                '_')[-1] == 'Prx':  # remove PROXY object from check
            if i.get() == 0:
                object = pm.PyNode(i.split('.')[0])
                setSBD.add(object)
    # Check SG
    listSG = pm.ls(type='shadingEngine')
    listSG.remove('initialParticleSE')
    listSG.remove('initialShadingGroup')
    listFile = pm.ls(type='file')
    listSHN = listFile + listSG
    if listSHN:
        setSHN = pm.sets(em=1, name='__(SHN)__')
    # Check TX
    listAtr = pm.ls('*.mtoa_constant_mColor')
    if listAtr:
        setJPG = pm.sets(em=1, name='ERROR_IN_mColor')
        for i in listAtr:
            txt = i.get()
            if txt:
                if not txt.split('.')[-1] == 'tx':
                    object = pm.PyNode(i.split('.')[0])
                    setJPG.add(object)
コード例 #11
0
        def applyCloseComp( root, *args):
            newName = pName.getText()
            newSide = pSide.getValue()
            newIndex = pIndex.getValue1()
            if pm.attributeQuery("mode", node=root, ex=True):
                root.attr("mode").set(modeSet.index(pMode.getValue()))
            if pm.attributeQuery("default_rotorder", node=root, ex=True):
                root.attr("default_rotorder").set(rotOrderSet.index(pRotOrder.getValue()))

            guide = shifter.RigGuide()
            guide.updateProperties(root, newName, newSide, newIndex)
            pm.select(root, r=True)

            pm.deleteUI(window, window=True)
コード例 #12
0
ファイル: CGEV_genLib.py プロジェクト: Rotomator/noid
def attrCmd(mode=0,
            cmd='',
            nodes=list(),
            attrList=list(),
            dataType=list(),
            value=list()):
    '''
    2 modes to control attr :

    -0 add attr
    -1 delete ,set,get attr

    '''

    listAttr = list()

    for node in nodes:

        attrs = list()
        values = list()

        i = 0
        for attr in attrList:

            if mode == 0:
                if pm.attributeQuery(attr, n=node, exists=True) == False:

                    if dataType[i] == 'string':
                        pm.addAttr(node, ln=attr, dt=dataType[i])
                    else:
                        pm.addAttr(node, ln=attr, at=dataType[i])

            elif mode == 1:

                if pm.attributeQuery(attr, n=node, exists=True) == True:
                    attrs.append(attr)
                    nodeAttr = node.attr(attr)

                    if cmd == 'delete':
                        funct = getattr(nodeAttr, cmd)()

                    else:
                        funct = getattr(nodeAttr, cmd)(value[i])
                        values.append(funct)

            i += 1
        listAttr.append({'node': node, 'attrs': attrs, 'values': values})
    return listAttr
コード例 #13
0
    def migrate(self, weights, new_mesh=''):

        if not new_mesh:
            om.MGlobal.displayError("No target mesh found in selection")
            return

        # new blend shape name
        new_BS_node = self.targetNode + '_' + \
            str(random.randint(4145, 1514545442))
        self.new_blendshape_node = new_BS_node

        # create BS node
        pm.blendShape(new_mesh, n=new_BS_node, foc=True)

        for idx, item in enumerate(weights):
            newTarg = item

            #
            pm.blendShape(new_BS_node,
                          edit=True,
                          t=(new_mesh, idx, str(newTarg), 1.0))

            if pm.attributeQuery('parent', node=newTarg, exists=True):
                downstreamNodes = pm.listConnections('{}.{}'.format(
                    newTarg, 'parent'),
                                                     d=True)

                for inBet in downstreamNodes:
                    val = float('%.3f' % pm.getAttr(inBet + '.value'))
                    pm.blendShape(new_BS_node,
                                  edit=True,
                                  t=(new_mesh, idx, inBet, float(val)))
コード例 #14
0
def resetAttrs(ctls):
    for ctl in ctls:
        attrs = ctl.listAttr(k=True)
        attrs = [attr for attr in attrs if attr.isFreeToChange()==0]
        for attr in attrs:
            dv = pm.attributeQuery(attr.attrName(), n=attr.node(), ld=True)[0]
            attr.set(dv)
コード例 #15
0
ファイル: utils.py プロジェクト: Quazo/breakingpoint
def attrType(attr):
    type = pm.getAttr(attr, type=True)
    if type == 'float3':
        node, at = attr.split('.', 1)
        if pm.attributeQuery(at, node=node, usedAsColor=1):
            type = 'color'
    return type
コード例 #16
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
コード例 #17
0
def rad_load_associations():
    someFailures = False
    targetFile = ""
    files = cmds.fileDialog2(dialogStyle=2, fileFilter="*.radpw", fileMode=1, caption="Load Pickwalk Configuration", okCaption="Load")
    if files:
        if len(files) > 0:
            targetFile = files[0]
    if not targetFile:
        return
    allNodes = cmds.ls(recursive=True)
    with open(targetFile) as f:
        for line in f:
            if not line.startswith("This"):
                infoArray = line.split()
                # node-name dir dir dir dir
                nodeName = infoArray[0]
                if pm.objExists(nodeName):
                    infoIndex = 1
                    for direction in DIRECTIONS:
                        dirNode = infoArray[infoIndex]
                        infoIndex += 1
                        if dirNode != "null":
                            try:
                                if not pm.attributeQuery(dir_to_attr(direction), node=nodeName, exists=True):
                                    pm.addAttr(nodeName, longName=dir_to_attr(direction), attributeType="message")
                                make_pick_walk(nodeName, dirNode, direction)
                            except:
                                print "Error during load of " + nodeName + " -> " + direction + " -> " + dirNode
                                someFailures = True
    if someFailures:
        pm.warning("Some relationships failed to load (possibly due to different set of nodes)")
コード例 #18
0
 def assign_attr(self, dic_nodes, name, node_attr, attr_name, attr_value):
     if isinstance(attr_value[1], list):
         if pm.attributeQuery(attr_name, node=dic_nodes[name], nc=1):
             for idx, attr_child in enumerate(node_attr.getChildren()):
                 if attr_child.isLocked() or attr_child.isConnected():
                     return
                 try:
                     attr_child.set(attr_value[1][idx])
                 except:
                     om.MGlobal.displayWarning(
                         'Can not set attribute {} ...'.format(attr_child))
         else:
             om.MGlobal.displayWarning('{} error ...'.format(node_attr))
     elif isinstance(attr_value[1], dict):
         om.MGlobal.displayError(
             'Attribute {} have a dictionary ...'.format(node_attr))
     else:
         if node_attr.isChild():
             node_attr_parent = node_attr.getParent()
             if node_attr_parent.isLocked() or node_attr_parent.isConnected(
             ):
                 return
         try:
             node_attr.set(attr_value[1])
         except:
             om.MGlobal.displayWarning(
                 'Can not set attribute {} ...'.format(node_attr))
コード例 #19
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)
コード例 #20
0
    def drawPoses(self, ctrl=None):
        """ Create individual control fields """
        attrs = self.getControlAttrs(ctrl=ctrl)
        self.poseVLayout.addWidget(QtGui.QLabel(str(ctrl)))
        for attr in attrs:
            if attr:
                try:
                    if attr == 'distance':
                        minV, maxV = -20, 20
                        pose = PoseWidget.PoseWidget(self.poseScrollArea,
                                                     sliderEnabled=False)
                        pose.setup(ctrl, attr, minV, maxV)
                    else:
                        minV, maxV = pm.attributeQuery(attr,
                                                       node=ctrl,
                                                       range=True)
                        pose = PoseWidget.PoseWidget(self.poseScrollArea)
                        pose.setup(ctrl, attr, minV, maxV)
                except Exception, e:
                    pose = PoseWidget.PoseWidget(self.poseScrollArea,
                                                 sliderEnabled=False)
                    pose.setup(ctrl, attr, -1000, 1000)

                self.poseVLayout.addWidget(pose)
                self.poses.append(pose)
コード例 #21
0
ファイル: My_use.py プロジェクト: lisy0123/Maya_Scripts
def addAttr(tmp):
    attr_text = cmds.textField(attr_tx, q=True, tx=True)
    
    objs = pm.ls(sl=True)
    for obj in objs:
        if tmp == 0:
            if cmds.checkBox(attr_check, q=True, v=True):
                pm.addAttr(obj, ln=attr_text, at="double", dv=0)
                pm.setAttr(obj+"."+attr_text, k=True)
            else:
                min_num = float(cmds.textField(min_attr, q=True, tx=True))
                max_num = float(cmds.textField(max_attr, q=True, tx=True))
                pm.addAttr(obj, ln=attr_text, at="double", dv=0, min=min_num, max=max_num)
                pm.setAttr(obj+"."+attr_text, k=True)
        elif tmp == 1:
                en = cmds.textField(en01_tx, q=True, tx=True)
                pm.addAttr(obj, ln=attr_text, at="enum", en=en)
                pm.setAttr(obj+"."+attr_text, k=True)
        else:
            cnt = 0
            flag = True
            while flag:
                cnt_str = "separator"+str(cnt)
                if pm.attributeQuery(cnt_str, n=obj.name(), ex=True):
                    cnt += 1
                else:
                    pm.addAttr(obj, ln=cnt_str, nn="----------", at="enum", en="--------:")
                    pm.setAttr(obj+"."+cnt_str, cb=True)
                    flag = False
コード例 #22
0
def getAttrsFromChannelbox():
    '''
    채널박스에서 선택된 어트리뷰트 이름 리턴
    블렌드 쉐입은 잘 안됨..ㅠㅠㅠ
    @return: 어트리뷰트 리스트 리턴
    '''
    mainObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                             q=True,
                             mainObjectList=True)
    mainAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                              q=True,
                              selectedMainAttributes=True)

    shapeObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                              q=True,
                              shapeObjectList=True)
    shapeAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                               q=True,
                               selectedShapeAttributes=True)

    histObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                             q=True,
                             historyObjectList=True)
    histAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                              q=True,
                              selectedHistoryAttributes=True)

    outputObjs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                               q=True,
                               outputObjectList=True)
    outputAttrs = pm.channelBox(pm.melGlobals['gChannelBoxName'],
                                q=True,
                                selectedOutputAttributes=True)

    shortNames = []
    for pair in ((mainObjs, mainAttrs), (shapeObjs, shapeAttrs),
                 (histObjs, histAttrs), (outputObjs, outputAttrs)):
        objs, attrs = pair
        # print pair
        if attrs:
            for obj in objs:
                for attr in attrs:
                    shortNames.append('%s.%s' % (obj, attr))

    longNames = []
    for pair in ((mainObjs, mainAttrs), (shapeObjs, shapeAttrs),
                 (histObjs, histAttrs), (outputObjs, outputAttrs)):
        objs, attrs = pair
        # print pair
        if attrs is not None:
            for node in objs:
                result = [
                    objs[0] + '.' + pm.attributeQuery(attr, n=node, ln=True)
                    for attr in attrs
                ]
                longNames.extend(result)

    longNames = list(set(longNames))

    return shortNames
コード例 #23
0
 def trackDag(self,inCon,nodeType):
     """
     uses the inCon as a source to track down the dag network to find 
     and return all nodes that are driven by the output attr on it
     """
     
     retValue=[]
     if pm.attributeQuery("output",n=inCon,ex=True):
         outs=pm.listConnections("{0}.output".format(inCon),s=0,d=1,p=1) 
         for out in outs:
             outNode=pm.PyNode(str(out).split(".")[0])
             attr=str(out).split(".")[1]
             if isinstance(nodeType, list):
                 for x in nodeType:
                     tempValue=None
                     if isinstance(outNode,x):
                         tempValue=(outNode,attr)
                     else:
                         tempValue=(self.trackDag(outNode,nodeType))
                 
                     if tempValue:
                         retValue.append(tempValue)
                         break        
             else:
                 if isinstance(outNode,nodeType):
                     retValue.append((outNode,attr))
                 else:
                     retValue.append(self.trackDag(outNode,nodeType))
         if len(retValue)>1:
             return retValue
         else:
             return retValue[0]
     else:
         return None
コード例 #24
0
def identifyCustomAttrs(control):
    '''
    Returns a list of attributes not made by the tool.
    
    Such attrs include 'space', 'stretch' (on ik) and so forth.
    
    
    :return: {'type': 'double', 'min': -3, 'max': 45}
    '''
    userKeyable = listAttr(control, ud=True, k=True)

    mainCtrl = core.findNode.leadController(control)

    func = mainCtrl.getCreateFunction()

    attrInfo = {}

    createAttrs = list(itertools.chain(func.fossilDynamicAttrs, ['space']))

    for attr in userKeyable:

        if attr not in createAttrs:

            attrInfo[attr] = {
                'attributeType': attributeQuery(attr, n=control, at=True)
            }

            min, max = control.attr(attr).getRange()

            if min is not None:
                attrInfo[attr]['min'] = min
            if max is not None:
                attrInfo[attr]['max'] = max

    return attrInfo
コード例 #25
0
def attrType(attr):
    type = pm.getAttr(attr, type=True)
    if type == 'float3':
        node, at = attr.split('.', 1)
        if pm.attributeQuery(at, node=node, usedAsColor=1):
            type = 'color'
    return type
コード例 #26
0
 def get_texture_file_node(self):
     # Get texture file node
     texturesList = pm.ls(textures=True)
     if texturesList :
         for tex in texturesList:
             if pm.attributeQuery( 'fileTextureName',node=tex,exists=1 ):
                 self.Texture_File_Nodes.add(tex)
コード例 #27
0
def make_pick_walk_button_click(name):
    button = main_buttons[name]
    if not button:
        raise NameError("Invalid button: " + name)
    direction = ""
    if name == UP_BUTTON:
        direction = "up"
    elif name == DOWN_BUTTON:
        direction = "down"
    elif name == LEFT_BUTTON:
        direction = "left"
    elif name == RIGHT_BUTTON:
        direction = "right"
    else:
        raise NameError("Invalid button: " + name)

    attr_name = dir_to_attr(direction)

    centre_obj = main_buttons[CENTRE_BUTTON]
    centre_obj_name = centre_obj.getLabel()
    print centre_obj_name
    print rad_pick_walk_mode
    if pm.objExists(centre_obj_name):
        if rad_pick_walk_mode == CREATE_MODE_NAME:
            selection = pm.ls(selection=True)
            if selection:
                if not pm.attributeQuery(
                        attr_name, node=centre_obj_name, exists=True):
                    pm.addAttr(centre_obj_name,
                               longName=attr_name,
                               attributeType="message")

                if centre_obj_name == selection[0]:
                    pm.confirmDialog(
                        message="Can't pickwalk to itself, silly...")
                    pm.error("Can't pickwalk to self, silly...")
                else:
                    make_pick_walk(centre_obj_name, selection[0], direction)
            else:
                label = button.getLabel()
                if label != "blank":
                    result = pm.confirmDialog(
                        message=
                        "You have nothing selected. Do you want to clear the "
                        + direction + " direction for " + centre_obj_name +
                        "?",
                        button=["Yes", "No"],
                        cancelButton="No")
                    if result == "Yes":
                        connections = pm.listConnections(centre_obj_name +
                                                         "." + attr_name)
                        if connections:
                            break_pick_walk(centre_obj_name, connections[0],
                                            direction)

        elif rad_pick_walk_mode == NAV_MODE_NAME:
            rad_pick_walk(direction, False)
            add_selected_obj_to_middle()

    update_pick_walk_window()
コード例 #28
0
def resetAttrs(ctls):
    for ctl in ctls:
        attrs = ctl.listAttr(k=True)
        attrs = [attr for attr in attrs if attr.isFreeToChange() == 0]
        for attr in attrs:
            dv = pm.attributeQuery(attr.attrName(), n=attr.node(), ld=True)[0]
            attr.set(dv)
コード例 #29
0
    def isViewableMaster(self, master):
        if isinstance(master, type('')) and pm.objExists(master):
            master = pm.PyNode(master)

        if pm.attributeQuery('lca_viewable', node=master, exists=True):
            return True
        return False
コード例 #30
0
    def setPreviewColorAttrib(self, shader, color):
        # TODO: it's very slow. OpenMaya is more preferable
        attrName = 'rdo_walter_previewColor'
        if not pm.attributeQuery(attrName, node=shader, exists=True):
            pm.addAttr(shader, longName=attrName, dt='float3')

        pm.setAttr(shader + '.' + attrName, color, type='float3')
コード例 #31
0
def tagGuerillaAuto(*arg):
    selectionGuerilla_List = pm.ls(sl=1)
    asset = asset_core.string_to_asset(os.environ[defaults._asset_var_])

    if selectionGuerilla_List:
        for mesh in selectionGuerilla_List:
            if pm.attributeQuery('GuerillaTags', node=mesh, exists=1) == 0:
                pm.addAttr(mesh, ln="GuerillaTags", dt="string")

            currentAttr = mesh.name() + '.GuerillaTags'
            currentTag = pm.getAttr(currentAttr)

            tags_list = []
            if currentTag:
                tags_list = currentTag.split(',')

            if mesh.name() not in tags_list:
                tags_list.append(mesh.name())
            if asset.category not in tags_list:
                tags_list.append(asset.category)
            if asset.name not in tags_list:
                tags_list.append(asset.name)
            if asset.variant not in tags_list:
                tags_list.append(asset.variant)
            name_variant = '{}_{}'.format(asset.name, asset.variant)
            if name_variant not in tags_list:
                tags_list.append(name_variant)

            attrs = (',').join(tags_list)

            pm.setAttr(mesh + '.GuerillaTags', attrs, type="string")

    else:
        pm.warning('Your selection is empty')
コード例 #32
0
    def reset_node(cls, node):

        for attr in node.listAttr(k=True):

            attr_name = attr.name(includeNode=False)

            if 'scale' in attr_name:
                value = 1.0

            elif 'translate' in attr_name or 'rotate' in attr_name:
                value = 0.0

            else:
                continue

            try:
                attr.set(value)

            except Exception:
                pass

        for attr in node.listAttr(k=True, ud=True):
            value = pm.attributeQuery(
                attr.name(includeNode=False),
                node=node,
                listDefault=True,
            )

            try:
                attr.set(value)

            except Exception:
                continue
コード例 #33
0
def attrfun(arg):
    sels = pm.ls(sl=1)
    attrname =pm.textField('attnamefield',q=True,tx=True)
    attrvalue = pm.textField('attvaluefield',q=True,tx=True)
    for sel in sels:
        newattrname = sel+"."+attrname
        attrealname = [a for a in sel.listAttr() if a.upper() ==newattrname.upper()]
        if attrealname!=[]:
            attrtype = pm.attributeQuery(attrealname[0].split(".")[-1],node = pm.general.PyNode(attrealname[0].split(".")[0]),at=1)
            try:
                if attrtype =="float":
                    if len(attrvalue.split(","))==1:
                        pm.setAttr(attrealname[0],float(attrvalue))
                    else:
                        pm.setAttr(attrealname[0],float(attrvalue.split(",")[0]))
                elif attrtype =="float3":
                    if len(attrvalue.split(","))==3:
                        colorR,colorG,colorB =  attrvalue.split(",")
                        pm.setAttr(attrealname[0],float(colorR),float(colorG),float(colorB))
                elif attrtype =="typed":
                    if len(attrvalue.split(","))==1:
                        pm.setAttr(attrealname[0],str(attrvalue),type="string")
                    else:
                        pass
            except:
                pass
コード例 #34
0
    def saveCharacterInfo(self):

        self.characterInfo['character_name'] = self.characterName
        self.characterInfo['character_root_module_info'] = {
            'name': self.characterRootModule.name,
            'type': self.characterRootModule.moduleType
        }
        self.characterInfo[
            'character_root_group'] = self.characterRootGrp.name()
        self.characterInfo[
            'character_modules_group'] = self.characterModulesGrp.name()
        self.characterInfo['character_controller'] = self.characterCtrl.name()
        self.characterInfo[
            'character_modules_info'] = self.characterModulesInfo
        strInfo = pickle.dumps(self.characterInfo)

        if pm.attributeQuery('characterInfo',
                             node=self.characterRootGrp.name(),
                             ex=1):
            pm.setAttr(self.characterRootGrp.name() + '.characterInfo',
                       str(strInfo),
                       type='string')
        else:
            utils.addStringAttr(self.characterRootGrp, 'characterInfo',
                                strInfo)
コード例 #35
0
 def convert_all_texture_to_relative(self):
     self.get_texture_file_node()
     for x in self.Texture_File_Nodes:
         if pm.attributeQuery( 'fileTextureName',node=x,exists=1 ):
             n = x.fileTextureName.get()
             if n :
                 x.fileTextureName.set( self.convert_to_relative('sourceimages', n) )
コード例 #36
0
ファイル: assetManager.py プロジェクト: kiryha/AnimationDNA
def checkAttr(*args): 
    # CHECK MTOA CUSTOM ATTR                                       
    attrList = [ 'mColor' , 'mMat' ] # attributes to check LIST 
    list = pm.ls(type = 'geometryShape') # select all geo shapes
    setNo = pm.sets(em = 1, name = 'NO_CUSTOM_ATTR' ) # create SET for objecs without custom attributes
    for e in attrList:
        set = pm.sets(em = 1, name = 'EMPTY_' + str(e) ) # create SET for blank ATTR
        for i in list:
            if pm.attributeQuery('mtoa_constant_%s' % e , node = i , ex = 1): # check if attribute exists
                if not i.attr('mtoa_constant_%s' % e ).get(): # check if attribute has any value
                    set.add(i)
            else:
                if not len(i.split('_Prx'))== 2:
                    setNo.add(i)
    # CHECK ATTRIBUTES ON TRANSFORMS                
    transform =  pm.ls(type = 'transform') # select all transforms
    setTRS =  pm.sets(em = 1, name = 'ATTR_TRANS' ) 
    for i in transform:
        if pm.attributeQuery('mtoa_constant_mMat' , node = i , ex = 1): # check if attribute exists
            setTRS.add(i)
    # CHECK BLANK SUBD
    setSBD = pm.sets(em = 1, name = 'NO_SUBDIV' ) 
    listAtrSBD = pm.ls('*.aiSubdivType')
    for i in listAtrSBD:
        if not i.split('.')[0].split('_')[-1] == 'Prx': # remove PROXY object from check
            if i.get() == 0:
                object = pm.PyNode(i.split('.')[0])
                setSBD.add(object)
    # Check SG
    listSG = pm.ls(type = 'shadingEngine')
    listSG.remove('initialParticleSE')
    listSG.remove('initialShadingGroup')
    listFile = pm.ls(type = 'file')
    listSHN =  listFile + listSG
    if listSHN:
        setSHN = pm.sets(em = 1, name = '__(SHN)__' )
    # Check TX
    listAtr = pm.ls('*.mtoa_constant_mColor')
    if listAtr:
        setJPG = pm.sets(em = 1, name = 'ERROR_IN_mColor' )
        for i in listAtr:
            txt = i.get()
            if txt:
                if not txt.split('.')[-1] == 'tx':
                    object = pm.PyNode(i.split('.')[0])
                    setJPG.add(object)
コード例 #37
0
 def _connect_output(self):
     for key, value in self.output.iteritems():
         src = "%s.%s" % (self.control_group, key)
         if pm.attributeQuery(key, node=self.control_group, exists=True):
             pm.connectAttr(src, value, f=True)
             print "Connecting %s to %s" % (src, value)
         else:
             pm.warning("Invalid Attribute %s" % src)
コード例 #38
0
ファイル: class_module.py プロジェクト: adamfok/afok_toolset
 def add_data(self, **kwargs):
     '''
     add_data logic:
         input type:          result:
         
         string               connection (object exists)
         string               connection (found . // ie: obj.tx)
         string               string
         
         None                 connection
         
         tuple                enum
         
         list                 multi (connections)
         
         int                  long
         float                double
         boolean              bool
         
     '''
     
     print "\t\tAdd Module Attribute"
     for key, value in kwargs.iteritems():
         
         #check if attr exists
         if pm.attributeQuery( key,  n=self.node, exists=True ): #attribute exists
             print "\t\t\tAttribute(%s) already exists" %key
             continue
         
         #add attribute
         print '\t\t\tAdding Attribute(%s)' %key
         if type(value) is StringType: #string
             if value.find('.') != -1 or pm.objExists(value): #connection or existing object
                 self.node.addAttr(key, at='message') 
             else:   #non existing string
                 self.node.addAttr(key, dt='string')
                 
         elif type(value) is TupleType: #enum
             self.node.addAttr(key, at='enum', en='null')
         
         elif type(value) is NoneType: #None
             self.node.addAttr(key, at='message')
             
         elif type(value) is ListType: #list
             self.node.addAttr(key, multi=True)
             
         elif type(value) is IntType: #int
             self.node.addAttr(key, at='long')
         
         elif type(value) is FloatType: #float
             self.node.addAttr(key, at='double')
                                 
         elif type(value) is BooleanType: #boolean
             self.node.addAttr(key, at='bool')
             
         else: print "Invalid Type for Attribute (%s)" %key
     
     self.set_data(**kwargs)                        
コード例 #39
0
ファイル: Gui.py プロジェクト: Svegarn/Tron3k_Exporter
    def __init__(self, ui):
        QObject.__init__(self)
	
	cmds.loadPlugin(os.getenv('MAYA_SCRIPT_PATH').split(';')[2] + "/OnImportSettings.mll")
	
        # Assembler
        ui.buttonCreateObject.clicked.connect(self.buttonCreateObjectClicked)
        ui.buttonAddObject.clicked.connect(self.buttonAddObjectClicked)
        ui.buttonCreatePh.clicked.connect(self.buttonCreatePhClicked)
        ui.buttonReplacePh.clicked.connect(self.buttonReplacePhClicked)
        ui.buttonCreateOBB.clicked.connect(self.buttonCreateOBBClicked)
        ui.buttonRemoveAttr.clicked.connect(self.buttonRemoveAttrClicked)
        ui.buttonExit2.clicked.connect(self.buttonExitClicked)
	
	# Room/Portal Management
	ui.buttonHide.clicked.connect(self.buttonHideClicked)
	ui.buttonHideAllRoom.clicked.connect(self.buttonHideAllRoomClicked)
	ui.buttonHideAllPortal.clicked.connect(self.buttonHideAllPortalClicked)
	ui.buttonHideContent.clicked.connect(self.buttonHideContentClicked)
	ui.buttonHideContentRoom.clicked.connect(self.buttonHideContentRoomClicked)
	ui.buttonHideContentPortal.clicked.connect(self.buttonHideContentPortalClicked)
	ui.buttonHideContentNonSelected.clicked.connect(self.buttonHideContentNonSelectedClicked)
	ui.buttonHideNonSelected.clicked.connect(self.buttonHideNonSelectedClicked)
	ui.buttonRefresh.clicked.connect(self.buttonRefreshClicked)
	ui.buttonExit3.clicked.connect(self.buttonExitClicked)
        
        # Exporter
        ui.buttonExit.clicked.connect(self.buttonExitClicked)
        ui.exportAll.clicked.connect(self.exportAllChecked)
        ui.exportCharacter.clicked.connect(self.uncheckAllBox)
        ui.exportAnimation.clicked.connect(self.uncheckAllBox)
        ui.buttonExportAnimated.clicked.connect(self.buttonExportAnimatedClicked)
        ui.buttonExportStatic.clicked.connect(self.buttonExportStaticClicked)
        
        # UI
        self.ui = ui
	#self.ui.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint);
        self.ui.show()
	self.ui.activateWindow()
        
        transPath = OM.MDagPath()
        transIt = OM.MItDag(OM.MItDag.kBreadthFirst, OM.MFn.kTransform)
        self.ui.placeholderList.setSortingEnabled(True)
        duplicateCount = 0
        while not transIt.isDone():
            if not(transIt.getPath(transPath)):
                transform = OM.MFnTransform(transPath)          
                
                if pm.attributeQuery("Placeholder", node=transform.name(), exists=True):
                    attribute = transform.name() + ".Placeholder"
                    placeholderType = pm.getAttr(attribute)
                    
                    placeholderExists = self.ui.placeholderList.findItems(placeholderType, Qt.MatchCaseSensitive)
                    if len(placeholderExists) == 0:
                        self.ui.placeholderList.addItem(placeholderType)
    
            transIt.next()        
コード例 #40
0
 def convert_texture_to_relative(self):
     self.Texture_Files = set()
     # Get texture file
     texturesList = pm.ls(textures=True)
     if texturesList :
         for tex in texturesList:
             if pm.attributeQuery( 'fileTextureName',node=tex,exists=1 ):
                 texFile = tex.fileTextureName.get()
                 tex.fileTextureName.set( self.convert_to_relative(self.RuleEntry_SourceImages, texFile) )
コード例 #41
0
ファイル: renderManager.py プロジェクト: kiryha/AnimationDNA
def matAsignSel(): # ASIGN MATERIAL FOR SELECTED OBJECTS
    sel = pm.ls(dag=1,o=1,s=1,sl=1)
    print sel
    for i in sel:
        if pm.attributeQuery( 'mtoa_constant_mMat' , node = i , exists = 1):
            mat = i.mtoa_constant_mMat.get()
            print mat
            if mat:
                asign = pm.sets(str(mat) + 'SG', forceElement = i)  
コード例 #42
0
 def convert_tga_to_jpg(self):
     self.Texture_Files = set()
     # Get texture file
     texturesList = pm.ls(textures=True)
     if texturesList :
         for tex in texturesList:
             if pm.attributeQuery( 'fileTextureName',node=tex,exists=1 ):
                 texFile = tex.fileTextureName.get()
                 if texFile.endswith('.tga') or texFile.endswith('.TGA'):
                     tex.fileTextureName.set( texFile.replace('.TGA','.tga').replace('.tga','.jpg') )
コード例 #43
0
ファイル: aiCreateAttr.py プロジェクト: mkolar/Tapp
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)
コード例 #44
0
ファイル: aiCreateAttr.py プロジェクト: mkolar/Tapp
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!'
コード例 #45
0
ファイル: aiCreateAttr.py プロジェクト: mkolar/Tapp
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')
コード例 #46
0
ファイル: attrManager.py プロジェクト: mkolar/AnimationDNA
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')
コード例 #47
0
ファイル: attrManager.py プロジェクト: mkolar/AnimationDNA
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!'
コード例 #48
0
 def resetAttrs(ctls):
     for ctl in ctls:
         attrs = ctl.listAttr(k=True)
         attrs = [attr for attr in attrs if attr.isFreeToChange() == 0]
         for attr in attrs:
             dv = pm.attributeQuery(attr.attrName(), n=attr.node(), ld=True)[0]
             try:
                 attr.set(dv)
             except RuntimeError as detail:
                 mc.warning(str(detail))
コード例 #49
0
ファイル: bdShadowRig.py プロジェクト: Mortaciunea/bdScripts
def bdCreateTSM2ShadowRig():
    selection = pm.ls(sl=1)
    TSM2 = []
    for obj in selection:
        if pm.attributeQuery('TSM2Control',node= obj,exists=1):
            TSM2.append(obj)
    
    upperBody = pm.ls('*:Upper_Body',type='transform')[0]
    TSM2.append(upperBody)
    
    bdCreateLocators(TSM2)
コード例 #50
0
def getAttribute(node, attr, **kwargs):
    """
    If attr exists on the control, return the control and attribute as controlname.attrname
    If the attribute doesn't exist, this function will create the attribute using the specified flags
    Look at the addAttr command in the documentation for the full list of commands.
    """

    if not pmc.attributeQuery(attr, node=node, exists=True):
        pmc.addAttr(node, ln=attr, **kwargs)

    return pmc.Attribute('{0:s}.{1:s}'.format(node, attr))
コード例 #51
0
    def resetAttributes(self, *args):
        if not self.items:
            return

        for item_dict in self.items.values():
            node = item_dict[NODE]
            attrs = self.getAttributes(node)

            for attr in attrs:
                default_value = pm.attributeQuery(attr, node=node, ld=True)[0]
                node.attr(attr).set(default_value)
コード例 #52
0
ファイル: assetManager.py プロジェクト: kiryha/AnimationDNA
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')
コード例 #53
0
ファイル: assetManager.py プロジェクト: kiryha/AnimationDNA
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'        
コード例 #54
0
ファイル: mo_setDefaults.py プロジェクト: AndresMWeber/aw
 def setDefaults():
 	# Main procedure.
 	sel = pm.ls(selection=1)
 	# For every node in selecition #
 	for node in sel:
 		# For every animatable attr in the node #
 		# If no channels are selected:
 		if getSelectedChannels() == []:
 			for attr in node.listAnimatable():
 				# Sort out the actual name of just the attribute.
 				pAttr = attr.partition('.')[2]
 				# Figure out the default value for the current attribute.
 				defaultValue = pm.attributeQuery(pAttr, node=node, ld=1)[0]
 				# Set the attribute.
 				attr.set(defaultValue)
 		else: 
 			for attr in getSelectedChannels():
 				# Figure out the default value for the current attribute.
 				defaultValue = pm.attributeQuery(attr, node=node, ld=1)[0]
 				# Set the attribute.
 				pm.setAttr(node+"."+attr, defaultValue)
コード例 #55
0
    def custom_sets(self, *args):
        self.log.clear()
        self.log.insertText('Create Custom Sets...\n')
        self.log.insertText('\nFind all geo/pfxHair under the groups: \n  "md", "GRP_paintEffects"\n\nGenerate two sets as result : \n  "cacheSet" contains all tagged objects\n  "_NON_TAGGED_GEO" contains all non-tagged objects\n')
       
        cacheSets = pm.ls("*cacheSet")
        if not cacheSets:
            self.cacheSet = pm.sets(empty=True, name = "cacheSet")

        grps = [grp for grp in ['md', 'GRP_paintEffects'] if pm.objExists(grp)] 
        pm.select(grps, hi=True)
        all_mesh = pm.ls(sl=True, type=['mesh', 'pfxHair'])
        pm.select(clear=True)

        all_geo = [mesh.getParent() for mesh in all_mesh]
        #pm.sets(all_geo, name="_ALL_GEO")
        
        no_tags = [geo for geo in all_geo if not pm.attributeQuery ('arc_renderable', node= geo, ex=True)]
        pm.sets(no_tags, name="_NON_TAGGED_GEO")
        
        tags = [geo for geo in all_geo if pm.attributeQuery ('arc_renderable', node= geo, ex=True)]
        self.cacheSet.addMembers(tags)
コード例 #56
0
ファイル: attrManager.py プロジェクト: mkolar/AnimationDNA
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 )            
コード例 #57
0
def make_pick_walk(source, destination, direction):
    check_valid_dir(direction)
    check_valid_obj(source)
    check_valid_obj(destination)

    print "Adding pick walk from " + source + " to " + destination + " with direction " + direction

    attr_name = dir_to_attr(direction)
    if not pm.attributeQuery(attr_name, node=source, exists=True):
        pm.addAttr(source, attributeType="message", longName=attr_name)

    pm.connectAttr(destination + ".message", source + "." + attr_name, force=True)
    mark_scene_dirty()
コード例 #58
0
ファイル: fileTexture.py プロジェクト: hongloull/digital37
 def change_texture_file_detail(self,map_partten,map_detail):
     for x in self.Texture_File_Nodes:
         if pm.attributeQuery( 'fileTextureName',node=x,exists=1 ):
             n = x.fileTextureName.get()
             if n :
                 base,ext = os.path.splitext(n)
                 # file ends with '__L'
                 if re.search(map_partten,base) :
                     base = re.sub(map_partten,'',base)
                 # file not ends with '__L'
                 fn = base + map_detail + ext
                 print fn
                 #print os.path.isfile(fn)
                 #if os.path.isfile(fn):
                 x.fileTextureName.set( fn )