Example #1
0
    def __init__(self, name=None, prefix='', metaclass=metaclass, version=version):
        print '\n'
        logger.info('Initialize Metadata %s (%s)' %(name, metaclass))
        
        if not name and not prefix:
            pm.warning("Please Define Metadata Name or Prefix.. Aborting..")
            return
        
        if prefix: prefix = prefix + "_"
        self.prefix = prefix

        self.name = name or "%s%s" %(prefix, metaclass)

        self.metaclass = metaclass
        self.version = version
        self.metaChildren = {}
        
        # check if the object already exists
        if not pm.objExists(self.name):
            logger.info("Object %s Not Exists..." %self.name)
            
            # create new metadata node
            self._init_metadata_node()

        else:
            logger.info("Object %s Exists..." %self.name)
            
            # load existing node
            self.node = pm.PyNode(self.name)         
            
            # check if metaclass is latest
            scene_info = "Scene : %s v%.02f "%(self.node.metaclass.get(), self.node.version.get())
            current_info = "Current : %s v%.02f" %(self.metaclass, self.version)
        
            if self.node.metaclass.get() == self.metaclass and self.node.version.get() == self.version:
                logger.info("Result: Up to Date ( %s vs %s )" %(scene_info, current_info))
                
            else:
                logger.info("Result: Out Of Date  ( %s vs %s )" %(scene_info, current_info))
                
                # renew metadata
                self.unlock()
                
                # create new metadata
                temp_node = self.node.rename("TEMP_METADATA")
                
                self._init_metadata_node()
                
                # transfer all attributes 
                logger.info("Copy Metadata Attributes for %s... " %self.node)
                pm.copyAttr( temp_node , self.node ,inConnections=True, outConnections=True, values=True)
                
                # delete old metadata
        
                pm.delete(temp_node)

        self._init_metaChildren()
        self.lock()
def addCtrlToSpreadJnt(jnt):
    ctl = pm.circle(n=jnt.replace('_jnt', '_ctrl'), normal=(1,0,0), ch=False, sweep=359)[0]
    ctg = pm.group(ctl, n=ctl+'_grp')
    cth = pm.group(ctg, n=ctl+'_cth')
    
    mat = jnt.getMatrix(ws=True)
    cth.setMatrix(mat, ws=True)
    
    par = jnt.getParent()
    par | cth
    
    pm.copyAttr(jnt, ctg, inConnections=True)
    
    ctl | jnt
Example #3
0
def addCtrlToSpreadJnt(jnt):
    ctl = pm.circle(n=jnt.replace('_jnt', '_ctrl'),
                    normal=(1, 0, 0),
                    ch=False,
                    sweep=359)[0]
    ctg = pm.group(ctl, n=ctl + '_grp')
    cth = pm.group(ctg, n=ctl + '_cth')

    mat = jnt.getMatrix(ws=True)
    cth.setMatrix(mat, ws=True)

    par = jnt.getParent()
    par | cth

    pm.copyAttr(jnt, ctg, inConnections=True)

    ctl | jnt
Example #4
0
def copyTagAttribiutes(srcRoot, dstRoot):
    """
    Copies animation tag attributes from the source root to the destination root.
    
    Args:
        source(Joint): A source root joint. 
        destination(Joint): A destination root joint.
    """
    for srcAttr in srcRoot.listAttr(userDefined=True):
        if not dstRoot.hasAttr(srcAttr.attrName()):
            cmd = srcAttr.__apimattr__().getAddAttrCmd(True)
            cmd = cmd.replace(';', ' %s;' % dstRoot)
            pmc.mel.eval(cmd)

        pmc.copyAttr(srcRoot, dstRoot, at=[srcAttr.attrName()], v=True)
        # Copy Animation
        if pmc.keyframe(srcRoot, at=[srcAttr.attrName()], q=True):
            pmc.copyKey(srcRoot, at=[srcAttr.attrName()])
            pmc.pasteKey(dstRoot, at=[srcAttr.attrName()])
def addTranslateControlToJoint(jnt):
    '''
    add translate control for FK wrist
    jnt = nt.Joint(u'Ori_lf_wrist_jnt')
    '''
    ctl = ctlsys.createControl(jnt.replace('_jnt', '_translate_ctrl'))
    cth = ctl.getParent(2)
    par = jnt.getParent()
    cth.setParent(par, r=True)
    # transfer translates
    pm.copyAttr(jnt, cth, inConnections=True, oc=True, at=['tx', 'ty', 'tz'])
    # transfer orients
    cons = pm.orientConstraint(jnt, q=True, n=True)
    cons = pm.PyNode(cons)
    # replace inputs
    all_input_cons = cons.inputs(p=True, c=True)
    for destPlug, srcPlug in all_input_cons:
        if jnt.name() in srcPlug.nodeName():
            srcPlug // destPlug
            attr = srcPlug.attrName()
            try:
                newSrcPlug = cth.attr(attr)
                print newSrcPlug
                newSrcPlug >> destPlug
            except:
                pass
    # replace outputs
    all_output_cons = cons.outputs(p=True, c=True)
    for srcPlug, destPlug in all_output_cons:
        if jnt.name() in destPlug.nodeName():
            srcPlug // destPlug
            attr = destPlug.attrName()
            try:
                newDestPlug = cth.attr(attr)
                print newDestPlug
                srcPlug >> newDestPlug
            except:
                pass
    ctl | jnt
    ctl.v.set(l=True, k=False, ch=False)
    pm.select(ctl)
