예제 #1
0
    def snapVertsToGrid(cls, log=False):
        originalSelection = pm.ls(selection=True, flatten=True)
        pm.mel.eval('ConvertSelectionToVertices;')
        selVerts = pm.ls(selection=True, flatten=True)
        #objectSelection = pm.ls(selection=True, shapes=True )

        #selObjs = originalSelection[:]  ## copy the list
        #selVerts = pm.polyListComponentConversion(
        #    fromFace=True, fromVertex=True, fromEdge=True,
        #    fromVertexFace=True,
        #    toVertex=True )
        #
        #selVerts =

        spacing = cls.getSpacing()

        for v in selVerts:
            if isinstance(v, pm.MeshVertex):
                pW = v.getPosition(space='world')
                p = pW.homogenize()  ## Turn it into simply coords

                #print( type(p.x)  )
                def onGrid(n, s):
                    return (spacing * float(round(n / float(s))))

                p.x = onGrid(p.x, spacing)
                p.y = onGrid(p.y, spacing)
                p.z = onGrid(p.z, spacing)
                #print( p.x, p.y, p.z )
                v.setPosition(p.homogenize(), space='world')
                #print p.x,p.y,p.z
                #print( help(p)  )
                #break
        pm.select(originalSelection)
 def snapVertsToGrid(cls, log=False):
     originalSelection = pm.ls( selection=True, flatten=True )
     pm.mel.eval('ConvertSelectionToVertices;')
     selVerts = pm.ls( selection=True, flatten=True )
     #objectSelection = pm.ls(selection=True, shapes=True )
     
     #selObjs = originalSelection[:]  ## copy the list
     #selVerts = pm.polyListComponentConversion(
     #    fromFace=True, fromVertex=True, fromEdge=True,
     #    fromVertexFace=True,
     #    toVertex=True )
     #    
     #selVerts = 
         
         
         
     spacing = cls.getSpacing()
     
     for v in selVerts:
         if isinstance( v, pm.MeshVertex ):
             pW = v.getPosition(space='world')
             p = pW.homogenize()  ## Turn it into simply coords
             #print( type(p.x)  )                
             def onGrid(n, s):
                 return (  spacing * float(   round( n/float(s) )  )   )
             p.x = onGrid( p.x, spacing )
             p.y = onGrid( p.y, spacing )
             p.z = onGrid( p.z, spacing )
             #print( p.x, p.y, p.z )                               
             v.setPosition( p.homogenize(), space='world' )
             #print p.x,p.y,p.z
             #print( help(p)  )
             #break
     pm.select( originalSelection )
    def applyVertexColorAttributeToSelection(self=None):

        sel = pm.ls(selection=True)

        shapesToAdd = []

        for obj in sel:
            try:
                shape = obj.getShape()
                shapesToAdd.append( shape )
            except:
                pass

        print( shapesToAdd )
        print( sel )

        selWithShapes = sel + shapesToAdd
        print(selWithShapes)

        shapes = pm.ls(selWithShapes, shapes=True )

        print( shapes )

        for obj in shapes:
            try:
                obj.mmmmExportVertexColorsForMr.get()
                try:
                    obj.mmmmExportVertexColorsForMr.set(True)
                except:
                    pass
            except:
                obj.addAttr( 'mmmmExportVertexColorsForMr', attributeType=bool, defaultValue=True )
예제 #4
0
    def applyUvToWorldRatioToSelection(self, targetRatio=None):
        oSel = pm.ls(sl=True)

        pm.mel.eval("ConvertSelectionToFaces;")

        sel = pm.ls(sl=True)

        if targetRatio == None:
            targetRatio = input()
        currentRatio = self.calcUvToWorldAreaRatio()
        amountToScaleBeforeSqrt = targetRatio / currentRatio
        amountToScale = math.sqrt(amountToScaleBeforeSqrt)

        ## Calc a bounding box in uv space, and it's center, for a scale pivot
        bb = pm.polyEvaluate(sel, boundingBoxComponent2d=True)
        bbUMin = bb[0][0]
        bbUMax = bb[0][1]
        bbVMin = bb[1][0]
        bbVMax = bb[1][1]
        bbUCenter = (bbUMax + bbUMin) * 0.5
        bbVCenter = (bbVMax + bbVMin) * 0.5

        pm.polyEditUV(sel,
                      pu=bbUCenter,
                      pv=bbVCenter,
                      su=amountToScale,
                      sv=amountToScale)

        pm.select(oSel)
예제 #5
0
    def volumeSelect(cls, faces=False ):
      sel = pm.ls(sl=1)
    
      if len(sel) < 2:
          print( "You must have at least two objects selected" )
          return []
    
      checkInsideObj = sel.pop()
      #checkInsideObj = sel[1]
      
      allIn = []
           
      for container in sel:

            
          allVtx = pm.ls(str(checkInsideObj)+'.vtx[*]',fl=1)

          start = pm.timerX()
        
          for eachVtx in allVtx:
              location = pm.pointPosition(eachVtx,w=1)
              test = cls.pyRayIntersect(container,location,(0,1,0))
        
              if(test):
                  allIn.append(eachVtx)
                  
      elapsedTime = pm.timerX(startTime = start)
      print "time :",elapsedTime
      pm.select(allIn,replace=1)
      if faces==True:
          pm.mel.eval( 'ConvertSelectionToContainedFaces;' )
      return pm.ls(selection=True)
