def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.l_created = lists.returnListNoDuplicates(self.l_created)
        self.l_return = lists.returnListNoDuplicates(self.l_return)

        if self._createMode in ['curve','jointChain','group','follicle'] and self.l_return:
            if self._createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.l_created):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.l_created = bufferList

            elif self._createMode =='follicle':
                if self.mode == 'midPoint':
                    log.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.l_created:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        log.info("uv: {0}".format(uv))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        log.info("follicle: {0}".format(follicle))                        
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.l_created:
                    try:mc.delete(o)
                    except:pass
                if self._createMode == 'curve' and len(self.l_return)>1:
                    if len(self.l_return) > 1:
                        self.l_created = [curves.curveFromPosList(self.l_return)]
                    else:
                        log.warning("Need at least 2 points for a curve")                        
                elif self._createMode == 'jointChain':
                    self.l_created = []
                    mc.select(cl=True)
                    for pos in self.l_return:                             
                        self.l_created.append( mc.joint (p = (pos[0], pos[1], pos[2]),radius = 1) ) 
        log.debug( self.l_created)

        if self.d_tagAndName:
            for o in self.l_created:
                try:
                    i_o = cgmMeta.cgmNode(o)
                    for tag in self.d_tagAndName.keys():
                        i_o.doStore(tag,self.d_tagAndName[tag])
                    i_o.doName()
                except StandardError,error:
                    log.error(">>> clickMesh >> Failed to tag and name: %s | error: %s"%(i_o.p_nameShort,error))            	            		
Example #2
0
 def copyRotateOrder(self,targetObject):
     """ 
     Copy the rotate order from a target object to the current instanced maya object.
     """
     try:
         #If we have an Object Factory instance, link it
         targetObject.nameShort
         targetObject = targetObject.nameShort
     except:	
         assert mc.objExists(targetObject) is True, "'%s' - target object doesn't exist" %targetObject    
     assert self.transform ,"'%s' has no transform"%obj	
     assert mc.ls(targetObject,type = 'transform'),"'%s' has no transform"%targetObject
     buffer = mc.getAttr(targetObject + '.rotateOrder')
     attributes.doSetAttr(self.nameLong, 'rotateOrder',buffer) 
    def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.createdList = lists.returnListNoDuplicates(self.createdList)
        self.returnList = lists.returnListNoDuplicates(self.returnList)
        
        if self.createMode in ['curve','jointChain','group','follicle'] and self.returnList:
            if self.createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.createdList):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.createdList = bufferList
                
            elif self.createMode =='follicle':
                if self.mode == 'midPoint':
                    guiFactory.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.createdList:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.createdList:
                    try:mc.delete(o)
                    except:pass
                if self.createMode == 'curve' and len(self.returnList)>1:
                    if len(self.returnList) > 1:
                        self.createdList = [mc.curve (d=3, p = self.returnList , ws=True)]
                    else:
                        guiFactory.warning("Need at least 2 points for a curve")                        
                elif self.createMode == 'jointChain':
                    self.createdList = []
                    mc.select(cl=True)
                    for pos in self.returnList:        
                        self.createdList.append( mc.joint (p = (pos[0], pos[1], pos[2])) )
                                

        self.reset()
Example #4
0
    def __init__(self, *args, **kws):
        log.info('ChildClass.__init__ --')
        #Pull out our args/kws we need  ----------------------------------------------------------------------
        node = kws.get('node')
        name = kws.get('name')
        _setClass = kws.get('setClass') or None
        if args:
            node = args[0]
            if len(args) > 1:
                name = args[1]
            else:
                name = kws.get('name')

        if node is None or name is not None and mc.objExists(name):
            log.info("Created node")
            createdState = True
        else:
            createdState = False

        if _setClass:
            log.info(
                "Preinitialize, setClass | default {0} | Maybe you shouldn't do this..."
                .format(type(self).__name__))
            try:  #>>> TO CHECK IF WE NEED TO CLEAR CACHE ---------------------------------------------------------
                _currentMClass = attributes.doGetAttr(
                    node, 'mClass')  #...use to avoid exceptions

                if _setClass in [True, 1]:
                    _setClass = type(self).__name__

                if _setClass not in r9Meta.RED9_META_REGISTERY:
                    log.error("mClass value not registered - '{0}'".format(
                        _setClass))
                _setMClass = False
                if _setClass:  #...if we're going to set the mClass attr...
                    if _currentMClass:  #...does it have a current mClass attr value?
                        if _currentMClass != _setClass:  #...if not the same, replace
                            log.warning(
                                "mClasses don't match. Changing to '{0}'".
                                format(_setClass))
                            #mc.setAttr('%s.mClass' %(node), value = _setClass)
                            attributes.doSetAttr(node, 'mClass', _setClass,
                                                 True)
                            attributes.doSetAttr(node, 'UUID', '', True)
                            _setMClass = True
                        else:
                            log.info("mClasses match. ignoring...")
                    else:  #...if we have no value, set it
                        log.info("No mClass value, setting...")
                        _setMClass = True
                    if _setMClass:
                        if not mc.objExists("{0}.mClass".format(node)):
                            attributes.doAddAttr(node, 'mClass', 'string')
                        if not mc.objExists("{0}.UUID".format(node)):
                            attributes.doAddAttr(node, 'UUID', 'string')
                        attributes.doSetAttr(node, 'UUID', '', True)
                        attributes.doSetAttr(node, 'mClass', _setClass, True)
            except Exception, error:
                log.error("pre setClass fail >> %s" % error)
    def finalize(self):
        """
        Press action. Clears buffers.
        """
        #Clean our lists...
        self.createdList = lists.returnListNoDuplicates(self.createdList)
        self.returnList = lists.returnListNoDuplicates(self.returnList)
        
        if self.createMode in ['curve','jointChain','group','follicle'] and self.returnList:
            if self.createMode == 'group':
                bufferList = []
                for i,o in enumerate(self.createdList):
                    buffer = rigging.groupMeObject(o,False)
                    bufferList.append(buffer)                    
                    try:mc.delete(o)
                    except:pass
                self.createdList = bufferList
                
            elif self.createMode =='follicle':
                if self.mode == 'midPoint':
                    guiFactory.warning("Mid point mode doesn't work with follicles")
                    return
                bufferList = []
                for o in self.createdList:
                    mesh = attributes.doGetAttr(o,'cgmHitTarget')
                    if mc.objExists(mesh):
                        uv = distance.returnClosestUVToPos(mesh,distance.returnWorldSpacePosition(o))
                        follicle = nodes.createFollicleOnMesh(mesh)
                        attributes.doSetAttr(follicle[0],'parameterU',uv[0])
                        attributes.doSetAttr(follicle[0],'parameterV',uv[1])
                        try:mc.delete(o)
                        except:pass                        
            else:
                for o in self.createdList:
                    try:mc.delete(o)
                    except:pass
                if self.createMode == 'curve' and len(self.returnList)>1:
                    if len(self.returnList) > 1:
                        self.createdList = [curves.curveFromPosList(self.returnList)]
                    else:
                        guiFactory.warning("Need at least 2 points for a curve")                        
                elif self.createMode == 'jointChain':
                    self.createdList = []
                    mc.select(cl=True)
                    for pos in self.returnList:                             
                        self.createdList.append( mc.joint (p = (pos[0], pos[1], pos[2]),radius = 1) )
                                

        self.reset()
Example #6
0
def addFollicleSingleAttach(obj, mesh):
    from cgm.lib import (distance, nodes, attributes)
    mi_obj = cgmMeta.validateObjArg(obj, cgmMeta.cgmObject)
    mi_mesh = cgmMeta.validateObjArg(mesh, mayaType='mesh')
    uv = distance.returnClosestUVToPos(mi_mesh.mNode, mi_obj.getPosition())
    follicle = nodes.createFollicleOnMesh(mi_mesh.mNode)
    attributes.doSetAttr(follicle[0], 'parameterU', uv[0])
    attributes.doSetAttr(follicle[0], 'parameterV', uv[1])

    #create group
    mi_attachPoint = mi_obj.doLoc()
    mi_attachPoint.parent = follicle[1]

    #parent constrain
    mc.pointConstraint(mi_attachPoint.mNode, mi_obj.mNode, maintainOffset=True)
    mc.orientConstraint(mi_attachPoint.mNode,
                        mi_obj.mNode,
                        maintainOffset=True)
Example #7
0
    def __init__(self,*args,**kws):    
        log.info('ChildClass.__init__ --')	
        #Pull out our args/kws we need  ----------------------------------------------------------------------	
        node = kws.get('node')
        name = kws.get('name')
        _setClass = kws.get('setClass') or None
        if args:
            node = args[0]
            if len(args)>1:
                name = args[1]
            else:
                name = kws.get('name')

        if node is None or name is not None and mc.objExists(name):
            log.info("Created node")
            createdState = True
        else:
            createdState = False
            
        if _setClass:
            log.info("Preinitialize, setClass | default {0} | Maybe you shouldn't do this...".format(type(self).__name__))	
            try:#>>> TO CHECK IF WE NEED TO CLEAR CACHE ---------------------------------------------------------
                _currentMClass = attributes.doGetAttr(node,'mClass')#...use to avoid exceptions	
        
                if _setClass in [True, 1]:
                    _setClass = type(self).__name__	
        
                if _setClass not in r9Meta.RED9_META_REGISTERY:
                    log.error("mClass value not registered - '{0}'".format(_setClass))
                _setMClass = False
                if _setClass:#...if we're going to set the mClass attr...
                    if _currentMClass:#...does it have a current mClass attr value?
                        if _currentMClass != _setClass:#...if not the same, replace
                            log.warning("mClasses don't match. Changing to '{0}'".format(_setClass))				    
                            #mc.setAttr('%s.mClass' %(node), value = _setClass)	
                            attributes.doSetAttr(node,'mClass',_setClass,True)				
                            attributes.doSetAttr(node,'UUID','',True)
                            _setMClass = True
                        else:
                            log.info("mClasses match. ignoring...")				    		
                    else:#...if we have no value, set it
                        log.info("No mClass value, setting...")
                        _setMClass = True
                    if _setMClass:
                        if not mc.objExists("{0}.mClass".format(node)):
                            attributes.doAddAttr(node, 'mClass', 'string')
                        if not mc.objExists("{0}.UUID".format(node)):
                            attributes.doAddAttr(node, 'UUID', 'string')				
                        attributes.doSetAttr(node,'UUID','',True)
                        attributes.doSetAttr(node,'mClass',_setClass,True)			    
            except Exception,error:
                log.error("pre setClass fail >> %s"%error)
