示例#1
0
 def create_new_pose_prompt(self):
     if not pm.selected():
         pm.warning ("Please Select an Object")
         return
     
     namespace = pm.selected()[0].split(":")[0]
     targetObj = "%s:geo"%(namespace)           
             
     result = pm.promptDialog(
         title='Create New Pose',
         message='Enter Pose Name:',
         button=['OK', 'Cancel'],
         defaultButton='OK',
         cancelButton='Cancel',
         dismissString='Cancel')
     
     if result == 'OK':
         name = pm.promptDialog(query=True, text=True)
         directory = self.get_active_directory()
         
         path = os.path.join(directory, "%s.pose" %name)
         pose_obj = Pose(path)
         pose_obj.create()
         
         pose_obj.save_pose()
         pose_obj.update_thumbnail(targetObj)
         
         self.populate_library_layout()
示例#2
0
def createLocToCenter():
    old_selection = pymel.selected()
    p3Pos = get_center(pymel.selected(flatten=True))
    pPoint = pymel.general.spaceLocator()
    pPoint.setTranslation(p3Pos, space='world')
    if old_selection:
        pymel.select(old_selection)
示例#3
0
    def export(self, dirpath, all=False, center=True, child=True):
        if os.path.isfile(self.opts['presetFile']):
            pm.mel.FBXLoadExportPresetFile(f=self.opts['presetFile'])
        ext = '.fbx'

        if all:
            pm.select(self.meshList.getAllItems())
            sel = pm.selected()
        else:
            sel = pm.selected()

        if len(sel) == 0:
            pm.warning('Nothing is selected!')
        else:
            for obj in sel:
                pm.select(obj)
                if center:
                    oldLoc = obj.getRotatePivot()
                    self.centerPiv(obj)
                exportPath = self._get_filename(dirpath, obj.name(), ext)
                if child:
                    children = obj.getChildren()
                    for i in children:
                        if isinstance(i, pm.nt.Transform):
                            pm.select(i, add=True)
                pm.mel.FBXExport(f=exportPath, s=True)
                if center:
                    obj.setTranslation([oldLoc[0], oldLoc[1], oldLoc[2]])
示例#4
0
    def save_set(self):
        if not pm.selected():
            pm.warning ("Please Select an Object")
            return

        selected = [obj.name().split(":")[-1] for obj in pm.selected()]
    
        with open(self.set_path, 'w') as outfile:
            json.dump(selected, outfile,  separators=(',',':'))
示例#5
0
文件: previs.py 项目: eoyilmaz/anima
def one_cam_to_shots():
    if not pm.ls(type='shot'):
        raise RuntimeError('There are no Shots in this scene.')

    if len(pm.selected()) != 1 or pm.selected()[0].getShape().type() != 'camera':
        raise RuntimeError('Select just 1 camera.')

    the_cam = pm.selected()[0]

    for shot in pm.ls(type='shot'):
        shot.set_camera(the_cam)
 def snapPivot(self):
     haircap = self.capName.getText()
     oldSel = pm.selected()
     self.transform()
     if pm.objExists(haircap):
         geo = pm.ls(haircap)[0]
         for sel in pm.selected():
             point = geo.getClosestPoint(sel.getTranslation())
             pm.move( point[0][0], point[0][1], point[0][2], sel)
         pm.select(oldSel)
     else: pm.error('hair cap doesnt exist in scene')
示例#7
0
def selectSkinnedJoints(node=None):
    '''
    selects all joints bound to the specified node
    '''
    if node==None:
        if len(pmc.selected())==1:
            node=pmc.selected()[0]
        else:
            return 'Please select or specify a skinCluster node'

    influences = pmc.skinCluster(node, q=1, influence=1)
    pmc.select(influences)
示例#8
0
 def library_button_save_pose(self, obj):
     if not pm.selected():
         pm.warning ("Please Select an Object")
         return        
     
     namespace = pm.selected()[0].split(":")[0]
     targetObj = "%s:geo"%(namespace)
     
     obj.save_pose()
     obj.update_thumbnail(targetObj)
     
     self.populate_library_layout()
示例#9
0
    def create_ribbon_callback(self, *args):
        
        startObj = None
        endObj = None
        
        if len(pm.selected()) == 2:
            startObj = pm.selected()[0]
            endObj = pm.selected()[-1]
        
        prefix = self.widgets["prefix_textField"].getText()        
        numJoints = self.widgets["numJoint_intField"].getValue()[0]
        numSpans = self.widgets["spans_intField"].getValue()[0]

        utils.create_ribbon(numJoints=numJoints, prefix=prefix, numSpans=numSpans, startObj=startObj, endObj=endObj)
    def create_BTN_pressed(self):
        ctrl_suffix = self.widgets['suffix_TFG'].getText()
        
        create_offsetNode = self.widgets['offsetNode_CB'].getValue()
        offsetNode_suffix = self.widgets['offsetNode_TF'].getText()
        
        create_cluster = self.widgets['cluster_CB'].getValue()
        cluster_group = self.widgets['clusterGroup_RBG'].getSelect()
        
        create_shape = self.widgets['shape_CB'].getValue()
        shape_type = self.widgets['shape_TSL'].getSelectItem()[0]
        
        shape_axis = self.widgets['shapeAxis_OM'].getValue()
        
        hierarchy = self.widgets['hierarchry_RB'].getSelect()
        
        tConst = self.widgets['tConst_CB'].getValue()
        rConst = self.widgets['rConst_CB'].getValue()
        pConst = self.widgets['pConst_CB'].getValue()
        sConst = self.widgets['sConst_CB'].getValue()


        clusterHandles = []
        if create_cluster:
            if cluster_group == 1: #each
                for obj in pm.selected():
                    c, hdl = pm.cluster(obj, name='%s_cluster'%obj.name())
                    clusterHandles.append(hdl)
                    
            elif cluster_group == 2: #all
                c, hdl = pm.cluster(pm.selected())
                clusterHandles.append(hdl)
        
        ctrls = []
        objects = clusterHandles or pm.selected()
        for i, obj in enumerate(objects):
            
            ctrlName = "%s_%s" %(obj.name(), ctrl_suffix)
            ctrl = obj.add_ctrl(name=ctrlName, point=tConst, orient=rConst, scale=sConst, parent=pConst)
            ctrls.append(ctrl)
            
            if hierarchy == 2 and i != 0: #selectionOrder
                pm.parent(ctrl, ctrls[ i-1 ])
            
            if create_offsetNode:
                ctrl.add_parent_group(suffix=offsetNode_suffix)
                
            if create_shape:
                ctrl.add_shape(shape=shape_type, axis=shape_axis)
 def setCage(self, node):
     meshes = pm.selected( type="transform" )
     if not meshes:
         return
     shape=meshes[-1].getShapes()[0]
     cmds.connectAttr(shape+".worldMesh[0]", node.name()+".cageMesh")
     self.updateUI()
