示例#1
0
def returnObjectSize(obj,debugReport = False):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Semi intelligent object sizer. Currently works for verts, edges,
    faces, poly meshes, nurbs surfaces, nurbs curve

    ARGUMENTS:
    obj(string) - mesh or mesh group

    RETURNS:
    size(float)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objType = search.returnObjectType(obj)

    #>>> Poly
    if objType == 'mesh':
        size =  mc.polyEvaluate(obj,worldArea = True)

        if debugReport: print ('%s%f' %('mesh area is ',size))
	return size

    elif objType == 'polyVertex':
        meshArea = mc.polyEvaluate(obj,worldArea = True)
        splitBuffer = obj.split('.')
        vertices = mc.ls ([splitBuffer[0]+'.vtx[*]'],flatten=True)
        size = meshArea/len(vertices)

        if debugReport: print ('%s%f' %('Average mesh area per vert is  ',size))
        return size

    elif objType == 'polyEdge':
        size = returnEdgeLength(obj)

        if debugReport: print ('%s%f' %('The Edge length is ',size))
        return size

    elif objType == 'polyFace':
        size =  returnFaceArea(obj)

        if debugReport: print ('%s%f' %('face area is ',size))
        return size

    #>>> Nurbs
    elif objType == 'nurbsSurface':
        boundingBoxSize = returnBoundingBoxSize(obj)
        size = cgmMath.multiplyList(boundingBoxSize)

        if debugReport: print ('%s%f' %('Bounding box volume is ',size))
        return size

    elif objType == 'nurbsCurve':
        size =  returnCurveLength(obj)

        if debugReport: print ('%s%f' %('Curve length is ',size))
        return size
    else:
        if debugReport: print ("Don't know how to handle that one")
        return False
示例#2
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']

        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:
            mc.rotate(objRot[0], objRot[1], objRot[2], locatorName, ws=True)

        return True
    else:
        guiFactory.warning('Not a locator.')
        return False
    def skinIt():
        #Skin it
        geoGroupObjects = search.returnAllChildrenObjects('geo_grp', True)
        #Get our group objects

        jointChains = getSkinJointChains()

        for i, g in enumerate([
                u'torso_geoGrp', u'armLeft_geoGrp', u'armRight_geoGrp',
                u'legLeft_geoGrp', u'legRight_geoGrp'
        ]):
            geoGroupObjects = search.returnAllChildrenObjects(g, True)

            toSkin = []
            for o in geoGroupObjects:
                if search.returnObjectType(o) in ['mesh', 'nurbsSurface']:
                    toSkin.append(o)

            if toSkin:
                for o in toSkin:
                    toBind = jointChains[i] + [o]
                    mc.skinCluster(toBind,
                                   tsb=True,
                                   normalizeWeights=True,
                                   mi=4,
                                   dr=10,
                                   polySmoothness=3)
            else:
                print("'%s' has nothing to skin!" % g)
示例#4
0
def returnConstraintTargetWeights(constraint):
    objType = search.returnObjectType(constraint)
    targetsDict = {}
    targetList = []
    constaintCmdDict = {
        'parentConstraint': mc.parentConstraint,
        'orientConstraint': mc.orientConstraint,
        'pointConstraint': mc.pointConstraint,
        'aimConstraint': mc.aimConstraint
    }

    if objType in constaintCmdDict.keys():
        cmd = constaintCmdDict.get(objType)
        aliasList = mc.parentConstraint(constraint,
                                        q=True,
                                        weightAliasList=True)
        if aliasList:
            for o in aliasList:
                targetsDict[o] = mc.getAttr(constraint + '.' + o)

    if not targetsDict:
        guiFactory.warning('%s has no targets' % constraint)
        return False
    else:
        return targetsDict
    def getMessage(self, *a, **kw):
        """ 
        Get and store attribute value as if they were messages. Used for bufferFactory to use a connected
        attribute as a poor man's attribute message function
        
        Keyword arguments:
        *a, **kw
        """
        try:
            if self.form == 'message':
                self.value = attributes.returnMessageObject(
                    self.obj.nameShort, self.attr)
                if search.returnObjectType(self.value) == 'reference':
                    if attributes.repairMessageToReferencedTarget(
                            self.obj.nameLong, self.attr, *a, **kw):
                        self.value = attributes.returnMessageObject(
                            self.obj.nameShort, self.attr)
            else:
                self.value = attributes.returnDriverAttribute(
                    "%s.%s" % (self.obj.nameShort, self.attr))

            guiFactory.report("'%s.%s' >Message> '%s'" %
                              (self.obj.nameShort, self.attr, self.value))
            return self.value

        except:
            guiFactory.warning("'%s.%s' failed to get" %
                               (self.obj.nameShort, self.attr))