예제 #6
0
    def applyUvToWorldRatioToSelection(self, targetRatio=None):
        oSel = pm.ls(sl=True)

        pm.mel.eval("ConvertSelectionToFaces;")

        sel = pm.ls(sl=True)

        if targetRatio == None:
            targetRatio = input()
        currentRatio = self.calcUvToWorldAreaRatio()
        amountToScaleBeforeSqrt = targetRatio / currentRatio
        amountToScale = math.sqrt(amountToScaleBeforeSqrt)

        ## Calc a bounding box in uv space, and it's center, for a scale pivot
        bb = pm.polyEvaluate(sel, boundingBoxComponent2d=True)
        bbUMin = bb[0][0]
        bbUMax = bb[0][1]
        bbVMin = bb[1][0]
        bbVMax = bb[1][1]
        bbUCenter = (bbUMax + bbUMin) * 0.5
        bbVCenter = (bbVMax + bbVMin) * 0.5

        pm.polyEditUV(sel, pu=bbUCenter, pv=bbVCenter, su=amountToScale, sv=amountToScale)

        pm.select(oSel)
예제 #7
0
def copyObjects(**kwargs):
    """
        Input object to be copied
        select positions where the objects needs be copied and run the script
        the copied object constraints the position objects if options are selected
    """
    print "TEST"
    obj = kwargs.get("obj", "")
    prFlg = kwargs.get("prFlg", False)
    scFlg = kwargs.get("scFlg", False)
    sel = pm.ls(selection=True, flatten=True)
    ch = None
    for comp in sel:
        pos = pm.xform(comp, query=True, worldSpace=True, translation=True)
        new_obj = pm.duplicate(obj)
        pm.xform(new_obj, worldSpace=True, translation=pos)
        if prFlg or scFlg:
            typ = str(pm.nodeType(comp))
            if typ == "transform":
                ch = comp
            else:
                shp = pm.ls(comp, objectsOnly=True)[0]
                trn = pm.listRelatives(shp, parent=True)[0]
                ch = trn
            if prFlg:
                pm.parentConstraint(new_obj, ch, maintainOffset=True)
            if scFlg:
                pm.scaleConstraint(new_obj, ch, maintainOffset=True)
    return None
예제 #8
0
         try:
             self.node.addAttr( self.attrName, dt='string' )
             print( 'An attribute named "' + self.attrName + '" was added to ' + self.node.name()  )                
         except:
             print( "Couldn't add attribute. Continuing anyway...")            
         
 def getScriptFromSelection(self):
     try:
         sel = pm.ls(selection=True)
         attr = None
         foundObj = None
         for obj in sel:
             try:
                 attr = getattr( obj, self.attrName ) 
                     ## this will fail if the attribute doesn't
                     ## exist, and the next line won't run
                 foundObj = obj
             except:
                 continue
         if foundObj is None:
             try:
                 foundObj= pm.ls(selection=True)[0]
             except:
                 print( "An object must be selected in order to get the script." )
                 raise
         else:
             self.node = foundObj
             n = foundObj.name()
             self.updateScriptNames()
             pre = self.scriptPrefix
             if n.startswith( pre ) and len(n) > len( pre ):
                 n = n[ len(self.scriptPrefix) : ]
                 self.scriptNameTextField.setText( n )
             else:
                 self.scriptPrefixTextField.setText('')
    def applyVertexColorAttributeToSelection(self=None):

        sel = pm.ls(selection=True)

        shapesToAdd = []

        for obj in sel:
            try:
                shape = obj.getShape()
                shapesToAdd.append(shape)
            except:
                pass

        print(shapesToAdd)
        print(sel)

        selWithShapes = sel + shapesToAdd
        print(selWithShapes)

        shapes = pm.ls(selWithShapes, shapes=True)

        print(shapes)

        for obj in shapes:
            try:
                obj.mmmmExportVertexColorsForMr.get()
                try:
                    obj.mmmmExportVertexColorsForMr.set(True)
                except:
                    pass
            except:
                obj.addAttr('mmmmExportVertexColorsForMr',
                            attributeType=bool,
                            defaultValue=True)
예제 #10
0
def get_loop_from_edge():
    sel = pm.ls(orderedSelection=True)
    mid_pos = []
    pm.select(clear=True)
    for edg in sel:
        obj_sh_name = str(edg).split(".")[0]
        obj_name = pm.listRelatives(obj_sh_name, parent=True)
        edg_num = int((edg.split("[")[1]).replace("]", ""))
        pm.polySelect(obj_name, edgeLoopOrBorder=edg_num)
        edg_sel = pm.ls(selection=True)
        mid_pos.append(CustomScripts.midPos(selected_items=edg_sel))
        pm.select(clear=True)
    pm.select(clear=True)
    jnts = []
    for pos in mid_pos:
        cur_jnt = pm.joint(position=pos)
        jnts.append(cur_jnt)
        index = mid_pos.index(pos)
        if index > 0:
            pm.joint(jnts[index - 1],
                     edit=True,
                     orientJoint="xyz",
                     secondaryAxisOrient="yup",
                     children=True,
                     zeroScaleOrient=True)
    pm.select(clear=True)
    pm.select(jnts[-2], jnts[-1])
    CustomScripts.CopyJntOri()
    pm.select(clear=True)
    pm.select(jnts[-1])
    return None