示例#12
0
 def makeCube():
     squareCrv = dtLib.makeSquare()
     squareCrv2 = dtLib.makeSquare()
     squareCrv2.setRotation([90, 0,0])
     squareCrv2.setTranslation([0,0.5,-0.5])
     pm.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1)
     
     crvs = squareCrv2.getShapes()
     
     for current in crvs:
         pm.parent(current, squareCrv, relative=True, shape=True)
     pm.delete(squareCrv2)
     
     pm.select(squareCrv)
     dupCrv = pm.duplicate()
     dupCrv[0].setRotation([180, 0, 0])
     dupCrv[0].setTranslation([0,0,-1])
     pm.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1)
     crvs = dupCrv[0].getShapes()
     for current in crvs:
         pm.parent(current, squareCrv, relative=True, shape=True)
         
     pm.delete(dupCrv)
     #中央にピポットを移動
     pm.select(squareCrv)
     pm.xform(cp=True)
     return pm.selected()
示例#13
0
    def remove_cache_tag(self, *args):
        selection = pm.selected()
        if selection:
            for obj in selection:
                try:
                    if pm.objExists(obj + ".arc_renderable"):
                        pm.deleteAttr(obj, at='arc_renderable')
                        self.log.insertText("  %s%s\n" %('Remove arc_renderable Tag'.ljust(40, "."), obj))
                except:
                    self.log.insertText("  %s%s\n" %('Unable To Remove arc_renderable Tag'.ljust(40, "."), obj))                    

                try:                    
                    self.cacheSet.remove(obj)
                    self.tempSet.add(obj)
                except:
                    pass
                                
#===============================================================================
# 
# class CheckGeoTags(Check):
#     def __init__(self):
#         super(CheckGeoTags, self).__init__()
#         
#         self.main_button_label = "Geometry Tags"
#         self.options_label = "Geo Tags Options"
#         self.options = True
#         
#     def check(self, *args):
#         status = True
#         objs = []
#         log = "Checking Geometry Tags... \n"
# 
#         pm.select('md', hi=True)
#         all_geos = pm.ls(sl=True, type='mesh')
# 
#         attrs = ['objectName', 'arc_full_path', 'arc_master_path', 'tagName', 'arc_renderable']
# 
#         for geo in all_geos:
#             for attr in attrs:
#                 geo_attr = '%s.%s'%(geo, attr)
#                 if not pm.objExists(geo_attr):
#                     log += "  %s%s\n"%(geo_attr.ljust(40, '.'), "FAIL")
#                     status = False
#                     if geo not in objs:
#                         objs.append(geo)
# 
#         return [status, objs, log]
# 
#     def options_buttons(self, *args):
#         pm.button(label = "Add Tag", c=self.add_control_tag)
#         
#     def add_control_tag(self, *args):
#         selection = pm.selected()
#         if selection:
#             for obj in selection:
#                 pm.addAttr(obj, ln='ClientAnimCtrl', at="bool")
#                 print "Added ClientAnimCtrl tag to %s" %obj        
#         
#         
#===============================================================================
def convert_hierarchies_main(settings=SETTINGS_DEFAULT):
    nodes = pmc.selected(type='transform')
    if not nodes:
        pmc.warning('No transforms selected.')
        return
    new_roots = convert_hierarchies(nodes, settings)
    print 'Created:', ','.join([r.name() for r in new_roots])
示例#15
0
def copyPivot( *objs ):
    '''
    뒤에선택된 물체의 pivot을, 먼저선택된 물체의 pivot으로 맞춤
    @param objs: Transform Nodes
    @return: None
    @rtype: None
    '''
    tmp = []
    for obj in objs:
        if isinstance(obj,(list,tuple,set)):
            tmp.extend( list(obj) )
        else:
            tmp.append( obj )
    objs = tmp

    if not objs:
        objs = pm.selected(type='transform')

    if len(objs)<2 :
        pm.mel.error("Not enough objects selected.. exiting\n")

    if len(objs)>2 :
        pm.mel.warning("more than two objects selected.  Copying the pivot from the first object onto all the other objects..")

    objs = [ pm.PyNode(obj) for obj in objs ]

    # doIt
    pos = pm.xform( objs[0], q=True, ws=True, rp=True)
    objs[1].setPivots( pos, ws=True )
def rebuildDagPose():
    """
    Walks through bind pose data in selected skeleton and consolidates it down to one new bindPose node
    Directly inspired by Nathan Horne's NT_rebuildDagPose.mel script
    """

    dagPoses = set()
    connectedSkinClusters = set()
    selection = pmc.selected()
    joints = pmc.listRelatives(selection[0], path=True, allDescendents=True, type="joint")
    joints.insert(0, selection[0])

    for jnt in joints:
        dagPoses.update(jnt.listConnections(type="dagPose"))

    for dag in dagPoses:
        connectedSkinClusters.update(dag.listConnections(type="skinCluster"))

    pmc.delete(dagPoses)
    pmc.select(joints, replace=True)
    newDagPose = pmc.dagPose(save=True, selection=True, bindPose=True)

    print "New dagPose, {0}, created".format(newDagPose.shortName())

    for sc in connectedSkinClusters:
        print "Connecting {0}.message to {1}.bindPose".format(newDagPose.shortName(), sc.shortName())
        newDagPose.message.connect(sc.bindPose)
示例#17
0
文件: utils.py 项目: bohdon/boTools
def printSelection(longNames=True):
    """Print the selection in an organized, numbered list"""
    selList = pm.selected()
    print '\n//{0} Nodes Selected'.format(len(selList))
    nameMethod = None
    if longNames:
        nameMethod = 'longName'
    else:
        nameMethod = 'name'
    
    maxLen = 0
    for obj in selList:
        if hasattr(obj, nameMethod):
            name = getattr(obj, nameMethod)()
        else:
            name = obj.name()
        if len(name) > maxLen:
            maxLen = len(name)
    
    for i in range(len(selList)):
        obj = selList[i]
        typ = pm.nodeType(obj)
        if hasattr(obj, nameMethod):
            name = getattr(obj, nameMethod)()
        else:
            name = obj.name()
        print '{index:03}. {name:<{maxLen}} - {type}'.format(index=i, name=name, type=typ, maxLen=maxLen)
示例#18
0
def getSkinBones():
    aInfluences = []
    for oCurObj in pymel.selected():
        oSkinCluster = getSkinCluster(oCurObj)
        if oSkinCluster is not None:
            aInfluences += libSkinning.get_skin_cluster_influence_objects(oSkinCluster)
    pymel.select(aInfluences)
示例#19
0
def getSkinBones():
    aInfluences = []
    for oCurObj in pymel.selected():
        oSkinCluster = getSkinCluster(oCurObj)
        if oSkinCluster is not None:
            aInfluences += oSkinCluster.influenceObjects()
    pymel.select(aInfluences)