示例#6
0
def createCurveLengthNode(curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Creates a curve lenght measuring node

    ARGUMENTS:
    polyFace(string) - face of a poly

    RETURNS:
    length(float)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objType = search.returnObjectType(curve)
    shapes = []

    if objType == 'shape':
        shapes.append(curve)
    else:
        shapes = mc.listRelatives(curve,shapes=True)

    #first see if there's a length node
    isConnected = attributes.returnDrivenAttribute(shapes[0]+'.worldSpace[0]')
    if isConnected !=False:
        return (attributes.returnDrivenObject(shapes[0]+'.worldSpace'))
    else:
        infoNode = nodes.createNamedNode(curve,'curveInfo')
        attributes.doConnectAttr((shapes[0]+'.worldSpace'),(infoNode+'.inputCurve'))
        return infoNode
示例#7
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']

		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:
			mc.rotate (objRot[0], objRot[1], objRot[2], locatorName, ws=True)

		return True
	else:
		guiFactory.warning('Not a locator.')
		return False
示例#8
0
def objStringList(l_args=None, mayaType=None, noneValid=False, isTransform=False, calledFrom = None, **kwargs):
    """
    Return each item in l_args if that item is an existing, uniquely named Maya object, 
    meeting the optional requirements of mayaType and isTransform, otherwise raise an
    exception if noneValid is False

    :parameters:

    :returns:
        list

    """
    log.debug("validateArgs.objString arg={0}".format(l_args))

    _str_funcRoot = 'objStringList'
    if calledFrom: _str_funcName = "{0}.{1}({2})".format(calledFrom,_str_funcRoot,l_args)    
    else:_str_funcName = "{0}({1})".format(_str_funcRoot,l_args) 

    result = []

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

    for arg in l_args:
        tmp = objString(arg, mayaType, noneValid, isTransform)
        if tmp != False:
            result.append(tmp)
        else:
            str_argMayaType = search.returnObjectType(arg)
            log.warning(
                "Arg {0} from func '{1}' ".format(arg, _str_funcName) +\
                " is Maya type '{2}', not 'str'".format(str_argMayaType)
            )

    return result
示例#9
0
def MeshDict(mesh = None, pointCounts = True, calledFrom = None):
    """
    Validates a mesh and returns a dict of data.
    If a shape is the calling object, it will be the shape returned, otherwise, the first shape in the chain will be

    :param mesh: mesh to evaluate
    
    :returns:
    dict -- mesh,meshType,shapes,shape,pointCount,pointCountPerShape
    

    """        
    _str_funcName = 'MeshDict'
    if calledFrom: _str_funcName = "{0} calling {1}".format(calledFrom,_str_funcName) 
    
    _mesh = None 
    
    if mesh is None:
        _bfr = mc.ls(sl=True)
        if not _bfr:raise ValueError,"No selection found and no source arg"
        mesh = _bfr[0]
        log.info("{0}>> No source specified, found: '{1}'".format(_str_funcName,mesh))
           
    _type = search.returnObjectType(mesh)
    _shape = None
    _callObjType = None
    
    if _type in ['mesh']:
        _mesh = mesh
        _callObjType = 'meshCall'
    elif _type in ['shape']:
        _shape = mesh
        _callObjType = 'shapeCall'
        _mesh = getTransform(mesh)
    else:
        raise ValueError,"{0} error. Not a usable mesh type : obj: '{1}' | type: {2}".format(_str_funcName, mesh, _type)

    _shapes = mc.listRelatives(_mesh,shapes=True,fullPath=False)
    
    if _shape is None:
        _shape = _shapes[0]
        
    _return = {'mesh':_mesh,
               'meshType':_type,
               'shapes':_shapes,
               'shape':_shape,
               'callType':_callObjType,
               }
    
    if pointCounts:
        if _callObjType == 'shapeCall':
            _return['pointCount'] = mc.polyEvaluate(_shape, vertex=True)
        else:
            _l_counts = []
            for s in _return['shapes']:
                _l_counts.append( mc.polyEvaluate(s, vertex=True))
            _return['pointCountPerShape'] = _l_counts
            _return['pointCount'] = sum(_l_counts)

    return _return   
示例#10
0
def locMeCVOnCurve(curveCV):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's closest position on a curve

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	if search.returnObjectType(curveCV) == 'curveCV':
		cvPos = mc.pointPosition (curveCV,w=True)
		wantedName = (curveCV + '_loc')
		actualName = mc.spaceLocator (n= wantedName)
		mc.move (cvPos[0],cvPos[1],cvPos[2], [actualName[0]])
		splitBuffer = curveCV.split('.')
		uPos = distance.returnClosestUPosition (actualName[0],splitBuffer[0])
		mc.move (uPos[0],uPos[1],uPos[2], [actualName[0]])
		return actualName[0]
	else:
		guiFactory.warning  ('Not a curveCV')
		return False
示例#11
0
def returnConstraintTargets(constraint):
    objType = search.returnObjectType(constraint)
    targetsDict = {}
    targetList = []
    constaintCmdDict = {
        'parentConstraint': mc.parentConstraint,
        'orientConstraint': mc.orientConstraint,
        'pointConstraint': mc.pointConstraint,
        'scaleConstraint': mc.scaleConstraint,
        'aimConstraint': mc.aimConstraint
    }

    if objType in constaintCmdDict.keys():
        cmd = constaintCmdDict.get(objType)
        #>>> Get targets
        targetList = cmd(constraint, q=True, targetList=True)
    else:
        log.warning(
            "Unknown constraint type for returnConstraintTargets: '%s'" %
            objType)
        return False

    if not targetList:
        log.warning('%s has no targets' % constraint)
        return False
    else:
        return targetList
示例#12
0
def createCurveLengthNode(curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Creates a curve lenght measuring node

    ARGUMENTS:
    polyFace(string) - face of a poly

    RETURNS:
    length(float)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objType = search.returnObjectType(curve)
    shapes = []

    if objType == 'shape':
        shapes.append(curve)
    else:
        shapes = mc.listRelatives(curve,shapes=True)

    #first see if there's a length node
    isConnected = attributes.returnDrivenAttribute(shapes[0]+'.worldSpace[0]')
    if isConnected !=False:
        return (attributes.returnDrivenObject(shapes[0]+'.worldSpace'))
    else:
        infoNode = nodes.createNamedNode(curve,'curveInfo')
        attributes.doConnectAttr((shapes[0]+'.worldSpace'),(infoNode+'.inputCurve'))
        return infoNode
示例#13
0
def locMeCVOnCurve(curveCV):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's closest position on a curve

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    if search.returnObjectType(curveCV) == 'curveCV':
        cvPos = mc.pointPosition(curveCV, w=True)
        wantedName = (curveCV + '_loc')
        actualName = mc.spaceLocator(n=wantedName)
        mc.move(cvPos[0], cvPos[1], cvPos[2], [actualName[0]])
        splitBuffer = curveCV.split('.')
        uPos = distance.returnClosestUPosition(actualName[0], splitBuffer[0])
        mc.move(uPos[0], uPos[1], uPos[2], [actualName[0]])
        return actualName[0]
    else:
        guiFactory.warning('Not a curveCV')
        return False
示例#14
0
    def addGeo(self):
        """ 
        Add geo to a puppet
        """
        assert self.msgGeoGroup.get() is not False, "No geo group found!"

        selection = mc.ls(sl=True, flatten=True, long=True) or []

        if not selection:
            guiFactory.warning("No selection found to add to '%s'" %
                               self.nameBase)

        returnList = []
        for o in selection:
            if search.returnObjectType(o) in geoTypes:
                if self.msgGeoGroup.get() not in search.returnAllParents(
                        o, True):
                    o = rigging.doParentReturnName(o, self.msgGeoGroup.get())
                    self.geo.append(o)
                else:
                    guiFactory.warning("'%s' already a part of '%s'" %
                                       (o, self.nameBase))
            else:
                guiFactory.warning(
                    "'%s' doesn't seem to be geo. Not added to '%s'" %
                    (o, self.nameBase))
示例#15
0
def returnUniqueGeneratedName(obj,sceneUnique = False,fastIterate = True, ignore='none',**kws):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a generated name with iteration for heirarchy objects with the same tag info

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

    RETURNS:
    name(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    if type(ignore) is not list:ignore = [ignore]
    log.debug("sceneUnique: %s"%sceneUnique)
    log.debug("fastIterate: %s"%fastIterate)
    log.debug("ignore: %s"%ignore)
    
    #>>> Dictionary driven order first build
    def doBuildName():
        nameBuilder=[]
        for item in order:
            buffer = updatedNamesDict.get(item)
            # Check for short name
            buffer = search.returnTagInfoShortName(buffer,item)
            if buffer and buffer != 'ignore':
                nameBuilder.append(buffer)

        return divider.join(nameBuilder)
    
    rawNamesDict = returnObjectGeneratedNameDict(obj,ignore)
    divider = returnCGMDivider()
    updatedNamesDict = returnObjectGeneratedNameDict(obj,ignore)
    order = returnCGMOrder()
    
    if 'cgmName' not in updatedNamesDict.keys() and search.returnObjectType(obj) !='group':
        buffer = mc.ls(obj,shortNames = True)
        attributes.storeInfo(obj,'cgmName',buffer[0],True)
        updatedNamesDict = returnObjectGeneratedNameDict(obj,ignore)

    coreName = doBuildName()
    
    """ add the iterator to the name dictionary if our object exists"""
    nameFactory = NameFactory(obj)
    
    if sceneUnique:
        if fastIterate:
            iterator = returnFastIterateNumber(obj)            
        else:
            iterator = returnIterateNumber(obj)
        if iterator > 0:
            updatedNamesDict['cgmIterator'] = str(iterator)
            coreName = doBuildName()
            
    log.debug(returnCombinedNameFromDict(updatedNamesDict))
    return returnCombinedNameFromDict(updatedNamesDict)
示例#16
0
def getGeo(self):
    """
    Returns geo in a puppets geo folder, ALL geo to be used by a puppet should be in there
    """
    geo = []
    for o in self.masterNull.geoGroup.getAllChildren():
        if search.returnObjectType(o) in geoTypes:
            buff = mc.ls(o, long=True)
            geo.append(buff[0])
    return geo
def getGeo(self):
    """
    Returns geo in a puppets geo folder, ALL geo to be used by a puppet should be in there
    """    
    geo = []
    for o in self.masterNull.geoGroup.getAllChildren():
        if search.returnObjectType(o) in geoTypes:
            buff = mc.ls(o,long=True)
            geo.append(buff[0])
    return geo
示例#18
0
def doUpdateLocator(locatorName,forceBBCenter = False):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Update a locator created with our nifty tool.

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	if search.returnObjectType(locatorName) == 'locator':
		locatorMode = search.returnTagInfo(locatorName,'cgmLocMode')
		if locatorMode == 'fromObject':
			obj = search.returnTagInfo(locatorName,'cgmName')
			if mc.objExists(obj) == True:
				"""get stuff to transfer"""
				locInfo = returnInfoForLoc(obj,forceBBCenter)
				doPositionLocator(locatorName,locInfo)
				return True
			else:
				guiFactory.warning ("The stored object doesn't exist")
				return False
			
		else:
			sourceObjects = search.returnTagInfo(locatorName,'cgmSource')
			targetObjectsBuffer = sourceObjects.split(',')
			targetObjects = []
			for obj in targetObjectsBuffer:
				if mc.objExists(obj):
					targetObjects.append(obj)
				else:
					guiFactory.warning  ('%s%s' % (obj, " not found, using any that are... "))
			if locatorMode == 'selectCenter':
				locBuffer = locMeCenter(targetObjects,forceBBCenter)
				position.moveParentSnap(locatorName,locBuffer)
				mc.delete(locBuffer)

			if locatorMode == 'closestPoint':
				locBuffer = locClosest(targetObjects[:-1],targetObjects[-1])
				position.moveParentSnap(locatorName,locBuffer)
				mc.delete(locBuffer)
				


	else:
		return False

	return locatorName
示例#19
0
def doUpdateLocator(locatorName, forceBBCenter=False):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Update a locator created with our nifty tool.

	ARGUMENTS:
	obj(string)

	RETURNS:
	name(string)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    if search.returnObjectType(locatorName) == 'locator':
        locatorMode = search.returnTagInfo(locatorName, 'cgmLocMode')
        if locatorMode == 'fromObject':
            obj = search.returnTagInfo(locatorName, 'cgmName')
            if mc.objExists(obj) == True:
                """get stuff to transfer"""
                locInfo = returnInfoForLoc(obj, forceBBCenter)
                doPositionLocator(locatorName, locInfo)
                return True
            else:
                guiFactory.warning("The stored object doesn't exist")
                return False

        else:
            sourceObjects = search.returnTagInfo(locatorName, 'cgmSource')
            targetObjectsBuffer = sourceObjects.split(',')
            targetObjects = []
            for obj in targetObjectsBuffer:
                if mc.objExists(obj):
                    targetObjects.append(obj)
                else:
                    guiFactory.warning(
                        '%s%s' % (obj, " not found, using any that are... "))
            if locatorMode == 'selectCenter':
                locBuffer = locMeCenter(targetObjects, forceBBCenter)
                position.moveParentSnap(locatorName, locBuffer)
                mc.delete(locBuffer)

            if locatorMode == 'closestPoint':
                locBuffer = locClosest(targetObjects[:-1], targetObjects[-1])
                position.moveParentSnap(locatorName, locBuffer)
                mc.delete(locBuffer)

    else:
        return False

    return locatorName
示例#20
0
    def registerTarget(self, target):
        """
	if issubclass(type(target),r9Meta.MetaClass):
	    i_obj = target
	else:
	    i_obj = cgmMeta.cgmObject(target)
	    """
        if not mc.objExists(target):
            log.warning("One of the targets doesn't exist: '%s'" % target)
            return False

        if target not in self.l_targets: self.l_targets.append(target)
        self.d_targetTypes[target] = search.returnObjectType(target)
        return True
示例#21
0
    def registerTarget(self,target):
	"""
	if issubclass(type(target),r9Meta.MetaClass):
	    i_obj = target
	else:
	    i_obj = cgmMeta.cgmObject(target)
	    """
	if not mc.objExists(target):
	    log.warning("One of the targets doesn't exist: '%s'"%target)
	    return False
	
	if target not in self.l_targets:self.l_targets.append(target)
	self.d_targetTypes[target] = search.returnObjectType(target)
	return True
示例#22
0
    def validateMeshArg(self, mesh=None):
        '''
        Validates a mesh and returns a dict of data
        
        :param mesh: mesh to evaluate
        
        '''
        _mesh = None
        _skin = None
        if mesh is None:
            #if self.d_kws.get('sourceMesh'):
            #log.info("Using stored sourceMesh data")
            #sourceMesh = self.d_kws.get('sourceMesh')
            #else:
            log.info("No source specified, checking if selection found")
            _bfr = mc.ls(sl=True)
            if not _bfr:
                raise ValueError, "No selection found and no source arg"
            mesh = _bfr[0]

        _type = search.returnObjectType(mesh)

        if _type in ['mesh', 'nurbsCurve', 'nurbsSurface']:
            if _type in ['nurbsCurve', 'nurbsSurface']:
                raise NotImplementedError, "Haven't implemented nurbsCurve or nurbsSurface yet"
            log.info("Skinnable object '{0}', checking skin".format(mesh))
            _mesh = mesh
            _skin = skinning.querySkinCluster(_mesh) or False
            if _skin:
                log.info("Found skin '{0}' on '{1}'".format(_skin, _mesh))
        elif _type in ['skinCluster']:
            log.info("skinCluster '{0}' passed...".format(mesh))
            _skin = mesh
            _mesh = attributes.doGetAttr(_skin, 'outputGeometry')[0]
            log.info("Found: {0}".format(_mesh))
        else:
            raise ValueError, "Not a usable mesh type : {0}".format(_type)

        _shape = mc.listRelatives(_mesh, shapes=True, fullPath=False)[0]
        _return = {
            'mesh': _mesh,
            'meshType': _type,
            'shape': _shape,
            'skin': _skin,
            'component': data._geoToComponent.get(_type, False),
            'pointCount': mc.polyEvaluate(_shape, vertex=True)
        }
        return _return
示例#23
0
def returnClosestUPosition (targetObject,curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass target object and curve into it and return the closest U position

    ARGUMENTS:
    targetObject(string)
    surface(string)

    RETURNS:
    position(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ pass target object and surface into it and return the closest UV coordinates"""
    position = []
    if search.returnObjectType(curve) == 'shape':
        shapes = []
        shapes.append(curve)
    else:
        shapes = mc.listRelatives (curve, shapes=True)
    """ to account for target objects in heirarchies """
    tmpObj = rigging.locMeObjectStandAlone(targetObject)
    positions = []
    for shape in shapes:
        tmpNode = mc.createNode ('nearestPointOnCurve')
        position = []
        distances = []
        mc.connectAttr ((tmpObj+'.translate'),(tmpNode+'.inPosition'))
        mc.connectAttr ((shape+'.worldSpace'),(tmpNode+'.inputCurve'))
        position.append (mc.getAttr (tmpNode+'.positionX'))
        position.append (mc.getAttr (tmpNode+'.positionY'))
        position.append (mc.getAttr (tmpNode+'.positionZ'))
        positions.append(position)
        mc.delete (tmpNode)

    distances = []
    """ measure distances """
    locPos = returnWorldSpacePosition (tmpObj)
    mc.delete (tmpObj)
    for position in positions:
        distances.append(returnDistanceBetweenPoints(locPos,position))

    """ find the closest to our object """
    closestPosition = min(distances)
    matchIndex = distances.index(closestPosition)

    return positions[matchIndex]
示例#24
0
def returnClosestUPosition (targetObject,curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass target object and curve into it and return the closest U position

    ARGUMENTS:
    targetObject(string)
    surface(string)

    RETURNS:
    position(list)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    """ pass target object and surface into it and return the closest UV coordinates"""
    position = []
    if search.returnObjectType(curve) == 'shape':
        shapes = []
        shapes.append(curve)
    else:
        shapes = mc.listRelatives (curve, shapes=True)
    """ to account for target objects in heirarchies """
    tmpObj = rigging.locMeObjectStandAlone(targetObject)
    positions = []
    for shape in shapes:
        tmpNode = mc.createNode ('nearestPointOnCurve')
        position = []
        distances = []
        mc.connectAttr ((tmpObj+'.translate'),(tmpNode+'.inPosition'))
        mc.connectAttr ((shape+'.worldSpace'),(tmpNode+'.inputCurve'))
        position.append (mc.getAttr (tmpNode+'.positionX'))
        position.append (mc.getAttr (tmpNode+'.positionY'))
        position.append (mc.getAttr (tmpNode+'.positionZ'))
        positions.append(position)
        mc.delete (tmpNode)

    distances = []
    """ measure distances """
    locPos = returnWorldSpacePosition (tmpObj)
    mc.delete (tmpObj)
    for position in positions:
        distances.append(returnDistanceBetweenPoints(locPos,position))

    """ find the closest to our object """
    closestPosition = min(distances)
    matchIndex = distances.index(closestPosition)

    return positions[matchIndex]
示例#25
0
def returnBlendShapeNodeFromPoseBuffer(poseBuffer):
    poseBufferAttributes = attributes.returnUserAttributes(poseBuffer)
    drivenObjects = []
    if poseBufferAttributes:
        for attr in poseBufferAttributes:
            try:
                buffer = attributes.returnDrivenObject(poseBuffer+'.'+attr)
                if search.returnObjectType(buffer) == 'blendShape':
                    drivenObjects.append(buffer)
            except:
                pass
        drivenObjects = lists.returnListNoDuplicates(drivenObjects)
        return drivenObjects
    else:
        guiFactory.warning("No blendshape node connected to %s found" %poseBuffer)
        return False
示例#26
0
 def validateMeshArg(self, mesh = None):
     '''
     Validates a mesh and returns a dict of data
     
     :param mesh: mesh to evaluate
     
     '''        
     _mesh = None 
     _skin = None
     if mesh is None:
         #if self.d_kws.get('sourceMesh'):
             #log.info("Using stored sourceMesh data")
             #sourceMesh = self.d_kws.get('sourceMesh')
         #else:
         log.info("No source specified, checking if selection found")
         _bfr = mc.ls(sl=True)
         if not _bfr:raise ValueError,"No selection found and no source arg"
         mesh = _bfr[0]
         
     _type = search.returnObjectType(mesh)
     
     if _type in ['mesh', 'nurbsCurve', 'nurbsSurface']:
         if _type in ['nurbsCurve','nurbsSurface']:
             raise  NotImplementedError, "Haven't implemented nurbsCurve or nurbsSurface yet"
         log.info("Skinnable object '{0}', checking skin".format(mesh))
         _mesh = mesh
         _skin = skinning.querySkinCluster(_mesh) or False
         if _skin:
             log.info("Found skin '{0}' on '{1}'".format(_skin,_mesh))
     elif _type in ['skinCluster']:
         log.info("skinCluster '{0}' passed...".format(mesh))
         _skin = mesh
         _mesh = attributes.doGetAttr(_skin,'outputGeometry')[0]
         log.info("Found: {0}".format(_mesh))
     else:
         raise ValueError,"Not a usable mesh type : {0}".format(_type)
     
     _shape = mc.listRelatives(_mesh,shapes=True,fullPath=False)[0]
     _return = {'mesh':_mesh,
                'meshType':_type,
                'shape':_shape,
                'skin':_skin,
                'component':data._geoToComponent.get(_type, False),
                'pointCount':mc.polyEvaluate(_shape, vertex=True)
                }
     return _return  
示例#27
0
    def checkGeo(self):
        """
        Check a puppet's geo that it is actually geo
        """
        assert self.msgGeoGroup.get() is not False, "No geo group found!"

        children = search.returnAllChildrenObjects(self.msgGeoGroup.get())
        if not children:
            return False

        for o in children:
            if search.returnObjectType(o) in geoTypes:
                buff = mc.ls(o, long=True)
                self.geo.append(buff[0])
            else:
                rigging.doParentToWorld(o)
                guiFactory.warning("'%s' isn't geo, removing from group." % o)
        return True
示例#28
0
    def duplicateShape(shape):
        parentObj = mc.listRelatives(shape, p=True, fullPath=True)
        shapes = mc.listRelatives(parentObj, shapes=True, fullPath=True)
        matchObjName = mc.ls(shape, long=True)
        matchIndex = shapes.index(matchObjName[0])

        dupBuffer = mc.duplicate(parentObj)
        children = mc.listRelatives(dupBuffer[0], children = True, fullPath =True)
        if len(children) > 0:
            for c in children:
                if search.returnObjectType(c) != 'shape':
                    mc.delete(c)

        dupShapes = mc.listRelatives(dupBuffer[0], shapes=True, fullPath=True)
        for shape in dupShapes:
            if dupShapes.index(shape) != matchIndex:
                mc.delete(shape)
                return dupBuffer[0]
    def addTargetMesh(self,mesh):
        """
        Add target mesh to the tool
        """
        if not mc.objExists(mesh):
            guiFactory.warning("'%s' doesn't exist. Ignoring..."%mesh)
            return False

        if mesh not in self.meshList:
            buffer = search.returnObjectType(mesh)
            if buffer == 'mesh':
                self.meshList.append(mesh)
                self.updateMeshArea()
                return True
            else:
                guiFactory.warning("'%s' is not a mesh. It is returning as '%s'"%(mesh,buffer))
                return False
        return False
示例#30
0
    def addTargetMesh(self,mesh):
        """
        Add target mesh to the tool
        """
        if not mc.objExists(mesh):
            log.warning("'%s' doesn't exist. Ignoring..."%mesh)
            return False

        if mesh not in self.l_mesh:
            buffer = search.returnObjectType(mesh)
            if buffer in ['mesh','nurbsSurface']:
                self.l_mesh.append(mesh)
                self.updateMeshArea()
                return True
            else:
                log.warning("'%s' is not a mesh. It is returning as '%s'"%(mesh,buffer))
                return False
        return False
    def addTargetMesh(self,mesh):
        """
        Add target mesh to the tool
        """
        if not mc.objExists(mesh):
            guiFactory.warning("'%s' doesn't exist. Ignoring..."%mesh)
            return False

        if mesh not in self.meshList:
            buffer = search.returnObjectType(mesh)
            if buffer == 'mesh':
                self.meshList.append(mesh)
                self.updateMeshArea()
                return True
            else:
                guiFactory.warning("'%s' is not a mesh. It is returning as '%s'"%(mesh,buffer))
                return False
        return False
示例#32
0
def removePolyUniteNode(polyUniteNode):
    rawDrivers = returnPolyUniteSourceShapes(polyUniteNode)

    if not mc.objExists(polyUniteNode):
        return guiFactory.warning('%s does not exist' %polyUniteNode)
    mc.delete(polyUniteNode)
    
    for obj in rawDrivers:
        if search.returnObjectType(obj) is 'shape':
            transform = mc.listRelatives (obj,parent=True, type ='transform')
            nameBuffer = mc.listRelatives (obj,parent=True, type ='transform')
            mc.setAttr((transform[0]+'.visibility'),1)
            mc.setAttr((obj+'.intermediateObject'),0)
            
            
            if not mc.referenceQuery(obj, isNodeReferenced=True):
                buffer = rigging.doParentToWorld(transform[0])
                mc.rename(buffer,nameBuffer[0])
示例#33
0
    def duplicateShape(shape):
        parentObj = mc.listRelatives(shape, p=True, fullPath=True)
        shapes = mc.listRelatives(parentObj, shapes=True, fullPath=True)
        matchObjName = mc.ls(shape, long=True)
        matchIndex = shapes.index(matchObjName[0])

        dupBuffer = mc.duplicate(parentObj)
        children = mc.listRelatives(dupBuffer[0], children = True, fullPath =True)
        if len(children) > 0:
            for c in children:
                if search.returnObjectType(c) != 'shape':
                    mc.delete(c)

        dupShapes = mc.listRelatives(dupBuffer[0], shapes=True, fullPath=True)
        for shape in dupShapes:
            if dupShapes.index(shape) != matchIndex:
                mc.delete(shape)
                return dupBuffer[0]
示例#34
0
def returnConstraintTargets(constraint):
    objType = search.returnObjectType(constraint)
    targetsDict = {}
    targetList = []
    constaintCmdDict = {'parentConstraint':mc.parentConstraint,
                        'orientConstraint':mc.orientConstraint,
                        'pointConstraint':mc.pointConstraint,
                        'aimConstraint':mc.aimConstraint}
    
    if objType in constaintCmdDict.keys():
        cmd = constaintCmdDict.get(objType)
        #>>> Get targets
        targetList = cmd(constraint,q=True,targetList=True)

    if not targetList:
        guiFactory.warning('%s has no targets' %constraint)
        return False
    else:
        return targetList
示例#35
0
    def skinIt():
	#Skin it
	geoGroupObjects = search.returnAllChildrenObjects('geo_grp',True)
	#Get our group objects
	
	jointChains = getSkinJointChains()

	for i,g in enumerate([u'torso_geoGrp', u'armLeft_geoGrp', u'armRight_geoGrp', u'legLeft_geoGrp', u'legRight_geoGrp']):
	    geoGroupObjects = search.returnAllChildrenObjects(g,True)	
	
	    toSkin = []
	    for o in geoGroupObjects:
		if search.returnObjectType(o) in ['mesh','nurbsSurface']:
		    toSkin.append(o)
		
	    if toSkin:
		for o in toSkin:
		    toBind = jointChains[i] + [o]
		    mc.skinCluster(toBind, tsb = True, normalizeWeights = True, mi = 4, dr = 10,polySmoothness = 3)
	    else:
		print ("'%s' has nothing to skin!"%g)   
示例#36
0
def createFollicleOnMesh(mesh, name="follicle"):
    """
    Creates named follicle node on a mesh
    
    Keywords
    mesh -- mesh to attach to
    name -- base name to use ('follicle' default)
    
    Returns
    [follicleNode,follicleTransform]
    """
    assert mc.objExists(mesh), "'%s' doesn't exist!" % mesh
    objType = search.returnObjectType(mesh)
    assert objType in ["mesh", "nurbsSurface"], "'%s' isn't a mesh" % mesh

    follicleNode = createNamedNode((name), "follicle")

    """ make the closest point node """
    # closestPointNode = createNamedNode((targetObj+'_to_'+mesh),'closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh, shapes=True)[0]
    follicleTransform = mc.listRelatives(follicleNode, p=True)[0]

    attributes.doConnectAttr(
        (controlSurface + ".worldMatrix[0]"), (follicleNode + ".inputWorldMatrix")
    )  # surface to follicle node
    if objType == "mesh":
        attributes.doConnectAttr(
            (controlSurface + ".outMesh"), (follicleNode + ".inputMesh")
        )  # surface mesh to follicle input mesh
    else:
        attributes.doConnectAttr(
            (controlSurface + ".local"), (follicleNode + ".inputSurface")
        )  # surface mesh to follicle input mesh

    attributes.doConnectAttr((follicleNode + ".outTranslate"), (follicleTransform + ".translate"))
    attributes.doConnectAttr((follicleNode + ".outRotate"), (follicleTransform + ".rotate"))

    attributes.doSetLockHideKeyableAttr(follicleTransform)

    return [follicleNode, follicleTransform]
示例#37
0
    def getMessage(self,*a, **kw):
        """ 
        Get and store attribute value as if they were messages. Used for bufferFactory to use a connected
        attribute as a poor man's attribute message function
        
        Keyword arguments:
        *a, **kw
        """   
        try:
            if self.form == 'message':
                self.value = attributes.returnMessageObject(self.obj.nameShort,self.attr)
                if search.returnObjectType(self.value) == 'reference':
                    if attributes.repairMessageToReferencedTarget(self.obj.nameLong,self.attr,*a,**kw):
                        self.value = attributes.returnMessageObject(self.obj.nameShort,self.attr)                        
            else:
                self.value = attributes.returnDriverAttribute("%s.%s"%(self.obj.nameShort,self.attr))

            guiFactory.report("'%s.%s' >Message> '%s'"%(self.obj.nameShort,self.attr,self.value))
            return self.value
            
        except:
            guiFactory.warning("'%s.%s' failed to get"%(self.obj.nameShort,self.attr))
示例#38
0
def returnObjectDeformers(obj, deformerTypes = 'all'):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ACKNOWLEDGEMENT
    Pythonized from - http://www.scriptswell.net/2010/09/mel-list-all-deformers-on-mesh.html

    DESCRIPTION:
    Returns a list of deformers on an object in order from top to bottom

    ARGUMENTS:
    obj(string)

    RETURNS:
    deformers(list)/False
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    objHistory = mc.listHistory(obj,pruneDagObjects=True)
    deformers = []
    if objHistory:
        for node in objHistory:
            typeBuffer = mc.nodeType(node, inherited=True)
            if 'geometryFilter' in typeBuffer:
                deformers.append(node)
    if len(deformers)>0:
        if deformerTypes == 'all':
            return deformers
        else:
            foundDeformers = []
            #Do a loop to figure out if the types are there
            for deformer in deformers:
                if search.returnObjectType(deformer) == deformerTypes:
                    foundDeformers.append(deformer)
            if len(foundDeformers)>0:
                return foundDeformers
            else:
                return False

    else:
        return False
示例#39
0
def locMeEditPoint(editPoint):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's of a curve

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	if search.returnObjectType(editPoint) == 'editPoint':
		pos = mc.pointPosition (editPoint,w=True)
		wantedName = (editPoint + '_loc')
		actualName = mc.spaceLocator (n= wantedName)
		mc.move (pos[0],pos[1],pos[2], [actualName[0]])
		return actualName[0]
	else:
		guiFactory.warning  ('Not an editPoint')
		return False
示例#40
0
def locMeEditPoint(editPoint):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's of a curve

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    if search.returnObjectType(editPoint) == 'editPoint':
        pos = mc.pointPosition(editPoint, w=True)
        wantedName = (editPoint + '_loc')
        actualName = mc.spaceLocator(n=wantedName)
        mc.move(pos[0], pos[1], pos[2], [actualName[0]])
        return actualName[0]
    else:
        guiFactory.warning('Not an editPoint')
        return False
示例#41
0
def locMeCVOfCurve(curveCV):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's of a curve

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	if search.returnObjectType(curveCV) == 'curveCV':
		cvPos = mc.pointPosition (curveCV,w=True)
		wantedName = (curveCV + '_loc')
		actualName = mc.spaceLocator (n= wantedName)
		mc.move (cvPos[0],cvPos[1],cvPos[2], [actualName[0]])
		return actualName[0]
	else:
		guiFactory.warning  ('Not a curveCV')
		return False
示例#42
0
def locMeCVOfCurve(curveCV):
    """
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Places locators on the cv's of a curve

	ARGUMENTS:
	curve(string)

	RETURNS:
	locList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
    if search.returnObjectType(curveCV) == 'curveCV':
        cvPos = mc.pointPosition(curveCV, w=True)
        wantedName = (curveCV + '_loc')
        actualName = mc.spaceLocator(n=wantedName)
        mc.move(cvPos[0], cvPos[1], cvPos[2], [actualName[0]])
        return actualName[0]
    else:
        guiFactory.warning('Not a curveCV')
        return False
示例#43
0
def returnConstraintTargetWeights(constraint):
    objType = search.returnObjectType(constraint)
    targetsDict = {}
    targetList = []
    constaintCmdDict = {'parentConstraint':mc.parentConstraint,
                        'orientConstraint':mc.orientConstraint,
                        'pointConstraint':mc.pointConstraint,
                        'aimConstraint':mc.aimConstraint}
    
    if objType in constaintCmdDict.keys():
        cmd = constaintCmdDict.get(objType)
        aliasList = mc.parentConstraint(constraint,q=True, weightAliasList=True)
        if aliasList:
            for o in aliasList:
                targetsDict[o] = mc.getAttr(constraint+'.'+o)


    if not targetsDict:
        guiFactory.warning('%s has no targets' %constraint)
        return False
    else:
        return targetsDict
示例#44
0
def returnConstraintTargets(constraint):
    objType = search.returnObjectType(constraint)
    targetsDict = {}
    targetList = []
    constaintCmdDict = {'parentConstraint':mc.parentConstraint,
                        'orientConstraint':mc.orientConstraint,
                        'pointConstraint':mc.pointConstraint,
                        'scaleConstraint':mc.scaleConstraint,
                        'aimConstraint':mc.aimConstraint}
    
    if objType in constaintCmdDict.keys():
        cmd = constaintCmdDict.get(objType)
        #>>> Get targets
        targetList = cmd(constraint,q=True,targetList=True)
    else:
        log.warning("Unknown constraint type for returnConstraintTargets: '%s'"%objType)
        return False

    if not targetList:
        log.warning('%s has no targets' %constraint)
        return False
    else:
        return targetList
示例#45
0
def reorderDeformersByType(obj, deformerOrder = ['skinCluster','blendShape','tweak']):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ACKNOWLEDGEMENT
    Reorders deformers on an object by deformer type

    DESCRIPTION:
    Returns a list of deformers on an object in order from top to bottom

    ARGUMENTS:
    obj(string)
    deformerOrder(list) - (['skinCluster','blendShape','tweak'])
    >>>> Options are sculpt, cluster, jointCluster, lattice, wire, jointLattice, boneLattice, blendShape.

    RETURNS:
    Success(bool)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    deformers = returnObjectDeformers(obj)
    orderedDeformers = []
    if deformers:
        for deformerType in deformerOrder:
            for deformer in deformers:
                if search.returnObjectType(deformer) == deformerType:
                    orderedDeformers.append(deformer)
                    deformers.remove(deformer)

        for deformer in deformers:
            orderedDeformers.append(deformer)
        # pair up the list
        orderedDeformerPairs = lists.parseListToPairs(orderedDeformers)
        for pair in orderedDeformerPairs:
            mc.reorderDeformers(pair[0],pair[1],obj)
        return True
    else:
        print ('No deformers on ' + obj)
        return False
示例#46
0
def createFollicleOnMesh(mesh, name='follicle'):
    """
    Creates named follicle node on a mesh
    
    Keywords
    mesh -- mesh to attach to
    name -- base name to use ('follicle' default)
    
    Returns
    [follicleNode,follicleTransform]
    """
    assert mc.objExists(mesh), "'%s' doesn't exist!" % mesh
    assert search.returnObjectType(mesh) == 'mesh', ("'%s' isn't a mesh" %
                                                     mesh)

    follicleNode = createNamedNode((name), 'follicle')
    """ make the closest point node """
    #closestPointNode = createNamedNode((targetObj+'_to_'+mesh),'closestPointOnMesh')
    controlSurface = mc.listRelatives(mesh, shapes=True)[0]
    follicleTransform = mc.listRelatives(follicleNode, p=True)[0]

    attributes.doConnectAttr(
        (controlSurface + '.worldMatrix[0]'),
        (follicleNode + '.inputWorldMatrix'))  #surface to follicle node
    attributes.doConnectAttr(
        (controlSurface + '.outMesh'),
        (follicleNode + '.inputMesh'))  #surface mesh to follicle input mesh

    attributes.doConnectAttr((follicleNode + '.outTranslate'),
                             (follicleTransform + '.translate'))
    attributes.doConnectAttr((follicleNode + '.outRotate'),
                             (follicleTransform + '.rotate'))

    attributes.doSetLockHideKeyableAttr(follicleTransform)

    return [follicleNode, follicleTransform]
示例#47
0
def returnInfoForLoc(obj,forceBBCenter = False):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Return info to create or update a locator.

	ARGUMENTS:
	obj(string)

	RETURNS:
	locInfo(dict)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	"""pass  an object into it and get locator placed at the pivots - matching translation, rotation and rotation order"""
	rotationOrderDictionary = {'xyz':0,'yzx':1 ,'zxy':2 ,'xzy':3 ,'yxz':4,'zyx':5,'none':6}

	"""get stuff to transfer"""
	objType = search.returnObjectType(obj)

	# vertex
	if objType == 'polyVertex':
		objTrans = mc.pointPosition(obj,w=True)
	elif objType == 'polyEdge':
		mc.select(cl=True)
		mc.select(obj)
		mel.eval("PolySelectConvert 3")
		edgeVerts = mc.ls(sl=True,fl=True)
		posList = []
		for vert in edgeVerts:
			posList.append(mc.pointPosition(vert,w=True))
		objTrans = distance.returnAveragePointPosition(posList)
		mc.select(cl=True)
	elif objType == 'polyFace':
		mc.select(cl=True)
		mc.select(obj)
		mel.eval("PolySelectConvert 3")
		edgeVerts = mc.ls(sl=True,fl=True)
		posList = []
		for vert in edgeVerts:
			posList.append(mc.pointPosition(vert,w=True))
		objTrans = distance.returnAveragePointPosition(posList)
		mc.select(cl=True)
	elif objType in ['surfaceCV','curveCV','editPoint','nurbsUV','curvePoint']:
		mc.select(cl=True)
		objTrans = mc.pointPosition (obj,w=True)
	else:
		if forceBBCenter == True:
			objTrans = distance.returnCenterPivotPosition(obj)
		else:
			objTrans = mc.xform (obj, q=True, ws=True, sp=True)

	objRot = mc.xform (obj, q=True, ws=True, ro=True)
	objRoo = mc.xform (obj, q=True, roo=True )

	"""get rotation order"""
	correctRo = rotationOrderDictionary[objRoo]


	locInfo = {}
	locInfo['createdFrom']=obj
	locInfo['objectType']=objType
	locInfo['position']=objTrans
	locInfo['rotation']=objRot
	locInfo['rotationOrder']=correctRo


	return locInfo
示例#48
0
def returnAbsoluteSizeCurve(curve):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass an curve into it and it returns absolute distance scale

    ARGUMENTS:
    curve(string) - curve

    RETURNS:
    distances(list) - [xLength,yLength,zLength]
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    def duplicateShape(shape):
        parentObj = mc.listRelatives(shape, p=True, fullPath=True)
        shapes = mc.listRelatives(parentObj, shapes=True, fullPath=True)
        matchObjName = mc.ls(shape, long=True)
        matchIndex = shapes.index(matchObjName[0])

        dupBuffer = mc.duplicate(parentObj)
        children = mc.listRelatives(dupBuffer[0], children = True, fullPath =True)
        if len(children) > 0:
            for c in children:
                if search.returnObjectType(c) != 'shape':
                    mc.delete(c)

        dupShapes = mc.listRelatives(dupBuffer[0], shapes=True, fullPath=True)
        for shape in dupShapes:
            if dupShapes.index(shape) != matchIndex:
                mc.delete(shape)
                return dupBuffer[0]


    boundingBoxSize = returnBoundingBoxSize(curve)
    if mayaVersion <=2010:
        return boundingBoxSize
    else:
        distanceToMove = max(boundingBoxSize)
        positions = []
        isShape = False
        if search.returnObjectType(curve) == 'shape':
            dupCurve = duplicateShape(curve)
            curve = dupCurve
            isShape = True

        loc = rigging.locMeObjectStandAlone(curve)
        locGroup = rigging.groupMeObject(loc,False)
        loc = rigging.doParentReturnName(loc,locGroup)
        directions = ['x','y','z']
        for direction in directions:
            positionsBuffer = []
            mc.setAttr((loc+'.t'+direction),distanceToMove)
            positionsBuffer.append(returnClosestUPosition(loc,curve))
            mc.setAttr((loc+'.t'+direction),-distanceToMove)
            positionsBuffer.append(returnClosestUPosition(loc,curve))
            mc.setAttr((loc+'.t'+direction),0)
            positions.append(positionsBuffer)

        distances = []
        for set in positions:
            distances.append(returnDistanceBetweenPoints(set[0],set[1]))

        if isShape == True:
            mc.delete(dupCurve)

        mc.delete(locGroup)
        return distances
cgm.core._reload()
a = cgmPM.cgmPuppet(name='MorphyEye')
a.getGeo()
a.masterControl.controlSettings.mNode
a.masterControl.controlSettings.addAttr('skeleton',
                                        enumName='off:referenced:on',
                                        attrType='enum',
                                        defaultValue=2,
                                        keyable=False,
                                        hidden=False)
a.masterNull.geoGroup.getAllChildren()
from cgm.lib import search

reload(search)
search.returnObjectType('Morphy_Body_GEO')
for o in a.masterNull.geoGroup.getAllChildren():
    search.returnObjectType(o)

cgmMeta.cgmObjectSet(setType='anim', qssState=True)
a._verifyMasterControl()
a = cgmPM.cgmPuppet(name='Kermit', initializeOnly=True)
a = cgmPM.cgmPuppet(name='Morphy')
a.__verify__()
a.cgmName
a._verifyMasterControl()
b = cgmPM.cgmMorpheusMakerNetwork('Morphy_customizationNetwork')
a.__verify__()
a.getMessage('asdf')
a.puppetSet.value = []
b.mNode
示例#50
0
def returnNearestPointOnCurveInfo(targetObject,curve,deleteNode = True,cullOriginalShapes = True):
    """
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Pass target object and curve into it and return the closest U position

    ARGUMENTS:
    targetObject(string)
    surface(string)
    deleteNode(bool)

    RETURNS:
    {'position':(list),'parameter':(float},'shape':(string),'object':(string)}
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    _str_funcName = 'returnNearestPointOnCurveInfo'
    log.debug(">>> %s >> "%_str_funcName + "="*75) 
    try:
	position = []
	if search.returnObjectType(curve) == 'shape':
	    shapes = []
	    shapes.append(curve)
	else:
	    shapes = mc.listRelatives (curve, shapes=True)
	if cullOriginalShapes:
	    for shape in shapes:
		if len(shape)>5 and shape[-4:] == 'Orig':
		    shapes.remove(shape)
	#to account for target objects in heirarchies """
	tmpObj = rigging.locMeObjectStandAlone(targetObject)
	l_positions = []
	l_uValues = []
	l_shapes = []
	l_objects = []
	l_nodes = []
	for shape in shapes:
	    tmpNode = mc.createNode ('nearestPointOnCurve',n='%s_npoc'%shape)
	    position = []
	    distances = []
	    mc.connectAttr ((tmpObj+'.translate'),(tmpNode+'.inPosition'))
	    mc.connectAttr ((shape+'.worldSpace'),(tmpNode+'.inputCurve'))
	    position.append (mc.getAttr (tmpNode+'.positionX'))
	    position.append (mc.getAttr (tmpNode+'.positionY'))
	    position.append (mc.getAttr (tmpNode+'.positionZ'))
	    l_positions.append(position)
	    l_shapes.append(shape)
	    l_uValues.append(mc.getAttr (tmpNode+'.parameter'))
	    l_objects.append("%s.u[%f]"%(shape,mc.getAttr (tmpNode+'.parameter')))
	    l_nodes.append(tmpNode)
    
	distances = []
	""" measure distances """
	locPos = returnWorldSpacePosition (tmpObj)
	mc.delete (tmpObj)
	for position in l_positions:
	    distances.append(returnDistanceBetweenPoints(locPos,position))
    
	""" find the closest to our object """
	closestPosition = min(distances)
	matchIndex = distances.index(closestPosition)
	d_return = {'position':l_positions[matchIndex],'parameter':l_uValues[matchIndex],'shape':l_shapes[matchIndex],'object':l_objects[matchIndex]}
	if not deleteNode:
	    d_return['node'] = l_nodes[matchIndex]
	    l_nodes.remove(l_nodes[matchIndex])	
	if l_nodes:mc.delete(l_nodes)
	
	return d_return
    except StandardError,error:
	raise StandardError,"%s >>> error : %s"%(_str_funcName,error)	    
示例#51
0
def objString(arg=None, mayaType=None, isTransform=None, noneValid=False, calledFrom = None, **kwargs):
    """
    Return 'arg' if 'arg' is an existing, uniquely named Maya object, meeting
    the optional requirements of mayaType and isTransform, otherwise
    return False if noneValid or raise an exception.

    :parameters:
        arg | str
            The name of the Maya object to be validated
        mayaType | str, list
            One or more Maya types - arg must be in this list for the test to pass.
        isTransform | bool
            Test whether 'arg' is a transform 
        noneValid | bool
            Return False if arg does not pass rather than raise an exception

    :returns:
        'arg' or False

    :raises:
        TypeError | if 'arg' is not a string
        NameError | if more than one object name 'arg' exists in the Maya scene
        NameError | if 'arg' does not exist in the Maya scene
        TypeError | if the Maya type of 'arg' is in the list 'mayaType' and noneValid is False
        TypeError | if isTransform is True, 'arg' is not a transform, and noneValid is False
    """
    log.debug("validateArgs.objString arg={0}".format(arg))

    _str_funcRoot = 'objString'
    if calledFrom: _str_funcName = "{0}.{1}({2})".format(calledFrom,_str_funcRoot,arg)    
    else:_str_funcName = "{0}({1})".format(_str_funcRoot,arg) 

    result = None 

    if not isinstance(arg, basestring):
        raise TypeError('arg must be string')

    if len(mc.ls(arg)) > 1:
        raise NameError("More than one object is named '{0}'".format(arg))

    if result is None and not mc.objExists(arg):
        if noneValid:
            result = False
        else:
            raise NameError("'{0}' does not exist".format(arg))
    
    if result != False and mayaType is not None:
        l_mayaTypes = mayaType
        if isinstance(mayaType, (basestring)):
            l_mayaTypes = [mayaType]

        str_argMayaType = search.returnObjectType(arg)

        if not str_argMayaType in l_mayaTypes:
            if noneValid: 
                result = False
            else:
                str_mayaTypes_formatted = ', '.join(l_mayaTypes)
                fmt_args = [arg, str_argMayaType, str_mayaTypes_formatted]

                raise TypeError("Arg {0} is type '{1}', expected '{2}'".format(*fmt_args))

    if result is None and isTransform:
        if not mc.objectType(arg, isType="transform"):
            if noneValid:
                result = False
            else:
                str_argMayaType = search.returnObjectType(arg)
                fmt_args = [arg, str_argMayaType]
                raise TypeError("'Arg {0}' is type {1}, expected 'transform'").format(*fmt_args)

    if result is None:
        result = arg

    return result
示例#52
0
def returnUniqueGeneratedName(obj,
                              sceneUnique=False,
                              fastIterate=True,
                              ignore='none',
                              **kws):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    DESCRIPTION:
    Returns a generated name with iteration for heirarchy objects with the same tag info

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

    RETURNS:
    name(string)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    if type(ignore) is not list: ignore = [ignore]
    log.debug("sceneUnique: %s" % sceneUnique)
    log.debug("fastIterate: %s" % fastIterate)
    log.debug("ignore: %s" % ignore)

    #>>> Dictionary driven order first build
    def doBuildName():
        nameBuilder = []
        for item in order:
            buffer = updatedNamesDict.get(item)
            # Check for short name
            buffer = search.returnTagInfoShortName(buffer, item)
            if buffer and buffer != 'ignore':
                nameBuilder.append(buffer)

        return divider.join(nameBuilder)

    rawNamesDict = returnObjectGeneratedNameDict(obj, ignore)
    divider = returnCGMDivider()
    updatedNamesDict = returnObjectGeneratedNameDict(obj, ignore)
    order = returnCGMOrder()

    if 'cgmName' not in updatedNamesDict.keys(
    ) and search.returnObjectType(obj) != 'group':
        buffer = mc.ls(obj, shortNames=True)
        attributes.storeInfo(obj, 'cgmName', buffer[0], True)
        updatedNamesDict = returnObjectGeneratedNameDict(obj, ignore)

    coreName = doBuildName()
    """ add the iterator to the name dictionary if our object exists"""
    nameFactory = NameFactory(obj)

    if sceneUnique:
        if fastIterate:
            iterator = returnFastIterateNumber(obj)
        else:
            iterator = returnIterateNumber(obj)
        if iterator > 0:
            updatedNamesDict['cgmIterator'] = str(iterator)
            coreName = doBuildName()

    log.debug(returnCombinedNameFromDict(updatedNamesDict))
    return returnCombinedNameFromDict(updatedNamesDict)
        def findSurfaceIntersection(self):
            '''
            Return the pierced point on a surface from a raySource and rayDir
            '''
            try:
                self._str_funcName = 'findSurfaceIntersection'
                log.debug(">>> %s >> "%self._str_funcName + "="*75)
                if len(mc.ls(surface))>1:
                    raise StandardError,"findSurfaceIntersection>>> More than one surface named: %s"%surface
                
                self.centerPoint = mc.xform(surface, q=1, ws=1, t=1)
                
                #checking the type 
                self.objType = search.returnObjectType(surface)
                
                if self.objType == 'nurbsSurface':
                    raySource = om.MPoint(raySource[0], raySource[1], raySource[2])
                    self.raySourceVector = om.MVector(raySource[0], raySource[1], raySource[2])
                    self.centerPointVector = om.MVector(self.centerPoint[0],self.centerPoint[1],self.centerPoint[2])
                    rayDir = om.MPoint(self.centerPointVector - self.raySourceVector)
                    self.rayDirection = om.MVector(rayDir[0], rayDir[1], rayDir[2])
                    self.hitPoint = om.MPoint()
                    self.selectionList = om.MSelectionList()
                    self.selectionList.add(surface)
                    self.surfacePath = om.MDagPath()
                    self.selectionList.getDagPath(0, self.surfacePath)
                    self.surfaceFn = om.MFnNurbsSurface(self.surfacePath)

                    #maxDist
                    self.maxDist = maxDistance

                    #other variables 
                    self.uSU = om.MScriptUtil()
                    self.vSU = om.MScriptUtil()
                    self.uPtr = self.uSU.asDoublePtr()
                    self.vPtr = self.vSU.asDoublePtr()
                    self.spc = om.MSpace.kWorld
                    self.toleranceSU = om.MScriptUtil()
                    self.tolerance = self.toleranceSU.asDoublePtr()
                    om.MScriptUtil.setDouble(self.tolerance, .1)

                    #Get the closest intersection.
                    self.gotHit = self.surfaceFn.intersect(raySource,self.rayDirection,self.uPtr,self.vPtr,self.hitPoint,self.toleranceSU.asDouble(),self.spc,False,None,False,None)
                    
                elif self.objType == 'mesh':
                    raySource = om.MFloatPoint(raySource[0], raySource[1], raySource[2])
                    self.raySourceVector = om.MFloatVector(raySource[0], raySource[1], raySource[2])
                    self.centerPointVector = om.MFloatVector(self.centerPoint[0],self.centerPoint[1],self.centerPoint[2]) 
                    rayDir = om.MFloatPoint(self.centerPointVector - self.raySourceVector)
                    self.rayDirection = om.MFloatVector(rayDir[0], rayDir[1], rayDir[2])
                    self.hitPoint = om.MFloatPoint()     
                    self.selectionList = om.MSelectionList()
                    self.selectionList.add(surface)
                    self.meshPath = om.MDagPath()
                    self.selectionList.getDagPath(0, self.meshPath)
                    self.meshFn = om.MFnMesh(self.meshPath)

                    #maxDist
                    self.maxDist = maxDistance

                    #other variables 
                    self.spc = om.MSpace.kWorld

                    #Get the closest intersection.
                    self.gotHit = self.meshFn.closestIntersection(raySource,self.rayDirection,None,None,False,self.spc,self.maxDist,False,None,self.hitPoint,None,None,None,None,None)
                    
                else : raise StandardError,"wrong surface type!"
                    
                #Return the intersection as a Python list.
                if self.gotHit:
                    self.returnDict = {}
                    self.hitList = []
                    self.uvList = []
                    for i in range(self.hitPoints.length()):
                        self.hitList.append( [self.hitPoints[i].x, self.hitPoints[i].y, self.hitPoints[i].z])
                        self.hitMPoint = om.MPoint(self.hitPoints[i])
                        self.pArray = [0.0,0.0]
                        self.x1 = om.MScriptUtil()
                        self.x1.createFromList(pArray, 2)
                        self.uvPoint = x1.asFloat2Ptr()
                        self.uvSet = None
                        self.uvReturn = self.surfaceFn.getParamAtPoint(self.hitMPoint,self.uvPoint,self.paramU,self.paramV, self.ignoreTrimBoundaries, om.MSpace.kObject, self.kMFnNurbsEpsilon)
                                    
                        self.uValue = om.MScriptUtil.getFloat2ArrayItem(self.uvPoint, 0, 0) or False
                        self.vValue = om.MScriptUtil.getFloat2ArrayItem(uvPoint, 0, 1) or False
                        self.uvList.append([self.uValue,self.vValue])
                                    
                        self.returnDict = {'hits':self.hitList,'source':[raySource.x,raySource.y,raySource.z],'uvs':self.uvList}
                        return self.returnDict
                else: return None
                        
            except StandardError,error:
                log.error(">>> surface| raysource | rayDir | error")
                return None
    log.debug("raySource: %s" % raySource)
    log.debug("maxDistance: %s" % maxDistance)

    try:
        _str_funcName = 'findSurfaceIntersection'
        log.debug(">>> %s >> " % _str_funcName + "=" * 75)
        if len(mc.ls(surface)) > 1:
            raise ValueError, "findSurfaceIntersection>>> More than one surface named: %s" % surface
    except Exception, error:
        log.error(
            ">>> %s >> surface: %s | raysource: %s | rayDir %s | error: %s" %
            (_str_funcName, surface, raySource, rayDir, error))
        raise Exception, error  #you need to raise the excepction still because we want to to stop if things aren't right

    #checking the type
    objType = search.returnObjectType(surface)

    if objType == 'nurbsSurface':
        raySource = om.MPoint(raySource[0], raySource[1], raySource[2])
        raySourceVector = om.MVector(raySource[0], raySource[1], raySource[2])
        centerPointVector = om.MVector(centerPoint[0], centerPoint[1],
                                       centerPoint[2])
        rayDir = om.MPoint(centerPointVector - raySourceVector)
        rayDirection = om.MVector(rayDir[0], rayDir[1], rayDir[2])
        hitPoint = om.MPoint()
        selectionList = om.MSelectionList()
        selectionList.add(surfaceShape)
        surfacePath = om.MDagPath()
        selectionList.getDagPath(0, surfacePath)
        surfaceFn = om.MFnNurbsSurface(surfacePath)
示例#55
0
def returnObjectGeneratedNameDict(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)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    typesDictionary = dictionary.initializeDictionary(typesDictionaryFile)
    namesDictionary = dictionary.initializeDictionary(namesDictionaryFile)
    settingsDictionary = dictionary.initializeDictionary(
        settingsDictionaryFile)
    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.findRawTagInfo(obj, tag)
        if tagInfo is not False:
            namesDict[tag] = (tagInfo)
    """ remove tags up stream that we don't want if they don't exist on the actual object"""
    if mc.objExists(obj + '.cgmTypeModifier') != True:
        if namesDict.get('cgmTypeModifier') != None:
            namesDict.pop('cgmTypeModifier')

    #>>> checks if the names exist as objects or it's a shape node
    ChildNameObj = False
    nameObj = search.returnTagInfo(obj, 'cgmName')
    typeTag = search.returnTagInfo(obj, 'cgmType')
    isType = search.returnObjectType(obj)
    childrenObjects = search.returnChildrenObjects(obj)
    """first see if it's a group """
    if childrenObjects > 0 and isType == 'transform' and typeTag == False:
        """ if it's a transform group """
        groupNamesDict = {}
        if not nameObj:
            groupNamesDict['cgmName'] = childrenObjects[0]
        else:
            groupNamesDict['cgmName'] = nameObj
        groupNamesDict['cgmType'] = typesDictionary.get('transform')
        if namesDict.get('cgmDirection') != None:
            groupNamesDict['cgmDirection'] = namesDict.get('cgmDirection')
        if namesDict.get('cgmDirectionModifier') != None:
            groupNamesDict['cgmDirectionModifier'] = namesDict.get(
                'cgmDirectionModifier')
        if namesDict.get('cgmTypeModifier') != None:
            groupNamesDict['cgmTypeModifier'] = namesDict.get(
                'cgmTypeModifier')
        return groupNamesDict
        """ see if there's a name tag"""
    elif nameObj != None or isType == 'shape':
        """if there is, does it exist """
        if mc.objExists(nameObj) == True:
            """basic child object with cgmName tag """
            childNamesDict = {}
            childNamesDict['cgmName'] = namesDict.get('cgmName')
            childNamesDict['cgmType'] = namesDict.get('cgmType')
            if namesDict.get('cgmDirection') != None:
                childNamesDict['cgmDirection'] = namesDict.get('cgmDirection')
            if namesDict.get('cgmNameModifier') != None:
                childNamesDict['cgmNameModifier'] = namesDict.get(
                    'cgmNameModifier')
            if namesDict.get('cgmDirectionModifier') != None:
                childNamesDict['cgmDirectionModifier'] = namesDict.get(
                    'cgmDirectionModifier')
            if namesDict.get('cgmTypeModifier') != None:
                childNamesDict['cgmTypeModifier'] = namesDict.get(
                    'cgmTypeModifier')
            return childNamesDict
        elif isType == 'shape' or 'Constraint' in isType:
            """if so, it's a child name object"""
            childNamesDict = {}
            childNamesDict['cgmName'] = search.returnParentObject(obj, False)
            childNamesDict['cgmType'] = namesDict.get('cgmType')
            return childNamesDict
        elif typeTag == 'infoNull':
            """if so, it's a special case"""
            moduleObj = search.returnMatchedTagObjectUp(
                obj, 'cgmType', 'module')
            masterObj = search.returnMatchedTagObjectUp(
                obj, 'cgmType', 'master')
            if moduleObj != False:
                moduleName = returnUniqueGeneratedName(moduleObj,
                                                       ignore='cgmType')
                childNamesDict = {}
                childNamesDict['cgmName'] = (moduleName + '_' + nameObj)
                childNamesDict['cgmType'] = namesDict.get('cgmType')
                return childNamesDict
            elif masterObj != False:
                masterName = returnUniqueGeneratedName(masterObj,
                                                       ignore='cgmType')
                childNamesDict = {}
                childNamesDict['cgmName'] = (masterName + '_' + nameObj)
                childNamesDict['cgmType'] = namesDict.get('cgmType')
                return childNamesDict
            else:
                return namesDict
        else:
            return namesDict
    else:
        return namesDict
示例#56
0
def returnObjectGeneratedNameDict(obj,ignore='none'):
    """ 
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    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)
    >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    """
    typesDictionary = dictionary.initializeDictionary(typesDictionaryFile)
    namesDictionary = dictionary.initializeDictionary(namesDictionaryFile)
    settingsDictionary = dictionary.initializeDictionary(settingsDictionaryFile)
    namesDict={}
    divider = returnCGMDivider()
    order = returnCGMOrder()
    nameBuilder = []
    #>>> Get our cgmVar_iables
    userAttrs = attributes.returnUserAttributes(obj)
    cgmAttrs = lists.returnMatchList(userAttrs,order)
    #>>> Tag ignoring
    if ignore != 'none':
        if ignore in order:
            order.remove(ignore)

    #>>> Geting our data
    for tag in order:
        tagInfo = search.findRawTagInfo(obj,tag)
        if tagInfo is not False:
            namesDict[tag] = (tagInfo)
    """ remove tags up stream that we don't want if they don't exist on the actual object"""
    if mc.objExists(obj+'.cgmTypeModifier') != True:
        if namesDict.get('cgmTypeModifier') != None:
            namesDict.pop('cgmTypeModifier')   


    #>>> checks if the names exist as objects or it's a shape node
    ChildNameObj = False
    nameObj = search.returnTagInfo(obj,'cgmName')
    typeTag = search.returnTagInfo(obj,'cgmType')
    isType = search.returnObjectType(obj)
    childrenObjects = search.returnChildrenObjects(obj)
    """first see if it's a group """
    if childrenObjects > 0 and isType == 'transform' and typeTag == False:
        """ if it's a transform group """
        groupNamesDict = {}
        if not nameObj:
            groupNamesDict['cgmName'] = childrenObjects[0]
        else:
            groupNamesDict['cgmName'] = nameObj
        groupNamesDict['cgmType'] = typesDictionary.get('transform')
        if namesDict.get('cgmDirection') != None:
            groupNamesDict['cgmDirection'] = namesDict.get('cgmDirection')
        if namesDict.get('cgmDirectionModifier') != None:
            groupNamesDict['cgmDirectionModifier'] = namesDict.get('cgmDirectionModifier')
        if namesDict.get('cgmTypeModifier') != None:
            groupNamesDict['cgmTypeModifier'] = namesDict.get('cgmTypeModifier')
        return groupNamesDict
        """ see if there's a name tag"""
    elif nameObj != None or isType == 'shape':
        """if there is, does it exist """
        if mc.objExists(nameObj) == True:
            """basic child object with cgmName tag """
            childNamesDict = {}
            childNamesDict['cgmName'] = namesDict.get('cgmName')
            childNamesDict['cgmType'] = namesDict.get('cgmType')
            if namesDict.get('cgmDirection') != None:
                childNamesDict['cgmDirection'] = namesDict.get('cgmDirection')
            if namesDict.get('cgmNameModifier') != None:
                childNamesDict['cgmNameModifier'] = namesDict.get('cgmNameModifier')
            if namesDict.get('cgmDirectionModifier') != None:
                childNamesDict['cgmDirectionModifier'] = namesDict.get('cgmDirectionModifier')
            if namesDict.get('cgmTypeModifier') != None:
                childNamesDict['cgmTypeModifier'] = namesDict.get('cgmTypeModifier')
            return childNamesDict
        elif isType == 'shape' or 'Constraint' in isType:
            """if so, it's a child name object"""
            childNamesDict = {}
            childNamesDict['cgmName'] = search.returnParentObject(obj,False)
            childNamesDict['cgmType'] = namesDict.get('cgmType')
            return childNamesDict
        elif typeTag == 'infoNull':
            """if so, it's a special case"""
            moduleObj = search.returnMatchedTagObjectUp(obj,'cgmType','module')
            masterObj = search.returnMatchedTagObjectUp(obj,'cgmType','master')
            if moduleObj != False:
                moduleName = returnUniqueGeneratedName(moduleObj,ignore='cgmType')
                childNamesDict = {}
                childNamesDict['cgmName'] = (moduleName+'_'+nameObj)
                childNamesDict['cgmType'] = namesDict.get('cgmType')
                return childNamesDict   
            elif masterObj != False:
                masterName = returnUniqueGeneratedName(masterObj,ignore='cgmType')
                childNamesDict = {}
                childNamesDict['cgmName'] = (masterName+'_'+nameObj)
                childNamesDict['cgmType'] = namesDict.get('cgmType')
                return childNamesDict   
            else:
                return namesDict
        else:
            return namesDict
    else:
        return namesDict
示例#57
0
 def getType(self):
     """ get the type of the object """
     self.mType = search.returnObjectType(self.nameLong)
示例#58
0
def locClosest(objectList,targetObject):
	"""
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	DESCRIPTION:
	Creates a locator on the surface of the last object in a selection set closest
	to each remaining object in the selection

	ARGUMENTS:
	objectList

	RETURNS:
	locatorList(list)
	>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	"""
	bufferList = []

	lastObjectType = search.returnObjectType(targetObject)
	
	#Get our source objects locators as sometimes the pivot has no correlation to the objects pivot - like a cv
	fromObjects = []
	for item in objectList:
		fromObjects.append(locMeObject(item))
	

	if lastObjectType == 'mesh':
		if mayaVersion >=2011:
			for item in fromObjects:
				bufferList.append( locMeClosestPointOnMesh(item, targetObject) )
		else:
			guiFactory.warning('Apologies, but in maya 2010 and below this only supports nurbsSurface target objects')
			return False
	elif lastObjectType == 'nurbsSurface':
		for item in fromObjects:
			bufferList.append( locMeClosestUVOnSurface(item, targetObject) )
	elif lastObjectType == 'nurbsCurve':
		if mayaVersion >=2011:
			for item in fromObjects:
				bufferList.append( locMeClosestPointOnCurve(item, targetObject) )
		else:
			guiFactory.warning('Apologies, but in maya 2010 and below this only supports nurbsSurface target objects')
			return False

	else:
		guiFactory.warning('Your target object must be a mesh, nurbsSurface, or nurbsCurve')
		return False

	for loc in fromObjects:
		mc.delete(loc)
		
	for loc in bufferList:
		cnt = bufferList.index(loc)
		storeList = []
		storeList = objectList
		storeList.append(targetObject)
		attributes.storeInfo(loc,'cgmName',('%s_to_%s'%(objectList[0],objectList[-1])),False)		
		attributes.storeInfo(loc,'cgmSource',(','.join(storeList)),False)
		attributes.storeInfo(loc,'cgmLocMode','closestPoint',False)
		attributes.storeInfo(loc,'cgmTypeModifier','closestPoint',False)
		#bufferList[cnt] = NameFactory.doNameObject(loc)
		bufferList[cnt] =  cgmMeta.NameFactory(loc).doNameObject()

	return bufferList[0]