예제 #1
0
def create_distanceMeasure(start=None, end=None, baseName='measure'):
    """
    Get the the closest return based on a source and target and variable modes
    
    :parameters:
        :start(str): Our start obj
        :end(str): End obj
        :baseName(str):What mode are we checking data from
    
    :returns
        {shape,dag,loc_start,loc_end,start,end}
    """
    try:
        _str_func = 'create_distanceMeasure'

        #Create ====================================================================================
        plug_start = POS.get_positionPlug(start)
        plug_end = POS.get_positionPlug(end)
        _res = {'start': start, 'end': end}

        if not plug_start:
            pos_start = POS.get(start)
            loc_start = mc.spaceLocator(name="{0}_{1}_start_loc".format(
                NAMES.get_base(start), baseName))[0]
            POS.set(loc_start, pos_start)
            plug_start = POS.get_positionPlug(loc_start)
            _res['loc_start'] = loc_start
        if not plug_end:
            pos_end = POS.get(end)
            loc_end = mc.spaceLocator(name="{0}_{1}_end_loc".format(
                NAMES.get_base(end), baseName))[0]
            POS.set(loc_end, pos_end)
            plug_end = POS.get_positionPlug(loc_end)
            _res['loc_end'] = loc_end

        mDistShape = r9Meta.MetaClass(mc.createNode('distanceDimShape'))
        mDistShape.rename("{0}_distShape".format(baseName))

        mDistTrans = r9Meta.MetaClass(VALID.getTransform(mDistShape.mNode))
        mDistTrans.rename("{0}_dist".format(baseName))

        _res['dag'] = mDistTrans.mNode
        _res['shape'] = mDistShape.mNode

        ATTR.set_message(_res['dag'], 'distShape', _res['shape'], simple=True)

        ATTR.connect(plug_start, "{0}.startPoint".format(_res['shape']))
        ATTR.connect(plug_end, "{0}.endPoint".format(_res['shape']))

        return _res
    except Exception, err:
        cgmGen.cgmExceptCB(Exception, err)
예제 #2
0
def reset_channels(nodes=None,selectedChannels=False, transformsOnly=False, excludeChannels=None, keyableOnly=False):
    '''
    Modified from Morgan Loomis' great reset call to expand options...
    '''
    gChannelBoxName = mel.eval('$temp=$gChannelBoxName')
    _reset = {}
    
    if not nodes:
        nodes = mc.ls(sl=True)
        if not nodes:
            return

    if excludeChannels:
        if not isinstance(excludeChannels, (list, tuple)):
            excludeChannels = [excludeChannels]

    chans = None
    if selectedChannels:
        chans = mc.channelBox(gChannelBoxName, query=True, sma=True)

    l_trans = ['translateX','translateY','translateZ','rotateX','rotateY','rotateZ','scaleX','scaleY','scaleZ','tx','ty','yz','rx','ry','rz','sx','sy','sz']


    for obj in nodes:
        #mObj = r9Meta.MetaClass(obj)

        attrs = chans
        if not chans:
            attrs = mc.listAttr(obj, keyable=True, unlocked=True)
            if excludeChannels:
                attrs = [x for x in attrs if x not in excludeChannels]

        if transformsOnly:
            attrs = [x for x in attrs if x in l_trans]
        if keyableOnly:
            attrs = [x for x in attrs if ATTR.is_keyable(obj,x)]

        d_defaults = {}
        for plug in ['defaultValues','transResets']:
            if ATTR.has_attr(obj, plug):
                d_defaults = getattr(r9Meta.MetaClass(obj),plug)

        if not attrs:
            log.warning("{0} resetAttrs | no attributes offered!".format(obj))            
            continue
        for a in attrs:
            try:
                if transformsOnly is not None and transformsOnly:
                    if ATTR.get_nameLong(obj,a) not in l_trans:
                        continue
                dVal = d_defaults.get(a)
                if dVal is not None:
                    default = dVal
                else:
                    default = mc.attributeQuery(a, listDefault=True, node=obj)[0]
                ATTR.set(obj,a,default)
                _reset[a] = default
            except Exception,err:
                log.error("{0}.{1} resetAttrs | error: {2}".format(obj, a,err))
def verify_customizationData(i_network, skinDepth=2.5):
    """
    Gather info from customization asset
    
    from morpheusRig_v2.core import MorpheusFactory as morphyF
    reload(morphyF)
    morphyF.verify_customizationData('Morphy_customizationNetwork')
    """
    #These are the controls we'll drive positional data from to plug to our modules
    d_initialData = {}

    #>>> Verify our arg
    try:
        i_network.mNode
    except:
        if mc.objExists(i_network):
            i_network = r9Meta.MetaClass(i_network)
        else:
            log.error("'%s' doesn't exist" % i_network)
            return False
    assert i_network.mClass == 'cgmMorpheusMakerNetwork', "Not a cgmMorpheusMakerNetwork. Aborted!"

    #>> Collect our positional info
    #====================================================================
    i_objSet = i_network.objSetAll  #Should I use this or the message info
    log.debug(i_objSet.value)

    controlBuffer = i_network.objSetAll.value
    for moduleKey in l_modulesToDoOrder:
        if moduleKey not in d_moduleControls.keys():
            log.warning("Missing controls info for: '%s'" % moduleKey)
            return False
        log.debug("On moduleKey: '%s'" % moduleKey)
        controls = d_moduleControls.get(moduleKey)
        posBuffer = []
        for c in controls:
            if not mc.objExists(c):
                log.warning("Necessary positioning control not found: '%s'" %
                            c)
                return False
            else:
                log.debug("Found: '%s'" % c)
                i_c = cgmMeta.cgmNode(c)
                if i_c.isComponent():  #If it's a component
                    i_loc = cgmMeta.cgmObject(
                        mc.spaceLocator()[0])  #make a loc
                    Snap.go(i_loc.mNode, targets=c, move=True,
                            orient=True)  #Snap to the surface
                    i_loc.tz -= skinDepth  #Offset on z by skin depth
                    pos = i_loc.getPosition()  #get position
                    i_loc.delete()
                else:
                    pos = i_c.getPosition()
                if not pos: return False
                posBuffer.append(pos)
        d_initialData[moduleKey] = posBuffer

    return d_initialData