示例#20
0
def fixedSeed():
  sel = pm.selected()
  
  animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
  animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
    
  for attr in sel:
    animStartTime = pm.playbackOptions(animationStartTime=1, q=1)
    animEndTime = pm.playbackOptions(animationEndTime=1, q=1)
    
    xVal = attr.rotateX.get()
    yVal = attr.rotateY.get()
    zVal = attr.rotateZ.get()
  
    print animStartTime
    print animEndTime
    print xVal
    print yVal
    print zVal
      
    while animStartTime<=animEndTime:
      attr.rotateX.set(xVal+random.uniform(-.1,.1))
      attr.rotateY.set(yVal+random.uniform(-.1,.1))
      attr.rotateZ.set(zVal+random.uniform(-.1,.1))
      pm.setKeyframe(attribute="rotate", time=animStartTime)
      animStartTime+=1
示例#21
0
def insertFirstSelected( *args ):
    sel = pm.selected()
    if len(sel) > 0:
        pm.textField('input_inputCurve', edit = True, text = sel[0])
    else: 
        pm.textField('input_inputCurve', edit = True, text = 'Draw a curve, 1 Joint per CV.')
        pm.warning('Nothing is selected.')
示例#22
0
def init(discard=False):
    
    selection = pm.selected()
    if len(selection) != 1:
        print 'Must select one object'
    else:
        selection = selection[0]
        uuid = cmds.ls(selection.name(), uuid=True)[0]
        #bn = BridgedNode(uuid)
        #bn = BRIDGE_NODE
        if BRIDGE_NODE.uuid == None:
            BRIDGE_NODE.uuid = uuid
            BRIDGE_NODE.ingest()
        
        if discard:
            BRIDGE_NODE.erase_history()
        
        if BRIDGE_NODE.is_valid():
            if BRIDGE_NODE.has_history():
                print '> file has history. opening source.'
            else:
                BRIDGE_NODE.dump_geo()
                BRIDGE_NODE.dump_metadata()
        else:
            BRIDGE_NODE.dump_geo()
            BRIDGE_NODE.dump_metadata()

        open_port(PORT)
        BRIDGE_NODE.edit_in_app()
def getPoleVectorFromJoints(offset):
    """
    Creates pole vector locator from a selected set of joints
    """

    loc = getPoleVectorPosition(pmc.selected(), offset)
    loc.select(replace=True)
示例#24
0
文件: gui.py 项目: pritishd/PKD_Tools
 def lock_child(self):
     selection = pm.selected()
     child_locker = pm.createNode("transform", name="PKD_child_locker")
     child_joint = pm.listRelatives(self.joint)[0]
     pm.parentConstraint(child_locker, child_joint, maintainOffset=True)
     if selection:
         pm.select(selection)
示例#25
0
 def _actionAddPart(self, _cls):
     part = _cls(_input=pymel.selected())
     self.root.append(part)
     net = libSerialization.export_network(self.root) # Export part and only part
     pymel.select(net)
     self.updateData()
     self.updateUi()
示例#26
0
def GetExportTagFromSelected(Nodes=None, AsMetaData=True):
    """
    From selected or given Maya Nodes return all linked ExportTags as MExportTags
    This is backward compatible, all old Tags will return an MExport_Proxy object
    :param Nodes: Maya nodes to process, cmds or Pymel
    :param AsMetaData: bool
    :rtype: [`MExportTags`]
    """
    mTags = []
    found = False
    if not Nodes:
        Nodes = pCore.selected()
    if not issubclass(type(Nodes), list): Nodes = [Nodes]

    for node in Nodes:
        try:
            #see if we have a valid ExportTag already
            if 'MExportTag' in node.metaClass.get():
                mTags.append(eMetaData.MetaData(node))
        except:
            mData = eMetaData.MetaData.m_GetMetaData(node)
            if mData:
                _logger.debug(mData)
                for m in mData:
                    if issubclass(type(m), MExportTag):
                        mTags.append(m)
                        found = True
                        break
    return mTags
示例#27
0
def align_selected_joints_to_active_view(default_cam='persp'):
    sel = pymel.selected()
    cam = get_active_camera()
    if not cam:
        pymel.warning("Can't find active camera, will use {0}.".format(default_cam))
        cam = pymel.PyNode(default_cam)
    align_joints_to_view(sel, cam)
示例#28
0
def zero_out_bend(**kwargs):
    """
    Zero out all the bend joint
    Here we assume it already has a optimised rotate order
        - joint_list: (list) List of joint to zero out te bend
        - axis: (str) Which axis is the joint bending
        - rotate_order: (str) What is the current rotate order
    @return the rotate order
    """
    joint_list = libUtilities.pyList(kwargs.get("joint_list") or get_joint_children(pm.selected()[0]))
    libUtilities.freeze_rotation(joint_list)
    libUtilities.freeze_scale(joint_list)
    rotate_order = kwargs.get("rotate_order") or joint_list[0].rotateOrder.get(asString=True)
    target_axis = kwargs.get("axis", rotate_order[0])
    new_rotate_order = None
    if target_axis != rotate_order[0]:
        new_rotate_order = "{}{}{}".format(target_axis, rotate_order[0], rotate_order[2])
    pm.undoInfo(openChunk=True)
    for joint in joint_list:
        for rotate_axis in rotate_order:
            if rotate_axis != target_axis:
                joint.attr("jointOrient{}".format(rotate_axis.upper())).set(0)
        if new_rotate_order:
            joint.rotateOrder.set(new_rotate_order)
    pm.undoInfo(closeChunk=True)
    return new_rotate_order
示例#29
0
文件: ui.py 项目: kudiaborm/mkScripts
    def assignToSelected(self, layerIndex, channelIndex):
        for obj in pm.selected():
            materialChannelList = [".diffuse", ".diffuse_weight", ".transparency", ".reflectivity", ".refl_gloss",
                                   ".cutout_opacity", ".bump", ".normal"]
            shapeNode = pm.listRelatives(obj, c=True, s=True)
            shadingGrp = pm.listConnections(shapeNode, type="shadingEngine")[0]
            mat = list(set(
                pm.listConnections(shadingGrp, type=['mia_material_x', 'mia_material_x_passes', 'lambert', 'phong'])))[
                0]
            try:
                currentItem = self.layeredTextureTreeModel.itemFromIndex(layerIndex[0]).node
            except:
                pm.cmds.warning("Please select a texture from the list.")
            try:
                if channelIndex < 6:
                    outAttr = ".outColor"
                    if channelIndex != 0:
                        outAttr = ".outAlpha"

                    currentItemOutColor = currentItem + outAttr
                    materialInput = mat + materialChannelList[channelIndex]
                    pm.connectAttr(currentItemOutColor, materialInput, f=True)
                elif channelIndex == 6:
                    createBump(currentItem, mat)
                else:
                    createBump(currentItem, mat, normal=True)
            except:
                pm.cmds.warning("Could not connect materials to " + obj)