Example #6
0
def addTranslateControlToJoint(jnt):
    '''
    add translate control for FK wrist
    jnt = nt.Joint(u'Ori_lf_wrist_jnt')
    '''
    ctl = ctlsys.createControl(jnt.replace('_jnt', '_translate_ctrl'))
    cth = ctl.getParent(2)
    par = jnt.getParent()
    cth.setParent(par, r=True)
    # transfer translates
    pm.copyAttr(jnt, cth, inConnections=True, oc=True, at=['tx', 'ty', 'tz'])
    # transfer orients
    cons = pm.orientConstraint(jnt, q=True, n=True)
    cons = pm.PyNode(cons)
    # replace inputs
    all_input_cons = cons.inputs(p=True, c=True)
    for destPlug, srcPlug in all_input_cons:
        if jnt.name() in srcPlug.nodeName():
            srcPlug // destPlug
            attr = srcPlug.attrName()
            try:
                newSrcPlug = cth.attr(attr)
                print newSrcPlug
                newSrcPlug >> destPlug
            except:
                pass
    # replace outputs
    all_output_cons = cons.outputs(p=True, c=True)
    for srcPlug, destPlug in all_output_cons:
        if jnt.name() in destPlug.nodeName():
            srcPlug // destPlug
            attr = destPlug.attrName()
            try:
                newDestPlug = cth.attr(attr)
                print newDestPlug
                srcPlug >> newDestPlug
            except:
                pass
    ctl | jnt
    ctl.v.set(l=True, k=False, ch=False)
    pm.select(ctl)
Example #7
0
 def _renew_metadata(self):
     logger.info("Renew Metadata %s... " %self.node)
     
     # renew metadata process:
     #    1. create new metadata
     #    2. transfer all idential attribute/connection from old to new metadata.
     #    3. delete old metadata
     
     # create new metadata
     temp_node = self.node.rename("TEMP_METADATA")
     temp_node.metaRoot.disconnect()
     
     self._create_metadata()
     
     # transfer all attributes 
     logger.info("Copy Metadata Attributes for %s... " %self.node)
     pm.copyAttr( temp_node , self.node ,inConnections=True, outConnections=True, values=True)
     
     # delete old metadata
     temp_node.unlock()        
     pm.delete(temp_node)
def importAtomFile(sFilePath, **kwargs):

    if not osp.isfile(sFilePath):
        raise EnvironmentError("No such file: '{}'".format(sFilePath))

    sBaseName = osp.basename(osp.splitext(sFilePath)[0])
    sNamespace = kwargs.pop("namespace", kwargs.pop("ns", sBaseName))

    sValidKwargs = ATOM_IMPORT_KWARGS.keys()

    sOptList = []
    for k, v in kwargs.iteritems():

        if k not in sValidKwargs:
            raise TypeError("Unexpected keyword argument: '{}'. \n    Are valid: {}"
                            .format(k, ", ".join(sValidKwargs)))

        valueCast = ATOM_IMPORT_KWARGS[k]
        if isinstance(valueCast, dict):
            try:
                value = valueCast[v]
            except KeyError:
                raise ValueError("Invalid '{}' value: '{}'. Are valid: {}."
                                 .format(k, v, valueCast.keys()))
        elif isinstance(valueCast, list):
            if v in valueCast:
                value = v
            else:
                raise ValueError("Invalid '{}' value: '{}'. Are valid: {}."
                                 .format(k, v, valueCast))
        else:
            try:
                value = valueCast(v)
            except Exception as e:
                raise ValueError("Invalid '{}' value: {}. {}."
                                 .format(k, v, toStr(e)))

        sOpt = "{}={}".format(k, value)
        sOptList.append(sOpt)

    sSelected = kwargs.get("selected", "selectedOnly")
    if sSelected == "selectedOnly":
        sXfmList = mc.ls(sl=True, tr=True)
    elif sSelected == "childrenToo":
        sXfmList = mc.ls(sl=True, dag=True, tr=True)

    def listAttr_(sNode):
        return listForNone(mc.listAttr(sNode, k=True, ud=True))

    sPreAttrSet = set()
    for sXfm in sXfmList:
        sPreAttrSet.update(sXfm + "." + attr for attr in listAttr_(sXfm))

    print "Importing atom file:", sFilePath
    print ";".join(sOptList)

    res = pm.importFile(sFilePath, type="atomImport",
                         renameAll=True,
                         namespace=sNamespace,
                         options=";".join(sOptList))

    sPostAttrSet = set()
    for sXfm in sXfmList:
        sPostAttrSet.update(sXfm + "." + attr for attr in listAttr_(sXfm))

    keyFunc = lambda s: s.split(".", 1)[0]
    sNewAttrList = sorted((sPostAttrSet - sPreAttrSet), key=keyFunc)
    if sNewAttrList:
        for sXfm, attrs in itr.groupby(sNewAttrList, keyFunc):

            oXfm = pm.PyNode(sXfm)
            oShape = oXfm.getShape()
            if not oShape:
                continue

            sAttrSet = set(a.split(".", 1)[1] for a in attrs)
            sAttrList = list(sAttrSet & set(pm.listAttr(oShape, k=True)))
            if not sAttrList:
                continue

            sSep = "\n    -"
            print (("transfering imported attrs from '{}' to '{}':" + sSep + "{}")
                   .format(oXfm, oShape, sSep.join(sAttrList)))
            pm.copyAttr(oXfm, oShape, attribute=sAttrList,
                        inConnections=True, keepSourceConnections=True)

            for sAttr in sAttrList:
                #print "deleting imported attr:", oXfm.name() + "." + sAttr
                oXfm.deleteAttr(sAttr)

    return res
