Пример #1
0
def dag_sort(objList=None):
    """    
    Dag sort children under their parent
    
    """
    _str_func = 'dag_sort'
    if not objList:
        objList = mc.ls(sl=1)
    else:
        objList = VALID.mNodeStringList(objList)
    log.info("|{0}| >> ObjList: {1} ".format(_str_func, objList))

    d_p = {}
    l_p = []
    l_world = []

    for o in objList:
        p = TRANS.parent_get(o)
        if not p:
            l_world.append(o)
        elif p not in l_p:
            l = TRANS.children_get(p) or []
            l.sort()
            l.reverse()
            for c in l:
                try:
                    mc.reorder(c, front=True)
                except Exception, err:
                    print err
Пример #2
0
def mirror_controlShape(source=None,
                        target=None,
                        colorDirection='right',
                        controlType='main'):
    _str_func = "mirror_controlShape"
    if target is None:
        _sel = mc.ls(sl=True)
        if len(_sel) == 2:
            return mirror_controlShape(_sel[0], _sel[1])

    if not source:
        raise ValueError, "|{0}|  >> Must have a source".format(_str_func)
    if not target:
        raise ValueError, "|{0}|  >> Must have a target".format(_str_func)
    _dup_curve = mc.duplicate(source)[0]
    for child in TRANS.children_get(_dup_curve, True):
        mc.delete(child)
    ATTR.set_standardFlags(_dup_curve, lock=False, keyable=True, visible=True)
    _grp = mc.group(em=True)
    _dup_curve = TRANS.parent_set(_dup_curve, _grp)
    ATTR.set(_grp, 'scaleX', -1)
    _dup_curve = TRANS.parent_set(_dup_curve, False)
    mc.makeIdentity(_dup_curve,
                    apply=True,
                    translate=True,
                    rotate=True,
                    scale=False)
    return
    shapeParent_in_place(target, _dup_curve, True, True)
    mc.delete(_grp)

    colorControl(target, colorDirection, controlType)
    mc.select(target)
    return target