示例#30
0
def createMiddleCrv( curves=[], parameter=0.5 ):
    '''
    update : 2015-04-24
    '''
    if curves:
        curves = pm.select(curves)
    curves = pm.selected()
    if not curves:
        raise    

    surface, loft = pm.loft( 
        curves, 
        ch           = True, 
        uniform      = True, 
        close        = False, 
        autoReverse  = True, 
        degree       = 3, 
        sectionSpans = 1, 
        range        = False, 
        polygon=0,  # 0: nurbs surface 
                    # 1: polygon (use nurbsToPolygonsPref to set the parameters for the conversion) 
                    # 2: subdivision surface (use nurbsToSubdivPref to set the parameters for the conversion) 
                    # 3: Bezier surface 
                    # 4: subdivision surface solid (use nurbsToSubdivPref to set the parameters for the conversion) 
        reverseSurfaceNormals = True )

    dupCrv, crvFromSurf = pm.duplicateCurve( surface.getShape().v[ parameter ], ch=True, range=False, local=False )
    pm.delete( surface, loft, crvFromSurf )

    dupCrv = pm.PyNode( dupCrv )
    dupCrv.rename('middleCrv#')   

    return dupCrv
示例#31
0
 def copyShape(mirror=False):
     sel = selected()
     if len(sel) > 1:
         controller.copyShape(sel[0], sel[1], mirror=mirror)
示例#32
0
    def scaleCvs(val):
        scaleFactor = [val] * 3

        for obj in selected():
            for shape in core.shape.getShapes(obj):
                scale(shape.cv, scaleFactor, r=True, os=True)
示例#33
0
 def ScaleVertex(self, scale):
     sub = pm.selected()
     adb.scaleVertex(scale, subject=sub)
示例#34
0
def exportSkin(filePath=None, objs=None, *args):
    if not objs:
        if pm.selected():
            objs = pm.selected()
        else:
            pm.displayWarning("Please Select One or more objects")
            return False

    packDic = {"objs": [], "objDDic": [], "bypassObj": []}

    if not filePath:

        f2 = "jSkin ASCII  (*{});;gSkin Binary (*{})".format(
            FILE_JSON_EXT, FILE_EXT)
        f3 = ";;All Files (*.*)"
        fileFilters = f2 + f3
        startDir = pm.workspace(q=True, rootDirectory=True)
        filePath = pm.fileDialog2(dialogStyle=2,
                                  fileMode=0,
                                  startingDirectory=startDir,
                                  fileFilter=fileFilters)
        if filePath:
            filePath = filePath[0]

        else:
            return False

    if (not filePath.endswith(FILE_EXT)
            and not filePath.endswith(FILE_JSON_EXT)):
        # filePath += file_ext
        pm.displayWarning("Not valid file extension for: {}".format(filePath))
        return

    _, file_ext = os.path.splitext(filePath)
    # object parsing
    for obj in objs:
        skinCls = getSkinCluster(obj)
        if not skinCls:
            pm.displayWarning(obj.name() +
                              ": Skipped because don't have Skin Cluster")
            pass
        else:
            # start by pruning by a tiny amount. Enough to not make a noticeable
            # change to the skin, but it will remove infinitely small weights.
            # Otherwise, compressing will do almost nothing!
            if isinstance(obj.getShape(), pm.nodetypes.Mesh):
                # TODO: Implement pruning on nurbs. Less straight-forward
                pm.skinPercent(skinCls, obj, pruneWeights=0.001)

            dataDic = {
                'weights': {},
                'blendWeights': [],
                'skinClsName': "",
                'objName': "",
                'nameSpace': "",
                'vertexCount': 0,
                'skinDataFormat': 'compressed',
            }

            dataDic["objName"] = obj.name()
            dataDic["nameSpace"] = obj.namespace()

            collectData(skinCls, dataDic)

            packDic["objs"].append(obj.name())
            packDic["objDDic"].append(dataDic)
            exportMsg = "Exported skinCluster {} ({} influences, {} points) {}"
            pm.displayInfo(
                exportMsg.format(skinCls.name(),
                                 len(dataDic['weights'].keys()),
                                 len(dataDic['blendWeights']), obj.name()))

    if packDic["objs"]:
        with open(filePath, 'w') as fp:
            if filePath.endswith(FILE_EXT):
                pickle.dump(packDic, fp, pickle.HIGHEST_PROTOCOL)
            else:
                json.dump(packDic, fp, indent=4, sort_keys=True)

        return True
示例#35
0
 def selectCVs():
     sel = selected()
     select(cl=True)
     for obj in sel:
         for shape in core.shape.getShapes(obj):
             select(shape.cv, add=True)
示例#36
0
def createOffsetForSelected():
    """
    Create an offset group for the selected nodes
    """
    pm.select([createOffsetGroup(s) for s in pm.selected(type='transform')])