예제 #4
0
    def test_caching(self):
        self.assertEquals(
            self.r9Node1.cached,
            None,
        )

        self.r9Node1.addAttr('mClass', 'MetaClass')
        r9Node1Cached = r9Meta.MetaClass(self.r9Node1.mNode)

        self.assertEquals(self.r9Node1.cached, True)
        self.assertEquals(self.r9Node1, r9Node1Cached)
예제 #5
0
 def release_post_insert(self):
     #ATTR.set_messagse(_catch, 'tmpMsg', self.l_created[-1])
     _loc = self.l_created[-1]
     _mLoc = r9Meta.MetaClass(_loc)
     _buffer = _mLoc.cgmLocDat
     _target = ATTR.get_message(_loc,'meshTarget')[0]
     _loc = mc.rename(_loc, "{0}_u{1}_v{2}_rayCast_loc".format(coreNames.get_base(_target),
                                                           "{0:.4f}".format(_buffer['uv'][0]),
                                                           "{0:.4f}".format(_buffer['uv'][1]),
                                                           ))
     self.dropTool()
예제 #6
0
        def _buildStuff_(self):
            mi_rootJoint = r9Meta.MetaClass(mc.joint(name='root'))
            #mc.parent(mi_rootJoint.mNode,world = True)
            #mi_rootJoint.parent = False
            self.md_rootToChildren[mi_rootJoint] = []
            _last = mi_rootJoint
            for i in range(self.int_children):
                self.progressBar_set(status=("Creating obj %i" % i),
                                     progress=i,
                                     maxValue=self.int_children)
                mi_child = r9Meta.MetaClass(mc.joint(name=' "child"%i' % i))
                self.md_rootToChildren[mi_rootJoint].append(mi_child)
                #mi_child.parent = _last
                try:
                    mc.parent(mi_child.mNode, _last.mNode)
                except:
                    pass
                mi_child.ty = (i)
                _last = mi_child  #...change for the next

            self._toCall = self.md_rootToChildren[mi_rootJoint][4]
            self.mi_rootJoint = mi_rootJoint
예제 #7
0
def override_clear(target=None, pushToShapes=True):
    """
    Clear override flags on target and shapes if you choose
    
    :parameters
        target(str): What to color - shape or transform with shapes
        pushToShapes(bool): Push the overrides to shapes of passed transforms

    :returns
        info(dict)
    """
    _str_func = "override_clear"
    if not target:
        raise ValueError, "|{0}|  >> Must have a target".format(_str_func)

    _shapes = []

    mTarget = r9Meta.MetaClass(target, autoFill=False)

    if mTarget.hasAttr('overrideEnabled'):
        log.debug("|{0}|  >> overrideEnabled  on target...".format(_str_func))
        _shapes.append(mTarget.mNode)

    if pushToShapes:
        _bfr = mc.listRelatives(target, s=True, fullPath=True)
        if _bfr:
            _shapes.extend(_bfr)

    if not _shapes:
        raise ValueError, "|{0}|  >> Not a shape and has no shapes: '{1}'".format(
            _str_func, target)

    for i, s in enumerate(_shapes):
        mShape = r9Meta.MetaClass(s)
        try:
            mShape.overrideEnabled = False
        except Exception, err:
            log.warning("|{0}|  >> target failed: {1} | err: {2}".format(
                _str_func, s, err))
예제 #8
0
 def getTimecode_from_node(node):
     '''
     wrapper method to get the timecode back from a given node
     :param node: node containing correctly formatted timecode data
     
     .. note:
             the node passed in has to have the correctly formatted timecode data to compute
     '''
     import Red9.core.Red9_Meta as r9Meta
     node = r9Meta.MetaClass(node)
     if node.hasAttr(Timecode.ref):
         ms = (getattr(node, Timecode.ref) + ((float(getattr(node, Timecode.count)) / getattr(node,Timecode.samplerate)) * 1000))
         return milliseconds_to_Timecode(ms)
예제 #9
0
def speedTest_objectCount(iterations=100, ):
    """
    Test to see how meta reloading affects file new/open
    """
    l_times = []
    mc.file(new=True, f=True)
    t_start = time.clock()
    _jnt = mc.joint()
    for i in range(iterations):
        log.info("On...{0}".format(i))
        _jnt = mc.joint()
        #_jnt = mc.createNode('multiplyDivide')
        #_jnt = mc.createNode('transform')

        t1 = time.clock()
        #r9Meta.MetaClass(name = 'test_{0}'.format(i),nodeType='transform')
        #import maya.cmds as mc

        r9Meta.MetaClass(_jnt)
        #r9Meta.MetaClass(_jnt,autofill='messageOnly')
        t2 = time.clock()
        l_times.append(t2 - t1)

    t_end = time.clock()

    #for i,t in enumerate(l_times):
    #log.info("Step {0} |  {1}".format(i,"%0.3f"%t))

    _str_dif = l_times[-1] - l_times[0]
    _l_diffs = []
    for i in range(len(l_times) - 1):
        _l_diffs.append(l_times[i + 1] - l_times[i])
    _averageDiff = sum(_l_diffs) / len(_l_diffs)
    _totalTime = t_end - t_start
    _totalIterTime = (sum(l_times))
    log.info(
        " speedTest_reloadMeta -- {0} | Start -- {1} | End -- {2} | [Diff] -- {3} | AverageIncrease: {4}"
        .format("%0.3f" % (sum(l_times)), "%0.3f" % l_times[0],
                "%0.3f" % l_times[-1], "%0.3f" % _str_dif, _averageDiff))
    log.info("Time total: {0} | IterTime: {1} | Unaccounted: {2}".format(
        "%0.3f" % (_totalTime), "%0.3f" % (_totalIterTime),
        "%0.3f" % (_totalTime - _totalIterTime)))
    log.info(" Maya: {0} | OS: {1}".format(
        mel.eval('about -%s' % 'version'),
        mel.eval('about -%s' % 'operatingSystemVersion')))