예제 #11
0
    def hs_verts(self, f1, f2):
        """
        this function finds the average of the face normals on each side of
        an edge then adjusts the vtx normals to that average
        """
        average_n = (f1.getNormal(space='world') +
                     f2.getNormal(space='world')) / (2, 2, 2)

        verts1 = pm.polyListComponentConversion(f1,
                                                fromFace=True,
                                                toVertex=True)

        pm.select(verts1)
        v1 = pm.ls(sl=True, flatten=True)

        verts2 = pm.polyListComponentConversion(f2,
                                                fromFace=True,
                                                toVertex=True)

        pm.select(verts2)
        v2 = pm.ls(sl=True, flatten=True)

        sVerts = [i for i in v1 if i in v2]

        pm.select(sVerts)

        pm.polyNormalPerVertex(normalXYZ=average_n)
예제 #12
0
def createController(object):
    # object = pma.ls(sl=True)
    pivotObj = pma.xform(object, query=True, t=True, worldSpace=True)
    edges = pma.filterExpand(pma.polyListComponentConversion(te=1), sm=32,
                             ex=1)  # convert edges to curve ancd create one object
    for edge in edges:
        vtx = pma.ls(pma.polyListComponentConversion(edge, fe=1, tv=1), fl=1)
        p1 = pma.pointPosition(vtx[0])
        p2 = pma.pointPosition(vtx[1])
        curves = pma.curve(n="line_ctrl_curve", d=1, p=(p1, p2))

    ctrl = pma.curve(n="bool_ctrl", d=1, ws=True, p=pivotObj)
    pma.xform(centerPivots=True)
    for curveEdge in pma.ls("line_ctrl*"):
        pma.parent(curveEdge, ctrl, s=1, r=1)
        pma.rename(curveEdge, "shapeunused")

    transforms = pma.ls(type='transform')
    deleteList = []
    for tran in transforms:
        if pma.nodeType(tran) == 'transform':
            children = pma.listRelatives(tran, c=True)
            if children is None:
                # print '%s, has no childred' %(tran)
                deleteList.append(tran)

    if not deleteList:
        pma.delete(deleteList)
    return ctrl
예제 #13
0
    def projectSelection(self):

        hiliteOrig = pm.ls(hilite=True)

        selOrig = pm.ls(selection=True)
        selPre = pm.polyListComponentConversion(selOrig, tv=True)

        try:
            pm.select(self.referenceXformNode, replace=True)
            pm.select(selPre, add=True)
            selForTransfer = pm.ls(selection=True)
            pm.transferAttributes(
                transferPositions=1, transferNormals=0, transferUVs=0, transferColors=0, sampleSpace=0, searchMethod=0
            )
            objsToAddToSelection = []
            for o in selForTransfer:
                # s = str( type(o) )
                # print "y" + s + "y"
                if str(type(o)) == "<class 'pymel.core.general.MeshVertex'>":
                    n = o.name().split(".")[0]
                    objsToAddToSelection.append(n)
            for obj in objsToAddToSelection:
                pm.select(obj, add=True)
            pm.delete(ch=True)  ##was #pm.mel.eval( "DeleteHistory;" )
            print(selForTransfer)
            pm.select(selOrig, replace=True)
            pm.hilite(hiliteOrig)
        except:
            pm.select(selOrig)
            pm.hilite(hiliteOrig)

            print(
                "Please ensure that you have a valid reference mesh selected, and that you have verticies or objects select to project."
            )
예제 #14
0
def arsenal_proxyShaderAutoConnect(ignoreNamespace = False):
    if ignoreNamespace:
        print '[Arsenal ToolBox] Namespace ignored'
    else:
        print '[Arsenal ToolBox] Namespace not ignored'
    proxyMaterialNodes = pm.ls(type='VRayMeshMaterial')
    allMaterials = pm.ls(materials=True)
    materialClean = list(set(allMaterials) - set(proxyMaterialNodes))
    if len(proxyMaterialNodes) == 0:
        OpenMaya.MGlobal.displayWarning('No VRayMeshMaterial in the scene !')
    for proxyMaterialNode in proxyMaterialNodes:
        numberOfSlot = proxyMaterialNode.shaderNames.get(size=True)
        for i in range(numberOfSlot):
            nameSlot = pm.getAttr(proxyMaterialNode + '.shaderNames[' + str(i) + ']')
            if pm.connectionInfo(proxyMaterialNode + '.shaders[' + str(i) + ']', isDestination=True):
                connected = pm.connectionInfo(proxyMaterialNode + '.shaders[' + str(i) + ']', sourceFromDestination=True)
                pm.disconnectAttr(connected, proxyMaterialNode + '.shaders[' + str(i) + ']')
                print '[Arsenal ToolBox] Disconnect ' + proxyMaterialNode + '.shaders[' + str(i) + ']'
            for myMat in materialClean:
                okConnect = False
                if ignoreNamespace:
                    if myMat.split(':')[-1] == nameSlot.split(':')[-1]:
                        okConnect = True
                elif myMat == nameSlot:
                    okConnect = True
                if okConnect:
                    pm.connectAttr(myMat + '.outColor', proxyMaterialNode + '.shaders[' + str(i) + ']', f=True)
                    print '[Arsenal ToolBox] ' + proxyMaterialNode + '.shaders[' + str(i) + '] connected.'