示例#37
0
def orient_joint(**kwargs):
    """
    Orient the joint
    @param kwargs: Takes the following keyword arguments
                    - joint (node): the node which will be process. It picks up the default node by default
                    - up (str): in which direction do move up and down the joint
                    - forward (str): in which direction do you want to move it forward/back
                    - flip_forward (bool): whether the joint forward direction will be reversed
                    - flip up (bool): whether the joint up and down will be reversed
                    - details (bool)
    @return the rotate order
    """
    # Get all the keyword arguements
    selection = pm.selected() or []
    try:
        target_joint = libUtilities.force_pynode(kwargs.get("joint") or pm.selected()[0])
    except IndexError:
        pm.confirmDialog(title="User Error",
                         message="{: <22}".format("Please select a joint"),
                         icon="critical")
        return
    up = kwargs.get("up", "y").lower()
    forward = kwargs.get("forward", "z").lower()
    flip_forward = kwargs.get("flip_forward", False)
    flip_up = kwargs.get("flip_up", False)
    details = kwargs.get("details", False)

    # Get the preferred rotation axis
    prefered_axis = "{}{}".format(up, forward)

    # Get the joint mapping data
    reverse_lookup, rotate_secondary_axis, detailed_info = _get_joint_orient_info()
    rotate_order = reverse_lookup[prefered_axis]
    pm.undoInfo(openChunk=True)
    children_joints = get_joint_children(target_joint)
    libUtilities.freeze_rotation([target_joint] + children_joints)
    libUtilities.freeze_scale([target_joint] + children_joints)
    secondary_orient = rotate_secondary_axis[rotate_order]
    if children_joints:
        if flip_forward:
            secondary_orient = secondary_orient.replace("up", "down")
        pm.joint(target_joint,
                 edit=True,
                 zeroScaleOrient=True,
                 children=True,
                 orientJoint=rotate_order,
                 secondaryAxisOrient=secondary_orient)

        if flip_up:
            joints = [target_joint]
            if len(children_joints) > 1:
                joints = reversed(joints + children_joints[:-1])
            for flip_joint in joints:
                childJoint = pm.listRelatives(flip_joint)[0]
                childJoint.setParent(world=True)
                flip_joint.attr('r{}'.format(forward)).set(180)
                libUtilities.freeze_rotation([flip_joint])
                libUtilities.freeze_scale([flip_joint])
                childJoint.setParent(flip_joint)
        children_joints[-1].jointOrient.set(0, 0, 0)

        if details:
            for key in ["Pitch/Bend Forward", "Yaw/Twist", "Forward", "Up"]:
                print "{} : {}".format(key, detailed_info[rotate_order][key])
            if flip_up:
                print "The joint chain was flipped up in the end"
        pm.select(selection)

    all_joints = [target_joint] + children_joints

    # Calculate the last axis to resolves
    last_axis = (set("xyz") - set(prefered_axis)).pop()
    preferred_rotate_order = "{}{}{}".format(last_axis, forward, up)

    # Set the rotate order
    set_rotate_order(preferred_rotate_order, all_joints)
    pm.undoInfo(closeChunk=True)
    return preferred_rotate_order
    def transfer_deformer_weights(self,
                                  geo_source,
                                  geo_target=None,
                                  deformer_source=None,
                                  deformer_target=None,
                                  surface_association="closestPoint"):
        """
        Copies the weight map of a deformer of an object to the deformer of another object.
        :param geo_source: Source Shape
        :param geo_target: Target Shape
        :param deformer_source: Source Deformer
        :param deformer_target: Target Deformer
        :param surface_association: Surface Association. Valid values: closestPoint, rayCast, or closestComponent.
        """
        assert geo_source and deformer_source and deformer_target, \
            "select a source and target geometry and then the source and target deformers"

        previous_selection = pm.selected()

        if not geo_target:
            geo_target = geo_source

        self.progress_bar_init()
        self.progress_bar_next()

        source_weight_list = self.get_weight_list(deformer_source, geo_source)
        if not source_weight_list:
            pm.warning(
                "The deformer {} does not have the weight list for {}".format(
                    deformer_source, geo_source))
            self.progress_bar_ends(message="Finished with errors!")
            return

        target_weight_list = self.get_weight_list(deformer_target, geo_target)
        if not target_weight_list:
            pm.warning(
                "The deformer {} does not have the weight list for {}".format(
                    deformer_target, geo_target))
            self.progress_bar_ends(message="Finished with errors!")
            return

        self.initialize_weight_list(target_weight_list, geo_target)

        self.progress_bar_next()
        tmp_source = pm.duplicate(geo_source)[0]
        tmp_target = pm.duplicate(geo_target)[0]
        pm.rename(tmp_source, tmp_source.nodeName() + "_cdw_DUP")
        pm.rename(tmp_target, tmp_target.nodeName() + "_cdw_DUP")
        tmp_source.v.set(True)
        tmp_target.v.set(True)

        self.progress_bar_next()
        pm.select(clear=True)
        l_jnt = list()
        l_jnt.append(pm.joint(n="jnt_tmpA_01", p=[0, 0, 0]))
        l_jnt.append(pm.joint(n="jnt_tmpA_02", p=[0, 1, 0]))
        skin_source = pm.skinCluster(l_jnt, tmp_source, nw=1)
        skin_target = pm.skinCluster(l_jnt, tmp_target, nw=1)

        self.progress_bar_next()
        skin_source.setNormalizeWeights(0)
        pm.skinPercent(skin_source, tmp_source, nrm=False, prw=100)
        skin_source.setNormalizeWeights(True)
        n_points = len(geo_source.getShape().getPoints())
        [
            skin_source.wl[i].w[0].set(source_weight_list.weights[i].get())
            for i in range(n_points)
        ]
        [
            skin_source.wl[i].w[1].set(1.0 -
                                       source_weight_list.weights[i].get())
            for i in range(n_points)
        ]

        self.progress_bar_next()
        pm.copySkinWeights(ss=skin_source,
                           ds=skin_target,
                           nm=True,
                           sa=surface_association)

        self.progress_bar_next()
        deformer_target_weights = [
            v for v in skin_target.getWeights(tmp_target, 0)
        ]
        [
            target_weight_list.weights[i].set(val)
            for i, val in enumerate(deformer_target_weights)
        ]

        self.progress_bar_next()
        pm.delete([tmp_source, tmp_target, l_jnt])
        pm.select(previous_selection)

        self.progress_bar_next()
        self.progress_bar_ends(message="Finished successfully!")