Пример #3
0
def freezeOrientation(targetJoints):
    """
    Freeze joint orientations in place. 
    """
    _str_funcName = "metaFreezeJointOrientation"		
    #t1 = time.time()

    if type(targetJoints) not in [list,tuple]:targetJoints=[targetJoints]

    ml_targetJoints = cgmMeta.validateObjListArg(targetJoints,'cgmObject')

    #log.info("{0}>> meta'd: {1}".format(_str_funcName, "%0.3f seconds"%(time.time() - t1)))
    #t1 = time.time()				
    '''
    for i_jnt in ml_targetJoints:
        if i_jnt.getConstraintsTo():
        log.warning("freezeJointOrientation>> target joint has constraints. Can't change orientation. Culling from targets: '%s'"%i_jnt.getShortName())
        return False
        '''
    #buffer parents and children of 
    d_children = {}
    d_parent = {}
    mi_parent = cgmMeta.validateObjArg(ml_targetJoints[0].parent,noneValid=True)
    #log.info('validate')
    for i,i_jnt in enumerate(ml_targetJoints):
        _relatives = TRANS.children_get(i_jnt.mNode)
        log.debug("{0} relatives: {1}".format(i,_relatives))
        d_children[i_jnt] = cgmMeta.validateObjListArg( _relatives ,'cgmObject',True) or []
        d_parent[i_jnt] = cgmMeta.validateObjArg(i_jnt.parent,noneValid=True)
    for i_jnt in ml_targetJoints:
        for i,i_c in enumerate(d_children[i_jnt]):
        #log.debug(i_c.getShortName())
        #log.debug("freezeJointOrientation>> parented '%s' to world to orient parent"%i_c.mNode)
            i_c.parent = False
    if mi_parent:
        ml_targetJoints[0].parent = False

    #Orient
    t_loop = time.time()
    for i,i_jnt in enumerate(ml_targetJoints):
        """
        So....jointOrient is always in xyz rotate order
        dup,rotate order
        Unparent, add rotate & joint rotate, push value, zero rotate, parent back, done
        """    
        log.debug("parent...")
        if i != 0 and d_parent.get(i_jnt):
            i_jnt.parent = d_parent.get(i_jnt)#parent back first before duping

        #New method  ----
        log.debug("loc...")
    
        #mi_rootLoc = i_jnt.doLoc(fastMode = True)#Make some locs
        mi_zLoc = i_jnt.doLoc(fastMode = True)#Make some locs
        mi_yLoc = mi_zLoc.doDuplicate()

        log.debug("dup...")
        i_dup = i_jnt.doDuplicate(parentOnly = True)

        i_dup.parent = i_jnt.parent
        i_dup.rotate = 0,0,0
        i_dup.rotateOrder = 0
        i_dup.jointOrient = 0,0,0

        log.debug("group...")
        str_group = TRANS.group_me(i_jnt,False,True) #group for easy move
        
        mi_yLoc.parent = str_group
        mi_zLoc.parent = str_group

        mi_zLoc.tz = 1#Move
        mi_yLoc.ty = 1

        mc.makeIdentity(i_dup.mNode, apply = 1, jo = 1)#Freeze

        #Aim
        log.debug("constrain...")

        str_const = mc.aimConstraint(mi_zLoc.mNode,
                                     i_dup.mNode,
                                     maintainOffset = False,
                                     weight = 1,
                                     aimVector = [0,0,1],
                                     upVector = [0,1,0],
                                     worldUpVector = [0,1,0],
                                     worldUpObject = mi_yLoc.mNode,
                                     worldUpType = 'object' )[0]
        

        
        i_jnt.rotate = [0,0,0] #Move to joint
        i_jnt.jointOrient = i_dup.rotate
        
        #log.info('{0} delete'.format(i))

        log.debug("delete...")	    
        mc.delete([str_const,str_group])#Delete extra stuff str_group
        i_dup.delete()
        
    #reparent
    if mi_parent:
        try:ml_targetJoints[0].parent = mi_parent
        except Exception,error: raise StandardError,"Failed to parent back %s"%error
    for i,i_jnt in enumerate(ml_targetJoints):
        for ii,i_c in enumerate(d_children[i_jnt]):
            #log.info("{0} | {1}".format(i,ii))
            #log.info(i_c)
            log.debug("freezeJointOrientation>> parented '%s' back"%i_c.getShortName())
            i_c.parent = i_jnt.mNode 
            cgmMeta.cgmAttr(i_c,"inverseScale").doConnectIn("%s.scale"%i_jnt.mNode )
    #log.info('reparent')
    #log.info("{0}>> reparent: {1}".format(_str_funcName, "%0.3f seconds"%(time.time() - t1)))
    #t1 = time.time()				
    return True