Example #8
0
        def _buildPupilIris_(self):
            mi_go = self._go#Rig Go instance link
            str_mirrorSide = self.str_mirrorSide

            try:#>>>> Iris pupil #==================================================================	
                try:
                    _l_build = [{'tag':'iris','buildCheck':self.mi_helper.buildIris,'shape':self.md_rigList['iris_shape'],'joint':self.md_rigList['iris'],'parent':self.md_rigList['eye']},
                                {'tag':'pupil','buildCheck':self.mi_helper.buildPupil,'shape':self.md_rigList['pupil_shape'],'joint':self.md_rigList['pupil'],'parent':self.md_rigList['iris']}]
                except Exception,error:raise Exception,"[build dict]{%s}"%(error)

                for _d in _l_build:
                    try:
                        self._d_buffer = _d
                        self.log_infoNestedDict('_d_buffer')
                        _tag = _d['tag']
                        _shape = _d['shape']
                        _joint = _d['joint']
                        _b_buildCheck = _d['buildCheck']

                        if not _b_buildCheck:
                            self.log_info("Build %s toggle: off"%(_tag))
                            _shape.delete()

                        else:
                            _joint.parent =  mi_go._i_constrainNull.eyeTrackNull.mNode
                            d_buffer = mControlFactory.registerControl(_joint,useShape = _shape,
                                                                       mirrorSide = str_mirrorSide, mirrorAxis="",
                                                                       makeAimable=True,setRotateOrder ='zxy') 	    

                            mi_control = d_buffer['instance']
                            _shape.delete()

                            attributes.doSetAttr(mi_control.mNode,'overrideEnabled',0)
                            attributes.doSetAttr(mi_control.mNode,'overrideDisplayType',0)
                            cgmMeta.cgmAttr(mi_control,'radius',.0001,hidden=True)
                            mi_go._i_rigNull.connectChildNode(mi_control,'control%s'%_tag.capitalize(),"rigNull")
                            self.ml_controlsAll.append(mi_control)	
                            attributes.doSetLockHideKeyableAttr(mi_control.mNode,channels=['tx','ty','tz','rx','ry','rz','v','s%s'%mi_go._jointOrientation[0]])				
                    except Exception,error:raise Exception,"[%s]{%s}"%(_tag,error)
            except Exception,error:raise Exception,"[Build iris/pupil fail]{%s}"%(error)
Example #9
0
 def set(self,value,*a, **kw):
     """ 
     Set attr value based on attr type
     
     Keyword arguments:
     value(varied)   
     *a, **kw
     """
     try:
         if self.children:
             guiFactory.warning("'%s' has children, running set command on '%s'"%(self.nameCombined,"','".join(self.children)))
             
             for i,c in enumerate(self.children):
                 try:
                     cInstance = AttrFactory(self.obj.nameShort,c)                        
                     if type(value) is list and len(self.children) == len(value): #if we have the same length of values in our list as we have children, use them
                         attributes.doSetAttr(cInstance.obj.nameShort,cInstance.attr, value[i], *a, **kw)
                         cInstance.value = value[i]
                         self.value = value
                     else:    
                         attributes.doSetAttr(cInstance.obj.nameShort,cInstance.attr, value, *a, **kw)
                         self.value = value
                 except:
                     guiFactory.warning("'%s' failed to set"%c)
                     
         elif self.form == 'message':
             if value:
                 self.doStore(value)
         else:
             attributes.doSetAttr(self.obj.nameShort,self.attr, value, *a, **kw)
             self.value = value
     
     except:
         guiFactory.warning("'%s.%s' failed to set '%s'"%(self.obj.nameShort,self.attr,value))
Example #10
0
def doPositionLocator(locatorName, locInfo):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Position a locator with locator info generated from returnInfoForLoc

	ARGUMENTS:
	locatorName(string)
	locInfo(dict)

	RETURNS:
	success(bool)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    if search.returnObjectType(locatorName) == 'locator':
        objTrans = locInfo['position']
        objRot = locInfo['rotation']
        correctRo = locInfo['rotationOrder']
        rotateAxis = locInfo['rotateAxis']

        mc.move(objTrans[0], objTrans[1], objTrans[2], locatorName)
        mc.setAttr((locatorName + '.rotateOrder'), correctRo)

        #Rotate
        if locInfo['objectType'] == 'polyFace':
            constBuffer = mc.normalConstraint((locInfo['createdFrom']),
                                              locatorName)
            mc.delete(constBuffer[0])
        else:
            attributes.doSetAttr(locatorName, 'rotateOrder', correctRo)
            mc.rotate(objRot[0], objRot[1], objRot[2], locatorName, ws=True)
            for i, a in enumerate(['X', 'Y', 'Z']):
                attributes.doSetAttr(locatorName, 'rotateAxis{0}'.format(a),
                                     rotateAxis[i])
        return True
    else:
        guiFactory.warning('Not a locator.')
        return False