예제 #10
0
def jointStuff_meta():
    ml_joints = cgmMeta.validateObjListArg(
        mc.ls(sl=1), mayaType='joint'
    )  #...gets us a validated meta data list of our selection

    for i, mJnt in enumerate(ml_joints):
        mJnt.rename("ourChain_{0}_jnt".format(i))
        mi_crv = r9Meta.MetaClass(mc.circle(normal=[1, 0, 0], ch=0)[0])
        mc.parent(mi_crv.mNode, mJnt.mNode)
        mi_crv.rename('{0}_crv'.format(
            mJnt.p_nameBase))  #...p_nameBase property cgmMeta only
        mc.delete(
            mc.parentConstraint(mJnt.mNode, mi_crv.mNode,
                                maintainOffset=False))

        #...loc
        mJnt.doLoc()  #..doLoc cgmMeta only

        #...same data storage
        mJnt.connectChildNode(mi_crv, 'curveObject', 'targetJoint')
예제 #11
0
        def _iterate_(self):
            self.call2_func = self.test2_func
            mObj = r9Meta.MetaClass(name="obj", nodeType='transform')
            for i in range(self.int_targetCount):
                self.progressBar_set(status=("Pass 1: Substantiating Call %i" %
                                             i),
                                     progress=i,
                                     maxValue=self.int_targetCount)
                mObj.addAttr('test_{0}'.format(i), attrType='string')

                t1 = time.clock()
                n1 = self.test1_func(mObj)
                t2 = time.clock()
                self.l_times_1.append(t2 - t1)

                t1 = time.clock()
                #self.l_roots_2.extend( [self.test2_func(self._toCall)] )
                self.call2_func(mObj)
                t2 = time.clock()
                self.l_times_2.append(t2 - t1)
예제 #12
0
------------------------------------------