예제 #15
0
 def copy_shader(self):
     cp_sel = pm.ls(selection=True)
     sel_shader = None
     sh_eng = pm.ls(pm.listHistory(cp_sel[0], f=1), type="shadingEngine")[0]
     if sh_eng:
         sel_shader = pm.listConnections(str(sh_eng) + ".surfaceShader")[0]
     if sel_shader:
         pm.hyperShade(cp_sel[1], assign=sel_shader)
     return None
 def applyMultiplier(self, selection=False, multiplier=1.0):
     originalSelection = pm.ls(selection=True)
     pm.select(hierarchy=True)
     lights = pm.ls(selection=selection, lights=True)
     for light in lights:
         try:
             v = light.intensity.get() * multiplier
             light.intensity.set(v)
         except:
             print("Coundn't set intensity on light: " + light.name())
     pm.select(originalSelection)
 def applyMultiplier(self, selection=False, multiplier = 1.0 ):
     originalSelection = pm.ls(selection=True)
     pm.select( hierarchy=True )
     lights = pm.ls(selection=selection, lights=True)
     for light in lights:
         try:
             v = light.intensity.get() * multiplier
             light.intensity.set( v )
         except:
             print( "Coundn't set intensity on light: " + light.name()  )
     pm.select(originalSelection)
 def extractShapeNodeNames(self):
     shapeNodes = []
     shapes = pm.ls(pm.ls(selection=True, shapes=True))
     if shapes:
         for shape in shapes:
             shapeNodes.append(str(shape))
         for i in range(len(shapeNodes)):
             shapeNodes[i] = shapeNodes[i].split('|')
             for shapeNd in shapeNodes[i]:
                 if shapeNd.find('Shape'):
                     shapeNodes[i] = shapeNd
         return shapeNodes
예제 #19
0
def __get_object_list( selected_only ) :
	objects = []
	if( not selected_only ) :
		objects = pm.ls( assemblies=True, visible=True )
	else :
		objects = pm.ls( sl=True )
		for obj in objects :
			if(  obj.getShape() ) :
				pm.error( 'Please group your meshes when using selective export' )
	remove_list = [ 'top', 'front', 'side', 'perp' ]
	objects[:] = [ obj for obj in objects if obj.name() not in remove_list ]
	return objects
    def extract_loops(self, **kwargs):
        max_count = kwargs.get("max", 0)
        if not max_count:
            max_count = 2
        prev_con_edg = kwargs.get("prev_con_edg", [])
        selected_edges = kwargs.get("next_edg", [])
        self.safe_count += 1
        if self.safe_count > max_count:
            pm.displayWarning("Loop not ending")
            return self.FAIL
        if not selected_edges:
            selected_edges = pm.ls(orderedSelection=True, flatten=True)
        if self.init_flag:
            if len(selected_edges) < 2:
                pm.displayError("Minimum 2 edge selection needed")
                return self.FAIL
            if len(selected_edges) > 3:
                pm.displayError("More than 3 edges selected")
                return self.FAIL
            if len(selected_edges) == 3:
                self.stop_edge = selected_edges.pop(2)

            self.transform_node, self.shape_node = self.get_transform_from_component(
                comp=selected_edges[0])
            max_count = len(
                pm.ls(str(self.transform_node) + ".e[*]", flatten=True))

        next_edge = None
        for sel_edg in selected_edges:
            loop = self.get_loop_from_edge(edg=sel_edg,
                                           obj=self.transform_node)
            self.loop.append(loop)
            con_edg = pm.ls(sel_edg.connectedEdges(), flatten=True)
            if self.init_flag:
                self.init_flag = False
                prev_con_edg = con_edg
                self.init_loop = loop
                continue
            next_edge = self.get_next_edge(edg_con=con_edg,
                                           edg_loop=loop,
                                           prev_edg_con=prev_con_edg)
            if self.stop_edge in loop:
                return None
        if next_edge and len(next_edge) == 1:
            if next_edge[0] in self.init_loop:
                return None
            self.extract_loops(prev_con_edg=con_edg,
                               next_edg=next_edge,
                               max=max_count)

        return self.SUCCESS
예제 #21
0
    def unfold3dOnlySelected(self):

        origSel = pm.ls(selection=True)

        pm.mel.eval("PolySelectConvert 4;")  ##"ConvertSelectionToUVs;" )
        origUvs = pm.ls(selection=True)
        pm.mel.eval("InvertSelection;")

        selCount = len(pm.ls(selection=True))

        ## In case all uvs are selected, the inverted selection will be zero!
        if selCount == 0:
            pm.select(origSel)
            pm.mel.eval("ConvertSelectionToUVs;")
            pm.mel.eval(
                "Unfold3D -unfold -iterations 1 -p 1 -borderintersection 1 -triangleflip 1;"
            )
            pm.select(origSel)
        else:
            ## Beware!  there's a huge potential bug  in this commands behavior
            ##   the way it is now working here is to get u and v  values, as back to back entries added into a list
            ##   so the list is twice as long as the number of uvs   eg.   v = coords[i*2  +1]
            uvsToRestore = pm.ls(selection=True, flatten=True)
            coords = pm.polyEditUV(uvsToRestore,
                                   query=True,
                                   uValue=True,
                                   vValue=True)

            pm.select(origSel)
            pm.mel.eval("ConvertSelectionToUVs;")
            pm.mel.eval(
                "Unfold3D -unfold -iterations 1 -p 1 -borderintersection 1 -triangleflip 1;"
            )

            #print( uvsToRestore )
            #print len(coordsU)
            #print len( uvsToRestore )

            #print( coords )

            for i, uv in enumerate(uvsToRestore):
                #print( coords )
                pm.polyEditUV(uv,
                              relative=False,
                              uValue=coords[i * 2],
                              vValue=coords[i * 2 + 1])

            #cmds.Unfold3D( cmds.ls(sl=True), u=True, p=True, ite=1, bi=True, tf=True, ms=1024, rs=2 )

            pm.select(origSel)