Example #9
0
def importAtomFile(sFilePath, **kwargs):

    if not osp.isfile(sFilePath):
        raise EnvironmentError("No such file: '{}'".format(sFilePath))

    sBaseName = osp.basename(osp.splitext(sFilePath)[0])
    sNamespace = kwargs.pop("namespace", kwargs.pop("ns", sBaseName))

    sValidKwargs = ATOM_IMPORT_KWARGS.keys()

    sOptList = []
    for k, v in kwargs.iteritems():

        if k not in sValidKwargs:
            raise TypeError(
                "Unexpected keyword argument: '{}'. \n    Are valid: {}".
                format(k, ", ".join(sValidKwargs)))

        valueCast = ATOM_IMPORT_KWARGS[k]
        if isinstance(valueCast, dict):
            try:
                value = valueCast[v]
            except KeyError:
                raise ValueError(
                    "Invalid '{}' value: '{}'. Are valid: {}.".format(
                        k, v, valueCast.keys()))
        elif isinstance(valueCast, list):
            if v in valueCast:
                value = v
            else:
                raise ValueError(
                    "Invalid '{}' value: '{}'. Are valid: {}.".format(
                        k, v, valueCast))
        else:
            try:
                value = valueCast(v)
            except Exception as e:
                raise ValueError("Invalid '{}' value: {}. {}.".format(
                    k, v, toStr(e)))

        sOpt = "{}={}".format(k, value)
        sOptList.append(sOpt)

    sSelected = kwargs.get("selected", "selectedOnly")
    if sSelected == "selectedOnly":
        sXfmList = mc.ls(sl=True, tr=True)
    elif sSelected == "childrenToo":
        sXfmList = mc.ls(sl=True, dag=True, tr=True)

    def listAttr_(sNode):
        return listForNone(mc.listAttr(sNode, k=True, ud=True))

    sPreAttrSet = set()
    for sXfm in sXfmList:
        sPreAttrSet.update(sXfm + "." + attr for attr in listAttr_(sXfm))

    print "Importing atom file:", sFilePath
    print ";".join(sOptList)

    res = pm.importFile(sFilePath,
                        type="atomImport",
                        renameAll=True,
                        namespace=sNamespace,
                        options=";".join(sOptList))

    sPostAttrSet = set()
    for sXfm in sXfmList:
        sPostAttrSet.update(sXfm + "." + attr for attr in listAttr_(sXfm))

    keyFunc = lambda s: s.split(".", 1)[0]
    sNewAttrList = sorted((sPostAttrSet - sPreAttrSet), key=keyFunc)
    if sNewAttrList:
        for sXfm, attrs in itr.groupby(sNewAttrList, keyFunc):

            oXfm = pm.PyNode(sXfm)
            oShape = oXfm.getShape()
            if not oShape:
                continue

            sAttrSet = set(a.split(".", 1)[1] for a in attrs)
            sAttrList = list(sAttrSet & set(pm.listAttr(oShape, k=True)))
            if not sAttrList:
                continue

            sSep = "\n    -"
            print(("transfering imported attrs from '{}' to '{}':" + sSep +
                   "{}").format(oXfm, oShape, sSep.join(sAttrList)))
            pm.copyAttr(oXfm,
                        oShape,
                        attribute=sAttrList,
                        inConnections=True,
                        keepSourceConnections=True)

            for sAttr in sAttrList:
                #print "deleting imported attr:", oXfm.name() + "." + sAttr
                oXfm.deleteAttr(sAttr)

    return res