Help for learning the basis of meta
================================================================
"""
import maya.cmds as mc
from Red9.core import Red9_Meta as r9Meta
from cgm.core import cgm_Meta as cgmMeta

#==============================================================================================
#>> mNode
#==============================================================================================
mc.file(new=True, f=True)  #...let's start with a clean file
mc.group(em=True, n='testingNull')  #...let's make a null
n1 = r9Meta.MetaClass(
    'testingNull'
)  #...now it's instantiated as a MetaClass to our given catcher 'n1'
n1.mNode  #...returns it's dag handle
mc.group(n1.mNode)  #...let's group our null
n1.mNode  #...still returns our object

#>>Rename it =========================================================================
mc.rename('testingNull', 'Whatchamacallit')
n1.mNode  #...still returns our object

#==============================================================================================
#>> Special attributes, caching and the registries
#==============================================================================================
mc.file(new=True, f=True)  #...let's start with a clean file
#Go to the outliner and make sure DAG objects only is off
import cgm.core
cgm.core._reload()
from cgm.core import cgm_Meta as cgmMeta
from cgm.core import cgm_PuppetMeta as cgmPM
import Red9.core.Red9_Meta as r9Meta
from cgm.core.rigger import RigFactory as Rig
#======================================================================
cgm.core._reload()
cgmMeta.log.setLevel(cgmMeta.logging.INFO)
cgmMeta.log.setLevel(cgmMeta.logging.DEBUG)
neckHead = r9Meta.MetaClass('neck_part')
neckHead.rig
neckHead.doRig()
neckHead.isSkeletonized()
reload(Rig)
reload(jFactory)
neckHead.isTemplated()
neckHead.rig_getSkinJoints()
neckHead.setState('skeleton', forceNew=True)
jFactory.connectToParentModule(neckHead)
jFactory.deleteSkeleton(neckHead)

neckHead.setState(3, forceNew=True)
Rig.get_report(spine)
Rig.get_report(neckHead)
Rig.get_segmentHandleTargets(neckHead)
neckHead.rigNull.getMessage('rigJoints', False)
neckHead.rigNull.getMessage('skinJoints', False)
if len(spine.rigNull.getMessage('rigJoints')) != 9: print False
neckHead.rigNull.moduleJoints[-1].getShortName()
neckHead.setState('skeleton', forceNew=True)
m1.i_coreNames.value
cgmPM.cgmModule('spine_part').__verify__()
m1.coreNames.__verify__()
#518 w doStore
m1.initialize()
m1.getPartNameBase()

a.getState()
a.templateNull.handles = 1
a.templateNull.__setattr__('handles', 0)
str_m1 = 'spine_part'
str_m1 = 'l_foot_part'
mFactory.deleteSkeleton(m1)
mFactory.returnExpectedJointCount(m1)
m1.isSized()
m1 = r9Meta.MetaClass(str_m1)
m1.setState('template', forceNew=True)
m1.storeTemplatePose()
m1.loadTemplatePose()
m1.isSkeletonized()
m1.getGeneratedCoreNames()
tFactory.updateTemplate(m1, False)

r9Meta.MetaClass('pelvis_tmplObj').translate

m1.setState('size')
m1.setState('skeleton', forceNew=True)
m2.setState('template', forceNew=True)
tFactory.returnModuleBaseSize(m2)
m2.rigNull.skinJoints
m2.moduleParent.rigNull.skinJoints
예제 #15
0
from cgm.core import cgm_PuppetMeta as cgmPM
import Red9.core.Red9_Meta as r9Meta

from cgm.core.classes import SnapFactory as Snap
reload(Snap)
from cgm.core.rigger import ModuleControlFactory as mControlFactory
reload(mControlFactory)
from cgm.lib import search
obj = mc.ls(sl=True)[0] or False
obj = ''
objList = []

#>>> Modules
#=======================================================
m1 = cgmPM.cgmModule(name='test')
m1 = r9Meta.MetaClass('spine_part')
m1.setState('skeleton')
m1.getPartNameBase()
m1.modulePuppet.getGeo()
mObj = cgmMeta.cgmObject(control)
i_loc = mObj.doLoc()
i_loc.rx = i_loc.rx + 90
mObj.doCopyTransform(i_loc.mNode)
mObj.mNode
mObj.getAttr('asdfasdf')

#>>> Testing control registering
control = 'cog_controlCurve'
mControlFactory.registerControl(mc.ls(sl=True)[0])
mControlFactory.registerControl(control)
for i in range(2):
예제 #16
0
    def getAndMove(loc, targets=None, mode=None, forceBBCenter=False):

        log.debug("|{0}| >> mode: {1} | targets: {2}".format(
            _str_func, mode, targets))
        if not targets:
            raise ValueError, "Must have targets"

        _kws = {'target': loc, 'move': True, 'rotate': True}

        if mode == 'fromTarget':
            _d = POS.get_info(targets[0])
            _kws['infoDict'] = _d

        elif mode == 'midPoint':
            if len(targets) == 1:
                _d = POS.get_info(targets[0], boundingBox=True)
                _kws['infoDict'] = _d

            elif not len(targets) >= 2:
                raise ValueError, "midPoint mode must have at least two targets"
            else:
                _d = get_midPointDict(targets, forceBBCenter)
                _kws['infoDict'] = _d

        elif mode == 'closestPoint':
            if not len(targets) >= 2:
                raise ValueError, "midPoint mode must have at least two targets"

            _d = {
                'position':
                DIST.get_by_dist(targets[0],
                                 targets[1:],
                                 resMode='pointOnSurface')
            }
            _kws['infoDict'] = _d
            _kws['rotate'] = False

        elif mode == 'closestTarget':
            if not len(targets) >= 3:
                raise ValueError, "midPoint mode must have at least three targets"

            _d = POS.get_info(
                DIST.get_by_dist(targets[0], targets[1:], resMode='object'))
            _d['rotateOrder'] = False
            _d['rotateAxis'] = False

            _kws['infoDict'] = _d

        elif mode == 'rayCast':
            _dbuffer = r9Meta.MetaClass(_loc).cgmLocDat
            _d = {}
            _p = POS.get_uv_position(_target[0], _dbuffer['uv'])
            if _dbuffer.get('offsetDist'):
                _v = POS.get_uv_normal(_target[0], _dbuffer['uv'])
                _dist = _dbuffer.get('offsetDist')
                _p = DIST.get_pos_by_vec_dist(_p, _v, _dist)
            _d['position'] = _p
            _kws['infoDict'] = _d
            _kws['rotate'] = False
        else:
            log.error("|{0}| >> unknown mode: {1}".format(_str_func, _mode))
            return False

        try:
            return position(**_kws)
        except Exception, err:
            log.error("|{0}| >> loc: {1}".format(_str_func, loc))
            cgmGeneral.log_info_dict(_kws['infoDict'],
                                     "{0} >> {1}".format(_str_func, mode))
            log.error("|{0}| >> err: {1}".format(_str_func, _err))
            return False
obj = mc.ls(sl=True)[0] or False
obj = ''
objList = []

import cgm.core
cgm.core._reload()
#>>> Morpheus
#=======================================================
p = cgmPM.cgmMorpheusMakerNetwork('Morphy_customizationNetwork')
p.setState('skeleton',forceNew = True)
p.mNode
p.mNode
morphyF.verify_customizationData(p)['clavicle_right'][0]
cgmPM.cgmPuppet('Morphy_puppetNetwork')
k = cgmPM.cgmMorpheusMakerNetwork('Morphy_customizationNetwork')
k.mNode
str_m1 = 'spine_part'
#[2.4872662425041199, 132.08547973632812, 11.861419200897217] #
m1 = r9Meta.MetaClass(str_m1)
p.setState('skeleton')
log.info(m1.getState())
m1.getGeneratedCoreNames()
tFactory.updateTemplate(m2)
m2.setState('size')
m2.setState('skeleton',forceNew = True)
m2.setState('template',forceNew = True)
tFactory.returnModuleBaseSize(m2)
m2.rigNull.skinJoints
m2.moduleParent.rigNull.skinJoints
m2.templateNull.controlObjects
m2 = r9Meta.MetaClass('l_hand_part')
예제 #18
0
 def test_duplicate(self):
     self.r9Node1_dup = r9Meta.MetaClass(
         mc.duplicate(self.r9Node1.mNode)[0])
     self.assertNotEqual(self.r9Node1, self.r9Node1_dup)
     self.r9Node1_dup.delete()
from cgm.core.classes import SnapFactory as Snap
reload(Snap)
from cgm.core.rigger import TemplateFactory as TemplateF
from cgm.core.rigger import JointFactory as jFactory
from cgm.core.classes import NodeFactory as nodeF
reload(TemplateF)
TemplateF.doOrientTemplateObjectsToMaster(m1)
reload(jFactory)
reload(Rig)
nodeF.validateAttrArg(['spine_1_anchorJoint', 'rz'])
assert 1 == 2

#Optimization - 05.01.2014
part = 'spine_part'
m1 = r9Meta.MetaClass(part)
TemplateF.go(m1, True)

#Get our module
#=======================================================
part = 'spine_part'
part = 'l_leg_part'
m1 = r9Meta.MetaClass(part)
m1 = cgmPM.cgmModule('l_eye_part')
m1.doTemplate()
m1.isSized()
m1.getState()
m1.isTemplated()
TemplateF.go(m1, True)

TemplateF.hasPivots(m1)
예제 #20
0
 def setUp(self):
     self.r9Node1 = r9Meta.MetaClass(name='net', nodeType='network')
import cgm.core
cgm.core._reload()
import maya.cmds as mc

from cgm.core import cgm_Meta as cgmMeta
from cgm.core import cgm_PuppetMeta as cgmPM
from cgm.core import cgm_RigMeta as cgmRigMeta
import Red9.core.Red9_Meta as r9Meta
from cgm.core.rigger import ModuleFactory as mFactory
from cgm.core.rigger import TemplateFactory as tFactory
from cgm.core.rigger import JointFactory as jFactory
from cgm.core.rigger import RigFactory as rFactory
reload(rFactory)
from cgm.core import cgm_PuppetMeta as cgmPM
m1 = r9Meta.MetaClass('r_index_part')

reload(mFactory)
mFactory.animReset_children(m1)
mFactory.get_moduleSiblings(m1)
mFactory.get_moduleSiblings(m1, False)
mFactory.animSelect_siblings(m1, False)
mFactory.animKey_siblings(
    m1,
    False,
)
mFactory.animPushPose_siblings(m1)
mFactory.animSetAttr_children(m1, 'visSub', 0, True, False)
mFactory.animSetAttr_children(m1, 'visSub', 1, True, False)
mFactory.animSelect_siblings(m1, True)
reload(tFactory)
reload(jFactory)
예제 #22
0
def override_color(target=None,
                   key=None,
                   index=None,
                   rgb=None,
                   pushToShapes=True):
    """
    Sets the color of a shape or object via override. In Maya 2016, they introduced 
    rgb value override.
    
    :parameters
        target(str): What to color - shape or transform with shapes
        key(varied): if str will check against our shared color dict definitions for rgb and index entries
        index(int): Color index
        rgb(list): rgb values to set in Maya 2016 or above
        pushToShapes(bool): Push the overrides to shapes of passed transforms

    :returns
        info(dict)
    """
    _str_func = "set_color"
    if not target:
        raise ValueError, "|{0}|  >> Must have a target".format(_str_func)

    l_targets = VALID.listArg(target)

    for t in l_targets:
        _shapes = []
        #If it's accepable target to color

        #mTarget = r9Meta.MetaClass(target, autoFill=False)

        if ATTR.has_attr(t, 'overrideEnabled'):
            log.debug(
                "|{0}|  >> overrideEnabled  on target...".format(_str_func))
            _shapes.append(t)
        if pushToShapes:
            _bfr = mc.listRelatives(t, s=True, fullPath=True)
            if _bfr:
                _shapes.extend(_bfr)

        if not _shapes:
            raise ValueError, "|{0}|  >> Not a shape and has no shapes: '{1}'".format(
                _str_func, t)

        #log.debug(key)
        #log.debug(index)
        #log.debug(rgb)
        if index is None and rgb is None and key is None:
            raise ValueError, "|{0}|  >> Must have a value for index,rgb or key".format(
                _str_func)

        #...little dummy proofing..
        if key:
            _type = type(key)

            if _type not in [str, unicode]:
                log.debug(
                    "|{0}|  >> Not a string arg for key...".format(_str_func))

                if rgb is None and issubclass(_type, list) or issubclass(
                        _type, tuple):
                    log.debug(
                        "|{0}|  >> vector arg for key...".format(_str_func))
                    rgb = key
                    key = None
                elif index is None and issubclass(_type, int):
                    log.debug("|{0}|  >> int arg for key...".format(_str_func))
                    index = key
                    key = None
                else:
                    raise ValueError, "|{0}|  >> Not sure what to do with this key arg: {1}".format(
                        _str_func, key)

        _b_RBGMode = False
        _b_2016Plus = False
        if cgmGEN.__mayaVersion__ >= 2016:
            _b_2016Plus = True

        if key is not None:
            _color = False
            if _b_2016Plus:
                log.debug("|{0}|  >> 2016+ ...".format(_str_func))
                _color = SHARED._d_colors_to_RGB.get(key, False)

                if _color:
                    rgb = _color

            if _color is False:
                log.debug(
                    "|{0}|  >> Color key not found in rgb dict checking index..."
                    .format(_str_func))
                _color = SHARED._d_colors_to_index.get(key, False)
                if _color is False:
                    raise ValueError, "|{0}|  >> Unknown color key: '{1}'".format(
                        _str_func, key)

        if rgb is not None:
            if not _b_2016Plus:
                raise ValueError, "|{0}|  >> RGB values introduced in maya 2016. Current version: {1}".format(
                    _str_func, cgmGEN.__mayaVersion__)

            _b_RBGMode = True
            if len(rgb) == 3:
                _color = rgb
            else:
                raise ValueError, "|{0}|  >> Too many rgb values: '{1}'".format(
                    _str_func, rgb)

        if index is not None:
            _color = index

        log.debug("|{0}|  >> Color: {1} | rgbMode: {2}".format(
            _str_func, _color, _b_RBGMode))

        for i, s in enumerate(_shapes):
            mShape = r9Meta.MetaClass(s)

            mShape.overrideEnabled = True
            #attributes.doSetAttr(s,'overrideEnabled',True)

            if _b_RBGMode:
                mShape.overrideRGBColors = 1
                mShape.overrideColorRGB = _color
                #attributes.doSetAttr(s,'overrideRGBColors','RGB')#...brilliant attr naming here Autodesk...
                #attributes.doSetAttr(s,'overrideColorsRGB',[1,1,1])

            else:
                if _b_2016Plus:
                    mShape.overrideRGBColors = 0
                mShape.overrideColor = _color
예제 #23
0
#>>> Dynamic group
#=======================================================
parents = mc.ls(sl=True)
dParents = [u'parent1', u'parent2', u'parent3']
dynMode = 'follow'
a = cgmRigMeta.cgmDynParentGroup(dynChild = 'dynChild',dynParents = dParents,dynMode = dynMode)
a.rebuild()
#Hips
dynParents = [ u'cog_anim',u'worldCenter_loc']#hips
dynGroup = 'hips_anim_grp'
dynChild = 'dynChild'

a = cgmRigMeta.cgmDynParentGroup(dynChild = dynChild,dynParents = dynParents, dynGroup = dynGroup,dynMode = dynMode)
#Shoulders
c1 = r9Meta.MetaClass('shoulders_ik_anim')
c1.dynParentGroup
c1.dynParentGroup.dynChild
c1.dynParentGroup.addDynChild('shoulders_ik_anim')
c1.dynParentGroup.rebuild()

dynParents = ['spine_2_fk_anim','cog_anim','|Morphy|Morphy_1_masterAnim','shoulders_ik_anim_spacePivot_anim','shoulders_ik_anim_spacePivot_1_anim']
for o in dynParents:
    c1.dynParentGroup.addDynParent(o)
c1.dynParentGroup.rebuild()


spineFK,cog,world,pivots
dynParents = [ u'spine_2_fk_anim',u'cog_anim',u'worldCenter_loc','pivotAnim']#Shoulderes
dynParents = [ u'spine_2_fk_anim',u'cog_anim',u'worldCenter_loc']#Shoulderes
dynParents = [ u'spine_2_fk_anim',u'cog_anim','hips_anim',u'worldCenter_loc']#Shoulderes
예제 #24
0
#====================================================================================================
#>>>Rig building
#====================================================================================================
import maya.cmds as mc
from cgm.core import cgm_Meta as cgmMeta
import cgm.core.cgm_General as cgmGEN
import cgm.core.mrs.RigBlocks as RBLOCKS
import cgm.core.mrs.lib.block_utils as BLOCKUTILS
import cgm.core.mrs.lib.builder_utils as BUILDUTILS
import cgm.core.cgm_General as cgmGEN
import cgm.core.mrs.lib.shared_dat as BLOCKSHARE
import cgm.core.lib.transform_utils as TRANS

cgm.core._reload()
from Red9.core import Red9_Meta as r9Meta
r9Meta.MetaClass(_block)
RBLOCKS.cgmRigBlock(_block)

from cgm.core import cgm_Meta as cgmMeta
import cgm.core.mrs.RigBlocks as RBLOCKS
RBLOCKS.get_modules_dat()  #...also reloads

b1 = cgmMeta.createMetaNode('cgmRigBlock', blockType='head')
b1 = cgmMeta.asMeta(_block)

b1 = cgmMeta.asMeta('L_thumb_limbBlock')  #...end, no lever setup

mMirror = b1.atUtils('blockMirror_create')

b1.atUtils('blockMirror_create')
b1.atUtils('blockMirror_go')
예제 #25
0
def create(target=None,
           position=None,
           tag=True,
           setMatchTarget=True,
           pivot='rp',
           mode='fromTarget',
           name=None):
    """
    Return the short name of an object

    :parameters
        :target(str): What to create a loc from
        :tag(bool): Whether to tag for updating or special naming
        :pivot: Whether to force it to be created at the rotatePivot, scalePivot or BoundingBox center
        :mode
            fromTarget -- can be component or transform
            midPoint -- mid point of specfied targets
            closestPointOnTarget -- closest point from source to targets
            closestTarget -- closest target from source
            rayCast -- create a rayCast locator. For more options, see LOCINATOR
            attachPoint -- Create a rayCast follicle, and parent your loc to that.
        :setMatchTarget
    :returns
        short name(str)
    """
    _str_func = "create"

    try:
        if mode == 'rayCast':
            #_catch = mc.group(em=True)
            class rayCastLoc(cgmDrag.clickMesh):
                def release_post_insert(self):
                    #ATTR.set_messagse(_catch, 'tmpMsg', self.l_created[-1])
                    _loc = self.l_created[-1]
                    _mLoc = r9Meta.MetaClass(_loc)
                    _buffer = _mLoc.cgmLocDat
                    _target = ATTR.get_message(_loc, 'meshTarget')[0]
                    _loc = mc.rename(
                        _loc, "{0}_u{1}_v{2}_rayCast_loc".format(
                            coreNames.get_base(_target),
                            "{0:.4f}".format(_buffer['uv'][0]),
                            "{0:.4f}".format(_buffer['uv'][1]),
                        ))
                    self.dropTool()

            rayCastLoc(create='locator')
            #_res = ATTR.get_message(_catch,'tmpMsg')[0]
            return True

        _loc = mc.spaceLocator()[0]

        if position:
            mc.move(position[0], position[1], position[2], _loc, ws=True)
            if name:
                return mc.rename(_loc, name)
            return mc.rename("pos_loc")
        if not target:
            if name:
                return mc.rename(_loc, name)
            return mc.rename(_loc, "world_center_loc")

        _targets = VALID.objStringList(target,
                                       noneValid=False,
                                       calledFrom=__name__ + _str_func +
                                       ">> validate target")
        #_targets = VALID.listArg(target)
        if tag or mode:
            _mi_loc = r9Meta.MetaClass(_loc)
            if not _mi_loc.hasAttr('cgmLocDat'):
                _mi_loc.addAttr('cgmLocDat', attrType='string')

        log.debug("|{0}| >> {1} mode...".format(_str_func, mode))

        if mode in ['fromTarget', 'attachPoint']:
            if len(_targets) != 1:
                log.warning("|{0}| >> mode: {1} | targets: {2} | ".format(
                    _str_func, mode, _targets))
                raise ValueError, "May only have one target for mode: {0} | targets: {1}".format(
                    mode, _targets)

            _target = _targets[0]

            if name:
                _loc = mc.rename(_loc, name)
            else:
                _loc = mc.rename(
                    _loc,
                    "{0}_fromTarget_loc".format(coreNames.get_base(_target)))

            if tag:  #store info
                ATTR.store_info(_loc,
                                'cgmName',
                                coreNames.get_base(_target),
                                attrType='string',
                                lock=True)
                ATTR.store_info(_loc, 'cgmLocMode', 'fromTarget', lock=True)
                ATTR.set_message(_loc, 'cgmLocSource', _target, 'cgmLocDat')
                if not VALID.is_component(_target) and setMatchTarget:
                    SNAP.matchTarget_set(_target, _loc)
                #_d = r9Meta.MetaClass(_loc).cgmLocDat

                _res = update(_loc)
            _res = update(_loc, _target, 'fromTarget')

            if mode == 'attachPoint':

                class follicleAttach(cgmDrag.clickMesh):
                    def release_post_insert(self):
                        _str_funcName = 'follicleAttach.release'
                        """if not self.b_dragStoreMode:#If not on drag, do it here. Otherwise do it on update
                            if self._posBuffer:
                                self.l_return.extend(self._posBuffer)
                                if self._posBufferRaw:
                                    self.l_returnRaw.extend(self._posBufferRaw)
                                else:
                                    self.l_returnRaw.extend(self._posBuffer)
                        
                            if self._createModeBuffer:
                                self.l_created.extend(self._createModeBuffer)"""

                        for pos in self.l_returnRaw:
                            log.debug("|{0}|...pos {1}".format(
                                _str_funcName, pos))
                            for i, m in enumerate(self.d_meshPos.keys()):
                                log.debug("|{0}|...mesh: {1}".format(
                                    _str_funcName, m))
                                for i2, h in enumerate(self.d_meshPos[m]):
                                    if h == pos:
                                        log.debug("Found follicle match!")
                                        try:
                                            _set = [
                                                m, self.d_meshUV[m][i2],
                                                "{0}_u{1}_v{2}".format(
                                                    coreNames.get_short(m),
                                                    "{0:.4f}".format(
                                                        self.d_meshUV[m][i2]
                                                        [0]), "{0:.4f}".format(
                                                            self.d_meshUV[m]
                                                            [i2][1]))
                                            ]
                                            self._l_folliclesToMake.append(
                                                _set)
                                            log.debug("|{0}|...uv {1}".format(
                                                _str_funcName, _set))
                                        except Exception, err:
                                            log.error(
                                                "|{0}| >> Failed to query uv for hit {2} on shape {2} | err:{1}"
                                                .format(
                                                    _str_funcName, err, pos,
                                                    m))
                            if self._l_folliclesToMake:
                                for f_dat in self._l_folliclesToMake:
                                    _follicle = NODES.add_follicle(
                                        f_dat[0], f_dat[2])
                                    log.debug(
                                        "|finalize| >> Follicle created: {0}".
                                        format(_follicle))
                                    ATTR.set(_follicle[0], 'parameterU',
                                             f_dat[1][0])
                                    ATTR.set(_follicle[0], 'parameterV',
                                             f_dat[1][1])
                                    mc.parent(_loc, _follicle[0])
                        mc.delete(self.l_created)
                        self.dropTool()

                follicleAttach()

            return _loc
        elif not _targets:
            raise ValueError, "Must have targets for mode: {0} | targets: {1}".format(
                mode, _targets)
예제 #26
0
import maya.cmds as mc
from cgm.core import cgm_Meta as cgmMeta
from cgm.core import cgm_PuppetMeta as cgmPM
import Red9.core.Red9_Meta as r9Meta
import cgm.core
cgm.core._reload()

from cgm.core.classes import SnapFactory as Snap
reload(Snap)
from cgm.core.rigger.lib.Limb import leg
m1.modulePuppet.masterNull.deformGroup
m1 = r9Meta.MetaClass('r_index_part')
m1 = r9Meta.MetaClass('r_middle_part')
m1 = r9Meta.MetaClass('r_ring_part')
m1 = r9Meta.MetaClass('r_thumb_part')
m1 = r9Meta.MetaClass('r_pinky_part')
from cgm.core.rigger import RigFactory as Rig
from cgm.core.rigger import JointFactory as jFactory
from cgm.core.rigger import ModuleFactory as mFactory
from cgm.core.classes import NodeFactory as nodeF
reload(nodeF)
reload(jFactory)
reload(Rig)
assert 1 == 2
from cgm.lib import curves
from cgm.lib import distance
from cgm.lib import locators
from cgm.lib import attributes
from cgm.lib import constraints
reload(attributes)
reload(distance)
예제 #27
0
#===============================================================
# Basic MetaClass Use:
#===============================================================

import Red9.core.Red9_Meta as r9Meta
import maya.cmds as cmds
reload(r9Meta)

#make a new blank mClass MayaNode
node = r9Meta.MetaClass()
node.select()
'''
If a Maya node is passed in and it has the mClass attribute of a class
thats known then the following call with return the correct class object.

NOTE: there's a global RED9_META_REGISTERY which holds registered mClasses
found at start using itersubclasses, called in the r9Meta.registerMClassInheritanceMapping()
'''
new = r9Meta.MetaClass(cmds.ls(sl=True)[0])
type(new)
#// <class 'Red9_Meta.MetaClass'>
'''
Attribute Handling
===============================================================
Attribute management for the node. If no type flag is passed in
then the code automatically figures what attrType to add from the
given value. Note that the attribute is serialized to the Maya
Node AND the class object. All attributes are managed
'''
#standard attribute handling
node.addAttr('stringTest', "this_is_a_string")  #create a string attribute
from cgm.core.lib import nameTools

#>>> Rig Block - eye
#=======================================================
nameTools.log.setLevel(nameTools.logging.INFO)
nameTools.log.setLevel(nameTools.logging.DEBUG)
cgmPM.log.setLevel(cgmPM.logging.INFO)
cgmPM.log.setLevel(cgmPM.logging.DEBUG)
mFactory.log.setLevel(mFactory.logging.DEBUG)
import cgm.core

cgm.core._reload()
from cgm.core import cgm_PuppetMeta as cgmPM

a = cgmPM.cgmEyeballBlock(direction='left')
a = r9Meta.MetaClass('l_eye_rigHelper')
a.mNode
a.pupilHelper
a.__verifyModule__()
a.__updateSizeData__()
p = a.__buildSimplePuppet__()
cgmPM.getSettingsColors('')
p.getModules()
a.__rebuildShapes__()
a.doName(nameChildren=True)
a.connectModule(m1)
b = cgmPM.cgmEyeball(name='eye', direction='left')
m1 = cgmPM.cgmModule(name='eye', direction='left')
m1.__verifySelectionSet__()
m1 = cgmPM.cgmModule('l_eye_part')
m1 = cgmPM.cgmModule('l_eyelid_part')
예제 #29
0
import cgm.core
cgm.core._reload()
from cgm.core import cgm_Meta as cgmMeta
from cgm.core import cgm_PuppetMeta as cgmPM
import Red9.core.Red9_Meta as r9Meta
from cgm.core.rigger import RigFactory as Rig
#======================================================================
issubclass(type(i_rig._i_masterControl), cgmMeta.cgmObject)
cgmMeta.validateObjArg(i_rig._i_masterControl.mNode, cgmMeta.cgmObject)
cgmMeta.log.setLevel(cgmMeta.logging.INFO)
cgmMeta.log.setLevel(cgmMeta.logging.DEBUG)
jFactory.log.setLevel(jFactory.logging.DEBUG)
m1 = r9Meta.MetaClass('l_clav_part')
m1 = r9Meta.MetaClass('r_clav_part')
m1 = r9Meta.MetaClass('l_arm_part')
m1 = r9Meta.MetaClass('r_arm_part')
m1.rigDelete()
m1.doRig()
m1 = r9Meta.MetaClass('l_arm_part')
Rig.get_report(m1)
m1.rigNull.blendJoints
m1.rigConnect()
m1.isRigged()
m1.rigDelete()
m1.rigNull.moduleJoints
i_rig = Rig.go(m1, forceNew=False, autoBuild=False)  #call to do general rig
m1.setState('skeleton', forceNew=True)
m1.getState()
m1.modulePuppet.getModuleFromDict({'moduleType': 'thumb'})
m1.modulePuppet.getModuleFromDict(moduleType=['torso', 'spine'])
m1.modulePuppet.getModuleFromDict(checkDict={'moduleType': 'head'})
예제 #30
0
                                  curveDegree=curveDegree,
                                  posOffset=posOffset,
                                  points=points,
                                  latheAxis=latheAxis,
                                  aimAxis=aimAxis)

#Loli
extendMode = 'cylinder'
closedCurve = False
l_specifiedRotates = [-30, -20, -10, -5, 0, 5, 10, 20, 30]

#>>> Modules
#=======================================================
reload(mShapeCast)
m1 = cgmPM.cgmModule(name='test')
m1 = r9Meta.MetaClass('spine_part')
m1.setState('template')
m1.getPartNameBase()
m1.modulePuppet.getGeo()
mShapeCast.go(m1, ['loliHandles'], ['neck_1_1_jnt', 'neck_2_jnt'])
mShapeCast.go(m1, ['segmentIK'])
mShapeCast.go(m1, ['torsoIK'])

mShapeCast.go(m1, ['segmentFK'])
mShapeCast.go(m1, ['segmentFK_Loli'])
mShapeCast.go(m1, ['cog'])
mShapeCast.go(m1, ['hips'])
mShapeCast.go(m1)
mShapeCast.go(m1, ['segmentFK_Loli', 'segmentIK'])

a = dataHolder()