예제 #22
0
def dense_chain(**kwargs):
    import pymel.core.datatypes as dt
    joints = kwargs.get("joints", None)
    joints_inbetween = kwargs.get("joints_inbetween", 5)
    if not joints:
        joints = pm.ls(selection=True)
    joints.pop(-1)
    for jnt in joints:
        child = jnt.getChildren()
        pos = pm.xform(jnt, query=True, translation=True, worldSpace=True)
        vpos1 = dt.Vector(pos)
        pos = pm.xform(child[0], query=True, translation=True, worldSpace=True)
        vpos2 = dt.Vector(pos)
        vpos = vpos2 - vpos1
        div_vec = vpos / (joints_inbetween + 1)
        out_vec = vpos1
        cur_jnt = jnt
        for i in range(joints_inbetween):
            out_vec = (out_vec + div_vec)
            pos = [out_vec.x, out_vec.y, out_vec.z]
            new_jnt = pm.insertJoint(cur_jnt)
            pm.joint(new_jnt,
                     edit=True,
                     component=True,
                     position=pos,
                     name=str(i))
            cur_jnt = new_jnt
    return None
예제 #23
0
    def displayConnect(self, obj):
        # Create curve for display, between selected objects
        # Return [curve, locator1, locator2]
        if len(obj) == 0:
            obj = pm.ls(transforms=1, sl=1)

        if len(obj) < 2:
            pm.error(u"KH_curve_Connect : 선택된 오브젝트가 없습니다.")

        pointA = obj[0]
        pointB = obj[1]

        curve = pm.curve(p=[(0, 0, 0), (0, 0, 0)], k=[0, 1], d=1)
        pointCurveConstraint1 = pm.pointCurveConstraint(curve + ".ep[0]",
                                                        ch=True)
        pointCurveConstraint2 = pm.pointCurveConstraint(curve + ".ep[1]",
                                                        ch=True)

        pointCostraint1 = pm.pointConstraint(pointA, pointCurveConstraint1[0])
        pointCostraint2 = pm.pointConstraint(pointB, pointCurveConstraint2[0])

        locShape1 = pm.listRelatives(pointCurveConstraint1[0], s=1)
        locShape2 = pm.listRelatives(pointCurveConstraint2[0], s=1)
        pm.setAttr(locShape1[0] + ".visibility", 0)
        pm.setAttr(locShape2[0] + ".visibility", 0)

        return [
            curve,
            pm.PyNode(pointCurveConstraint1[0]),
            pm.PyNode(pointCurveConstraint2[0]), pointCostraint1,
            pointCostraint2
        ]
예제 #24
0
 #### DeprecationWarning - use version in Static.Mesh        
 @classmethod
 def uncreaseSelectedEdges(cls):
     cls.setCreaseValueOnSelection( 0.0 )
 
 #### DeprecationWarning - use version in Static.Mesh
 @staticmethod
예제 #25
0
             obj.addAttr( "mmmmExportFile", dataType="string")
         except:
             print( "Attribute not added, it might already exist on the selected object.")
             print traceback.format_exc()
 def addAttributeForExportPath(self):
     for obj in pm.ls(selection=True, transforms=True):
         try:
예제 #26
0
def __rename_from_ui() :	
	# rename_replace( pm.ls( sl=True ), searchfield.getText(), replacefield.getText() )
	sel = pm.ls( sl=True )
	new = __rename_list_from_textfields( *[i.name() for i in sel] )
	for name, obj in zip( new, sel ) :
		obj.rename( name )
	pm.select(sel)
    def connectAttributes(self, sourceAttrName, targetAttrName, multiplier=0.0):

        sourceAttrName = sourceAttrName
        targetAttrName = targetAttrName

        multValue = multiplier
        ##print( help( multValue )   )

        ## Get a list of all selected objects
        objs = pm.ls(selection=True)

        sourceObj = objs.pop(0)
        sourceAttr = getattr(sourceObj, sourceAttrName)

        doMult = False
        if multiplier != 0.0:
            doMult = True

        if doMult:
            m = pm.createNode("multiplyDivide")
            m.input2X.set(multValue)

        ## Loop through all the selected objects, except the first one
        for obj in objs:
            ## This stuff might fail, so put it in a try block
            try:
                targetAttr = getattr(obj, targetAttrName)
                if doMult:
                    sourceAttr >> m.input1X
                    m.outputX >> targetAttr
                else:
                    sourceAttr >> targetAttr

            except:
                print("An error occured on object: " + obj.name() + "\n" + traceback.format_exc() + "\n")