示例#39
0
def postSpring(dist=5, hostUI=False, hostUI2=False, invertX=False):
    """Create the dynamic spring rig.

    This spring system use the mgear_spring node
    And transfer the position spring
    to rotation spring using an aim constraint.

    Note:
        The selected chain of object should be align with the X axis.

    Args:
        dist (float): The distance of the position spring.
        hostUI (dagNode): The spring active and intensity channel host.
        hostUI2 (dagNode): The daping and stiffness channel host for each
            object in the chain.
        invertX (bool): reverse the direction of the x axis.

    """
    oSel = pm.selected()

    if not hostUI2:
        hostUI2 = oSel[0]

    aSpring_active = attribute.addAttribute(
        hostUI2, "spring_active_%s" % oSel[0].name(), "double", 1.0,
        "___spring_active_______%s" % oSel[0].name(),
        "spring_active_%s" % oSel[0].name(), 0, 1)

    aSpring_intensity = attribute.addAttribute(
        hostUI2, "spring_intensity_%s" % oSel[0].name(), "double", 1.0,
        "___spring_intensity_______%s" % oSel[0].name(),
        "spring_intensity_%s" % oSel[0].name(), 0, 1)

    if invertX:
        dist = dist * -1
        # aim constraint
        aimAxis = "-xy"
    else:
        # aim constraint
        aimAxis = "xy"

    for obj in oSel:

        oParent = obj.getParent()

        oNpo = pm.PyNode(
            pm.createNode("transform",
                          n=obj.name() + "_npo",
                          p=oParent,
                          ss=True))
        oNpo.setTransformation(obj.getMatrix())
        pm.parent(obj, oNpo)

        oSpring_cns = pm.PyNode(
            pm.createNode("transform",
                          n=obj.name() + "_spr_cns",
                          p=oNpo,
                          ss=True))
        oSpring_cns.setTransformation(obj.getMatrix())
        pm.parent(obj, oSpring_cns)

        oSpringLvl = pm.PyNode(
            pm.createNode("transform",
                          n=obj.name() + "_spr_lvl",
                          p=oNpo,
                          ss=True))
        oM = obj.getTransformation()
        oM.addTranslation([dist, 0, 0], "object")
        oSpringLvl.setTransformation(oM.asMatrix())

        oSpringDriver = pm.PyNode(
            pm.createNode("transform",
                          n=obj.name() + "_spr",
                          p=oSpringLvl,
                          ss=True))

        try:
            defSet = pm.PyNode("rig_PLOT_grp")
            pm.sets(defSet, add=oSpring_cns)
        except TypeError:
            defSet = pm.sets(name="rig_PLOT_grp")
            pm.sets(defSet, remove=obj)
            pm.sets(defSet, add=oSpring_cns)

        # adding attributes:
        if not hostUI:
            hostUI = obj

        aSpring_damping = attribute.addAttribute(
            hostUI, "spring_damping_%s" % obj.name(), "double", .5,
            "damping_%s" % obj.name(), "damping_%s" % obj.name(), 0, 1)

        aSpring_stiffness_ = attribute.addAttribute(
            hostUI, "spring_stiffness_%s" % obj.name(), "double", .5,
            "stiffness_%s" % obj.name(), "stiffness_%s" % obj.name(), 0, 1)

        cns = applyop.aimCns(oSpring_cns, oSpringDriver, aimAxis, 2, [0, 1, 0],
                             oNpo, False)

        # change from fcurves to spring
        pb_node = pm.createNode("pairBlend")

        pm.connectAttr(cns + ".constraintRotateX", pb_node + ".inRotateX2")
        pm.connectAttr(cns + ".constraintRotateY", pb_node + ".inRotateY2")
        pm.connectAttr(cns + ".constraintRotateZ", pb_node + ".inRotateZ2")
        pm.setAttr(pb_node + ".translateXMode", 2)
        pm.setAttr(pb_node + ".translateYMode", 2)
        pm.setAttr(pb_node + ".translateZMode", 2)

        pm.connectAttr(pb_node + ".outRotateX",
                       oSpring_cns + ".rotateX",
                       f=True)
        pm.connectAttr(pb_node + ".outRotateY",
                       oSpring_cns + ".rotateY",
                       f=True)
        pm.connectAttr(pb_node + ".outRotateZ",
                       oSpring_cns + ".rotateZ",
                       f=True)

        pm.setKeyframe(oSpring_cns, at="rotateX")
        pm.setKeyframe(oSpring_cns, at="rotateY")
        pm.setKeyframe(oSpring_cns, at="rotateZ")

        # add sprint op
        springOP = applyop.gear_spring_op(oSpringDriver)

        # connecting attributes
        pm.connectAttr(aSpring_active, pb_node + ".weight")
        pm.connectAttr(aSpring_intensity, springOP + ".intensity")
        pm.connectAttr(aSpring_damping, springOP + ".damping")
        pm.connectAttr(aSpring_stiffness_, springOP + ".stiffness")
示例#40
0
import maya.cmds as cmds
import json
import pdb


def get_object_shaderset(obj):
    shaders, sg = [], None
    sgs = obj.shadingGroups()
    if sgs:
        sg = sgs[0]
        for atrname in ('surfaceShader', 'miMaterialShader'):
            atr = getattr(sg, atrname, None)
            shaders.extend(atr.connections()) if atr else None
            pdb.set_trace()
    return shaders, sg


res = [x.node() for x in pmc.selected()]
shape = res[0].getShape()
t = type(shape)

# ss = get_object_shaderset(res[0])
# print ss

# print t
#
# sgs = pmc.ls(typ=pmc.nt.ShadingEngine)
# print sgs
#
# cns = sgs[1].dagSetMembers.connections()
# print cns
示例#41
0
 def copyColor_(self):
     sel = selected()
     if len(sel) > 1:
         for other in sel[1:]:
             controllerShape.copyColors(sel[0], other)
示例#42
0
def get_top_level_nodes():
    assemblies = pm.ls(assemblies=True)
    pm.select(pm.listCameras(), replace=True)
    cameras = pm.selected()
    pm.select([])
    return [assembly for assembly in assemblies if assembly not in cameras]
示例#43
0
def rope(DEF_nb=10,
         ropeName="rope",
         keepRatio=False,
         lvlType="transform",
         oSel=None):
    """Create rope rig based in 2 parallel curves.

    Args:
        DEF_nb (int): Number of deformer joints.
        ropeName (str): Name for the rope rig.
        keepRatio (bool): If True, the deformers will keep the length
            position when the curve is stretched.
    """
    if oSel and len(oSel) == 2 and isinstance(oSel, list):
        oCrv = oSel[0]
        if isinstance(oCrv, str):
            oCrv = pm.PyNode(oCrv)
        oCrvUpV = oSel[1]
        if isinstance(oCrvUpV, str):
            oCrvUpV = pm.PyNode(oCrvUpV)
    else:
        if len(pm.selected()) != 2:
            print "You need to select 2 nurbsCurve"
            return
        oCrv = pm.selected()[0]
        oCrvUpV = pm.selected()[1]
    if (oCrv.getShape().type() != "nurbsCurve"
            or oCrvUpV.getShape().type() != "nurbsCurve"):
        print "One of the selected objects is not of type: 'nurbsCurve'"
        print oCrv.getShape().type()
        print oCrvUpV.getShape().type()
        return
    if keepRatio:
        arclen_node = pm.arclen(oCrv, ch=True)
        alAttr = pm.getAttr(arclen_node + ".arcLength")
        muldiv_node = pm.createNode("multiplyDivide")
        pm.connectAttr(arclen_node + ".arcLength", muldiv_node + ".input1X")
        pm.setAttr(muldiv_node + ".input2X", alAttr)
        pm.setAttr(muldiv_node + ".operation", 2)
        pm.addAttr(oCrv, ln="length_ratio", k=True, w=True)
        pm.connectAttr(muldiv_node + ".outputX", oCrv + ".length_ratio")

    root = pm.PyNode(pm.createNode(lvlType, n=ropeName + "_root", ss=True))
    step = 1.000 / (DEF_nb - 1)
    i = 0.000
    shds = []
    for x in range(DEF_nb):

        oTransUpV = pm.PyNode(pm.createNode(
            lvlType, n=ropeName + str(x).zfill(3) + "_upv", p=root, ss=True))

        oTrans = pm.PyNode(pm.createNode(
            lvlType, n=ropeName + str(x).zfill(3) + "_lvl", p=root, ss=True))

        cnsUpv = applyop.pathCns(
            oTransUpV, oCrvUpV, cnsType=False, u=i, tangent=False)

        cns = applyop.pathCns(oTrans, oCrv, cnsType=False, u=i, tangent=False)

        if keepRatio:
            muldiv_node2 = pm.createNode("multiplyDivide")
            condition_node = pm.createNode("condition")
            pm.setAttr(muldiv_node2 + ".operation", 2)
            pm.setAttr(muldiv_node2 + ".input1X", i)
            pm.connectAttr(oCrv + ".length_ratio", muldiv_node2 + ".input2X")
            pm.connectAttr(muldiv_node2 + ".outputX",
                           condition_node + ".colorIfFalseR")
            pm.connectAttr(muldiv_node2 + ".outputX",
                           condition_node + ".secondTerm")
            pm.connectAttr(muldiv_node2 + ".input1X",
                           condition_node + ".colorIfTrueR")
            pm.connectAttr(muldiv_node2 + ".input1X",
                           condition_node + ".firstTerm")
            pm.setAttr(condition_node + ".operation", 4)

            pm.connectAttr(condition_node + ".outColorR", cnsUpv + ".uValue")
            pm.connectAttr(condition_node + ".outColorR", cns + ".uValue")

        cns.setAttr("worldUpType", 1)
        cns.setAttr("frontAxis", 0)
        cns.setAttr("upAxis", 1)

        pm.connectAttr(oTransUpV.attr("worldMatrix[0]"),
                       cns.attr("worldUpMatrix"))
        shd = rigbits.addJnt(oTrans)
        shds.append(shd[0])
        i += step

    return shds