Example #11
0
def returnClosestPointOnSurfaceInfo(targetObj, surface):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns pertinent info of the closest point of a mesh to a target object -
    position, normal, parameterU,parameterV,closestFaceIndex,closestVertexIndex

    ARGUMENTS:
    targetObj(string)
    mesh(string)

    RETURNS:
    closestPointInfo(dict)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """   
    # make the closest point node #
    closestPointNode = mc.createNode ('closestPointOnSurface')
    pointOnSurfaceNode = mc.createNode ('pointOnSurfaceInfo')
    controlSurface = mc.listRelatives(surface,shapes=True)
        
    #>>>Surface Info
    #Thanks - http://www.kylenikolich.com/scripting/lod/parentToSurface.mel
    f_minU = attributes.doGetAttr(controlSurface[0],'mnu')
    f_maxU = attributes.doGetAttr(controlSurface[0],'mxu')
    f_sizeU = f_maxU - f_minU
    f_minV = attributes.doGetAttr(controlSurface[0],'mnv')
    f_maxV = attributes.doGetAttr(controlSurface[0],'mxv')
    f_sizeV = f_maxV - f_minV    

    # to account for target objects in heirarchies #
    pos = returnWorldSpacePosition(targetObj)
    attributes.doSetAttr(closestPointNode,'inPositionX',pos[0])
    attributes.doSetAttr(closestPointNode,'inPositionY',pos[1])
    attributes.doSetAttr(closestPointNode,'inPositionZ',pos[2])
    
    attributes.doConnectAttr((controlSurface[0]+'.worldSpace'),(closestPointNode+'.inputSurface'))
    # Connect the info node to the surface #
    attributes.doConnectAttr  ((controlSurface[0]+'.local'),(pointOnSurfaceNode+'.inputSurface'))
    # Contect the pos group to the info node#
    attributes.doConnectAttr ((closestPointNode+'.parameterU'),(pointOnSurfaceNode+'.parameterU'))
    attributes.doConnectAttr  ((closestPointNode+'.parameterV'),(pointOnSurfaceNode+'.parameterV'))

    pointInfo = {}
    pointInfo['position']=attributes.doGetAttr(pointOnSurfaceNode,'position')
    pointInfo['normal']=attributes.doGetAttr(pointOnSurfaceNode,'normal')
    pointInfo['parameterU']=mc.getAttr(pointOnSurfaceNode+'.parameterU')
    pointInfo['parameterV']=mc.getAttr(pointOnSurfaceNode+'.parameterV')
    pointInfo['normalizedU'] = (pointInfo['parameterU'] + f_minU)/f_sizeU
    pointInfo['normalizedV'] =  (pointInfo['parameterV'] + f_minV)/f_sizeV  
    pointInfo['tangentU']=mc.getAttr(pointOnSurfaceNode+'.tangentU')
    pointInfo['tangentV']=mc.getAttr(pointOnSurfaceNode+'.tangentV')
    
    mc.delete(closestPointNode)
    mc.delete(pointOnSurfaceNode)
    log.debug(pointInfo)
    return pointInfo
    def set(self, value, *a, **kw):
        """ 
        Set attr value based on attr type
        
        Keyword arguments:
        value(varied)   
        *a, **kw
        """
        try:
            if self.children:
                guiFactory.warning(
                    "'%s' has children, running set command on '%s'" %
                    (self.nameCombined, "','".join(self.children)))

                for i, c in enumerate(self.children):
                    try:
                        cInstance = AttrFactory(self.obj.nameShort, c)
                        if type(value) is list and len(self.children) == len(
                                value
                        ):  #if we have the same length of values in our list as we have children, use them
                            attributes.doSetAttr(cInstance.obj.nameShort,
                                                 cInstance.attr, value[i], *a,
                                                 **kw)
                            cInstance.value = value[i]
                            self.value = value
                        else:
                            attributes.doSetAttr(cInstance.obj.nameShort,
                                                 cInstance.attr, value, *a,
                                                 **kw)
                            self.value = value
                    except:
                        guiFactory.warning("'%s' failed to set" % c)

            elif self.form == 'message':
                if value:
                    self.doStore(value)
            else:
                attributes.doSetAttr(self.obj.nameShort, self.attr, value, *a,
                                     **kw)
                self.value = value

        except:
            guiFactory.warning("'%s.%s' failed to set '%s'" %
                               (self.obj.nameShort, self.attr, value))
def groupToConditionNodeSet(group,
                            chooseAttr='switcher',
                            controlObject=None,
                            connectTo='visibility'):
    """
    Hack job for the gig to make a visibility switcher for all the first level of children of a group
    """
    children = search.returnChildrenObjects(group)  #Check for children

    if not children:  #If none, break out
        guiFactory("'%s' has no children! Aborted." % group)
        return False
    if controlObject is None:
        controlObject = group

    #Make our attr
    a = AttrFactory.AttrFactory(controlObject, chooseAttr, 'enum')
    children.insert(0, 'none')
    print children
    if len(children) == 2:
        a.setEnum('off:on')
    else:
        a.setEnum(':'.join(children))

    for i, c in enumerate(children[1:]):
        print i
        print c
        #see if the node exists
        condNodeTest = attributes.returnDriverObject('%s.%s' % (c, connectTo))
        if condNodeTest:
            buffer = condNodeTest
        else:
            if mc.objExists('%s_condNode' % c):
                mc.delete('%s_condNode' % c)
            buffer = nodes.createNamedNode('%s_picker' % c,
                                           'condition')  #Make our node
        print buffer
        attributes.doSetAttr(buffer, 'secondTerm', i + 1)
        attributes.doSetAttr(buffer, 'colorIfTrueR', 1)
        attributes.doSetAttr(buffer, 'colorIfFalseR', 0)

        a.doConnectOut('%s.firstTerm' % buffer)
        attributes.doConnectAttr('%s.outColorR' % buffer,
                                 '%s.%s' % (c, connectTo))
Example #14
0
def singleObjectVisToggle(obj,chooseAttr = 'switcher', controlObject = None, connectTo = 'visibility'):
    #Make our attr
    a = AttrFactory.AttrFactory(controlObject,chooseAttr,'enum')
    a.setEnum('off:on')


    condNodeTest = attributes.returnDriverObject('%s.%s'%(obj,connectTo))
    if condNodeTest:
	buffer = condNodeTest
    else:
	if mc.objExists('%s_condNode'%obj):
	    mc.delete('%s_condNode'%obj)
	buffer = nodes.createNamedNode('%s_picker'%obj,'condition') #Make our node
    print buffer
    attributes.doSetAttr(buffer,'secondTerm',1)
    attributes.doSetAttr(buffer,'colorIfTrueR',1)
    attributes.doSetAttr(buffer,'colorIfFalseR',0)
    
    a.doConnectOut('%s.firstTerm'%buffer)
    attributes.doConnectAttr('%s.outColorR'%buffer,'%s.%s'%(obj,connectTo))
Example #15
0
    def setDrawingOverrideSettings(self, attrs = None, pushToShapes = False):
        """
        Function for changing drawing override settings on on object

        Keyword arguments:
        attrs -- default will set all override attributes to default settings
                 (dict) - pass a dict in and it will attempt to set the key to it's indexed value ('attr':1}
                 (list) - if a name is provided and that attr is an override attr, it'll reset only that one
        """
        # First make sure the drawing override attributes exist on our instanced object
        for a in drawingOverrideAttrsDict:
            assert mc.objExists('%s.%s'%(self.nameLong,a)),"'%s.%s' doesn't exist"%(self.nameLong,a)

        if attrs is None or False:
            for a in drawingOverrideAttrsDict:
                attributes.doSetAttr(self.nameLong,a,drawingOverrideAttrsDict[a])

        if type(attrs) is dict:
            for a in attrs.keys():
                if a in drawingOverrideAttrsDict:
                    try:
                        attributes.doSetAttr(self.nameLong,a,attrs[a])
                    except:
                        raise AttributeError, "There was a problem setting '%s.%s' to %s"%(self.nameBase,a,drawingOverrideAttrsDict[a])
                else:
                    guiFactory.warning("'%s.%s' doesn't exist"%(self.nameBase,a))
                    
        if type(attrs) is list:
            for a in attrs:
                if a in drawingOverrideAttrsDict:
                    try:
                        attributes.doSetAttr(self.nameLong,a,drawingOverrideAttrsDict[a])
                    except:
                        raise AttributeError, "There was a problem setting '%s.%s' to %s"%(self.nameBase,a,drawingOverrideAttrsDict[a])
                else:
                    guiFactory.warning("'%s.%s' doesn't exist"%(self.nameBase,a))       
                    
                    
        if pushToShapes:
            raise NotImplementedError,"This feature isn't done yet"
Example #16
0
def groupToConditionNodeSet(group,chooseAttr = 'switcher', controlObject = None, connectTo = 'visibility'):
    """
    Hack job for the gig to make a visibility switcher for all the first level of children of a group
    """
    children = search.returnChildrenObjects(group) #Check for children

    if not children: #If none, break out
	guiFactory("'%s' has no children! Aborted."%group)
	return False
    if controlObject is None:
	controlObject = group
    
    #Make our attr
    a = AttrFactory.AttrFactory(controlObject,chooseAttr,'enum')
    children.insert(0,'none')
    print children
    if len(children) == 2:
	a.setEnum('off:on')
    else:
	a.setEnum(':'.join(children))
    
    for i,c in enumerate(children[1:]):
	print i
	print c
	#see if the node exists
	condNodeTest = attributes.returnDriverObject('%s.%s'%(c,connectTo))
	if condNodeTest:
	    buffer = condNodeTest
	else:
	    if mc.objExists('%s_condNode'%c):
		mc.delete('%s_condNode'%c)
	    buffer = nodes.createNamedNode('%s_picker'%c,'condition') #Make our node
	print buffer
	attributes.doSetAttr(buffer,'secondTerm',i+1)
	attributes.doSetAttr(buffer,'colorIfTrueR',1)
	attributes.doSetAttr(buffer,'colorIfFalseR',0)
	
	a.doConnectOut('%s.firstTerm'%buffer)
	attributes.doConnectAttr('%s.outColorR'%buffer,'%s.%s'%(c,connectTo))
def singleObjectVisToggle(obj,
                          chooseAttr='switcher',
                          controlObject=None,
                          connectTo='visibility'):
    #Make our attr
    a = AttrFactory.AttrFactory(controlObject, chooseAttr, 'enum')
    a.setEnum('off:on')

    condNodeTest = attributes.returnDriverObject('%s.%s' % (obj, connectTo))
    if condNodeTest:
        buffer = condNodeTest
    else:
        if mc.objExists('%s_condNode' % obj):
            mc.delete('%s_condNode' % obj)
        buffer = nodes.createNamedNode('%s_picker' % obj,
                                       'condition')  #Make our node
    print buffer
    attributes.doSetAttr(buffer, 'secondTerm', 1)
    attributes.doSetAttr(buffer, 'colorIfTrueR', 1)
    attributes.doSetAttr(buffer, 'colorIfFalseR', 0)

    a.doConnectOut('%s.firstTerm' % buffer)
    attributes.doConnectAttr('%s.outColorR' % buffer,
                             '%s.%s' % (obj, connectTo))
Example #18
0
for k in i_dBuffer.d_indexToAttr.keys():
    attrName = 'spineMult_%s' % k
    cgmMeta.cgmAttr(i_dBuffer.mNode,
                    'scaleMult_%s' % k).doCopyTo('cog_anim',
                                                 attrName,
                                                 connectSourceToTarget=True)
    cgmMeta.cgmAttr('cog_anim', attrName, keyable=True, lock=False)

i_rig.d_controlShapes
rig_segmentFK(i_rig.d_controlShapes)
Rig.registerControl('pelvis_anim')
l_joints = mc.ls(sl=True)
s = cgmMeta.cgmAttr('pelvis_surfaceJoint', 'scaleX')
s.p_hidden = False
curves.createControlCurve('semiSphere', 10, 'z-')
attributes.doSetAttr('closestPointOnSurface1', 'inPostionX', 5)
mc.setAttr('closestPointOnSurface1.inPostionX', 5)
m1 = cgmPM.cgmModule(name='test')
m1 = cgmMeta.cgmNode('spine_part')
m1.setState('skeleton', forceNew=True)
m1.rigNull.skinJoints
m1.getModuleColors()
m1.getPartNameBase()
m1.modulePuppet.getGeo()
targetObj = mc.ls(sl=True)[0]
distance.returnClosestPointOnSurfaceInfo(targetObj, 'test_controlSurface')
distance.returnClosestUV(targetObj, 'test_controlSurface')
log.info(a)
nodes.createFollicleOnMesh('spine_controlSurface', 'test')
locators.locMeClosestUVOnSurface(mc.ls(sl=True)[0],
                                 'test_controlSurface',
Example #19
0
def randomizeCubey(nameSpace):
    import random

    settingsObject = ('%s:Cubey_masterAnim_settings'%nameSpace)
    
    #reset stuff
    for a in 'Nose','Hair','Beard','BaseballHat','Belt','Buckle','Collar','Suit':
	attributes.doSetAttr(settingsObject,a, 0)
	
    #set it
    if not mc.objExists(settingsObject):
	print "'%s' doesn't exist!"%settingsObject
    attributes.doSetAttr(settingsObject,'Nose', random.randint(1,5))
    attributes.doSetAttr(settingsObject,'Hair', random.randint(0,6))
    beardOptions = [0,1,2,3,4,5,0,0,0,0,0]
    attributes.doSetAttr(settingsObject,'Beard', beardOptions[random.randint(0,9)])
    
    case = random.randint(0,10)

    if case in  [1,5,8]:
	attributes.doSetAttr(settingsObject,'BaseballHat', 1)
	attributes.doSetAttr(settingsObject,'Hair', 0)
    if case in [5,2,6]:
	attributes.doSetAttr(settingsObject,'Belt', 1)
	attributes.doSetAttr(settingsObject,'Buckle', 1)
    if case == 7:
	attributes.doSetAttr(settingsObject,'Suit', 1)
    if case in [9,3]:
	attributes.doSetAttr(settingsObject,'Collar', 1)
	
    #Nose and ears
    options = [.75,.8,.9,1,1]
    noseMult = options[random.randint(0,4)] 
    
    noseControl = ('%s:nose_jnt_anim'%nameSpace)
    attributes.doSetAttr(noseControl,'sx', noseMult)
    attributes.doSetAttr(noseControl,'sy', noseMult)
    attributes.doSetAttr(noseControl,'sz', noseMult)
    
    #eary = 0.513,1.02
    #earZ = 1, 1.857
    earOptionsY = [0.513,.62,.75,.8,1,1.02,1,1]
    earOptionsZ = [.75,1,1.25,1.5,1.8,1,1]
    
    earMultY = earOptionsY[random.randint(0,6)] 
    earMultZ = earOptionsZ[random.randint(0,6)]
    
    earLeftControl = ('%s:ear_l_jnt_anim'%nameSpace)
    earRightControl = ('%s:ear_r_jnt_anim'%nameSpace)
    
    
    attributes.doSetAttr(earLeftControl,'sy', earMultY)
    attributes.doSetAttr(earLeftControl,'sz', earMultZ) 
    
    attributes.doSetAttr(earRightControl,'sy', earMultY)
    attributes.doSetAttr(earRightControl,'sz', earMultZ)    
    
    #Eyes
    #l eye = -0.089,0.132  eye_l_mover_jnt_anim
    earLeftControl = ('%s:eye_l_mover_jnt_anim'%nameSpace)
    earRightControl = ('%s:eye_r_mover_jnt_anim'%nameSpace)
    
    eyeOptions = [-0.089,-.06,-.04,-.02,0,0,0,.025,.04,.06,.13]
    eyeMult = eyeOptions[random.randint(0,10)] 
    
    attributes.doSetAttr(earLeftControl,'tx', eyeMult)
    attributes.doSetAttr(earRightControl,'tx', -eyeMult)       
def randomizeCubey(nameSpace):
    import random

    settingsObject = ('%s:Cubey_masterAnim_settings' % nameSpace)

    #reset stuff
    for a in 'Nose', 'Hair', 'Beard', 'BaseballHat', 'Belt', 'Buckle', 'Collar', 'Suit':
        attributes.doSetAttr(settingsObject, a, 0)

    #set it
    if not mc.objExists(settingsObject):
        print "'%s' doesn't exist!" % settingsObject
    attributes.doSetAttr(settingsObject, 'Nose', random.randint(1, 5))
    attributes.doSetAttr(settingsObject, 'Hair', random.randint(0, 6))
    beardOptions = [0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
    attributes.doSetAttr(settingsObject, 'Beard',
                         beardOptions[random.randint(0, 9)])

    case = random.randint(0, 10)

    if case in [1, 5, 8]:
        attributes.doSetAttr(settingsObject, 'BaseballHat', 1)
        attributes.doSetAttr(settingsObject, 'Hair', 0)
Example #21
0
        def _fnc_applyData(self):
            '''
            '''    
            _targetSkin = self.mData.d_target['skin']      
            mi_skinCluster = cgmMeta.cgmNode(_targetSkin)
            skinFn = OMA.MFnSkinCluster( mi_skinCluster.mNodeMObject )
            
            #...get some api stuff
            fnSet = OM.MFnSet(skinFn.deformerSet())
            members = OM.MSelectionList()
            fnSet.getMembers(members, False)
            dagPath = OM.MDagPath()
            components = OM.MObject()
            members.getDagPath(0, dagPath, components)         
            influencePaths = OM.MDagPathArray()
            numInfluences = skinFn.influenceObjects(influencePaths)
            if numInfluences != len(self.l_jointsToUse):
                return self._FailBreak_("Influences don't match data")              
            
            #...get weights
            weights = OM.MDoubleArray()
            util = OM.MScriptUtil()
            util.createFromInt(0)
            pUInt = util.asUintPtr()
            skinFn.getWeights(dagPath, components, weights, pUInt)  
                
            numComponentsPerInfluence = weights.length() / numInfluences   
            
            influenceIndices = OM.MIntArray(numInfluences)
            for i in range(numInfluences):
                influenceIndices.set(i, i)   
                
            #...Set our weights ------------------------------------------------------------------------------------
            #weightListP = skinFn.findPlug( "weightList" )
            #weightListObj = weightListP.attribute()
            #weightsP = skinFn.findPlug( "weights" )
        
            #tmpIntArray = OM.MIntArray()
            #baseFmtStr = mi_skinCluster.mNode +'.weightList[{0}]'  #pre build this string: fewer string ops == faster-ness!
            
            self.progressBar_start(stepMaxValue=self.mData.d_target['pointCount'], 
                                   statusMessage='Calculating....', 
                                   interruptableState=False)    
            
            
            for i in range(numInfluences):
                for c in range(numComponentsPerInfluence):
                    weights.set(0.0, c*numInfluences+i)                    
            
            for vertIdx in self._d_vertToWeighting.keys():
                self.progressBar_iter(status = 'Setting {0}'.format(vertIdx))                
                _d_vert = self._d_vertToWeighting[vertIdx]#...{0:value,...}
                
                #we need to use the api to query the physical indices used
                #weightsP.selectAncestorLogicalIndex( vertIdx, weightListObj )
                #weightsP.getExistingArrayAttributeIndices( tmpIntArray )
        
                #weightFmtStr = baseFmtStr.format(vertIdx) +'.weights[{0}]'
            
                #clear out any existing skin data - and awesomely we cannot do this with the api - so we need to use a weird ass mel command
                #for n in range( tmpIntArray.length() ):
                    #mc.removeMultiInstance( weightFmtStr.format(tmpIntArray[n]) )            
            
                #at this point using the api or mel to set the data is a moot point...  we have the strings already so just use mel
                    
                for jointIdx in _d_vert.keys():
                    #self.log_info(" vtx: {0} | jnt:{1} | value:{2}".format(vertIdx,jointIdx, _d_vert[jointIdx]))
                    #self.log_info("{0} | {1}".format( weightFmtStr.format(jointIdx),_d_vert[jointIdx]))
                    #mc.setAttr( weightFmtStr.format(jointIdx), _d_vert[jointIdx] ) 
                    #weights.set(self.data['weights'][src][j], j*numInfluences+1)
                    #weights.set(_d_vert[jointIdx], vertIdx)
                    weights.set(_d_vert[jointIdx], vertIdx*numInfluences+jointIdx)#...this was a bugger to get to, 
            self.progressBar_end()
            
            skinFn.setWeights(dagPath, components, influenceIndices, weights, False)
            

            #...blendWeights
            
            #self.setBlendWeights(dagPath, components)
                    
            #...apply our settings from our skin...
            
            for k in _skinclusterAttributesToCopy:
                _value = _skinclusterAttributesToCopy[k](self.mData.d_sourceSkin[k])
                self.log_info("Setting '{0}' to {1}".format(k,_value))
                try:attributes.doSetAttr(_targetSkin,k,_value)
                except Exception,error:
                    self.log_error("{0} failed | {1}".format(k,error))
Example #22
0
    def createSizeTemplateControl(self):
        """ 
        >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   
        DESCRIPTION:
        Generates a sizeTemplateObject. It's been deleted, it recreates it. Guess the size based off of there
        being a mesh there. If there is no mesh, it sets sets an intial size of a 
        [155,170,29] unit character.
        
        ARGUMENTS:
        self.PuppetNull.nameShort(string)
        
        RETURNS:
        returnList(list) = [startCrv(string),EndCrv(list)]
        >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        """
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Get info
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        startColors = modules.returnSettingsData('colorStart')
        endColors = modules.returnSettingsData('colorEnd')

        font = mc.getAttr((self.msgSettingsInfo.get() + '.font'))
        """ checks for there being anything in our geo group """
        if not self.geo:
            return guiFactory.warning(
                'Need some geo defined to make this tool worthwhile')
            boundingBoxSize = modules.returnSettingsDataAsFloat(
                'meshlessSizeTemplate')
        else:
            boundingBoxSize = distance.returnBoundingBoxSize(
                self.msgGeoGroup.get())
            boundingBox = mc.exactWorldBoundingBox(self.msgGeoGroup.get())
        """determine orienation """
        maxSize = max(boundingBoxSize)
        matchIndex = boundingBoxSize.index(maxSize)
        """Find the pivot of the bounding box """
        pivotPosition = distance.returnCenterPivotPosition(
            self.msgGeoGroup.get())

        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Get our positions
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        if self.optionPuppetMode.get() == 0:
            #If bio...
            if matchIndex == 1 or matchIndex == 0:
                #Vertical
                posBuffers = [[0, .5, 0], [0, .75, 0]]
                width = (boundingBoxSize[0] / 2)
                height = (boundingBoxSize[1])
                depth = boundingBoxSize[2]

                for cnt, pos in enumerate(posBuffers):
                    posBuffer = posBuffers[cnt]
                    posBuffer[0] = 0
                    posBuffer[1] = (posBuffer[1] * height)
                    posBuffer[2] = 0

            elif matchIndex == 2:
                #Horizontal
                posBuffers = [[0, 0, -.33], [0, 0, .66]]
                width = boundingBoxSize[1]
                height = boundingBoxSize[2] / 2
                depth = (boundingBoxSize[0])

                for cnt, pos in enumerate(posBuffers):
                    posBuffer = posBuffers[cnt]
                    posBuffer[0] = 0
                    posBuffer[1] = boundingBoxSize[1] * .75
                    posBuffer[2] = (posBuffer[2] * height)

        else:
            #Otherwise
            if matchIndex == 1 or matchIndex == 0:
                #Vertical
                width = (boundingBoxSize[0] / 2)
                height = (boundingBoxSize[1])
                depth = boundingBoxSize[2]
                posBuffers = [[0, boundingBox[1], 0], [0, boundingBox[4], 0]]

            elif matchIndex == 2:
                #Horizontal
                width = boundingBoxSize[0]
                height = boundingBoxSize[2] / 2
                depth = (boundingBoxSize[1])
                startHeight = max([boundingBox[4], boundingBox[1]]) - depth / 2
                print startHeight
                posBuffers = [[0, startHeight, boundingBox[2]],
                              [0, startHeight, boundingBox[5]]]
        # Simple reverse of start pos buffers if the object is pointing negative
        if self.optionAimAxis < 2:
            posBuffers.reverse()

        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Making the controls
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        """ make our control object """
        startCurves = []
        startCurve = curves.createControlCurve('circle', depth * .8)
        mc.xform(startCurve, t=posBuffers[0], ws=True)
        attributes.doSetAttr(startCurve, 'rotateOrder', 5)
        curves.setCurveColorByName(startCurve, startColors[1])
        startCurves.append(startCurve)

        startText = curves.createTextCurve('start',
                                           size=depth * .75,
                                           font=font)
        mc.xform(startText, t=posBuffers[0], ws=True)
        curves.setCurveColorByName(startText, startColors[0])
        startCurves.append(startText)

        endCurves = []
        endCurve = curves.createControlCurve('circle', depth * .8)
        mc.xform(endCurve, t=posBuffers[1], ws=True)
        curves.setCurveColorByName(endCurve, endColors[1])
        attributes.doSetAttr(endCurve, 'rotateOrder', 5)
        endCurves.append(endCurve)

        endText = curves.createTextCurve('end', size=depth * .6, font=font)
        mc.xform(endText, t=posBuffers[1], ws=True)
        curves.setCurveColorByName(endText, endColors[0])
        endCurves.append(endText)
        """ aiming """
        position.aimSnap(startCurve, endCurve, [0, 0, 1], [0, 1, 0])
        position.aimSnap(startText, endCurve, [0, 0, 1], [0, 1, 0])

        position.aimSnap(endCurve, startCurve, [0, 0, -1], [0, 1, 0])
        position.aimSnap(endText, startCurve, [0, 0, -1], [0, 1, 0])

        sizeCurveControlStart = curves.combineCurves(startCurves)
        sizeCurveControlEnd = curves.combineCurves(endCurves)
        """ store our info to name our objects"""
        attributes.storeInfo(sizeCurveControlStart, 'cgmName',
                             (self.PuppetNull.nameShort + '.cgmName'))
        attributes.storeInfo(sizeCurveControlStart, 'cgmDirection', 'start')
        attributes.storeInfo(sizeCurveControlStart, 'cgmType',
                             'templateSizeObject')
        sizeCurveControlStart = NameFactory.doNameObject(sizeCurveControlStart)
        mc.makeIdentity(sizeCurveControlStart,
                        apply=True,
                        t=True,
                        s=True,
                        r=True)

        attributes.storeInfo(sizeCurveControlEnd, 'cgmName',
                             (self.PuppetNull.nameShort + '.cgmName'))
        attributes.storeInfo(sizeCurveControlEnd, 'cgmDirection', 'end')
        attributes.storeInfo(sizeCurveControlEnd, 'cgmType',
                             'templateSizeObject')
        sizeCurveControlEnd = NameFactory.doNameObject(sizeCurveControlEnd)

        endGroup = rigging.groupMeObject(sizeCurveControlEnd)
        mc.makeIdentity(sizeCurveControlEnd,
                        apply=True,
                        t=True,
                        s=True,
                        r=True)

        mc.parentConstraint(sizeCurveControlStart,
                            endGroup,
                            maintainOffset=True)
        """ make control group """
        controlGroup = rigging.groupMeObject(sizeCurveControlStart)
        attributes.storeInfo(controlGroup, 'cgmName',
                             (self.PuppetNull.nameShort + '.cgmName'))
        attributes.storeInfo(controlGroup, 'cgmType',
                             'templateSizeObjectGroup')
        controlGroup = NameFactory.doNameObject(controlGroup)

        endGroup = rigging.doParentReturnName(endGroup, controlGroup)
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        # Getting data ready
        #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        attributes.storeInfo(controlGroup, 'controlStart',
                             sizeCurveControlStart)
        attributes.storeInfo(controlGroup, 'controlEnd', sizeCurveControlEnd)
        attributes.storeInfo(self.PuppetNull.nameShort, 'templateSizeObject',
                             controlGroup)

        self.templateSizeObjects['root'] = controlGroup
        self.templateSizeObjects['start'] = sizeCurveControlStart
        self.templateSizeObjects['end'] = sizeCurveControlEnd

        returnList = []
        returnList.append(sizeCurveControlStart)
        returnList.append(sizeCurveControlEnd)
        return returnList
Example #23
0
	def build(self):#================================================================================   	
	    
	    #>>>Get data
	    ml_controlsFK =  self._go._i_rigNull.msgList_get('controlsFK')   
	    ml_rigJoints = self._go._i_rigNull.msgList_get('rigJoints')
	    ml_blendJoints = self._go._i_rigNull.msgList_get('blendJoints')
	    ml_fkJoints = self._go._i_rigNull.msgList_get('fkJoints')
	    ml_ikJoints = self._go._i_rigNull.msgList_get('ikJoints')
		    
	    mi_settings = self._go._i_rigNull.settings
		
	    aimVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[0])
	    upVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[1])
	    outVector = dictionary.stringToVectorDict.get("%s+"%self._go._jointOrientation[2])
	    
	    mi_controlIK = self._go._i_rigNull.controlIK
	
	    for chain in [ml_ikJoints,ml_blendJoints]:
		chain[0].parent = self._go._i_constrainNull.mNode
		
	    self.ml_fkAttachJoints = []
	    if self._go._str_mirrorDirection == 'Right':#mirror control setup
		self.ml_fkAttachJoints = self._go._i_rigNull.msgList_get('fkAttachJoints')
		
	    #for more stable ik, we're gonna lock off the lower channels degrees of freedom
	    for chain in [ml_ikJoints]:
		for axis in self._go._jointOrientation[:2]:
		    log.info(axis)
		    for i_j in chain[1:]:
			attributes.doSetAttr(i_j.mNode,"jointType%s"%axis.upper(),1)
	    
	    #=============================================================    
	    try:#>>>Finger Root Control and root follow
		for attr in ['tx','ty','tz']:#Unlock a few things
		    i_attr = cgmMeta.cgmAttr(ml_fkJoints[0],attr)
		    i_attr.p_keyable = True
		    i_attr.p_locked = False	   	
	
		#we have to rebuild a little so that we can use our fk base control both for fk and ik
		#Create a orient group that tracks the  module constrain null
		if self._go._partType == 'finger':
		    buffer_fkGroup = ml_fkJoints[0].parent
		    i_orientGroup = cgmMeta.asMeta( ml_fkJoints[1].doGroup(True),'cgmObject',setClass=True )
		    i_orientGroup.addAttr('cgmTypeModifier','toOrient')
		    i_orientGroup.doName()
		    
		    #constrain it 
		    str_orConst = mc.orientConstraint(self._go._i_constrainNull.mNode,i_orientGroup.mNode,maintainOffset = True)[0]
		    self._go._i_constrainNull.connectChildNode(i_orientGroup,'fingerRoot','owner')#Connect
		    i_orientGroup.parent = self._go._i_constrainNull.mNode
		    
		    attributes.doSetLockHideKeyableAttr(i_orientGroup.mNode)#lockNHide
		    
		    i_parentGroup = cgmMeta.asMeta( i_orientGroup.doGroup(True),'cgmObject',setClass=True )
		    i_parentGroup.addAttr('cgmTypeModifier','toParent')
		    i_parentGroup.doName()	
		    str_prntConst = mc.parentConstraint( ml_fkJoints[0].mNode,i_parentGroup.mNode,maintainOffset = True)[0]
		    i_parentGroup.parent = buffer_fkGroup
		    
		    #attributes.doSetLockHideKeyableAttr(ml_fkJoints[0].mNode,lock = False, visible=True, keyable=True, channels=['tx','ty','tz'])
		    
		    #Constrain ik base to fk base
		    mc.orientConstraint(ml_fkJoints[0].mNode,ml_ikJoints[0].mNode,maintainOffset = True)
		    ml_fkJoints[0].parent = self._go._i_constrainNull.mNode
	
	    except Exception,error:
		raise Exception,"%s.build_FKIK>>> Finger Root Control error: %s"%(self._go._strShortName,error)
    #set it
    if not mc.objExists(settingsObject):
        print "'%s' doesn't exist!" % settingsObject
    attributes.doSetAttr(settingsObject, 'Nose', random.randint(1, 5))
    attributes.doSetAttr(settingsObject, 'Hair', random.randint(0, 6))
    beardOptions = [0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
    attributes.doSetAttr(settingsObject, 'Beard',
                         beardOptions[random.randint(0, 9)])

    case = random.randint(0, 10)

    if case in [1, 5, 8]:
        attributes.doSetAttr(settingsObject, 'BaseballHat', 1)
        attributes.doSetAttr(settingsObject, 'Hair', 0)
    if case in [5, 2, 6]:
        attributes.doSetAttr(settingsObject, 'Belt', 1)
        attributes.doSetAttr(settingsObject, 'Buckle', 1)
    if case == 7:
        attributes.doSetAttr(settingsObject, 'Suit', 1)
    if case in [9, 3]:
        attributes.doSetAttr(settingsObject, 'Collar', 1)

    #Nose and ears
    options = [.75, .8, .9, 1, 1]
    noseMult = options[random.randint(0, 4)]

    noseControl = ('%s:nose_jnt_anim' % nameSpace)
    attributes.doSetAttr(noseControl, 'sx', noseMult)
    attributes.doSetAttr(noseControl, 'sy', noseMult)
    attributes.doSetAttr(noseControl, 'sz', noseMult)
def randomizeCubette(namespace):
    import random

    settingsObject = ('%s:Cubey_masterAnim_settings' % namespace)

    #reset stuff
    for a in 'Tops', 'Hair', 'Bottom', 'Noses', 'Belts', 'ShortSleeves':
        attributes.doSetAttr(settingsObject, a, 0)

    attributes.doSetAttr(settingsObject, 'RegTop', 1)

    #set it
    if not mc.objExists(settingsObject):
        print "'%s' doesn't exist!" % settingsObject
    attributes.doSetAttr(settingsObject, 'Tops', random.randint(0, 3))
    attributes.doSetAttr(settingsObject, 'Hair', random.randint(0, 5))
    attributes.doSetAttr(settingsObject, 'Bottom', random.randint(0, 3))
    attributes.doSetAttr(settingsObject, 'Noses', random.randint(1, 5))

    case = random.randint(0, 10)
    if case in [5, 2, 6]:
        attributes.doSetAttr(settingsObject, 'ShortSleeves', 1)
def placerLocsToCubey():
    import random
    from cgm.lib import position
    selection = mc.ls(sl=True) or []
    mStable = [
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male1.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male2.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male3.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male4.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male5.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male6.ma'
    ]
    fStable = [
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/female1.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/female2.ma',
        'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/female3.ma'
    ]

    maleFileCnt = 0
    femaleFileCnt = 0
    maleCnt = 0
    femCnt = 0

    length = len(selection)
    for i, loc in enumerate(selection):
        guiFactory.report("On %s of %s" % (i, length))

        #Pick a sex
        sexInt = random.randint(0, 10)
        sex = 'male'
        if sexInt in [2, 3]:
            sex = 'female'

        guiFactory.report("sex is '%s'" % sex)

        #Pick a file
        if sex is 'male':
            locFile = mStable[maleFileCnt]
            maleFileCnt += 1
            maleCnt += 1
            if not maleFileCnt < len(mStable):
                maleFileCnt = 0
            locNameSpace = 'male_%s' % maleCnt
        else:
            locFile = fStable[femaleFileCnt]
            femaleFileCnt += 1
            femCnt += 1
            if not femaleFileCnt < len(fStable):
                femaleFileCnt = 0
            locNameSpace = 'female_%s' % femCnt

        guiFactory.report("File is '%s'" % locFile)

        #Import the file
        mc.file(locFile,
                i=True,
                namespace=locNameSpace,
                pr=True,
                force=True,
                prompt=False)  # prompt means no error message
        buffer = mc.ls('%s:*' % locNameSpace)

        if not 'RN' in buffer[0]:
            return guiFactory.warning('Failed to find name space')

        splitBuffer = buffer[0].split('RN')
        realLocNameSpace = splitBuffer[0]

        #Snap Master constraint group and constrain to loc
        nestedNameSpace = 'male'
        if sex == 'female':
            nestedNameSpace = 'female'

        snappingObject = ('%s:%s:Cubey_masterAnim_constraint_grp' %
                          (locNameSpace, nestedNameSpace))
        if not mc.objExists(snappingObject):
            return "Snapping object doesn't exist = '%s'" % snappingObject
        position.moveParentSnap(snappingObject, loc)

        masterObject = ('%s:%s:Cubey_masterAnim' %
                        (locNameSpace, nestedNameSpace))
        if not mc.objExists(masterObject):
            return "Master object doesn't exist = '%s'" % masterObject

        mc.parentConstraint(loc, snappingObject, maintainOffset=False)
        if sex == 'male':
            attributes.doSetAttr(masterObject, 'tz', .606)
        attributes.doSetAttr(masterObject, 'rz', -90)

        #Randomize
        if sex == 'male':
            randomizeCubey('%s:%s' % (locNameSpace, nestedNameSpace))
        if sex == 'female':
            randomizeCubette('%s:%s' % (locNameSpace, nestedNameSpace))
attributes.doConnectAttr('pelvis_influenceJoint.rotateZ','plusMinusAverage1.input1D[0]')
attributes.doConnectAttr('spine_2_influenceJoint.rotateZ','plusMinusAverage1.input1D[1]')
mc.ls('spine_2_1_surfaceJoint_ikH_poleVectorConstraint1',sn = True)
attributes.doConnectAttr('plusMinusAverage1.output1D','plusMinusAverage2.input1D[0]')
attributes.doConnectAttr('pelvis_influenceJoint.rotateZ','plusMinusAverage2.input1D[1]')

attributes.doConnectAttr('plusMinusAverage1.output1D','plusMinusAverage3.input1D[0]')
attributes.doConnectAttr('spine_2_influenceJoint.rotateZ','plusMinusAverage3.input1D[1]')

attributes.doConnectAttr('plusMinusAverage2.output1D','spine_1_surfaceJoint_rotate_grp.ry')
attributes.doConnectAttr('plusMinusAverage3.output1D','spine_1_1_surfaceJoint_rotate_grp.ry')


attributes.doConnectAttr('plusMinusAverage1.output1D','multiplyDivide1.input1X')
#mode 2
attributes.doSetAttr('multiplyDivide1','input2X',2)
attributes.doSetAttr('multiplyDivide2','input2X',2)


'multiplyDivide1'
#Working through zero equivalency 
'%f'%(-4.11241646134e-07)
round(4.11241646134e-07,1)
round(f1,places)
round(.005,3)
number = .2
number = scientific
number = .000065183
number = 0.0
for n in [1,2,3,4,5,6,7,8,9]:
    log.info(round(number,n))
    def updatePos(self, debugReport=False):
        """
        Get updated position data via shooting rays
        """
        if not self.meshList:
            return guiFactory.warning(
                "No mesh objects have been added to '%s'" % (self.name))

        buffer = screenToWorld(int(self.x),
                               int(self.y))  #get world point and vector!

        self.clickPos = buffer[0]  #Our world space click point
        self.clickVector = buffer[1]  #Camera vector
        self.posBuffer = []  #Clear our pos buffer

        for m in self.meshList:  #Get positions per mesh piece
            #First get the distance to try to check
            checkDistance = self.getDistanceToCheck(m)
            #print ("Checking distance of %s"%checkDistance)
            if m not in self.meshPosDict.keys():
                self.meshPosDict[m] = []
                self.meshUVDict[m] = []

            if mc.objExists(m):
                if self.mode == 'surface':
                    buffer = findMeshIntersection(m, self.clickPos,
                                                  self.clickVector,
                                                  checkDistance)
                    if buffer is not None:
                        hit = self.convertPosToLocalSpace(buffer['hit'])
                        self.posBuffer.append(hit)
                        self.startPoint = self.convertPosToLocalSpace(
                            buffer['source'])
                        self.meshPosDict[m].append(hit)
                        self.meshUVDict[m].append(buffer['uv'])
                else:
                    buffer = findMeshIntersections(m, self.clickPos,
                                                   self.clickVector,
                                                   checkDistance)
                    if buffer:
                        conversionBuffer = []
                        #Need to convert to local space
                        for hit in buffer['hits']:
                            conversionBuffer.append(
                                self.convertPosToLocalSpace(hit))

                        self.posBuffer.extend(conversionBuffer)
                        self.startPoint = self.convertPosToLocalSpace(
                            buffer['source'])

                        self.meshPosDict[m].extend(conversionBuffer)
                        self.meshUVDict[m].extend(buffer['uvs'])

        if not self.posBuffer:
            if debugReport: guiFactory.warning('No hits detected!')
            return

        if self.clampSetting and self.clampSetting < len(self.posBuffer):
            if debugReport:
                guiFactory.warning(
                    "Position buffer was clamped. Check settings if this was not desired."
                )
            self.posBuffer = distance.returnPositionDataDistanceSortedList(
                self.startPoint, self.posBuffer)
            self.posBuffer = self.posBuffer[:self.clampSetting]

        if self.mode == 'midPoint':
            self.posBuffer = [
                distance.returnAveragePointPosition(self.posBuffer)
            ]

        if self.posBuffer:  #Check for closest and just for hits
            if self.closestOnly and self.mode != 'intersections':
                buffer = distance.returnClosestPoint(self.startPoint,
                                                     self.posBuffer)
                self.posBuffer = [buffer]
        else:
            pass
        #guiFactory.warning("No hits detected")

        if self.createMode and self.posBuffer:  # Make our stuff
            #Delete the old stuff
            if self.createModeBuffer and not self.dragStoreMode:
                for o in self.createModeBuffer:
                    try:
                        mc.delete(o)
                    except:
                        pass
                self.createModeBuffer = []

            for pos in self.posBuffer:
                if len(pos) == 3:
                    baseScale = distance.returnMayaSpaceFromWorldSpace(10)
                    if self.createMode == 'joint':
                        nameBuffer = mc.joint(radius=1)
                        #attributes.doSetAttr(nameBuffer,'radius',1)

                        mc.select(cl=True)
                    else:
                        nameBuffer = mc.spaceLocator()[0]
                        for m in self.meshPosDict.keys(
                        ):  #check each mesh dictionary to see where it came from
                            if pos in self.meshPosDict[
                                    m]:  #if the mesh has a match
                                attributes.storeInfo(nameBuffer,
                                                     'cgmHitTarget', m)

                                attributes.doSetAttr(nameBuffer, 'localScaleX',
                                                     (self.meshArea * .025))
                                attributes.doSetAttr(nameBuffer, 'localScaleY',
                                                     (self.meshArea * .025))
                                attributes.doSetAttr(nameBuffer, 'localScaleZ',
                                                     (self.meshArea * .025))
                                break

                    mc.move(pos[0], pos[1], pos[2], nameBuffer)

                    self.createModeBuffer.append(nameBuffer)
                else:
                    if debugReport:
                        guiFactory.warning("'%s' isn't a valid position" % pos)

        if self.dragStoreMode:
            if self.posBuffer:
                for p in self.posBuffer:
                    self.returnList.append(p)

        mc.refresh()  #Update maya to make it interactive!
Example #29
0
        def _buildPupilIris_(self):
            mi_go = self._go  #Rig Go instance link
            str_mirrorSide = self.str_mirrorSide

            try:  #>>>> Iris pupil #==================================================================
                try:
                    _l_build = [{
                        'tag': 'iris',
                        'buildCheck': self.mi_helper.buildIris,
                        'shape': self.md_rigList['iris_shape'],
                        'joint': self.md_rigList['iris'],
                        'parent': self.md_rigList['eye']
                    }, {
                        'tag': 'pupil',
                        'buildCheck': self.mi_helper.buildPupil,
                        'shape': self.md_rigList['pupil_shape'],
                        'joint': self.md_rigList['pupil'],
                        'parent': self.md_rigList['iris']
                    }]
                except Exception, error:
                    raise Exception, "[build dict]{%s}" % (error)

                for _d in _l_build:
                    try:
                        self._d_buffer = _d
                        self.log_infoNestedDict('_d_buffer')
                        _tag = _d['tag']
                        _shape = _d['shape']
                        _joint = _d['joint']
                        _b_buildCheck = _d['buildCheck']

                        if not _b_buildCheck:
                            self.log_info("Build %s toggle: off" % (_tag))
                            _shape.delete()

                        else:
                            _joint.parent = mi_go._i_constrainNull.eyeTrackNull.mNode
                            d_buffer = mControlFactory.registerControl(
                                _joint,
                                useShape=_shape,
                                mirrorSide=str_mirrorSide,
                                mirrorAxis="",
                                makeAimable=True,
                                setRotateOrder='zxy')

                            mi_control = d_buffer['instance']
                            _shape.delete()

                            attributes.doSetAttr(mi_control.mNode,
                                                 'overrideEnabled', 0)
                            attributes.doSetAttr(mi_control.mNode,
                                                 'overrideDisplayType', 0)
                            cgmMeta.cgmAttr(mi_control,
                                            'radius',
                                            .0001,
                                            hidden=True)
                            mi_go._i_rigNull.connectChildNode(
                                mi_control, 'control%s' % _tag.capitalize(),
                                "rigNull")
                            self.ml_controlsAll.append(mi_control)
                            attributes.doSetLockHideKeyableAttr(
                                mi_control.mNode,
                                channels=[
                                    'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'v',
                                    's%s' % mi_go._jointOrientation[0]
                                ])
                    except Exception, error:
                        raise Exception, "[%s]{%s}" % (_tag, error)
Example #30
0
def placerLocsToCubey():
    import random
    from cgm.lib import position
    selection = mc.ls(sl=True) or []
    mStable = ['J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male1.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male2.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male3.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male4.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male5.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/male6.ma']
    fStable = ['J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/female1.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/female2.ma',
               'J:/Dropbox/MasterCard/Sequences/mc/mc0010/Anim/maya/scenes/cycles/female3.ma']
    
    maleFileCnt = 0
    femaleFileCnt = 0
    maleCnt = 0
    femCnt = 0
    
    length = len(selection)
    for i,loc in enumerate(selection):
	guiFactory.report("On %s of %s"%(i,length))
	
	#Pick a sex
	sexInt = random.randint(0,10)
	sex = 'male'
	if sexInt in [2,3]:
	    sex = 'female'
	    
	guiFactory.report("sex is '%s'"%sex)
	
	#Pick a file
	if sex is 'male':
	    locFile = mStable[maleFileCnt]
	    maleFileCnt +=1
	    maleCnt +=1
	    if not maleFileCnt < len(mStable):
		maleFileCnt = 0
	    locNameSpace = 'male_%s'%maleCnt
	else:
	    locFile = fStable[femaleFileCnt]
	    femaleFileCnt +=1
	    femCnt +=1
	    if not femaleFileCnt < len(fStable):
		femaleFileCnt = 0
	    locNameSpace = 'female_%s'%femCnt
		
	guiFactory.report("File is '%s'"%locFile)
	
	#Import the file
	mc.file(locFile, i = True,namespace = locNameSpace,pr = True, force = True,prompt = False) # prompt means no error message
	buffer =  mc.ls('%s:*'%locNameSpace) 
	
	if not 'RN' in buffer[0]:
	    return guiFactory.warning('Failed to find name space')
	
	splitBuffer = buffer[0].split('RN')
	realLocNameSpace = splitBuffer[0]
	
	#Snap Master constraint group and constrain to loc
	nestedNameSpace = 'male'
	if sex == 'female':
	    nestedNameSpace = 'female'
	    
	snappingObject = ('%s:%s:Cubey_masterAnim_constraint_grp'%(locNameSpace,nestedNameSpace))
	if not mc.objExists(snappingObject):
	    return "Snapping object doesn't exist = '%s'"%snappingObject
	position.moveParentSnap(snappingObject,loc)
	
	masterObject = ('%s:%s:Cubey_masterAnim'%(locNameSpace,nestedNameSpace))
	if not mc.objExists(masterObject):
	    return "Master object doesn't exist = '%s'"%masterObject
	
	mc.parentConstraint(loc,snappingObject, maintainOffset=False)
	if sex == 'male':
	    attributes.doSetAttr(masterObject,'tz',.606)
	attributes.doSetAttr(masterObject,'rz',-90)
	
	#Randomize
	if sex == 'male':
	    randomizeCubey('%s:%s'%(locNameSpace,nestedNameSpace))
	if sex == 'female':
	    randomizeCubette('%s:%s'%(locNameSpace,nestedNameSpace))
Example #31
0
def zeroTransformMeObject(obj, scaleZero=False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Makes sure an object is zeroed out, parents the zero group back to the original objects parent

    ARGUMENTS:
    obj(string)

    RETURNS:
    groupName(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    parent = mc.listRelatives(obj, parent=True, fullPath=True)

    group = groupMeObject(obj, True, True)
    group2 = ''
    attributes.storeInfo(group, 'cgmTypeModifier', 'zero')

    objScale = []
    objScale.append(mc.getAttr(obj + '.sx'))
    objScale.append(mc.getAttr(obj + '.sy'))
    objScale.append(mc.getAttr(obj + '.sz'))

    #Check if we got zero translates
    zeroCheck = mc.xform(obj, q=True, os=True, rp=True)
    if zeroCheck:
        if scaleZero:
            mc.makeIdentity(obj, apply=True, t=0, r=0, s=1)
        group2 = groupMeObject(obj, True, True)
        zeroCheck = mc.xform(obj, q=True, os=True, rp=True)

        zeroCheck = cgmMath.multiplyLists([objScale, zeroCheck])
        mc.xform(group2,
                 t=(-zeroCheck[0], -zeroCheck[1], -zeroCheck[2]),
                 os=True)
        attributes.storeInfo(group, 'cgmTypeModifier', 'zeroParent')
        attributes.storeInfo(group2, 'cgmTypeModifier', 'zero')
        group2 = NameFactoryOld.doNameObject(group2)

        for attr in 'tx', 'ty', 'tz':
            attributes.doSetAttr(obj, attr, 0)

    #Check for zero rotates
    rotateCheck = mc.xform(obj, q=True, os=True, ro=True)
    if rotateCheck:
        if not group2:
            group2 = groupMeObject(obj, True, True)
            attributes.storeInfo(group, 'cgmTypeModifier', 'zeroParent')
            attributes.storeInfo(group2, 'cgmTypeModifier', 'zero')
            NameFactoryOld.doNameObject(group2)

        mc.xform(group2,
                 ro=(rotateCheck[0], rotateCheck[1], rotateCheck[2]),
                 os=True)
        for attr in 'rx', 'ry', 'rz':
            attributes.doSetAttr(obj, attr, 0)
    """
    objScale = []
    objScale.append(mc.getAttr(obj+'.sx'))
    objScale.append(mc.getAttr(obj+'.sy'))
    objScale.append(mc.getAttr(obj+'.sz'))
    grpScale = []
    grpScale.append(mc.getAttr(group+'.sx'))
    grpScale.append(mc.getAttr(group+'.sy'))
    grpScale.append(mc.getAttr(group+'.sz'))
    multScale = cgmMath.multiplyLists([objScale,grpScale])
    
    mc.scale(multScale[0], multScale[1], multScale[2],[group])
    for attr in 'sx','sy','sz':
        attributes.doSetAttr(obj,attr,1)
    """
    return NameFactoryOld.doNameObject(group)
Example #32
0
def bakeCombinedBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes out from one object that have a split type

    ARGUMENTS:
    sourceObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(sourceObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        blendShape1Buffer = (blendShapeNode+'.'+shape1)
        blendShape2Buffer = (blendShapeNode+'.'+shape2)
        attributes.doSetAttr(blendShape1Buffer,1)
        attributes.doSetAttr(blendShape2Buffer,1)
        dupBuffer = mc.duplicate(sourceObject)


        splitBuffer = blendShapeShortNames[pair].split('_')
        if len(splitBuffer)>1:
            nameBuffer = splitBuffer[:-1]
        else:
            nameBuffer = splitBuffer
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        """ Unlock it """
        attributes.doSetLockHideKeyableAttr(dupBuffer,False,True,True)

        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShape1Buffer,0)
        attributes.doSetAttr(blendShape2Buffer,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
    def updatePos(self,debugReport = False):
        """
        Get updated position data via shooting rays
        """
        if not self.meshList:
            return guiFactory.warning("No mesh objects have been added to '%s'"%(self.name))
        
        buffer =  screenToWorld(int(self.x),int(self.y))#get world point and vector!
                
        self.clickPos = buffer[0] #Our world space click point
        self.clickVector = buffer[1] #Camera vector
        self.posBuffer = []#Clear our pos buffer
        
        for m in self.meshList:#Get positions per mesh piece
            #First get the distance to try to check
            checkDistance = self.getDistanceToCheck(m)
            #print ("Checking distance of %s"%checkDistance)
            if m not in self.meshPosDict.keys():
                self.meshPosDict[m] = []
                self.meshUVDict[m] = []
                
            if mc.objExists(m):
                if self.mode == 'surface':
                    buffer = findMeshIntersection(m, self.clickPos , self.clickVector, checkDistance)                
                    if buffer is not None:
                        hit = self.convertPosToLocalSpace( buffer['hit'] )
                        self.posBuffer.append(hit)  
                        self.startPoint = self.convertPosToLocalSpace( buffer['source'] )
                        self.meshPosDict[m].append(hit)
                        self.meshUVDict[m].append(buffer['uv'])
                else:
                    buffer = findMeshIntersections(m, self.clickPos , self.clickVector , checkDistance)                                    
                    if buffer:
                        conversionBuffer = []
                        #Need to convert to local space
                        for hit in buffer['hits']:
                            conversionBuffer.append(self.convertPosToLocalSpace( hit ))
                             
                        self.posBuffer.extend(conversionBuffer)
                        self.startPoint = self.convertPosToLocalSpace( buffer['source'] )
                        
                        self.meshPosDict[m].extend(conversionBuffer)
                        self.meshUVDict[m].extend(buffer['uvs'])
                        
                        
        if not self.posBuffer:
            if debugReport:guiFactory.warning('No hits detected!')
            return
        
        if self.clampSetting and self.clampSetting < len(self.posBuffer):
            if debugReport:guiFactory.warning("Position buffer was clamped. Check settings if this was not desired.")
            self.posBuffer = distance.returnPositionDataDistanceSortedList(self.startPoint,self.posBuffer)
            self.posBuffer = self.posBuffer[:self.clampSetting]
            
        if self.mode == 'midPoint':                
            self.posBuffer = [distance.returnAveragePointPosition(self.posBuffer)]

        if self.posBuffer: #Check for closest and just for hits
            if self.closestOnly and self.mode != 'intersections':
                buffer = distance.returnClosestPoint(self.startPoint,self.posBuffer)
                self.posBuffer = [buffer]               
        else:pass
            #guiFactory.warning("No hits detected")
            
        if self.createMode and self.posBuffer: # Make our stuff
            #Delete the old stuff
            if self.createModeBuffer and not self.dragStoreMode:
                for o in self.createModeBuffer:
                    try:mc.delete(o)
                    except:pass
                self.createModeBuffer = []
            
            for pos in self.posBuffer:
                if len(pos) == 3:
                    baseScale = distance.returnMayaSpaceFromWorldSpace(10)
                    if self.createMode == 'joint':
                        nameBuffer = mc.joint(radius = 1)
                        #attributes.doSetAttr(nameBuffer,'radius',1)
                        
                        mc.select(cl=True)
                    else:
                        nameBuffer = mc.spaceLocator()[0]
                        for m in self.meshPosDict.keys():#check each mesh dictionary to see where it came from
                            if pos in self.meshPosDict[m]:#if the mesh has a match
                                attributes.storeInfo(nameBuffer,'cgmHitTarget',m)
                                
                                attributes.doSetAttr(nameBuffer,'localScaleX',(self.meshArea*.025))
                                attributes.doSetAttr(nameBuffer,'localScaleY',(self.meshArea*.025))
                                attributes.doSetAttr(nameBuffer,'localScaleZ',(self.meshArea*.025))
                                break                              
                        
                    mc.move (pos[0],pos[1],pos[2], nameBuffer)
                    
                    self.createModeBuffer.append(nameBuffer)
                else:
                    if debugReport:guiFactory.warning("'%s' isn't a valid position"%pos)
        
        if self.dragStoreMode:
            if self.posBuffer:
                for p in self.posBuffer:
                    self.returnList.append(p)  
               
        mc.refresh()#Update maya to make it interactive!
Example #34
0
def bakeBlendShapeNode(sourceObject, blendShapeNode, baseNameToUse = False, stripPrefix = False, ignoreInbetweens = False, ignoreTargets = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for exporting an object's blendshapes

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool) - whether to strip the first '_' segment
    ignoreInbetweens(bool)
    ignoreTargets(list) - targets to ignore in the processing

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    targetDict = returnBlendShapeTargetsAndWeights(sourceObject,blendShapeNode)
    targetSets = []
    blendShapeNodeChannels = []

    for key in targetDict.keys():
        targetSetBuffer = targetDict.get(key)
        targetSets.append(targetSetBuffer)

        baseSet = targetSetBuffer[-1]
        blendShapeNodeChannels.append(baseSet[0])

    blendShapeShortNames = []

    """ first loop gets connections, breaks them and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ get the connection """
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        print blendShapeConnections
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeBuffer,0)


    # Bake it
    bakedGeo = bakeBlendShapes(sourceObject, sourceObject, blendShapeNode, baseNameToUse, stripPrefix, ignoreInbetweens, ignoreTargets)


    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """ group for geo """
    meshGroup = mc.group( em=True)
    if baseNameToUse != False:
        attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    return returnList
Example #35
0
        def _fnc_applyData(self):
            '''
            '''    
            _targetSkin = self.mData.d_target['skin']      
            mi_skinCluster = cgmMeta.cgmNode(_targetSkin)
            skinFn = OMA.MFnSkinCluster( mi_skinCluster.mNodeMObject )
            
            #...get some api stuff
            fnSet = OM.MFnSet(skinFn.deformerSet())
            members = OM.MSelectionList()
            fnSet.getMembers(members, False)
            dagPath = OM.MDagPath()
            components = OM.MObject()
            members.getDagPath(0, dagPath, components)         
            influencePaths = OM.MDagPathArray()
            numInfluences = skinFn.influenceObjects(influencePaths)
            if numInfluences != len(self.l_jointsToUse):
                return self._FailBreak_("Influences don't match data")              
            
            #...get weights
            weights = OM.MDoubleArray()
            util = OM.MScriptUtil()
            util.createFromInt(0)
            pUInt = util.asUintPtr()
            skinFn.getWeights(dagPath, components, weights, pUInt)  
                
            numComponentsPerInfluence = weights.length() / numInfluences   
            
            influenceIndices = OM.MIntArray(numInfluences)
            for i in range(numInfluences):
                influenceIndices.set(i, i)   
                
            #...Set our weights ------------------------------------------------------------------------------------
            #weightListP = skinFn.findPlug( "weightList" )
            #weightListObj = weightListP.attribute()
            #weightsP = skinFn.findPlug( "weights" )
        
            #tmpIntArray = OM.MIntArray()
            #baseFmtStr = mi_skinCluster.mNode +'.weightList[{0}]'  #pre build this string: fewer string ops == faster-ness!
            
            self.progressBar_start(stepMaxValue=self.mData.d_target['pointCount'], 
                                   statusMessage='Calculating....', 
                                   interruptableState=False)    
            
            
            for i in range(numInfluences):
                for c in range(numComponentsPerInfluence):
                    weights.set(0.0, c*numInfluences+i)                    
            
            for vertIdx in self._d_vertToWeighting.keys():
                self.progressBar_iter(status = 'Setting {0}'.format(vertIdx))                
                _d_vert = self._d_vertToWeighting[vertIdx]#...{0:value,...}
                
                #we need to use the api to query the physical indices used
                #weightsP.selectAncestorLogicalIndex( vertIdx, weightListObj )
                #weightsP.getExistingArrayAttributeIndices( tmpIntArray )
        
                #weightFmtStr = baseFmtStr.format(vertIdx) +'.weights[{0}]'
            
                #clear out any existing skin data - and awesomely we cannot do this with the api - so we need to use a weird ass mel command
                #for n in range( tmpIntArray.length() ):
                    #mc.removeMultiInstance( weightFmtStr.format(tmpIntArray[n]) )            
            
                #at this point using the api or mel to set the data is a moot point...  we have the strings already so just use mel
                    
                for jointIdx in _d_vert.keys():
                    #self.log_info(" vtx: {0} | jnt:{1} | value:{2}".format(vertIdx,jointIdx, _d_vert[jointIdx]))
                    #self.log_info("{0} | {1}".format( weightFmtStr.format(jointIdx),_d_vert[jointIdx]))
                    #mc.setAttr( weightFmtStr.format(jointIdx), _d_vert[jointIdx] ) 
                    #weights.set(self.data['weights'][src][j], j*numInfluences+1)
                    #weights.set(_d_vert[jointIdx], vertIdx)
                    weights.set(_d_vert[jointIdx], vertIdx*numInfluences+jointIdx)#...this was a bugger to get to, 
            self.progressBar_end()
            
            skinFn.setWeights(dagPath, components, influenceIndices, weights, False)
            

            #...blendWeights
            
            #self.setBlendWeights(dagPath, components)
                    
            #...apply our settings from our skin...
            
            for k in _skinclusterAttributesToCopy:
                _value = _skinclusterAttributesToCopy[k](self.mData.d_sourceSkin[k])
                self.log_info("Setting '{0}' to {1}".format(k,_value))
                try:attributes.doSetAttr(_targetSkin,k,_value)
                except Exception,error:
                    self.log_error("{0} failed | {1}".format(k,error))
#>>> Modules
#=======================================================
m1 = r9Meta.MetaClass('spine_part')
m1.__dict__.keys()
m1.rigNull.skinJoints
i_rig = Rig.go(m1)
m1.getState()
i_rig.d_controlShapes
rig_segmentFK(i_rig.d_controlShapes)
Rig.registerControl('pelvis_anim')
l_joints = mc.ls(sl=True)

s = cgmMeta.cgmAttr('pelvis_surfaceJoint','scaleX')
s.p_hidden = False
curves.createControlCurve('semiSphere',10,'z-')
attributes.doSetAttr('closestPointOnSurface1','inPostionX',5)
mc.setAttr('closestPointOnSurface1.inPostionX',5)
m1 = cgmPM.cgmModule(name = 'test')
m1 = cgmMeta.cgmNode('spine_part')
m1.setState('skeleton',forceNew = True)
m1.rigNull.skinJoints
m1.getModuleColors()
m1.getPartNameBase()
m1.modulePuppet.getGeo()
targetObj = mc.ls(sl=True)[0]
distance.returnClosestPointOnSurfaceInfo(targetObj,'test_controlSurface')
distance.returnClosestUV(targetObj,'test_controlSurface')
log.info(a)
nodes.createFollicleOnMesh('spine_controlSurface','test')
locators.locMeClosestUVOnSurface(mc.ls(sl=True)[0], 'test_controlSurface', pivotOnSurfaceOnly = False)
Example #37
0
def bakeBlendShapeNodeToTargetObject(targetObject,sourceObject, blendShapeNode, baseNameToUse = False, stripPrefix = False,ignoreInbetweens = False, ignoreTargets = False, transferConnections = True):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes from one object to another

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseNameToUse(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    stripPrefix(bool)
    ignoreInbetweens(bool)
    ignoreTargets(list) - list of targets to ignore
    transferConnections(bool) - if True, builds a new blendshape node and transfers the connections from our base objects

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseNameToUse == False:
        baseName = ''
    else:
        baseName = baseNameToUse + '_'

    """ wrap deform object """
    wrapBuffer = wrapDeformObject(targetObject,sourceObject,True)
    targetObjectBaked = wrapBuffer[1]

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    blendShapeNodeChannels = returnBlendShapeAttributes(blendShapeNode)

    blendShapeShortNames = []
    """ first loop stores and sets everything to 0 """

    for shape in blendShapeNodeChannels:
        keepGoing = True
        if ignoreTargets != False:
            if shape in ignoreTargets:
                keepGoing = False
            else:
                keepGoing = True

        blendShapeBuffer = (blendShapeNode + '.' + shape)
        """ get the connection """
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))

        if keepGoing == True:
            print ('breaking....' + blendShapeBuffer)
            """break it """
            attributes.doBreakConnection(blendShapeBuffer)
            attributes.doSetAttr(blendShapeNode,shape,0)

    # Bake it
    bakedGeo = bakeBlendShapes(sourceObject, targetObjectBaked, blendShapeNode, baseNameToUse, stripPrefix, ignoreInbetweens, ignoreTargets)


    """ restore connections """
    for shape in blendShapeNodeChannels:
        keepGoing = True
        if ignoreTargets != False:
            if shape in ignoreTargets:
                keepGoing = False
            else:
                keepGoing = True

        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if keepGoing == True:
            print ('connecting....' + blendShapeBuffer)
            print blendShapeConnections[currentIndex]
            if blendShapeConnections[currentIndex] != False:
                attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)


    # Need to build a new blendshape node?
    if transferConnections == True:
        # Build it
        newBlendShapeNode = buildBlendShapeNode(targetObject, bakedGeo, baseNameToUse)

        newBlendShapeChannels = returnBlendShapeAttributes(newBlendShapeNode)

        for shape in newBlendShapeChannels:
            blendShapeBuffer = (newBlendShapeNode+'.'+shape)
            currentIndex = newBlendShapeChannels.index(shape)
            if blendShapeConnections[currentIndex] != False:
                attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """delete the wrap"""
    mc.delete(wrapBuffer[0])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    if baseNameToUse != False:
        attributes.storeInfo(meshGroup,'cgmName', baseNameToUse)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    mc.delete(targetObjectBaked)
    return returnList
Example #38
0
def bakeCombinedBlendShapeNodeToTargetObject(targetObject,sourceObject, blendShapeNode, baseName = False, directions=['left','right']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Function for baking a series of blendshapes from one object to another when you have a left/right variant

    ARGUMENTS:
    targetObject(string)
    sourceObject(string)
    blendShapeNode(string) the node to bake from
    baseName(bool/string) - if it's False, it uses the target Object name, else, it uses what is supplied
    directions[list] = (['left','right'])

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Prep
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ declare variables """
    returnList = []
    blendShapeNamesBaked = []
    blendShapeConnections = []
    currentConnections = []
    bakedGeo = []

    """ size """
    sizeBuffer = distance.returnBoundingBoxSize(targetObject)
    sizeX = sizeBuffer[0]
    sizeY = sizeBuffer[1]

    """ base name """
    if baseName == False:
        baseName = ''
    else:
        baseName = baseName + '_'

    """reference check """
    refPrefix = search.returnReferencePrefix(sourceObject)
    if refPrefix != False:
        referencePrefix = (search.returnReferencePrefix(sourceObject) + ':')
    else:
        referencePrefix = ''

    """ wrap deform object """
    wrapBuffer = wrapDeformObject(targetObject,sourceObject,True)
    targetObjectBaked = wrapBuffer[1]

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Meat of it
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    #setAttr ($wrapDeformer[0] + ".autoWeightThreshold") 1;
    """ cause maya is stupid and doesn't have a python equivalent"""
    mc.select(targetObjectBaked,r=True)
    mc.select(sourceObject,tgl=True)
    mel.eval('AddWrapInfluence')
    mc.select(cl=True)

    """
    may need to add this in later
    //reorders deformation order for proper baking of skinned mesh
    //reorderDeformers "tweak1" "face_skinCluster" $deformerGeo;
    """

    blendShapeNodeChannels = search.returnBlendShapeAttributes(blendShapeNode)
    blendShapeShortNames = []

    """ first loop stores and sets everything to 0 """
    for shape in blendShapeNodeChannels:
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        blendShapeConnections.append(attributes.returnDriverAttribute(blendShapeBuffer))
        """break it """
        attributes.doBreakConnection(blendShapeBuffer)
        attributes.doSetAttr(blendShapeNode,shape,0)

    """ Find pairs """
    blendshapePairs = lists.returnMatchedStrippedEndList(blendShapeNodeChannels,directions)

    """ first loop stores and sets everything to 0 """
    for pair in blendshapePairs:
        blendShapeBuffer = (blendShapeNode+'.'+pair[0])
        splitBuffer = pair[0].split('_')
        nameBuffer = splitBuffer[:-1]
        pairBaseName = '_'.join(nameBuffer)

        if '_' in list(pairBaseName):
            newSplitBuffer = pair[0].split('_')
            newNameBuffer = newSplitBuffer[1:]
            blendShapeShortNames.append('_'.join(newNameBuffer))
        else:
            blendShapeShortNames.append(pairBaseName)

    t=1
    pair = 0
    for i in range (len(blendshapePairs)):
        row = i//5
        if t>5:
            t=1
        """ start extracting """
        blendShapeNodeChannelsBuffer = blendshapePairs[pair]
        shape1 = blendShapeNodeChannelsBuffer[0]
        shape2 = blendShapeNodeChannelsBuffer[1]
        attributes.doSetAttr(blendShapeNode,shape1,1)
        attributes.doSetAttr(blendShapeNode,shape2,1)
        dupBuffer = mc.duplicate(targetObjectBaked)
        splitBuffer = blendShapeShortNames[pair].split('_')
        nameBuffer = splitBuffer[:-1]
        shortName = '_'.join(nameBuffer)

        dupBuffer = mc.rename (dupBuffer,(baseName+shortName))
        mc.xform(dupBuffer,r=True,t=[((sizeX*(t+1.2))*1.5),(sizeY*row*-1.5),0])
        bakedGeo.append(dupBuffer)

        attributes.doSetAttr(blendShapeNode,shape1,0)
        attributes.doSetAttr(blendShapeNode,shape2,0)
        pair +=1
        t+=1

    """ restore connections """
    for shape in blendShapeNodeChannels:
        currentIndex = blendShapeNodeChannels.index(shape)
        blendShapeBuffer = (blendShapeNode+'.'+shape)
        """ Restore the connection """
        if blendShapeConnections[currentIndex] != False:
            attributes.doConnectAttr(blendShapeConnections[currentIndex],blendShapeBuffer)

    """delete the wrap"""
    mc.delete(wrapBuffer[0])

    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    # Finish out
    #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """ group for geo """
    meshGroup = mc.group( em=True)
    attributes.storeInfo(meshGroup,'cgmName', baseName)
    attributes.storeInfo(meshGroup,'cgmTypeModifier', 'blendShapeGeo')
    meshGroup = NameFactory.doNameObject(meshGroup)

    for geo in bakedGeo:
        rigging.doParentReturnName(geo,meshGroup)

    returnList.append(meshGroup)
    returnList.append(bakedGeo)

    mc.delete(targetObjectBaked)
    return returnList