예제 #28
0
def export_models(
	res_path,
	model_rel_path,
	selected_only
	) :
	
	print 'Exporting models'

	res_path = os.path.abspath( res_path )
	model_rel_path = os.path.normpath( model_rel_path )

	sel = pm.ls( sl=True )

	try : os.makedirs( os.path.join( res_path, model_rel_path ) )
	except : pass
	
	objects = __get_object_list( selected_only )
	errors=[]
	for obj in objects :
		clean_obj = __create_clean_object( obj )
		errors.extend( __recursive_export_ffm( 
			clean_obj,			
			res_path,			
			model_rel_path			
		) )
		# pm.delete( clean_obj )

	pm.select( sel )

	if( len(errors) ) :
		for error in errors : print error

	print 'Exporting models finished'
	return True
 def setCreaseValueOnSelection( v ):
     objs = pm.ls(selection=True, flatten=True)
     for obj in objs:
         try:
             creaseValue = pm.polyCrease( obj, value = v )
         except:
             pass  ## we don't care if this fails, no big deal
 def addAttributeGroup( self, user_given_vray_attr_group ):
 
     ## Get selection
     sel = pm.ls(selection=True)
     ## Copy selection in case we modify the list
     objs = sel[:]
     
     for obj in objs:
         try:
             shp = obj
             try:
                 shp = obj.getShape()
             except:
                 shp = obj
             ##if hasattr( obj, "getShape" ):
             ##    shp = obj.getShape()
             pm.mel.eval(
                 'vray addAttributesFromGroup "'
                 + shp.name()
                 + '" "' + user_given_vray_attr_group + '" 1;'
             )
         except:
             print "not working"
     
     ##restore original selection
     pm.select(sel)
예제 #31
0
 def unfold3dMultipleObjects(self):
     origSel = pm.ls(selection=True)
     for obj in origSel:
         pm.select(obj)
         pm.mel.eval("ConvertSelectionToUVs;")
         pm.mel.eval("Unfold3D -unfold -iterations 1 -p 1 -borderintersection 1 -triangleflip 1;")
     pm.select(origSel)
예제 #32
0
def setAttributeOnSelected( attrName, v ):
    objs = pm.ls(selection=True, flatten=True)
    for obj in objs:
        try:
            obj.setAttr( attrName, v )
        except:
            print("Could not affect " + obj )
예제 #33
0
def midPosVec(**kwargs):
    """
        Returns the mid point from selected positions(objects or components)
    """
    selected_items = kwargs.get("objects", [])
    if not selected_items:
        selected_items = pm.ls(selection=True, flatten=True)
    if not isinstance(selected_items, list):
        print "please provide objects list"
        pm.displayInfo("please provide objects list")
        return None
    number_of_items = len(selected_items)
    position_vector = []
    final_vector = OpenMaya.MVector(0, 0, 0)
    for index in range(number_of_items):
        pos = pm.xform(selected_items[index],
                       query=True,
                       worldSpace=True,
                       translation=True)
        vec = OpenMaya.MVector(pos[0], pos[1], pos[2])
        position_vector.append(vec)

    for vector_index in range(len(position_vector)):
        final_vector = final_vector + position_vector[vector_index]

    final_vector = final_vector / len(position_vector)
    mid_position = [final_vector.x, final_vector.y, final_vector.z]
    return mid_position
예제 #34
0
def insJnt():
    selected = pm.ls(selection=True)
    for index in range(len(selected) - 1):
        mid_pos = midPos(selected_items=[selected[index], selected[index + 1]])
        new_joint = pm.insertJoint(selected[index])
        pm.joint(new_joint, edit=True, component=True, position=mid_pos)
    return None
예제 #35
0
    def getVerticesInOrder(self):
        """ Get vertices in continous order """

        sel = pm.ls(sl=True, fl=True)
        left = list(sel)

        finished = [sel[0]]
        left.remove(sel[0])

        while True:
            currentVertex = finished[-1]
            distance = 999999.0
            closestVertex = None
            for v in left:
                a = v.getPosition(space='world')
                b = currentVertex.getPosition(space='world')
                length = (a - b).length()
                if length < distance:
                    distance = length
                    closestVertex = v
            finished.append(closestVertex)
            left.remove(closestVertex)
            if left == []:
                break

        return finished
예제 #36
0
 def create_attr(self):
     # Create enum attribute on selected control object
     sel = pm.ls(selection=True)
     if not sel:
         pm.displayWarning("Select Control object")
         return None
     attr = self.attr_nm.getText()
     attr_lst = self.enum_val.getText().split("\n")
     enum_attr_val = ""
     for index in range(len(attr_lst)):
         if attr_lst[index]:
             enum_attr_val += attr_lst[index]
             if not index == len(attr_lst) - 1:
                 enum_attr_val += ":"
     for obj in sel:
         pm.addAttr(obj,
                    longName=attr,
                    attributeType="enum",
                    enumName=enum_attr_val,
                    keyable=True,
                    readable=True,
                    storable=True,
                    writable=True)
     self.populate_list()
     return None
 def clearSelectedCtrlsPosSlave(self):
     objs = pm.ls(sl=True)
     for obj in objs:
         try:
             obj.posSlave.disconnect()
         except:
             print( traceback.format_exc()  )
 def parentWithZeroes(self):
     oSel = pm.ls(sl=True)
     objs = oSel[:] ## copy list oSel so I can change objs list but leave oSel alone
     par = objs.pop(-1)
     for child in objs:
         childZero = child.getParent()
         pm.parent( childZero, par )