示例#44
0
 def selectCVs():
     sel = selected()
     select(cl=True)
     for obj in sel:
         for shape in pdil.shape.getNurbsShapes(obj):
             select(shape.cv, add=True)
示例#45
0
 def transferShape(mirror=False):
     sel = selected()
     if len(sel) > 1:
         for dest in sel[1:]:
             controllerShape.copyShape(sel[0], dest, mirror=mirror)
示例#46
0
 def RotateVertex(self, scale):
     sub = pm.selected()
     adb.rotateVertex(scale, subject=sub)
示例#47
0
    def equalize_node_speed(cls):
        """Equalizes the node animation to keep the speed constant
        """
        #
        # This only works for position
        #
        # To make it also work with Rotation you need to do some nasty stuff,
        # like creating the camera transformation frame with two locators, one
        # showing the up or the local y-axis and other showing the z-axis of
        # the camera, trace them with a curve, smooth them as you did with the
        # position, then read them back create local y and z axis and set the
        # euler rotations.
        #
        # For now I don't need it. So I'll code it later on.
        #
        start_frame = int(pm.playbackOptions(q=1, min=1))
        end_frame = int(pm.playbackOptions(q=1, max=1))

        selected_node = pm.selected()[0]

        # duplicate the input graph
        node = pm.duplicate(selected_node, un=1, rr=1)[0]
        node.rename("%s_Equalized#" % selected_node.name())

        # create speed attribute
        if not node.hasAttr("speed"):
            node.addAttr("speed", at="double")
        pm.currentTime(start_frame)
        pm.setKeyframe(node.speed)

        prev_pos = node.t.get()

        pos_data = []
        rot_data = []

        for i in range(start_frame, end_frame + 1):
            pm.currentTime(i)
            current_pos = node.t.get()
            pos_data.append(current_pos)
            rot_data.append(node.r.get())
            speed = (current_pos - prev_pos).length()
            prev_pos = current_pos
            node.speed.set(speed)
            pm.setKeyframe(node.speed)

        camera_path = pm.curve(d=3, p=pos_data)
        camera_path_curve = camera_path.getShape()

        pm.rebuildCurve(camera_path_curve,
                        ch=1,
                        rpo=1,
                        rt=0,
                        end=1,
                        kr=0,
                        kcp=0,
                        kep=1,
                        kt=0,
                        s=end_frame - start_frame + 1,
                        d=3,
                        tol=0.01)

        curve_cv_positions = camera_path_curve.getCVs()

        # pop the unnecessary CVs
        curve_cv_positions.pop(1)
        curve_cv_positions.pop(-2)

        prev_pos = curve_cv_positions[0]
        for i, j in enumerate(range(start_frame, end_frame)):
            pm.currentTime(j)
            current_pos = curve_cv_positions[i]
            node.t.set(curve_cv_positions[i])
            node.speed.set((current_pos - prev_pos).length())
            pm.setKeyframe(node.speed)
            prev_pos = current_pos
示例#48
0
def disableColorOverrideForSelected():
    for node in pm.selected():
        pulse.nodes.disableColorOverride(node)
示例#49
0
 def update(self):
     if selected():
         self._colorChangeObjs = selected()