Example #39
0
def zeroTransformMeObject(obj,scaleZero=False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Makes sure an object is zeroed out, parents the zero group back to the original objects parent

    ARGUMENTS:
    obj(string)

    RETURNS:
    groupName(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    parent = mc.listRelatives(obj,parent=True,fullPath = True)

    group = groupMeObject(obj,True,True)
    group2 = ''
    attributes.storeInfo(group,'cgmTypeModifier','zero')
    
    
    objScale = []
    objScale.append(mc.getAttr(obj+'.sx'))
    objScale.append(mc.getAttr(obj+'.sy'))
    objScale.append(mc.getAttr(obj+'.sz'))
    
    #Check if we got zero translates
    zeroCheck = mc.xform (obj, q=True, os=True, rp=True)
    if zeroCheck:
        if scaleZero:
            mc.makeIdentity(obj,apply=True,t=0,r=0,s=1)              
        group2 = groupMeObject(obj,True,True)
        zeroCheck = mc.xform (obj, q=True, os=True, rp=True)
        
        zeroCheck = cgmMath.multiplyLists([objScale,zeroCheck])
        mc.xform (group2,t=(-zeroCheck[0],-zeroCheck[1],-zeroCheck[2]), os=True)
        attributes.storeInfo(group,'cgmTypeModifier','zeroParent')
        attributes.storeInfo(group2,'cgmTypeModifier','zero')
        group2 = NameFactoryOld.doNameObject(group2) 
    
        for attr in 'tx','ty','tz':
            attributes.doSetAttr(obj, attr, 0)
    
    #Check for zero rotates
    rotateCheck = mc.xform(obj, q=True, os=True, ro=True)
    if rotateCheck:
        if not group2:
            group2 = groupMeObject(obj,True,True)
            attributes.storeInfo(group,'cgmTypeModifier','zeroParent')
            attributes.storeInfo(group2,'cgmTypeModifier','zero')
            NameFactoryOld.doNameObject(group2) 
        
        mc.xform (group2,ro=(rotateCheck[0],rotateCheck[1],rotateCheck[2]), os=True)
        for attr in 'rx','ry','rz':
            attributes.doSetAttr(obj, attr, 0)        
    
    """
    objScale = []
    objScale.append(mc.getAttr(obj+'.sx'))
    objScale.append(mc.getAttr(obj+'.sy'))
    objScale.append(mc.getAttr(obj+'.sz'))
    grpScale = []
    grpScale.append(mc.getAttr(group+'.sx'))
    grpScale.append(mc.getAttr(group+'.sy'))
    grpScale.append(mc.getAttr(group+'.sz'))
    multScale = cgmMath.multiplyLists([objScale,grpScale])
    
    mc.scale(multScale[0], multScale[1], multScale[2],[group])
    for attr in 'sx','sy','sz':
        attributes.doSetAttr(obj,attr,1)
    """
    return NameFactoryOld.doNameObject(group)
Example #40
0
def randomizeCubette(namespace):
    import random
    
    settingsObject = ('%s:Cubey_masterAnim_settings'%namespace)
    
    #reset stuff
    for a in 'Tops','Hair','Bottom','Noses','Belts','ShortSleeves':
	attributes.doSetAttr(settingsObject,a, 0)
	
    attributes.doSetAttr(settingsObject,'RegTop', 1)
	
    #set it
    if not mc.objExists(settingsObject):
	print "'%s' doesn't exist!"%settingsObject
    attributes.doSetAttr(settingsObject,'Tops', random.randint(0,3))
    attributes.doSetAttr(settingsObject,'Hair', random.randint(0,5))
    attributes.doSetAttr(settingsObject,'Bottom', random.randint(0,3))
    attributes.doSetAttr(settingsObject,'Noses', random.randint(1,5))
    
    case = random.randint(0,10)
    if case in [5,2,6]:
	attributes.doSetAttr(settingsObject,'ShortSleeves', 1)
	
	
    #Nose and ears
    options = [.75,.8,.9,1,1]
    noseMult = options[random.randint(0,4)] 
    
    noseControl = ('%s:nose_jnt_anim'%namespace)
    attributes.doSetAttr(noseControl,'sx', noseMult)
    attributes.doSetAttr(noseControl,'sy', noseMult)
    attributes.doSetAttr(noseControl,'sz', noseMult)
    
    #eary = 0.513,1.02
    #earZ = 1, 1.857
    earOptions = [.8,.9,1,1,1,1,1.1,1.2,1.3,1.364]
    
    earMult = earOptions[random.randint(0,9)] 
    
    earLeftControl = ('%s:ear_l_jnt_anim'%namespace)
    earRightControl = ('%s:ear_r_jnt_anim'%namespace)
    
    
    attributes.doSetAttr(earLeftControl,'sx', earMult)
    attributes.doSetAttr(earLeftControl,'sy', earMult) 
    attributes.doSetAttr(earLeftControl,'sz', earMult) 
    
    attributes.doSetAttr(earRightControl,'sx', earMult)    
    attributes.doSetAttr(earRightControl,'sy', earMult)
    attributes.doSetAttr(earRightControl,'sz', earMult)    
    
    #Eyes
    #l eye = -0.089,0.132  eye_l_mover_jnt_anim
    earLeftControl = ('%s:eye_l_mover_jnt_anim'%namespace)
    earRightControl = ('%s:eye_r_mover_jnt_anim'%namespace)
    
    eyeOptions = [-0.089,-.06,-.04,-.02,0,0,0,.025,.04,.06,.13]
    eyeMult = eyeOptions[random.randint(0,10)] 
    
    attributes.doSetAttr(earLeftControl,'tx', eyeMult)
    attributes.doSetAttr(earRightControl,'tx', -eyeMult)