예제 #39
0
def ins_jnt(**kwargs):
    num = kwargs.get("num_jts", 1)
    sel = pm.ls(selection=True)
    chld = pm.listRelatives(sel[0], children=True)
    if not chld[0].type() == "joint":
        print "end joint reached"
        return None
    #position_lst = []
    pos1 = pm.xform(sel[0], query=True, worldSpace=True, translation=True)
    pos2 = pm.xform(chld, query=True, worldSpace=True, translation=True)
    len_vec1 = OpenMaya.MVector(pos1[0], pos1[1], pos1[2])
    len_vec2 = OpenMaya.MVector(pos2[0], pos2[1], pos2[2])
    len_vec = len_vec2 - len_vec1
    print len_vec.x, len_vec.y, len_vec.z
    part_vec = len_vec / (num + 1)
    pos_vec = len_vec1 + len_vec / (num + 1)
    cur_jnt = sel[0]
    for i in range(num):
        new_position = [pos_vec.x, pos_vec.y, pos_vec.z]
        #print new_position
        new_joint = pm.insertJoint(cur_jnt)
        pm.joint(new_joint, edit=True, component=True, position=new_position)
        #pm.xform(new_joint, translation=new_position)
        pos_vec += part_vec
        cur_jnt = new_joint
    return None
예제 #40
0
def setCreaseValueOnSelection( v ):
    objs = pm.ls(selection=True) ## removed flatten=True because it makes it crazy slow
    for obj in objs:
        try:
            creaseValue = pm.polyCrease( obj, value = v )
        except:
            pass  ## we don't care if this fails, no big deal
예제 #41
0
def curve_through_points(**kwargs):
    selection_points = kwargs.get("selection_points", None)
    curve_degree = kwargs.get("curve_degree", 3)
    curve_name = kwargs.get("curve_name", "Curve")

    if not selection_points:
        selection_points = pm.ls(selection=True)
        if not selection_points:
            pm.displayInfo("Please select reference points")
            return None
    if len(selection_points) < curve_degree + 1:
        pm.displayInfo("please select more than " + str(curve_degree + 1) +
                       " points")
        return None

    points_locations = []
    for point in selection_points:
        points_locations.append(
            pm.xform(point, query=True, translation=True, worldSpace=True))
    pm.select(clear=True)
    current_curve = pm.curve(degree=curve_degree,
                             worldSpace=True,
                             point=points_locations)
    pm.rename(current_curve, curve_name)
    return current_curve
예제 #42
0
def setAttributeOnSelected(attrName, v):
    objs = pm.ls(selection=True, flatten=True)
    for obj in objs:
        try:
            obj.setAttr(attrName, v)
        except:
            print("Could not affect " + obj)
예제 #43
0
    def list(cls, *args, **kwargs):
        """ Returns all instances of all characters in the scene """

        kwargs["type"] = cls.__melnode__
        return [
            node for node in pmc.ls(*args, **kwargs) if isinstance(node, cls)
        ]
 def toPolygons(self):
     ## could have feature added to select joints if they have poly shape nodes
     
     objs = pm.ls( selection=True )
     
     converted = []
     #print pm.ls( selection=True, showType=True )
     for obj in objs:
         print obj.type()
         is_confirmed_as_mesh = False 
         if obj.type()=='transform':
             s = obj.getShape()
         if obj.type()=='mesh':
             s = obj
             obj = s.getParent()
             is_confirmed_as_mesh = True
             
         if is_confirmed_as_mesh==False:
            if s.type()=='mesh':
                is_confirmed_as_mesh = True
         
         if is_confirmed_as_mesh==True:
             converted.append( obj )
             
     pm.select( converted )
예제 #45
0
 def setCreaseValueOnSelection(v):
     objs = pm.ls(selection=True, flatten=True)
     for obj in objs:
         try:
             creaseValue = pm.polyCrease(obj, value=v)
         except:
             pass  ## we don't care if this fails, no big deal
예제 #46
0
    def deeXProxyObjectIDGeneratorFunc(self):
        OpenMaya.MGlobal.displayInfo(
            '[Arsenal] Proxy ObjectID Generator start')
        proxyNode = pm.ls(type='VRayMesh')
        for myProxy in proxyNode:
            mesh = myProxy.listHistory(future=True, exactType='mesh')
            allParent = mesh[0].listRelatives(ap=True, pa=True)
            go = False
            for myP in allParent:
                if myP.isVisible():
                    print myProxy.name() + ' is visible.'
                    go = True
                    break

            if not go:
                continue
            OpenMaya.MGlobal.displayInfo(
                '              Generate ID for proxy : ' + myProxy.name())
            idList = myProxy.objectListIDs.get()
            if len(idList) <= 1:
                continue
            count = 0
            maskNumber = 0
            for myID in idList:
                if myID != 0.0:
                    multiMatteName = str('MultiMatte_%04d' % maskNumber +
                                         '_%010d' % myID)
                    if count % 3 == 0:
                        n2 = 'None'
                        if len(idList) - 1 >= count + 2 and idList[(count +
                                                                    2)] != 0.0:
                            n2 = idList[(count + 2)]
                        n1 = 'None'
                        if len(idList) - 1 >= count + 1 and idList[(count +
                                                                    1)] != 0.0:
                            n1 = idList[(count + 1)]
                        n = 'None'
                        if len(idList) - 1 >= count and idList[count] != 0.0:
                            n = idList[count]
                        OpenMaya.MGlobal.displayInfo(
                            '                - Create multimatte : ' +
                            multiMatteName + ' with ID : ' + str(n) + ' - ' +
                            str(n1) + ' - ' + str(n2) + ' from ' + str(idList))
                        vrUtils.create('RenderChannelMultiMatte',
                                       multiMatteName)
                        myMask = vrUtils.findByName(multiMatteName)
                        myMask[0].set('name', str(multiMatteName))
                        if len(idList) - 1 >= count + 2 and idList[(count +
                                                                    2)] != 0.0:
                            myMask[0].set('red_id', idList[(count + 2)])
                        if len(idList) - 1 >= count + 1 and idList[(count +
                                                                    1)] != 0.0:
                            myMask[0].set('green_id', idList[(count + 1)])
                        if len(idList) - 1 >= count and idList[count] != 0.0:
                            myMask[0].set('blue_id', idList[count])
                        myMask[0].set('use_mtl_id', 0)
                        myMask[0].set('affect_matte_objects', 1)
                        myMask[0].set('consider_for_aa', 1)
                        maskNumber += 1
                    count += 1