示例#50
0
    def ui(self):
        template = pm.uiTemplate('ExampleTemplate', force=True)
        template.define(pm.button, width=200, height=25)
        template.define(pm.frameLayout,
                        borderVisible=False,
                        labelVisible=False)

        with template:
            with pm.formLayout():
                pm.dockControl("adb_Module", content=self.win, a="left")
                with pm.columnLayout(adj=True, rs=1):
                    with pm.columnLayout(adj=True, rs=4):
                        self.docString = pm.checkBox(l='Doc String')
                    with pm.frameLayout(cll=True,
                                        bgc=(0.202, 0.202, 0.202),
                                        labelVisible=True,
                                        cl=False,
                                        label="INFORMATION"):
                        with pm.columnLayout(adj=True, rs=4):
                            pm.button(label="Print List",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(adb.List))
                            pm.button(label="Print Type",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self.Type))
                            pm.button(label="Print Type PyMel",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self.TypePymel))

                    with pm.frameLayout(cll=True,
                                        bgc=(0.202, 0.202, 0.202),
                                        labelVisible=True,
                                        cl=False,
                                        label="RIGGING"):
                        with pm.columnLayout(adj=True, rs=4):
                            pm.button(label="Pv Guide",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self._pvGuide))
                            pm.button(label="Find Constraint Driver",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self.consDriver))
                            pm.button(label="Find Constraint Target",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self.consTarget))
                            pm.button(label="DrivenKeys to Remap Value",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self.DkToRv))
                            pm.button(label="Rivet From Face",
                                      backgroundColor=colordic['grey1'],
                                      c=lambda *args: adbRivet.
                                      rivet_from_faces(scale=0.2))
                            pm.button(label="Sticky From Face",
                                      backgroundColor=colordic['grey1'],
                                      c=lambda *args: adbRivet.
                                      sticky_from_faces(scale=0.2))

                            def proxyPlane(axis):
                                if axis == "                       - X AXIS -":
                                    adbProxy.plane_proxy(
                                        pm.selected(), 'proxy_plane', 'x')
                                elif axis == "                       - Y AXIS -":
                                    adbProxy.plane_proxy(
                                        pm.selected(), 'proxy_plane', 'y')
                                elif axis == "                       - Z AXIS -":
                                    adbProxy.plane_proxy(
                                        pm.selected(), 'proxy_plane', 'z')
                                elif axis == "               - Create Proxy Plane -":
                                    pass
                                else:
                                    pm.warning('Choice None Existant')

                            pm.optionMenu(w=200, h=30, cc=proxyPlane)
                            pm.menuItem(
                                label="               - Create Proxy Plane -")
                            pm.menuItem(
                                label="                       - X AXIS -")
                            pm.menuItem(
                                label="                       - Y AXIS -")
                            pm.menuItem(
                                label="                       - Z AXIS -")

                            def mirrorChoice(axis):
                                if axis == "                       - X AXIS -":
                                    adbTransform.Transform(
                                        pm.selected()).mirror(axis='x')
                                elif axis == "                       - Y AXIS -":
                                    adbTransform.Transform(
                                        pm.selected()).mirror(axis='y')
                                elif axis == "                       - Z AXIS -":
                                    adbTransform.Transform(
                                        pm.selected()).mirror(axis='z')
                                elif axis == "               - Choose Axis Mirror -":
                                    pass
                                else:
                                    pm.warning('Choice None Existant')

                            pm.optionMenu(w=200, h=30, cc=mirrorChoice)
                            pm.menuItem(
                                label="               - Choose Axis Mirror -")
                            pm.menuItem(
                                label="                       - X AXIS -")
                            pm.menuItem(
                                label="                       - Y AXIS -")
                            pm.menuItem(
                                label="                       - Z AXIS -")

                        with pm.rowLayout(adj=True, numberOfColumns=2):
                            pm.button(label="Get Node Type",
                                      backgroundColor=colordic['green3'],
                                      c=pm.Callback(self.NodeType),
                                      w=20,
                                      h=25)
                            self.nodeName = pm.textField(
                                pht="Name the animation node",
                                tx='animCurve',
                            )
                        with pm.columnLayout(adj=True, rs=4):
                            pm.button(label="DrivenKeys to Remap Value",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self.DkToRv))

                        pm.separator(h=2)

                        with pm.rowLayout(adj=True, numberOfColumns=1):
                            pm.text(
                                label="Follicules Options",
                                h=20,
                            )

                        with pm.rowLayout(adj=True, numberOfColumns=4):
                            pm.text(label="Number")
                            self.folli = pm.floatField(v=5,
                                                       precision=1,
                                                       showTrailingZeros=0)
                            pm.text(label=" Radius ")
                            self.radius = pm.floatField(v=1,
                                                        precision=2,
                                                        showTrailingZeros=0)

                        self.folli_ctrl = pm.checkBox(l='With Controls',
                                                      v=True)
                        pm.button(label="Create Follicules",
                                  backgroundColor=colordic['grey1'],
                                  c=pm.Callback(self.Folli))
                        pm.button(label="Add Controls",
                                  backgroundColor=colordic['grey1'],
                                  c=pm.Callback(self._addControls))

                    with pm.frameLayout(cll=True,
                                        bgc=(0.202, 0.202, 0.202),
                                        labelVisible=True,
                                        cl=False,
                                        label="OUTPUT WINDOW"):
                        with pm.columnLayout(adj=True, rs=5):
                            pm.text(label="Output Window", h=20)
                            self.outputWin = pm.textScrollList(w=150, h=60)
                            pm.button(
                                label="Refresh",
                                backgroundColor=colordic['grey2'],
                                c=lambda *args: pm.textScrollList(
                                    self.outputWin, edit=True, removeAll=True),
                                h=25)

                    with pm.frameLayout(cll=True,
                                        bgc=(0.202, 0.202, 0.202),
                                        labelVisible=True,
                                        cl=False,
                                        label="SKINNING"):
                        with pm.columnLayout(adj=True, rs=4):
                            pm.button(label="Reset Skin",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(adb.resetSkin))
                            pm.button(label="Replace Lattice",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(
                                          adb.find_and_replace_lattices))
                            pm.button(label="Blend Two Groups",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self._blend2grps))
                            pm.button(label="Wrap",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self._wrap))
                            pm.button(label="Wrap SetUp",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self._wrapSetup))

                    with pm.frameLayout(cll=True,
                                        bgc=(0.202, 0.202, 0.202),
                                        labelVisible=True,
                                        cl=False,
                                        label="CONTROLS"):
                        with pm.columnLayout(adj=True, rs=4):
                            pm.button(label="Get Curve Information",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(adb.GetCurveShape))
                            pm.button(label="Combine Shapes",
                                      backgroundColor=colordic['grey1'],
                                      c=lambda *agrs: adb.CombineShape(
                                          oNurbs=pm.selected()))
                            pm.button(label="Replace Shape",
                                      backgroundColor=colordic['grey1'],
                                      c=pm.Callback(self._ReplaceShape))
示例#51
0
def unpairSelected():
    for s in pm.selected():
        unpairMirrorNode(s)
示例#52
0
def pairSelected():
    sel = pm.selected()
    if len(sel) == 2:
        pairMirrorNodes(sel[0], sel[1])
示例#53
0
def setOverrideColorForSelected(color):
    """
    Set the display override color for the selected nodes
    """
    for node in pm.selected():
        pulse.nodes.setOverrideColor(node, color)
示例#54
0
 def copyColor():
     sel = selected()
     if len(sel) > 1:
         controller.copyColors(sel[0], sel[1])
示例#55
0
def matchJointRotationToOrientForSelected(preserveChildren=True):
    sel = pm.selected(type='joint')
    for node in sel:
        matchJointRotationToOrient(node, preserveChildren)
示例#56
0
import pymel.core as pm

selection = pm.selected()

for ctrl in selection:
    # Test whether the element is a controller
    try:
        pm.getAttr(str(ctrl) + ".childJoint")
    except:
        continue
    else:
        pm.xform(ctrl,
                 translation=[0, 0, 0],
                 rotation=[0, 0, 0],
                 objectSpace=True)
        constraints = pm.listRelatives(ctrl,
                                       children=True,
                                       type=('orientConstraint',
                                             'parentConstraint'))
        for constraint in constraints:
            parents = pm.listConnections(constraint,
                                         source=True,
                                         type='transform')
            ctrlParent = None
            for parent in parents:
                if str(parent) != ctrl and str(parent) != str(constraint):
                    ctrlParent = parent
                    break
            pm.parentConstraint(str(ctrlParent),
                                str(constraint),
                                e=True,
示例#57
0
def unlinkSelected():
    for s in pm.selected():
        pulse.links.unlink(s)
示例#58
0
 def __init__(self, parent=None):
     super(componentMainSettings, self).__init__()
     # the inspectSettings function set the current selection to the
     # component root before open the settings dialog
     self.root = pm.selected()[0]
示例#59
0
    def scaleCvs(val):
        #scaleFactor = [val] * 3  # Scale factor needs to be a 3 vector for all axes.

        for obj in selected():
            controllerShape.scaleAllCVs(obj, val)
示例#60
0

def walkLeft(node, add=False, multi=False):
    """Walk left

    Arguments:
        node (dagNode or list of dagNode): the starting object for the
            pickwalk
        add (bool, optional): If True add to selection
        multi (bool, optional): If true, selects all the siblings

    """
    _walk(node, "left", add, multi)


def walkRight(node, add=False, multi=False):
    """Walk right

    Arguments:
        node (dagNode or list of dagNode): the starting object for the
            pickwalk
        add (bool, optional): If True add to selection
        multi (bool, optional): If true, selects all the siblings

    """
    _walk(node, "right", add, multi)


if __name__ == "__main__":
    walkUp(pm.selected())