Пример #4
0
def get_objNameDict(obj, ignore=[False]):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a generated dictionary of name info

    ARGUMENTS:
    obj(string) - object
    ignore(string) - default is 'none', only culls out cgmtags that are 
                     generated via returnCGMOrder() function

    RETURNS:
    namesDict(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    try:
        _str_funcName = "get_objNameDict"
        log.debug(">>> %s >>> " % (_str_funcName) + "=" * 75)

        if type(ignore) is not list: ignore = [ignore]

        namesDict = {}
        divider = returnCGMDivider()
        order = returnCGMOrder()
        nameBuilder = []
        #>>> Get our cgmVar_iables
        #userAttrs = attributes.returnUserAttributes(obj)
        #cgmAttrs = lists.returnMatchList(userAttrs,order)
        #>>> Tag ignoring
        if ignore:
            for i in ignore:
                if i in order:
                    order.remove(i)

        #>>> Geting our data
        for tag in order:
            tagInfo = SEARCH.get_tagInfo(obj, tag)
            if tagInfo is not False:
                namesDict[tag] = (tagInfo)

        if 'cgmIterator' in order:
            _iterator = ATTR.get(obj, 'cgmIterator')
            if _iterator is not False:
                log.debug("Iterator found")
                namesDict['cgmIterator'] = (_iterator)

        # remove tags up stream that we don't want if they don't exist on the actual object"""
        if not mc.objExists(obj + '.cgmTypeModifier'):
            if namesDict.get('cgmTypeModifier') != None:
                namesDict.pop('cgmTypeModifier')

        log.debug("%s >>> initial nameDict: %s " % (_str_funcName, namesDict))

        #>>> checks if the names exist as objects or it's a shape node
        ChildNameObj = False

        nameObj = False
        cgmNameAttrType = ATTR.get_type(obj, 'cgmName')
        log.debug("cgmNameAttrType: {0}".format(cgmNameAttrType))

        if cgmNameAttrType == 'message':
            #nameObj = SEARCH.get_nodeTagInfo(obj,'cgmName')
            nameObj = ATTR.get_message(
                obj, 'cgmName',
                simple=True)  #SEARCH.get_nodeTagInfo(obj,'cgmName')
            if nameObj:
                nameObj = nameObj[0]
                nameObjDict = get_objNameDict(nameObj)
                #pprint.pprint(nameObjDict)
                for k in 'cgmDirection', 'cgmPosition':
                    #if nameObjDict.get(k) and namesDict.get(k):
                    try:
                        namesDict.pop(k)
                    except:
                        pass
                log.debug("nameObj: {0}".format(nameObj))
                namesDict['cgmName'] = names.getBaseName(nameObj)
                return namesDict

        typeTag = SEARCH.get_nodeTagInfo(obj, 'cgmType')
        isType = SEARCH.VALID.get_mayaType(obj)
        isShape = SEARCH.VALID.is_shape(obj)
        """first see if it's a group """
        if isType == 'group' and typeTag == False:
            childrenObjects = TRANS.children_get(obj, False)
            log.debug("%s >>> group and no typeTag..." % (_str_funcName))
            """ if it's a transform group """
            groupNamesDict = {}
            if not nameObj:
                groupNamesDict['cgmName'] = childrenObjects[0]
            else:
                groupNamesDict['cgmName'] = nameObj
            groupNamesDict['cgmType'] = CORESHARE.d_cgmTypes.get('transform')
            if namesDict.get('cgmTypeModifier') != None:
                groupNamesDict['cgmTypeModifier'] = namesDict.get(
                    'cgmTypeModifier')
            return groupNamesDict
            """ see if there's a name tag"""
        elif isType in ['joint']:
            return namesDict
        elif isShape:
            #If we have a name object or shape
            log.debug("%s >>> nameObj not None or isType is 'shape'..." %
                      (_str_funcName))

            if isShape:
                #log.debug("%s >>> nameObj exists: '%s'..."%(_str_funcName,nameObj))
                #Basic child object with cgmName tag
                childNamesDict = {}
                childNamesDict['cgmName'] = namesDict.get('cgmName')
                childNamesDict['cgmType'] = namesDict.get('cgmType')
                if namesDict.get('cgmTypeModifier') != None:
                    childNamesDict['cgmTypeModifier'] = namesDict.get(
                        'cgmTypeModifier')
                if namesDict.get('cgmIterator') != None:
                    childNamesDict['cgmIterator'] = namesDict.get(
                        'cgmIterator')

                return childNamesDict
            elif isShape or 'Constraint' in isType:
                """if so, it's a child name object"""
                log.debug("%s >>> child name object..." % (_str_funcName))
                childNamesDict = {}
                childNamesDict['cgmName'] = TRANS.parent_get(obj, False)
                childNamesDict['cgmType'] = namesDict.get('cgmType')
                return childNamesDict
            else:
                log.debug("%s >>> No special case found. %s" %
                          (_str_funcName, namesDict))
                return namesDict
        else:
            return namesDict
    except Exception, err:
        raise cgmGEN.cgmExceptCB(Exception, err, msg=vars())
Пример #5
0
def create_proxyGeo(proxyShape='cube',
                    size=[1, 1, 1],
                    direction='z+',
                    ch=True):
    try:
        #cube:sphere:cylinder:cone:torus
        _str_func = 'create_proxyGeo'

        _proxyShape = _d_proxyCreate.get(proxyShape, proxyShape)
        _call = getattr(mc, _proxyShape, None)
        if not _call:
            raise ValueError, "Failed to find maya.cmds call {0}".format(
                _proxyShape)
        #if proxyShape not in _d_create.keys():
        #raise ValueError,"Unknown shape: {0}".format(proxyShape)

        _kws = {'ch': ch}

        if proxyShape in ['cube']:
            _kws['width'] = size[0]
            _kws['ch'] = False
        if proxyShape in ['cylinder', 'sphere', 'cone', 'cylinder', 'torus']:
            _kws['radius'] = max(size) / 2.0
            _kws['axis'] = VALID.simpleAxis(direction).p_vector

        _res = _call(**_kws)

        if size is not None:
            if VALID.isListArg(size):
                TRANS.scale_to_boundingBox(_res[0], size)
            else:
                if absoluteSize:
                    _f_current = DIST.get_bb_size(_res[0], True, True)
                    multiplier = size / _f_current
                    mc.scale(multiplier,
                             multiplier,
                             multiplier,
                             _res[0],
                             relative=True)

                else:
                    mc.scale(size, size, size, _res[0], os=True)
            #mc.makeIdentity(_res[0], apply=True,s=1)
        """
        if proxyShape == 'cube':
            _d_directionXRotates = {'x+':[0,0,0],'x-':[0,180,0],'y+':[0,0,90],'y-':[0,0,-90],'z+':[0,-90,0],'z-':[0,90,0]}
            _r_factor = _d_directionXRotates.get(direction)
            mc.rotate (_r_factor[0], _r_factor[1], _r_factor[2], _res[0], ws=True)"""
        #mc.makeIdentity(_res[0], apply=True,r =1, n= 1)

        if proxyShape == 'cube':
            _children = TRANS.children_get(_res[0])
            for i, c in enumerate(_children):
                _children[i] = TRANS.parent_set(c, False)
            combineShapes(_children + [_res[0]],
                          keepSource=False,
                          replaceShapes=False)

        return _res
    except Exception, err:
        cgmGEN.cgmExceptCB(Exception, err, msg=vars())
Пример #6
0
def shapeParent_in_place(obj,
                         shapeSource,
                         keepSource=True,
                         replaceShapes=False,
                         snapFirst=False):
    """
    Shape parent a curve in place to a obj transform

    :parameters:
        obj(str): Object to modify
        shapeSource(str): Curve to shape parent
        keepSource(bool): Keep the curve shapeParented as well
        replaceShapes(bool): Whether to remove the obj's original shapes or not
        snapFirst(bool): whether to snap source to obj before transfer

    :returns
        success(bool)
    """
    _str_func = 'shapeParent_in_place'

    l_shapes = VALID.listArg(shapeSource)
    obj = VALID.mNodeString(obj)
    log.debug(
        "|{0}|  >> obj: {1} | shapeSource: {2} | keepSource: {3} | replaceShapes: {4}"
        .format(_str_func, obj, shapeSource, keepSource, replaceShapes))

    if replaceShapes:
        _l_objShapes = mc.listRelatives(obj, s=True, fullPath=True)
        if _l_objShapes:
            log.debug("|{0}|  >> Removing obj shapes...| {1}".format(
                _str_func, _l_objShapes))
            mc.delete(_l_objShapes)

    mc.select(cl=True)
    #mc.refresh()
    for c in l_shapes:
        try:
            _shapeCheck = SEARCH.is_shape(c)
            if not _shapeCheck and not mc.listRelatives(
                    c, f=True, shapes=True, fullPath=True):
                raise ValueError, "Has no shapes"
            if coreNames.get_long(obj) == coreNames.get_long(c):
                raise ValueError, "Cannot parentShape self"

            if VALID.get_mayaType(c) == 'nurbsCurve':
                mc.ls(['%s.ep[*]' % (c)], flatten=True)
                #This is for a really weird bug in 2016 where offset curve shapes don't work right unless they're components are queried.

            if _shapeCheck:
                _dup_curve = duplicate_shape(c)[0]
                log.debug("|{0}|  >> shape duplicate".format(_str_func))
                if snapFirst:
                    SNAP.go(_dup_curve, obj)
            else:
                log.debug("|{0}|  >> regular duplicate".format(_str_func))
                _dup_curve = mc.duplicate(c)[0]
                for child in TRANS.children_get(_dup_curve, True):
                    mc.delete(child)
                if snapFirst:
                    SNAP.go(_dup_curve, obj)

            _l_parents = SEARCH.get_all_parents(obj)
            ATTR.set_standardFlags(_dup_curve,
                                   lock=False,
                                   visible=True,
                                   keyable=True)
            _dup_curve = parent_set(_dup_curve, False)

            copy_pivot(_dup_curve, obj)
            #piv_pos = mc.xform(obj, q=True, ws=True, rp = True)
            #mc.xform(_dup_curve,ws=True, rp = piv_pos)

            pos = mc.xform(obj, q=True, os=True, rp=True)

            curveScale = mc.xform(_dup_curve, q=True, s=True, r=True)
            objScale = mc.xform(obj, q=True, s=True, r=True)

            #account for freezing
            #mc.makeIdentity(_dup_curve,apply=True,translate =True, rotate = True, scale=False)

            # make our zero out group
            #group = rigging.groupMeObject(obj,False)
            group = create_at(obj, 'null')

            _dup_curve = mc.parent(_dup_curve, group)[0]

            # zero out the group
            mc.xform(group, ws=True, t=pos)
            #mc.xform(group,roo = 'xyz', p=True)
            mc.xform(group, ra=[0, 0, 0], p=False)
            mc.xform(group, ro=[0, 0, 0], p=False)

            mc.makeIdentity(_dup_curve,
                            apply=True,
                            translate=True,
                            rotate=True,
                            scale=False)

            #main scale fix
            baseMultiplier = [0, 0, 0]
            baseMultiplier[0] = (curveScale[0] / objScale[0])
            baseMultiplier[1] = (curveScale[1] / objScale[1])
            baseMultiplier[2] = (curveScale[2] / objScale[2])
            mc.setAttr(_dup_curve + '.sx', baseMultiplier[0])
            mc.setAttr(_dup_curve + '.sy', baseMultiplier[1])
            mc.setAttr(_dup_curve + '.sz', baseMultiplier[2])

            #parent scale fix
            if _l_parents:
                _l_parents.reverse()
                multiplier = [
                    baseMultiplier[0], baseMultiplier[1], baseMultiplier[2]
                ]
                for p in _l_parents:
                    scaleBuffer = mc.xform(p, q=True, s=True, r=True)
                    multiplier[0] = ((multiplier[0] / scaleBuffer[0]))
                    multiplier[1] = ((multiplier[1] / scaleBuffer[1]))
                    multiplier[2] = ((multiplier[2] / scaleBuffer[2]))
                mc.setAttr(_dup_curve + '.sx', multiplier[0])
                mc.setAttr(_dup_curve + '.sy', multiplier[1])
                mc.setAttr(_dup_curve + '.sz', multiplier[2])

            _dup_curve = parent_set(_dup_curve, False)

            mc.delete(group)

            #freeze for parent shaping
            mc.makeIdentity(_dup_curve,
                            apply=True,
                            translate=True,
                            rotate=True,
                            scale=True)

            shape = mc.listRelatives(_dup_curve,
                                     f=True,
                                     shapes=True,
                                     fullPath=True)
            mc.parent(shape, obj, add=True, shape=True)
            mc.delete(_dup_curve)
            if not keepSource:
                mc.delete(c)
        except Exception, err:
            cgmGEN.cgmExceptCB(Exception, err, msg=vars())
TRANS.position_set(_root,_pos)
TRANS.rotate_set(_root,_rot)
TRANS.eulerAngles_set(_root,_rot)
TRANS.orient_set(_root,_rot)
TRANS.orientObject_set(_root,_rot)
TRANS.rotateAxis_set(_root,_rot)
TRANS.scaleLocal_set(_root,_scale)



#...heirarchy
_rootRoot = 'group2'
TRANS.parent_get(_root)
TRANS.parent_set(_root,TRANS.parent_get(_root))
TRANS.parents_get(_root)
TRANS.children_get(_rootRoot)
TRANS.descendents_get(_rootRoot)
TRANS.is_childTo(_root,TRANS.parents_get(_root)[0])
TRANS.is_childTo(_root,None)
TRANS.is_parentTo(_rootRoot, _root)
TRANS.is_parentTo(_root, _rootRoot)

cgmMeta.cgmObject(_rootRoot).getListPathTo(_root)
TRANS.get_listPathTo(_rootRoot, _root,False)

cgmMeta.cgmObject(_root).getListPathTo(_rootRoot)
TRANS.get_listPathTo(_root, _rootRoot,False)

TRANS.is_parentTo(_root,TRANS.parents_get(_root)[0])