예제 #47
0
    def fixXforms(self):
        ## Get the first selected object
        objs = pm.ls(selection=True)
        
        for obj in objs:
            pm.parent( obj, world=True )

        for obj in objs:        
            ## Unparent the object
            
            ## Move the pivot to the origin
            pm.move ( obj.scalePivot , [0,0,0] )
            pm.move ( obj.rotatePivot , [0,0,0] )
            ## Freeze transforms
            pm.makeIdentity(
                obj,
                apply = True,
                normal = 0,
                preserveNormals = True
            )
            ## Note that the options for makeIdentity were simply
            ## from the Mel script history or freeze transform
            
            ## Delete the history
            pm.delete (ch = True )        
예제 #48
0
def putObjOnSnappableSpacing(obj, snappableSpacing):
    oSel = pm.ls(selection=True)
    destinationObj = obj
    usedObj = obj

    pm.select(destinationObj)
    t = pm.xform(query=True, rotatePivot=True, worldSpace=True)
    vt = pm.core.datatypes.Vector(t[0], t[1], t[2])
    vt = onSnappableSpacingVec(vt, snappableSpacing)

    pm.select(usedObj)
    pm.move(vt, worldSpace=True, absolute=True, worldSpaceDistance=True)

    ## We compensate by getting the *object being moved*'s
    ## pivot
    t2 = pm.xform(query=True, rotatePivot=True, worldSpace=True)
    vt2 = pm.core.datatypes.Vector(t2[0], t2[1], t2[2])

    ## vExtra is the additional amount compensated
    vExtra = vt - vt2

    vDest = vt + vExtra

    vFinal = vDest

    pm.move(vFinal, worldSpace=True, absolute=True, worldSpaceDistance=True)

    pm.select(oSel)
예제 #49
0
         self.ui = RenamerRegexToolUi(parentRef=self, autorun=True)
 
 def rename(self, toName=None, fromName=None, count=0):
     re = Regex
     objs = pm.ls(selection=True)
     
     for obj in objs:
         nameOld = obj.name()
예제 #50
0
 def setReference(self):
     try:
         self.referenceXformNode = pm.ls(selection=True)[-1]
     except:
         print(
             "Please select at least one object in order to set the retoper reference mesh. ",
             "If multiple objects are selected, the last object will be used.",
         )
예제 #51
0
    def makeAndParentUcx(self):
        originalSelection = pm.ls(selection=True)
        ## Only attempt to export directly from transform nodes!
        objs = pm.ls( selection=True, transforms=True )
        
        parentObj = objs.pop( )
        
        for i, obj in enumerate(objs):
            newName = 'UCX_' + parentObj.name() + '_' + str(i).zfill(2)
            pm.parent( obj, parentObj )
            obj.rename( newName )
            
            s = obj.getShape()
            s.overrideEnabled.set(True)
            s.overrideShading.set(False)
        
예제 #52
0
 def reflectivityOfSelectedMaterialsToZero(self):
     objs = pm.ls(selection=True)
     for obj in objs:
         try:
             obj.reflectivity.set(0)
         except:
             print( "Could not set reflectivity for node: " + obj.name()  )
             traceback.print_exc()
예제 #53
0
    def addVrayTextureInputGammaAttributes(self):
        objs = pm.ls (selection = True)

        for obj in objs:
            try:
                pm.mel.eval( "vray addAttributesFromGroup " + obj.name() + " vray_file_gamma 1;")
            except :
                print( traceback.format_exc() )
예제 #54
0
def convertSelectionToHardEdges():
    pm.mel.eval( "ConvertSelectionToEdges;" )
    cmps = pm.ls(selection=True, flatten=True )
    to_select = []
    for cmp in cmps:
        if cmp.isSmooth()==False:
            to_select.append( cmp )
    pm.select( to_select )
예제 #55
0
    def setVrayTextureInputGamma(self, color_space_enumeration ):
        ## 0 is for linear mode, 2 is for SRGB    
        objs = pm.ls (selection = True)

        for obj in objs:
            try:
                obj.vrayFileColorSpace.set ( color_space_enumeration )
            except :
                print( traceback.format_exc() )
예제 #56
0
    def setSlot(self, n=None, listToSet=None):
        n = self.nFixDefault(n)

        n = int(n)
        if isinstance(listToSet, list):
            l = listToSet
        else:
            l = pm.ls(selection=True)
        self.slots[n] = l