Exemplo n.º 1
0
def assignShader2():
    shaderInfoNode = pm.PyNode('shaderInfoNode')
    numAttr = shaderInfoNode.shaderInfos.numChildren()
    message = ''
    for i in range(numAttr):
        shaderInfos = json.loads(
            shaderInfoNode.attr('shaderInfos{}'.format(i)).get())
        try:
            pm.select(shaderInfos.get('geometry'))

            surfaceShader = pm.PyNode(shaderInfos.get('surfaceShader'))
            pm.hyperShade(assign=surfaceShader)
            pm.select(cl=True)
            try:
                if shaderInfos.get('displacement'):
                    displacement = pm.PyNode(shaderInfos.get('displacement'))
                    sg = surfaceShader.outColor.outputs()[0]
                    displacement.displacement.connect(sg.displacementShader)
            except:
                message += (str(shaderInfos.get('displacement')) + '-->' +
                            sg.name() + '\n')
        except:
            message += (str(shaderInfos.get('surfaceShader')) + '-->' +
                        str(shaderInfos.get('geometry')) + '\n')

    shaderInfoNode.unlock()
    pm.delete(shaderInfoNode)
    return message
Exemplo n.º 2
0
def merge_cards(start, end, suit):
    cards = []
    # suits = [ 'Hearts', 'Diamonds', 'Clubs', 'Spades' ]
    ranks = range(start, end)

    total_cards = len(ranks)
    i = 0
    # for suit in suits :
    try:
        suit_group = pm.PyNode('%s_cards_GRP' % (suit))
    except:
        suit_group = pm.group(name='%s_cards_GRP' % (suit),
                              empty=True,
                              world=True)
    for rank in ranks:
        print 'Processing card %s of %s' % (i, total_cards)
        # print rank, suit
        # print get_card_sprites( rank, suit )
        # return
        card_sprites = pm.duplicate(get_card_sprites(rank, suit))
        for card_sprite in card_sprites:
            card_sprite.setParent(None)
        card = pm.polyUnite(card_sprites, mergeUVSets=1, ch=True)[0]
        pm.delete(card, ch=True)
        for cs in card_sprites:
            try:
                pm.delete(cs)
            except:
                pass
        card.rename('%s_%s_G' % (suit, rank))
        card.setParent(suit_group)
        cards.append(card)
        # pm.flushUndo()
        i += 1
    return cards
Exemplo n.º 3
0
def bind_card(source_mesh, target_mesh, combine=True):

    hasskin = True
    try:
        source_skin_cluster = pm.PyNode(
            pm.mel.eval('findRelatedSkinCluster %s' % (source_mesh)))
        joints = source_skin_cluster.getWeightedInfluence()
    except:
        hasskin = False

    if (combine):
        p = target_mesh.getParent()
        dup_source_mesh = source_mesh.duplicate()[0]
        dup_target_mesh = target_mesh.duplicate()[0]

        bind_mesh = pm.polyUnite(dup_source_mesh, dup_target_mesh)[0]
        bind_mesh.rename(target_mesh.name())
        pm.delete(bind_mesh, ch=True)
        try:
            pm.delete(dup_source_mesh)
        except:
            pass
    else:
        bind_mesh = target_mesh

    if hasskin:
        target_skin_cluster = pm.skinCluster(bind_mesh, joints)
        pm.copySkinWeights(source_mesh,
                           bind_mesh,
                           ia='oneToOne',
                           sa='closestPoint')

        pm.select(bind_mesh)
        th_skinClusterMerge.reduce_influences()
    pm.select(None)
Exemplo n.º 4
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 )        
Exemplo n.º 5
0
def delete_vertex(mesh):
    # print mesh
    pm.select(None)
    for v in mesh.getShape().vtx:
        d = True
        if (vert_on_rect_edge(v, mesh.getBoundingBox())):
            d = False
        try:
            if (len(v.connectedEdges()) > 2):
                d = False
        except:
            d = False

        if (d):
            # print v
            pm.delete(v)

    pm.polyMergeVertex(mesh, d=0.001, am=1)

    # faces = [f for f in mesh.f]

    # for i in range(len(faces)) :
    # 	try : f = faces[i]
    # 	except : break

    # 	if( f.isZeroArea() ) :
    # 		# print f
    # 		pm.delete(f)
    # 		delete_vertex(mesh)
    # 		break

    pm.delete(mesh, ch=True)
    return mesh
Exemplo n.º 6
0
def __create_curve_from_edge(edge):
    edgeloop = __get_edge_loop(edge, [], None)
    edgeloop.insert(0, edge)
    edge_curves = []
    for edgeloop_edge in edgeloop:
        edge_curves.append(
            pm.curve(
                # name=n,
                degree=1,
                ws=True,
                point=[
                    v.getPosition() for v in edgeloop_edge.connectedVertices()
                ]))

    pm.select(None)
    if (len(edge_curves) > 1):
        merged_curve = pm.attachCurve(edge_curves[:-1],
                                      method=1,
                                      keepMultipleKnots=False,
                                      ch=False)[0]
        edge_curves.pop(edge_curves.index(merged_curve))
        # closed_curve = pm.closeCurve( merged_curve )[0]
        closed_curve = merged_curve
        # pm.delete( merged_curve )
    else:
        closed_curve = None
    pm.delete(edge_curves)
    return closed_curve, edgeloop
Exemplo n.º 7
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
Exemplo n.º 8
0
    def sd_transfer_attributes(self, selection):

        new_sel = selection.pop(0)

        for obj in selection:
            transfer_from = [new_sel, obj]

            pm.select(transfer_from)

            pm.transferAttributes(
                transferPositions=0,
                transferNormals=0,
                transferUVs=1,
                sourceUvSet="tiling",
                targetUvSet="map1",
                transferColors=0,
                sampleSpace=5,
                sourceUvSpace="tiling",
                targetUvSpace="map1",
                searchMethod=3,
                flipUVs=0,
                colorBorders=1
            )

            pm.delete(ch=True)
Exemplo n.º 9
0
 def delete(self):
     #self.unlockNodes()
     rigNode = self.getRigNode()
     conNodes = rigNode.connections()
     for node in conNodes:
         if pm.objExists(node):
             pm.delete(node)
def delete_vertex( mesh ) :
	# print mesh
	pm.select(None)
	for v in mesh.getShape().vtx :
		d = True
		if( vert_on_rect_edge( v, mesh.getBoundingBox() ) ) :
			d = False
		try :			
			if( len( v.connectedEdges() ) > 2 ) :
				d = False
		except : 
			d = False
		
		if(d) :
			# print v
			pm.delete(v)
	
	pm.polyMergeVertex( mesh, d=0.001, am=1 )	
	
	# faces = [f for f in mesh.f]

	# for i in range(len(faces)) :
	# 	try : f = faces[i]
	# 	except : break

	# 	if( f.isZeroArea() ) :
	# 		# print f
	# 		pm.delete(f)			
	# 		delete_vertex(mesh)
	# 		break

	pm.delete( mesh, ch=True )
	return mesh
Exemplo n.º 11
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."
            )
    def rotateOnXToMatchZ( self, obj, target ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
    
        helperZ = pm.createNode('transform')
        helperX = pm.createNode('transform')

        ## get helperZ,
        ## parent helperZ to target
        pm.parent( helperZ, target)    
        ##  zero helperZ, except +tz
        helperZ.translate.set( [0,0,16] )
        ######################### pm.duplicate( helperZ )  ## just to visualize debug
        ## parent helperZ to obj
        pm.parent( helperZ, obj )
        ## zero helperZ tx
        helperZ.tx.set( 0 )    
        ## make another helperX
        ## parent helperX to obj
        pm.parent( helperX, obj )
        ## move helperX only +tz, zero all else
        helperX.translate.set( [1,0,0] )
        ## unparent helper and helperX
        pm.parent( helperX, world=True )
        pm.parent( helperZ, world=True )
        ## should probably zero everything out that we can here
        obj.jointOrient.set( 0,0,0 )
        obj.rotateAxis.set( 0,0,0 )
        con = pm.aimConstraint( helperX, obj,
            worldUpType='object',
            worldUpObject=helperZ,
            aimVector=[1,0,0],
            upVector=[0,0,1],
        )
        pm.delete( con )   
        pm.delete( [helperX, helperZ] )
def merge_cards( start, end, suit ) :
	cards = []
	# suits = [ 'Hearts', 'Diamonds', 'Clubs', 'Spades' ]
	ranks = range( start, end )

	total_cards = len( ranks )
	i = 0
	# for suit in suits :
	try : suit_group = pm.PyNode( '%s_cards_GRP' % ( suit ) )
	except : suit_group = pm.group( name='%s_cards_GRP' % ( suit ), empty=True, world=True )
	for rank in ranks :
		print 'Processing card %s of %s' % ( i, total_cards )
		# print rank, suit
		# print get_card_sprites( rank, suit )
		# return
		card_sprites = pm.duplicate( get_card_sprites( rank, suit ) )	
		for card_sprite in card_sprites : card_sprite.setParent(None)
		card = pm.polyUnite( card_sprites, mergeUVSets=1, ch=True )[0]		
		pm.delete( card, ch=True )
		for cs in card_sprites :
			try : pm.delete( cs )
			except : pass
		card.rename( '%s_%s_G' % ( suit, rank ) )
		card.setParent( suit_group )
		cards.append( card )
		# pm.flushUndo()
		i += 1
	return cards
def bind_card( source_mesh, target_mesh, combine=True ) :

	hasskin = True
	try :
		source_skin_cluster = pm.PyNode( pm.mel.eval( 'findRelatedSkinCluster %s' % ( source_mesh ) ) )
		joints = source_skin_cluster.getWeightedInfluence()	
	except :
		hasskin = False
			
	if( combine ) :
		p = target_mesh.getParent()
		dup_source_mesh = source_mesh.duplicate()[0]
		dup_target_mesh = target_mesh.duplicate()[0]
				
		bind_mesh = pm.polyUnite( dup_source_mesh, dup_target_mesh )[0]
		bind_mesh.rename( target_mesh.name() )
		pm.delete( bind_mesh, ch=True )
		try :
			pm.delete( dup_source_mesh )
		except : pass
	else :
		bind_mesh = target_mesh

	if hasskin :
		target_skin_cluster = pm.skinCluster( bind_mesh, joints )	
		pm.copySkinWeights( source_mesh, bind_mesh, ia='oneToOne', sa='closestPoint' )

		pm.select( bind_mesh )
		th_skinClusterMerge.reduce_influences()
	pm.select(None)
    def autoOrientXKeepZ(self, obj ):
        assert isinstance(obj, pymel.core.nodetypes.Transform)
        
        unrepar = Unreparenter( obj )
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        target = pm.createNode('joint')
        cons = [
            pm.pointConstraint( obj, target ),
            pm.orientConstraint( obj, target ),
            pm.scaleConstraint( obj, target )
        ]
        pm.delete( cons )
        
        
        unrepar.reparent()
        pm.joint( obj, edit=True,
            oj='xzy', secondaryAxisOrient='yup',
            zeroScaleOrient=True, children=False
        )
        unrepar.unparent( )
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        
        
        self.rotateOnXToMatchZ(obj,target)

        pm.delete( target )
        
        pm.makeIdentity( obj, apply=True, t=1, r=1, s=1, n=0, pn=1 )
        unrepar.reparent(clean=True)
Exemplo n.º 16
0
def exportYeti(path):
    yeitInfo = getYetiInfo()
    if pm.objExists('yetiInfoNode'):
        yetiInfoNode = pm.PyNode('yetiInfoNode')
        yetiInfoNode.unlock()
        pm.delete(yetiInfoNode)

    attrName = 'yetiInfo'
    yetiInfoNode = pm.createNode('network', n='yetiInfoNode')
    yetiInfoNode.addAttr(attrName, dt='string')
    jsonHandl = json.dumps(yeitInfo)
    yetiInfoNode.attr(attrName).set(jsonHandl)
    yetiInfoNode.attr(attrName).lock()
    yetiInfoNode.lock()

    exportList = [yetiInfoNode]
    for _, shader in yeitInfo.items():
        exportList.append(shader)

    pm.select(exportList)
    try:
        pm.exportSelected(path, pr=1, typ='mayaBinary', force=1, es=1)
        print 'Success Export Shader'
    except:
        print exportList
        print path
    finally:
        yetiInfoNode.unlock()
        pm.delete(yetiInfoNode)
Exemplo n.º 17
0
 def __exit__(self):
     if self.tmpObjectShape.name() == pm.PyNode( self.tmpObjectShape.name() ).name():
         pm.delete( tmpObjectShape )
     if self.tmpObject.name() == pm.PyNode( self.tmpObject.name() ).name():
         children = self.tmpObject.getChildren()
         if len( children ) == 0:
             pm.delete( tmpObjectShape )    
Exemplo n.º 18
0
 def __exit__(self):
     if self.tmpObjectShape.name() == pm.PyNode(
             self.tmpObjectShape.name()).name():
         pm.delete(tmpObjectShape)
     if self.tmpObject.name() == pm.PyNode(self.tmpObject.name()).name():
         children = self.tmpObject.getChildren()
         if len(children) == 0:
             pm.delete(tmpObjectShape)
Exemplo n.º 19
0
	def duplicate( self, simple=False, *args, **kwargs ) :	
		duplicatejoints = super( RigJoint, self ).duplicate( *args, **kwargs )
		if( simple ) :
			duplicatejoints = [ duplicatejoints.pop(0) ]
			duplicatejoints[0].setParent( None )
			duplicatejointchildren = duplicatejoints[0].getChildren()
			if( len( duplicatejointchildren ) ) :
				pm.delete( duplicatejointchildren )
		return duplicatejoints[0]
 def autoOrientTipJoint(self,obj):
     ## this currently assumes that tip has no children
     par = obj.getParent()
     pm.parent( obj )
     obj.rotate.set( [0,0,0] )
     obj.jointOrient.set( [0,0,0] )
     obj.rotateAxis.set( [0,0,0] )
     con = pm.orientConstraint( par, obj )
     pm.delete( con )
Exemplo n.º 21
0
def midPos(**kwargs):
    """
        Returns the mid point from selected positions(objects or components)
    """
    selected_items = kwargs.get("selected_items", [])
    temp_cluster = pm.cluster(selected_items)[1]
    cluster_shape = temp_cluster.getShape()
    mid_position = cluster_shape.origin.get()
    pm.delete(temp_cluster)
    return mid_position
Exemplo n.º 22
0
	def duplicate( self, *args, **kwargs ) :
		# duplicates the joint without children
		newrigjoints = super( RigJoint, self ).duplicate( *args, **kwargs )
		for newrigjoint in newrigjoints :
			newrigjoint.setParent( None )
			newrigjoint.setRotation( self.getRotation() )
			newrigjointchildren = newrigjoint.getChildren()
			if( len( newrigjointchildren ) ) :
				pm.delete( newrigjointchildren )			
		return newrigjoints
Exemplo n.º 23
0
def exportShader(path):
    """씬안에 쉐이딩 그룹으로 부터 정보를 모아 shaderInfoNode에 저장 한후 
    입력 받은 경로에 shader를 저장 한다.
    
    :param path: 파일 경로
    :type path: str
    
    """
    sgGrps = getShadingEngine()

    shaderInfos = []
    exportList = []

    for sg in sgGrps:
        shaderInfo = getShaderInfo(sg)
        shaderInfos.append(shaderInfo)
        if shaderInfo['surfaceShader'] != '':
            exportList.append(shaderInfo['surfaceShader'])
        if shaderInfo['displacement'] != '':
            exportList.append(shaderInfo['displacement'])

    numAttr = len(shaderInfos)

    if pm.objExists('shaderInfoNode'):
        shaderInfoNode = pm.PyNode('shaderInfoNode')
        shaderInfoNode.unlock()
        pm.delete(shaderInfoNode)
    shaderInfoNode = pm.createNode('network', n='shaderInfoNode')
    shaderInfoNode.addAttr('shaderInfos', at='compound', nc=numAttr)

    for i in range(numAttr):
        attrName = 'shaderInfos' + str(i)
        shaderInfoNode.addAttr(attrName, dt='string', p='shaderInfos')

    for i, shaderInfo in enumerate(shaderInfos):
        attrName = 'shaderInfos' + str(i)
        jsonHandl = json.dumps(shaderInfo)
        shaderInfoNode.attr(attrName).set(jsonHandl)
        shaderInfoNode.attr(attrName).lock()

    shaderInfoNode.lock()

    exportList.append(shaderInfoNode)
    pm.select(exportList)
    try:
        pm.exportSelected(path, pr=1, typ='mayaBinary', force=1, es=1)
        print 'Success Export Shader'
    except:
        print exportList
        print path

    finally:
        shaderInfoNode.unlock()
        pm.delete(shaderInfoNode)
Exemplo n.º 24
0
 def create_joint(self, **kwargs):
     crv = kwargs.get("crv_node", "")
     if isinstance(crv, list):
         crv = pm.PyNode(crv[0])
     crv = pm.PyNode(crv)
     shp = crv.getShape()
     pm.select(clear=True)
     ctr = pm.joint()
     pm.parent(shp, ctr, relative=True, shape=True)
     pm.delete(crv)
     return ctr
 def replaceInstances(self, parentNode, instanceNodes):
     for instanceNode in instanceNodes:
         trans = pm.getAttr(str(instanceNode) + '.translate')
         rot = pm.getAttr(str(instanceNode) + '.rotate')
         scl = pm.getAttr(str(instanceNode) + '.scale')
         pm.delete(instanceNode)
         pm.duplicate(parentNode, name=str(instanceNode))
         pm.setAttr(str(instanceNode) + '.translate', trans)
         pm.setAttr(str(instanceNode) + '.rotate', rot)
         pm.setAttr(str(instanceNode) + '.scale', scl)
     return
def mergeGroup( group ) :
	p = group.getParent()
	n = group.name().replace( '_split', '_G' )
	if( len( group.getChildren() ) < 2 ) :
		combinedmesh = group.getChildren()[0]
	else :
		combinedmesh = pm.polyUnite(group, ch=False)[0]

	combinedmesh.setParent(p)
	combinedmesh.rename( n )
	
	pm.delete(group)	
Exemplo n.º 27
0
def CopyJntOri(**kwargs):
    """
	    Copy orientation of one joint to another
	"""
    sel = pm.ls(selection=True)
    sel_jnts = kwargs.get("joint_selection", sel)
    print sel_jnts
    ref = sel_jnts.pop(0)
    for jnt in sel_jnts:
        ori_cnst = pm.orientConstraint(ref, jnt, maintainOffset=False)
        pm.delete(ori_cnst)
        pm.makeIdentity(apply=True, rotate=True)
    return None
Exemplo n.º 28
0
 def deleteFacesInSamePlace( self, faces_list, precision, tolerance ):
     faces = faces_list[:]
     face_center_dict = {}
     faces_to_delete = []
         
     for face in faces:
         pm.select( face )
         face_center = self.getFaceCenter( precision )
         if face_center in face_center_dict.keys():
             faces_to_delete.append( face )
             print( "marking face for deletion: " + str( face)   )
         else:
             face_center_dict[ face_center ] = face
     pm.delete( faces_to_delete )
Exemplo n.º 29
0
def project_curves_onto_mesh(mesh, curves_grp, direction):
    # projected_curves = []
    mesh = mesh
    old_meshes = []
    for i, curve in enumerate(curves_grp.getChildren()):
        try:
            if (not type(curve.getShape()) is pm.NurbsCurve):
                continue
        except:
            continue

        while True:
            nv = len(mesh.vtx)
            mesh = delete_vertex(mesh)
            if (len(mesh.vtx) == nv): break

        projected_curves = pm.polyProjectCurve(mesh,
                                               curve,
                                               direction=direction)[0]
        pm.delete(projected_curves.getChildren()[1:])
        projected_curve = projected_curves.getChildren()[0]

        split_mesh = pm.polySplit(mesh,
                                  detachEdges=0,
                                  projectedCurve=projected_curve)
        # print projected_curve
        split_mesh = split_mesh[0]

        pm.delete(split_mesh, ch=True)
        old_meshes.append(mesh)

        mesh = split_mesh

        if (projected_curves):
            pm.delete(projected_curves)

        # if( i == 10 ) : return

    for old_mesh in old_meshes:
        try:
            pm.delete(old_mesh)
        except:
            pm.warning('Could not delete %s' % (old_mesh))

    pm.polyTriangulate(mesh)
    # pm.polyQuad( mesh )
    # -ver 1 -trm 0 -p 50 -vct 0 -tct 0 -shp 0.5326 -keepBorder 1 -keepMapBorder 1 -keepColorBorder 1 -keepFaceGroupBorder 1 -keepHardEdge 1 -keepCreaseEdge 1 -keepBorderWeight 0.5 -keepMapBorderWeight 0.5 -keepColorBorderWeight 0.5 -keepFaceGroupBorderWeight 0.5 -keepHardEdgeWeight 0.5 -keepCreaseEdgeWeight 0.5 -useVirtualSymmetry 0 -symmetryTolerance 0.01 -sx 0 -sy 1 -sz 0 -sw 0 -preserveTopology 1 -keepQuadsWeight 1 -vertexMapName "" -replaceOriginal 1 -cachingReduce 1 -ch 1
    # pm.polyReduce( mesh, ver=True, trm=False, p=50, replaceOriginal=True, kb=True, kbw=1.0, kmb=True, kmw=1.0, kfb=True, kfw=1.0, kqw=1.0 )
    pm.polySoftEdge(mesh, a=180, ch=True)
    pm.delete(mesh, ch=True)
Exemplo n.º 30
0
def assignShader():
    """씬안에서 shaderInfoNode 노드를 검색 한다.\n
    shaderInfoNode 노드에 shaderInfos# 어트리뷰트를 검색한다.\n
    shaderInfos# 어트리뷰트의 값을 json 으로 가져 온다.\n
    어트리뷰트의 geometry, surfaceShader, displacement 키 값을 가져 온다.\n
    geometry에 surfaceShader, displacement 적용 한다.\n
    shaderInfoNode 삭제 한다.
    
    .. warning:: 
        씬안에 'shaderInfoNode' 노드가 없을 때 ``shaderInfoNode not exist!`` 예외 발생
    """
    try:
        shaderInfoNode = pm.PyNode('shaderInfoNode')
    except:
        print '"shaderInfoNode" not exist!'

    numAttr = shaderInfoNode.shaderInfos.numChildren()

    message = ''
    for i in range(numAttr):
        shaderInfos = json.loads(
            shaderInfoNode.attr('shaderInfos{}'.format(i)).get())
        geos = []
        for geo in shaderInfos.get('geometry'):
            if pm.objExists(geo):
                geos.append(geo)
        try:
            pm.select(geos)

            surfaceShader = pm.PyNode(shaderInfos.get('surfaceShader'))
            pm.hyperShade(assign=surfaceShader)
            pm.select(cl=True)
            try:
                if shaderInfos.get('displacement'):
                    displacement = pm.PyNode(shaderInfos.get('displacement'))
                    sg = surfaceShader.outColor.outputs()[0]
                    displacement.displacement.connect(sg.displacementShader)
            except:
                message += (str(shaderInfos.get('displacement')) + '-->' +
                            sg.name() + '\n')
        except:
            message += (str(shaderInfos.get('surfaceShader')) + '-->' +
                        str(geos) + '\n')

    shaderInfoNode.unlock()
    pm.delete(shaderInfoNode)

    if message:
        print 'Failed list:\n'
        print message
Exemplo n.º 31
0
    def at_selection(self, **kwargs):
        # get inputs
        setup_name = kwargs.get("name", None)
        path_name = kwargs.get("path", None)
        sample_obj = kwargs.get("sample", None)
        obj_lst = kwargs.get("selection_list", None)
        full_length = pm.arclen(path_name)
        paramVal = []
        uVal = []
        for obj in obj_lst:
            pos = pm.xform(obj, query=True, translation=True, worldSpace=True)
            param = self.getuParamVal(pnt=pos, crv=path_name)
            paramVal.append(param)
        crv_shp = pm.listRelatives(path_name, shapes=True)[0]
        arcLen = pm.arcLengthDimension(crv_shp + ".u[0]")
        for val in paramVal:
            pm.setAttr(str(arcLen) + ".uParamValue", val)
            len_at_pos = pm.getAttr(str(arcLen) + ".arcLength")
            uVal.append(len_at_pos / full_length)
        pm.delete(arcLen)
        path_anim_list = []
        if not self.get_use_selection():
            obj_lst = []
            if sample_obj:
                for i in uVal:
                    obj_lst.append(
                        pm.duplicate(sample_obj,
                                     name=setup_name + str(i + 1) + "_OBJECT"))
            else:
                for i in uVal:
                    pm.select(clear=True)
                    obj_lst.append(
                        pm.joint(name=setup_name + str(i + 1) + "_JNT"))

        index = 0
        for u in uVal:
            pm.select(clear=True)
            pathanim = pm.pathAnimation(obj_lst[index],
                                        curve=path_name,
                                        fractionMode=True,
                                        follow=True,
                                        followAxis="x",
                                        worldUpType="vector",
                                        worldUpVector=(0, 1, 0))
            index += 1
            path_anim_list.append(pathanim)
            pm.setAttr(str(pathanim) + ".uValue", u)
            pm.disconnectAttr(str(pathanim) + ".u")
        return (obj_lst, path_anim_list)
Exemplo n.º 32
0
def delete_layers(**kwargs):
    lyrs = pm.ls(type="displayLayer")
    lyrs.remove("defaultLayer")
    if not lyrs:
        raise RuntimeError("display layers", "No display layers found")
    print("Objects in layers")
    for lyr in lyrs:
        objs = pm.editDisplayLayerMembers(lyr, query=True)
        if objs:
            print("Layer : ", lyr)
            print(":::::::::::::::::::::::::")
            for obj in objs:
                print(obj)
            print("\n")
    pm.delete(lyrs)
Exemplo n.º 33
0
    def deletePass(self, layer = None):
        if layer is None:
            OpenMaya.MGlobal.displayError('[Arsenal] You must to select a pass')
            return 
        pm.editRenderLayerGlobals(currentRenderLayer='defaultRenderLayer')
        for dependance in pm.listConnections(layer + '.message', destination=True, source=False, type='arsenalPass'):
            pm.lockNode(dependance, lock=False)
            print '[Arsenal] ' + dependance + ' deleted.'
            pm.delete(dependance)

        if pm.objExists(layer):
            pm.delete(layer)
            print '[Arsenal] ' + layer + ' deleted.'
        if layer in self.passName:
            del self.passName[layer]
Exemplo n.º 34
0
def saveRenderGlobal():

    rgArnold   = pm.PyNode('defaultArnoldDriver')
    rgArnoldRO = pm.PyNode('defaultArnoldRenderOptions')
    rgCommon   = pm.PyNode('defaultRenderGlobals')
    rgRes      = pm.PyNode('defaultResolution')
    
    # get
    renderInfo = {}
    
    for attr in rgArnold.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
    
    for attr in rgCommon.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
        
    for attr in rgRes.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
        
    for attr in rgArnoldRO.listAttr():
        try:
            renderInfo[attr.name()] = cmds.getAttr(attr.name())
        except:
            pass
        
    # add data
    if pm.objExists('renderInfoNode'):
        lightInfoNode = pm.PyNode('renderInfoNode')
        lightInfoNode.unlock()
        pm.delete(lightInfoNode)
    lightInfoNode = pm.createNode('network', n='renderInfoNode')
    lightInfoNode.addAttr('renderInfo', dt='string')
    
    jsonHandl = json.dumps(renderInfo)
    lightInfoNode.attr('renderInfo').set(jsonHandl)
    lightInfoNode.attr('renderInfo').lock()
    

    print u'렌더 셋팅을 성공 적으로 저장 했습니다.'
Exemplo n.º 35
0
def copy_orientation():
    sel = pm.ls(selection=True)
    prnt = sel.pop(0)
    for obj in sel:
        tmp_con = pm.orientConstraint(prnt,
                                      obj,
                                      maintainOffset=False,
                                      name="tmp")
        pm.delete(tmp_con)
        pm.makeIdentity(apply=True,
                        translate=True,
                        rotate=True,
                        scale=True,
                        normal=False,
                        preserveNormals=True)
    return None
Exemplo n.º 36
0
def pivotToZeroDeleteHistoryAndFreezeTransformsInWorldSpace():

    original_selection = pm.ls(selection=True)
    objs = original_selection[:]

    for obj in objs:
        try:
            previous_parent = obj.getParent()
            pm.parent(obj, world=True)
            pm.move(obj.scalePivot, [0, 0, 0])
            pm.move(obj.rotatePivot, [0, 0, 0])
            pm.makeIdentity(obj, apply=True, normal=0, preserveNormals=True)
            pm.delete(ch=True)
            pm.parent(obj, previous_parent)
        except:
            print(traceback.format_exc())
Exemplo n.º 37
0
def pivotToZeroDeleteHistoryAndFreezeTransformsInWorldSpace():

    original_selection = pm.ls(selection = True)
    objs = original_selection[:]

    for obj in objs:
        try:
            previous_parent = obj.getParent()
            pm.parent( obj, world=True )                
            pm.move ( obj.scalePivot , [0,0,0] )
            pm.move ( obj.rotatePivot , [0,0,0] )
            pm.makeIdentity (obj, apply = True, normal = 0, preserveNormals = True )
            pm.delete (ch = True )
            pm.parent( obj, previous_parent )                
        except:
            print( traceback.format_exc()     )
def splitSelection() :

	__st(0)
	workingList, sel = getMeshesRecursivelyFromSelection()

	gMainProgressBar = pm.PyUI(pm.mel.eval( '$tmp = $gMainProgressBar' ))
	gMainProgressBar.setMaxValue( len(workingList) )

	if( len(workingList) > 0 ) :
		try :
			outputGrp = pm.PyNode(OUTPUT_GRP_NAME)
		except (pm.MayaNodeError) :
			outputGrp = pm.group(name=OUTPUT_GRP_NAME, world=True, empty=True)						

		outputContents = outputGrp.getChildren()
		for child in outputContents :
			pm.delete(child)

		
		pm.uitypes.ProgressBar.beginProgress(
			gMainProgressBar,
			status="Splitting meshes..."
		)
		gMainProgressBar.step(0)
		pm.refresh()


		for mesh in workingList :
			splitByMaterials(mesh, outputGrp)
			gMainProgressBar.step(1)
			pm.refresh()

		materialGroups = outputGrp.getChildren()
		for group in materialGroups :
			mergeGroup(group)
			
	else :
		pm.warning( 'No meshes found in selection' )

	gMainProgressBar.endProgress()

	# pm.select(sel)
	pm.select(outputGrp)

	print 'Splitting mesh by material COMPLETE'

	__et(0, 'Total')
def project_curves_onto_mesh( mesh, curves_grp, direction ) :
	# projected_curves = []	
	mesh = mesh
	old_meshes = []
	for i, curve in enumerate( curves_grp.getChildren( ) ) :		
		try :
			if( not type(curve.getShape()) is pm.NurbsCurve ) :				
				continue
		except :			
			continue				

		while True :
			nv = len(mesh.vtx)
			mesh = delete_vertex(mesh)
			if( len(mesh.vtx) == nv ) : break

		projected_curves = pm.polyProjectCurve( mesh, curve, direction=direction )[0]
		pm.delete( projected_curves.getChildren()[1:] )
		projected_curve = projected_curves.getChildren()[0]		

		split_mesh = pm.polySplit( mesh, detachEdges=0, projectedCurve=projected_curve )
		# print projected_curve
		split_mesh = split_mesh[0]

		pm.delete( split_mesh, ch=True )
		old_meshes.append( mesh )	

		mesh = split_mesh			

		if( projected_curves ) :
			pm.delete( projected_curves )

		# if( i == 10 ) : return

	for old_mesh in old_meshes :
		try : pm.delete( old_mesh )
		except : 
			pm.warning( 'Could not delete %s' % (old_mesh) )
	

	pm.polyTriangulate( mesh )
	# pm.polyQuad( mesh )
	# -ver 1 -trm 0 -p 50 -vct 0 -tct 0 -shp 0.5326 -keepBorder 1 -keepMapBorder 1 -keepColorBorder 1 -keepFaceGroupBorder 1 -keepHardEdge 1 -keepCreaseEdge 1 -keepBorderWeight 0.5 -keepMapBorderWeight 0.5 -keepColorBorderWeight 0.5 -keepFaceGroupBorderWeight 0.5 -keepHardEdgeWeight 0.5 -keepCreaseEdgeWeight 0.5 -useVirtualSymmetry 0 -symmetryTolerance 0.01 -sx 0 -sy 1 -sz 0 -sw 0 -preserveTopology 1 -keepQuadsWeight 1 -vertexMapName "" -replaceOriginal 1 -cachingReduce 1 -ch 1
	# pm.polyReduce( mesh, ver=True, trm=False, p=50, replaceOriginal=True, kb=True, kbw=1.0, kmb=True, kmw=1.0, kfb=True, kfw=1.0, kqw=1.0 )
	pm.polySoftEdge( mesh, a=180, ch=True )
	pm.delete( mesh, ch=True )
Exemplo n.º 40
0
def dupXformNoChildren( obj ):
    ## takes only a single object
    assert type(obj) == pymel.core.nodetypes.Transform
    print( obj )
    
    dupShapesFinal = []
    tempDuplicatedXforms = []
    
    for s in obj.getShapes():
    
        s = obj.getShape()

        ## we need a temporary xform to move the shape to
        tempXform = pm.createNode('transform')
        pm.parent( s, tempXform, shape=True, relative=True )

        ## Duplicate the original shape
        ## we'll get a new duplicate of the transform
        ## and our duplicated shape node will be its shape
        dups = pm.duplicate( s )
        tempDuplicatedXform = dups[0]
        tempDuplicatedXforms.append( tempDuplicatedXform )
        
        dupShapesFinal.append( tempDuplicatedXform.getShape() )
    
        ## Now put the original xform back where we got it from!
        pm.parent( s, obj, shape=True, relative=True )
        pm.delete( tempXform )
        
        ## Now we should be back where we started, except with a new
        ## duplicated shape node at the origin, with a indentity
        ## xform node
        
    ## Now that we have duplicates of all the shapes,
    ## we need a duplicated xform node
    dupList = pm.duplicate( obj, parentOnly=True, returnRootsOnly=True )
    dupXform = dupList[0]
    ## Now parent all the duplicated shapes to the duplicated xform
    for s in dupShapesFinal:
        pm.parent( s, dupXform, shape=True, relative=True )
        
        
    ## We have to delete tempInplaceXform later, because we need it for a bit
    pm.delete( tempDuplicatedXforms )
Exemplo n.º 41
0
    def backSetting(self, *args):
        if pm.attributeQuery('deeXVrayFastActualSettings', n='vraySettings', ex=True):
            if pm.objExists('deeXVrayFastExpression'):
                pm.delete('deeXVrayFastExpression')
                print '[Arsenal Quality] OdeeXVrayFastExpression deleted.'
            lines = pm.getAttr('vraySettings.deeXVrayFastActualSettings')
            dico = eval(lines)
            for myAttr in dico:
                value = dico[myAttr]
                if type(dico[myAttr]) == list:
                    value = dico[myAttr][0]
                if value:
                    try:
                        locked = 0
                        if pm.getAttr('vraySettings.' + myAttr, lock=True) == 1:
                            pm.setAttr('vraySettings.' + myAttr, lock=False)
                            locked = 1
                        pm.setAttr('vraySettings.' + myAttr, value)
                        if locked == 1:
                            pm.setAttr('vraySettings.' + myAttr, lock=True)
                    except:
                        print '[Arsenal Quality] ' + myAttr + ' value can not be setted.'

            locked = False
            if pm.lockNode('vraySettings', query=True, lock=True)[0]:
                locked = True
                pm.lockNode('vraySettings', lock=False)
            attToDelete = ['deeXVrayFastLastQuality',
             'deeXVrayFastOptimized',
             'deeXVrayFastActualSettings',
             'deeXVrayFastoptimizationChooserSettings',
             'deeXVrayFastLastTypePreset',
             'deeXVrayFastLastPresetPreComp']
            for myAttr in attToDelete:
                if pm.attributeQuery(myAttr, n='vraySettings', ex=True):
                    pm.deleteAttr('vraySettings.' + myAttr)

            if locked:
                pm.lockNode('vraySettings', lock=True)
            print '[Arsenal Quality] Original settings applied.'
        else:
            print '[Arsenal Quality] deeXVrayFastActualSettings attribute not found'
Exemplo n.º 42
0
def createTwistJointToSelectedChild():
    objs = pm.ls(selection=True)

    ## Make an empty list to store joints in
    newJoints = []

    for obj in objs:
        pm.select( clear=True )
        child = obj
        parentJnt = obj.getParent()
        jnt = pm.joint(position=[0,0,0])


        pc = pm.pointConstraint( [parentJnt, child] , jnt )
        oc = pm.orientConstraint( parentJnt, jnt )
        pm.delete( pc )
        pm.delete( oc )
        pm.parent( jnt, parentJnt )
        ## Put out new joint in the list!
        newJoints.append( jnt )
def __create_curve_from_edge( edge ) :
	edgeloop = __get_edge_loop( edge, [], None )
	edgeloop.insert(0, edge )
	edge_curves = []
	for edgeloop_edge in edgeloop :
		edge_curves.append( pm.curve(
			# name=n,
			degree=1,
			ws=True,
			point=[ v.getPosition() for v in edgeloop_edge.connectedVertices() ]
		) )	

	pm.select(None)
	if( len( edge_curves ) > 1 ) :
		merged_curve = pm.attachCurve( edge_curves[:-1], method=1, keepMultipleKnots=False, ch=False )[0]
		edge_curves.pop( edge_curves.index(merged_curve) )
		# closed_curve = pm.closeCurve( merged_curve )[0]
		closed_curve = merged_curve
		# pm.delete( merged_curve )
	else :
		closed_curve = None
	pm.delete( edge_curves )		
	return closed_curve, edgeloop
Exemplo n.º 44
0
    def deleteNegativeSide( self, selectionToFilter = None ):
        if selectionToFilter == None:
            selectionToFilter = pm.ls(selection=True)
        ## Bail early if we have no selected things to operate on!
        if len(selectionToFilter) == 0:
            return

        pm.mel.eval( 'PolySelectConvert 3;')
        verts = pm.ls(selection=True, flatten=True)
        vertsToDelete= []
        for vert in verts:
            x,y,z = pm.pointPosition( vert )
            if x < -0.0000000001:
                print( "For vert at:"+str(x)   )
                vertsToDelete.append( vert )
        try:
            ## fv and tf mean fromVertex, toFace
            facesToDelete = pm.polyListComponentConversion( vertsToDelete, fv=True, tf=True)
            faceToDelete = pm.ls(facesToDelete, flatten=True)
            pm.delete( facesToDelete )
            pm.select( selectionToFilter )
        except:
            print("Minor exception. No faces are on negative side to delete.")
Exemplo n.º 45
0
def duplicateShape( shape, selectDup=False ):

        '''
        Duplicates the shape node, does not by default select the result.
        Takes as an argument a single pymel shape node.
        '''

        oSel = pm.ls(selection=True)
        
        ## we need a temporary xform to move the shape to
        originalParent = shape.getParent()
        tempXform = pm.createNode('transform')
        pm.parent( shape, tempXform, shape=True, relative=True )

        ## Duplicate the original shape
        ## we'll get a new duplicate of the transform
        ## and our duplicated shape node will be its shape
        ## it's guaranteed to be a simple one xform
        ## hierarchy because we started from the new xform we created
        dups = pm.duplicate( shape )
        tempDuplicatedXform = dups[0]
        dupShape = tempDuplicatedXform.getShape()
        
    
        ## Now put the original xform back where we got it from!
        ## also parent new duplicated shape back to original xform
        pm.parent( shape, originalParent, shape=True, relative=True )
        pm.parent( dupShape, originalParent, shape=True, relative=True )
        ## Clean up the temporary xforms that were used
        pm.delete( tempXform )
        pm.delete( tempDuplicatedXform )
        
        ## restore selection and return result
        if selectDup==False:
            pm.select( oSel )
        return dupShape
Exemplo n.º 46
0
def __create_clean_object( obj ) :
	dup_obj = obj.duplicate()[0]
	ok_type_list = [ pm.Transform ]
	for dup_child in dup_obj.getChildren( ad=True, type='transform' ) :
		ok = True		
		if( not type(dup_child) in ok_type_list ) : ok = False		
		
		if( FFU_E_SETTINGS.get( 'hidden_ignore_bool' ).value ) :
			if( not dup_child.isVisible() ) : ok = False
		
		if( ok ) :
			dup_child_translation = dup_child.getTranslation()
			dup_child_rotation = dup_child.getRotation()
			for i, axis in enumerate( [ 'x', 'y', 'z' ] ) :
				flipsetting = 'flip'+axis
				if( FFU_E_FFEXPORT_SETTINGS.get(flipsetting).value ) :
					dup_child_translation[i] = -dup_child_translation[i]
					# dup_child_rotation[i] = -dup_child_rotation[i]
			dup_child.setTranslation( dup_child_translation )
			dup_child.setRotation( dup_child_rotation )


			if( type( dup_child.getShape() ) == pm.Mesh ) :
				# removed this to try fixing positions by applying appropriate flipping - see above
				# dup_child.setPivots( ( 0,0,0 ), ws=True )
				# pm.makeIdentity( dup_child, translate=True, apply=True )
				try : pm.polyTriangulate( dup_child )
				except : pm.warning( 'Could not triangulate %s' % ( dup_child ) )
			
			# pm.delete( dup_child, ch=True )			
			# pm.bakePartialHistory( dup_child, prePostDeformers=True )

		else :		
			pm.delete( dup_child )

	return dup_obj
            shapesToDelete = []
            shapes = obj.getShapes()
            for shape in shapes:
                ## get the number of faces on the shape
                facesCount = shape.numFaces()
        
                ## Find out if it is an intemediate shape
                isIntermediate = shape.intermediateObject.get()
        
                print( "isIntermediate: " + str(isIntermediate) )
        
                if facesCount == 0   or   isIntermediate==True:
                    shapesToDelete.append( shape )
            ## Now that extra shapes are deleted, check to see if any
            ## shapes are left, and if not, delete the entire object
            pm.delete( shapesToDelete )
            
            ## Get shapes again, partly too see if any are left at all
            ## if no shapes are left, delete the transform node
            shapes = obj.getShapes()
            if len(  obj.getChildren()  ) == 0:
                objsToDelete.append( obj )
    except:
        print( "error on obj: " + obj.name()  )
        print( traceback.format_exc()   )

print( shapesToDelete )
pm.delete( objsToDelete )


pm.select( oSel )
Exemplo n.º 48
0
    def importPass(self, paths = list()):
        if not paths:
            return 
        for path in paths:
            splited = path.split('.')
            splited.pop(-1)
            arpassinfo = '.'.join(splited) + '.arpassinfo'
            strFile = self.readTxtFile(path=arpassinfo)
            objectsNotFound = []
            if strFile:
                dico = eval(strFile)
                if not pm.objExists(dico['layer']['name']):
                    renderLayer = pm.createRenderLayer(name=dico['layer']['name'], g=dico['layer']['global'])
                else:
                    renderLayer = pm.PyNode(dico['layer']['name'])
                arsenalPassName = renderLayer.name() + '_arsenalPass'
                if pm.objExists(arsenalPassName):
                    pm.lockNode(arsenalPassName, lock=False)
                    pm.delete(arsenalPassName)
                pm.importFile(path, defaultNamespace=True)
                if renderLayer.name() != 'defaultRenderLayer':
                    for member in dico['layer']['members']:
                        listMembers = dico['layer']['members'][member]
                        if pm.objExists(listMembers[0]):
                            renderLayer.addMembers(listMembers[0])
                        elif pm.objExists(listMembers[1]):
                            if len(pm.ls(listMembers[1])) == 1:
                                renderLayer.addMembers(listMembers[1])
                        elif pm.objExists(listMembers[2]):
                            if len(pm.ls(listMembers[2])) == 1:
                                renderLayer.addMembers(listMembers[2])
                        elif pm.objExists(listMembers[3]):
                            if len(pm.ls(listMembers[3])) == 1:
                                renderLayer.addMembers(listMembers[3])
                        else:
                            objectsNotFound.append(listMembers[0])

                for member in dico['connections']:
                    dicoMembers = dico['connections'][member]
                    dsts = dicoMembers['destination']
                    listMembers = dicoMembers['sources']
                    if pm.objExists(listMembers[0]):
                        for dst in dsts:
                            pm.connectAttr(listMembers[0], dst, f=True)

                    elif pm.objExists(listMembers[1]):
                        if len(pm.ls(listMembers[1])) == 1:
                            for dst in dsts:
                                pm.connectAttr(listMembers[1], dst, f=True)

                    elif pm.objExists(listMembers[2]):
                        if len(pm.ls(listMembers[2])) == 1:
                            for dst in dsts:
                                pm.connectAttr(listMembers[2], dst, f=True)

                    elif pm.objExists(listMembers[3]):
                        if len(pm.ls(listMembers[3])) == 1:
                            for dst in dsts:
                                pm.connectAttr(listMembers[3], dst, f=True)


            else:
                OpenMaya.MGlobal.displayError('[Arsenal] Can not open ' + arpassinfo)
                return 
            if objectsNotFound:
                OpenMaya.MGlobal.displayError('[Arsenal] Object(s) not found in the scene : \n' + '\n'.join(objectsNotFound))
                return 
            self.refreshArsenalPass()
def project_curves_onto_mesh2( mesh, source_mesh, direction ) :
	# duplicate sources_mesh
	dup_source_mesh = pm.duplicate( source_mesh )[0]
	dup_source_mesh.setParent(None)

	# create curve around mesh	
	edge_curves = []
	for edge in mesh.getShape().e :
		edge_curves.append( pm.curve(
			# name=n,
			degree=1,
			ws=True,
			point=[ v.getPosition(space='world') for v in edge.connectedVertices() ]
		) )
	merged_curve = pm.attachCurve( edge_curves, method=1, keepMultipleKnots=False, ch=False )[0]
	merged_curve = pm.duplicate( merged_curve )
	pm.delete( edge_curves )

	# project curve onto dup_source_mesh	
	projected_curves = projected_curves = pm.polyProjectCurve( dup_source_mesh, merged_curve, direction=direction )[0]
	# pm.delete( projected_curves.getChildren()[1:] )
	projected_curve = projected_curves.getChildren()[0]

	split_mesh = pm.polySplit( dup_source_mesh, detachEdges=0, projectedCurve=projected_curve )	
	split_mesh = split_mesh[0]	

	# delete faces not within mesh bounds
	# faces_to_delete = []
	pm.select(None)
	for face in split_mesh.f :
		face_center = ( 0.0, 0.0, 0.0 )
		for v in face.connectedVertices() :
			face_center += v.getPosition( space='world' )
		face_center /= len( face.connectedVertices() )		

		if( point_in_rect_bb( face_center, mesh.getBoundingBox( space='world' ) ) ) :
			# faces_to_delete.append( face )
			dot = face.getNormal( space='world' ).dot( mesh.f[0].getNormal( space='world' ) )
			if( dot > 0.0 )	 :
				pm.select(face, add=True)
		
	# for face in faces_to_delete :		
	# 	dot = face.getNormal( space='world' ).dot( mesh.f[0].getNormal( space='world' ) )
	# 	if( dot > 0.0 )	 :
	# 		pm.select(face, add=True)

	pm.runtime.InvertSelection()
	pm.delete()

	# transfer UVs from mesh to dup_source_mesh
	pm.transferAttributes( mesh, split_mesh, transferUVs=2 )

	# assign mesh material to dup_source_mesh


	# rename dup_source_mesh to mesh
	pm.delete( split_mesh, ch=True )
	n = mesh.name()
	p = mesh.getParent()
	pm.delete( mesh )
	split_mesh.rename( n )

	for attr in split_mesh.listAttr() :		
		if attr.isLocked() : attr.setLocked(False)


	# cleanup

	pm.delete( projected_curves )
	pm.delete( merged_curve )
	pm.delete( dup_source_mesh )

	# split_mesh.centerPivots( True )
	# t = split_mesh.getPivots( worldSpace=1 )[0]
	# split_mesh.setTranslation((-t[0], -t[1], -t[2]), space='world')		
	# pm.makeIdentity( split_mesh, apply=True )
	# split_mesh.setParent( p )
	# split_mesh.setTranslation( ( 0,0,0 ) )
	# pm.makeIdentity( split_mesh, apply=True )

	# position bodge
	split_mesh.setTranslation( ( 0, 0, 1 ), space='world' )
	split_mesh.setParent( p )

	pm.polyTriangulate( split_mesh )

	if( not split_mesh.hasAttr( THU_MFT_SPRITE_ATTR ) ) :
		split_mesh.addAttr( THU_MFT_SPRITE_ATTR, dt='string' )
	split_mesh.setAttr( THU_MFT_SPRITE_ATTR, split_mesh.name().replace( '.png', '' ) )
Exemplo n.º 50
0
	def orient( self, orientchildless=True, rotationorder=None ) :
		# get the rotation order
		if( not rotationorder ) : rotationorder = settings.rotationorder

		# check we have a child to aim to and decide on aim vectors
		aimvector, upvector = utils.aim_axis_to_vectors( rotationorder )

		# if no children make aimvector is inverse of joint direction
		children = self.getChildren()
		parent = self.getParent()
		if( not parent ) : parent = self
		if( len( children ) < 1 ) :
			if( not orientchildless ) :
				utils.wrn( '%s has no children. Skipping orient...' % ( self.name() ) )
				return False
			else :
				aimvector = [ a * b for a, b in zip( aimvector, [-1] * 3 ) ]

		pm.select([])

		# create children average aim loc
		childrenlocator = pm.spaceLocator()
		if( len( children ) ) :			
			pm.delete( pm.pointConstraint( children + [ childrenlocator ], mo=False ) )
		else :
			childrenlocator.setTranslation( parent.getTranslation( space='world' ), space='world' )

		# create up aim loc and aim self towards it
		uplocator = pm.spaceLocator()
		pm.delete( pm.pointConstraint( [ parent, self, childrenlocator, uplocator ], mo=False ) )
		pm.delete( pm.aimConstraint( [ self, uplocator ], mo=False, wut='object', wuo=parent ) )
		uplocator.translateBy( ( 0, 0, 0.5 ) )

		# unparent children, aim the joint to the average of it's children, then reparent children
		for joint in children : joint.setParent( None )
		pm.delete( pm.aimConstraint( 
			[ childrenlocator, self ],
			mo=False,
			wut='object',
			wuo=uplocator,
			upVector=upvector,
			aim=aimvector
		) )
		pm.makeIdentity( self, a=True, r=True )
		for joint in children : joint.setParent( self )

		# tidy up
		pm.delete( childrenlocator )
		pm.delete( uplocator )
		pm.select( self )

		return True
Exemplo n.º 51
0
def export_scene( 
	res_path,
	scene_file_path,
	model_rel_path,
	texture_rel_path='',
	material_name='',
	selected_only=False,
	insert=False,
	insert_node_name=None
	) :
	
	print 'Exporting scene'

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

	sel = pm.ls( sl=True )

	objects = __get_object_list( selected_only )
	root = et.Element( 'Scene' )
	for obj in objects :
		clean_obj = __create_clean_object( obj )
		__recursive_create_scene_xml( 
			clean_obj,
			root,
			res_path,
			scene_file_path,
			model_rel_path,
			texture_rel_path,
			material_name			
		)
		pm.delete( clean_obj )

	tree = et.ElementTree( root )

	if( insert ) :
		try : old_tree = et.parse( scene_file_path )
		except : pm.error( 'Scene file is not an XML document' )
		if( old_tree ) : 
			element_to_insert_into = old_tree.find( ".//*[@name='%s']" % ( insert_node_name ) )
			if( not element_to_insert_into ) :
				pm.error( 'Could not find SceneObject named %s to insert into' % ( insert_node_name ) )
			for e in element_to_insert_into.findall( 'SceneObject' ) :
				element_to_insert_into.remove( e )
			index = len( list( element_to_insert_into ) )
			for e in list( tree.getroot() ) :
				element_to_insert_into.insert( index, e )
			tree = old_tree
	
		version_comment = et.Comment( '%s : Exported using ff_utils.export version %s' % ( time.strftime("%d/%m/%Y %H:%M:%S"), FFU_E_VERSION ) )
		tree.getroot().insert( 0, version_comment )

	xml_string = md.parseString( et.tostring( tree.getroot() ) ).toprettyxml( indent='\t' )
	xml_string = os.linesep.join( [ line for line in xml_string.split( os.linesep ) if line.strip() ] )

	with open( scene_file_path, 'w' ) as f :				
		f.write( xml_string )

	pm.select( sel )

	print 'Exporting scene finished'
	return True
import pymel.all as pm

objs = pm.ls(selection=True)

## Make an empty list to store joints in
newJoints = []

for obj in objs:
    pm.select( clear=True )
    child = obj
    parentJnt = obj.getParent()
    jnt = pm.joint(position=[0,0,0])


    pc = pm.pointConstraint( [parentJnt, child] , jnt )
    oc = pm.orientConstraint( parentJnt, jnt )
    pm.delete( pc )
    pm.delete( oc )
    pm.parent( jnt, parentJnt )
    ## Put out new joint in the list!
    newJoints.append( jnt )

pm.select( newJoints )
Exemplo n.º 53
0
    def bake( self, modelsPath="", highSuffix="", xnormalExe="", xmlFiles="", cageSuffix="", typeSuffixes="", cageOffset=None ):
        
        try:
            cmds.progressWindow( endProgress=True )
        except:
            pass  #print( "..." )
        cmds.progressWindow(isInterruptable=1)

        
        if highSuffix=="":
            highSuffix="_hi"
        
        if cageSuffix=="":
            cageSuffix= "_cage"
        
        if cageOffset==None:
            cageOffset=2.0
        
        if typeSuffixes=="":
            typeSuffixes=['normals','heights','vcols', 'occlusion', 'curvature', 'cavity']
        typeOfTypeSuffixes = type(typeSuffixes)
        if typeOfTypeSuffixes==type( "a_string" ) or typeOfTypeSuffixes==type( u"a_unicode_string" ):
            typeSuffixes = typeSuffixes.split(",")

        
        xnormal_exe = xnormalExe.replace("\\","/")
        folder_with_high_models = modelsPath.replace("\\","/")
        xml_files = xmlFiles.split(',')

        objExt = ".obj"
        
        ## Set pythons current working directory
        os.chdir( folder_with_high_models )
        
        ## Get the selected objects, store as both an original selection
        ## and a copy of the original selection, objs
        osel = pm.ls(selection=True)
        objs = osel[:]
        
        scriptIsCanceled = False
        
        cancelCheckSleepTimeStartup = 0.5
        cancelCheckSleepTime = 0.01
        
        for obj in objs:
            time.sleep( cancelCheckSleepTimeStartup )
            if cmds.progressWindow(query=1, isCancelled=1):
                print( "Script canceled by user,   eg. escape key." )
                scriptIsCanceled = True
                break
            try: ## try each obj
                ## Select the object and set up some basic variables,
                ## such as the name and the python cwd
                pm.select( obj )                
                obj_name = obj.name()
                cwd = os.getcwd()
                cwdUni = unicode(cwd)
                
                ## Triangulate before export
                print( obj )
                tri_op = pm.polyTriangulate( obj )
                
                ## Export lo,  triangulated
                export_target_including_file_and_path = os.getcwd().replace("\\","/") + "/" + obj_name + objExt
                pm.select( obj )
                pm.exportSelected(
                    export_target_including_file_and_path,sh = 1, pr = 1, typ = "OBJexport", es = 1, force=True
                )
                
                print( obj )
                
                try:
                    cageOffsetCustom = obj.mmmmBakerCageOffset.get()
                except:
                    cageOffsetCustom = cageOffset
                    print( "no custom cage offset found, using default" )
                
                trans_op = pm.polyMoveVertex( obj, localTranslateZ=cageOffsetCustom )
                
                ## Export Cage
                export_target_including_file_and_path = \
                    os.getcwd().replace("\\","/") + "/" + obj_name + cageSuffix + objExt
                pm.select( obj )                    
                pm.exportSelected( export_target_including_file_and_path,
                    sh = 1, pr = 1, typ = "OBJexport", es = 1, force=True
                )
                
                ## Cleanup cage offset and triangulation
                pm.delete( trans_op )
                pm.delete( tri_op )
                
                
                            #if obj_name.endswith( lo_suffix ):
                            #    high_name = obj_name.replace( lo_suffix, highSuffix )
                            #else:
                high_name = obj_name + highSuffix
                    

                for i, xml_file in enumerate(xml_files):
                    time.sleep( cancelCheckSleepTime )                
                    if cmds.progressWindow(query=1, isCancelled=1):
                        scriptIsCanceled=True
                        print( "Script canceled by user,   eg. escape key." )
                        break
                    
                    pm.select( obj )
                    pm.mel.eval(  "ConvertSelectionToUVs;" )
                    uvs = pm.ls(selection=True, flatten=True)
                    coUV =  pm.polyEditUV( uvs, query=True )
                    coU, coV = coUV[::2], coUV[1::2]
                    pm.select(obj)
                    
                    
                    """"
                    for c in coU:
                        if c >= 0.0 and c < 1.0:
                            udim1001=True  
                        if c >= 1.0 and c < 2.0:
                            udim1002=True    
                        if c >= 2.0 and c < 3.0:
                            udim1003=True    
                        if c >= 3.0 and c < 4.0:
                            udim1004=True
                    """

                            
                    dictOfUsedUvRanges = {}
                    for cIndex in xrange( len(coU) ):
                        tu = coU[cIndex]
                        tv = coV[cIndex]
                        tuInt = math.floor( tu )
                        tvInt = math.floor( tv )
                        
                        dictOfUsedUvRanges[ tuInt,tvInt ] = int( 1000 + (tuInt+1) + (tvInt*10) )
                        
                    #print(   "length of dictionary:")
                    #print(   len(  dictOfUsedUvRanges.keys()  )    )
                    #break
                    
                    
                    for keyRange, udim   in dictOfUsedUvRanges.items():
                        uInKey = keyRange[0]
                        vInKey = keyRange[1]
                        uOffset = uInKey * -1.0
                        vOffset = vInKey * -1.0
                        if uOffset==0.0:
                            uOffset=0.0  #in case of negative 0.0, f*****g hell!
                        if vOffset==0.0:
                            vOffset=0.0  #in case of negative 0.0, f*****g hell!
                            
                        
                        
                        # do something similar for vOffset.
                        ## edit xml export with uOffset and uOffset here!
                        
                    
                        """"
                        if udim1001==True: uOffsets.append( 0.0 )
                        if udim1002==True: uOffsets.append( -1.0 )
                        if udim1003==True: uOffsets.append( -2.0 )
                        if udim1004==True: uOffsets.append( -3.0 )
                        

                        
                        
                        for uOffset in uOffsets:
                        """
                        
                        time.sleep( cancelCheckSleepTime )
                        if cmds.progressWindow(query=1, isCancelled=1):
                            scriptIsCanceled=True
                            print( "Script canceled by user,   eg. escape key." )
                            break
                        xml_file_abs = os.path.join( cwdUni, xml_file )
                        print( xml_file_abs )
                        xml_file_modified = u'tmp_mmmmBaker.xml'
                        xml_file_modified_abs = os.path.join( cwdUni, xml_file_modified )
                        
                        xml_in_mem = ''
                        with open( xml_file_abs, 'r' ) as fh:
                            xml_in_mem = fh.read()
                        
                        xml_in_mem = xml_in_mem.replace(
                             'UOffset="0.', 'UOffset="' + str(uOffset)
                        )
                        xml_in_mem = xml_in_mem.replace(
                             'VOffset="0.', 'VOffset="' + str(vOffset)
                        )
                        
                        uOffsetAsInt = int( -1 * uOffset)
                        vOffsetAsInt = int( -1 * uOffset)
                        
                        
                        folder_with_high_models__no_trailing_slash = \
                            folder_with_high_models
                        if folder_with_high_models__no_trailing_slash.endswith("/"):
                            folder_with_high_models__no_trailing_slash =\
                                folder_with_high_models__no_trailing_slash[:-1]
                        xml_in_mem = xml_in_mem.replace(
                             "C:\\Users\\Public\\mmmmBaker",
                             folder_with_high_models.replace("/","\\")
                        )                        
                        
                        root = XmlTree.fromstring(xml_in_mem)
                        
                        ## Print the entire xml tree for reference'
                        #print( XmlTree.tostring( root ) )
                        
                        ## find used udims on objects
                        ## find u offset and v offset for low objects
                        ## set up a list to run a for loop for to
                        ## handle each udim found
                        
                        ## find low object
                        ## find cage object
                        ## find use cage option
                        #
                        ## find hi objects
                        ## find output

                        with open( xml_file_modified_abs, 'w' ) as fh:
                            fh.write( xml_in_mem )
                    
                        print( obj )
                        ##print( xml_in_mem )
                        print( uOffsetAsInt, vOffsetAsInt )    
                    
                    
                        try:
                            lo_to_copy_for_replacement = obj_name + objExt
                            cage_to_copy_for_replacement = obj_name + cageSuffix + objExt
                            hi_to_copy_for_replacement = obj_name + highSuffix + objExt
                                
                            shutil.copy2(lo_to_copy_for_replacement, "replaceme_lo" + objExt)
                            shutil.copy2(hi_to_copy_for_replacement, "replaceme_hi" + objExt)
                            shutil.copy2(cage_to_copy_for_replacement, "replaceme_cage" + objExt)

                            print( "xnormal subprocess starting...")
                            print(    xnormal_exe + " " + str(xml_file_modified)    )
                            subprocess.check_call( [ xnormal_exe, str(xml_file_modified)  ] )
                            print( "xnormal subprocess complete!  Continuing...")
                            for typeSuffix in typeSuffixes:
                                try:
                                    baked_name = "replaceme_" + typeSuffix + ".exr"
                                    proper_name = obj_name + "_" + "xml"+str(i).zfill(2) + "_" + "udim" + str( udim ) + "_" + typeSuffix + ".exr"
                                    shutil.copy2( baked_name, proper_name )
                                except:
                                    print(    traceback.format_exc()    )
                            
                        except:
                            print( traceback.format_exc() )

            except: ## except each obj
                print( traceback.format_exc() )
                
        pm.select( osel )
        
        ## Do something here to attempt to combine/composite textures together.
        ## Until then, just tell the user to use the photoshop action
        ## which should be provided with MmmmTools
        ## Add some explaination for how to use the action
        
        cmds.progressWindow( endProgress=True )
        if not scriptIsCanceled:
            print( "Baking complete!")
            print( "Baked (or at least attempted to bake) " + str( len(objs) ) + " objects." )
Exemplo n.º 54
0
	def create( self, _jointchain=None ) :
		super( IkRig, self ).create( _jointchain )

		jointchains = self.tree_children( 'jointchain' )
		if( len( jointchains ) != 1 ) :
			utils.err( 'IkRig children includes more than ONE jointchain. Not sure which to use. Skipping...' )
			return False		

		jointchain = jointchains[0]

		# create a simple joint chain
		simplejointchain = jointchain.duplicate_jointchain( self.PARTNAME, 'driver', _simple=True )
		self.add_child( simplejointchain )
		
		pm.PyNode( 'leftUpperArm_1_IKJ_DRIVER' ).hide()
		pm.PyNode( 'leftUpperArm_1_j' ).hide()

		for i in range( len( simplejointchain.rigjoints ) - 1 ) :
			# create a curve between each pair of simple rigjoints
			rigjoint1 = simplejointchain.rigjoints[i]
			rigjoint2 = simplejointchain.rigjoints[i+1]

			v1 = pm.datatypes.Vector( rigjoint1.getTranslation( space='world' ) )
			v2 = pm.datatypes.Vector( rigjoint2.getTranslation( space='world' ) )
			curvelength = float( v1.distanceTo( v2 ) )

			dirvector = [ a * b for a, b in zip( 
				( curvelength, curvelength, curvelength ),
				utils.aim_axis_to_vectors( settings.rotationorder )[0]
			) ]

			curve = pm.curve( degree=1, point=[
				( 0, 0, 0 ),
				dirvector
				# v1, v2
			], name=utils.name_from_tags( rigjoint1, 'curve' ) )

			# rebuild with numspan 2 and 3 degree
			pm.rebuildCurve( curve, degree=3, spans=2 )

			# move vtx[1] and vtx[-2] to respective ends of curve		
			curve.cv[1].setPosition( curve.cv[0].getPosition( space='world' ), space='world' )
			curve.cv[-2].setPosition( curve.cv[-1].getPosition( space='world' ), space='world' )

			ribbonlength = 0.2

			ribbon = pm.extrude(
				curve,
				polygon=0,
				useProfileNormal=1,
				extrudeType=0,
				length=ribbonlength,
				ch=False,
				name=utils.name_from_tags( rigjoint1, 'nurbs' )
			)[0]

			ribbon.setTranslation( ( 0, 0, -(ribbonlength)/2 ) )
			ribbon.setPivots( ( 0, 0, 0 ), worldSpace=True )
			pm.makeIdentity( ribbon, apply=True )
			pm.delete( ribbon, ch=True )
			pm.delete( curve )

			utils.create_zero_sdk_groups( ribbon, _replacelast=False )

			startcluster = pm.cluster( 	ribbon.cv[0:1][0:1], name=utils.name_from_tags( rigjoint1, 'start', 'cluster') )[1]
			midcluster = pm.cluster( 	ribbon.cv[2][0:1], name=utils.name_from_tags( rigjoint1, 'mid', 'cluster' ) )[1]
			endcluster = pm.cluster( 	ribbon.cv[-2:][0:1], name=utils.name_from_tags( rigjoint1, 'end', 'cluster' ) )[1]

			# parent clusters to respective rigjoints
			pm.parentConstraint( [ rigjoint1, startcluster ], mo=False )
			pm.parentConstraint( [ rigjoint2, endcluster ], mo=False )

			# group then point/parent constrain middle cluster to end clusters
			sdkgroup, zerogroup = utils.create_zero_sdk_groups( midcluster, _replacelast=False )
			zerogroup.setRotation( rigjoint1.getRotation( space='world' ), space='world' )
			pm.pointConstraint( [ rigjoint1, rigjoint2, zerogroup ], mo=False )
			pm.orientConstraint( [ rigjoint1, zerogroup ], mo=False )

			jointsToAttachToCurve = [ jointchain.rigjoints[i] ]
			jointsToAttachToCurve += jointchain.minorrigjoints[ jointsToAttachToCurve[0] ]
			jointsToAttachToCurve += [ jointchain.rigjoints[i+1] ]

	
			for rigjoint in jointsToAttachToCurve :

				p = rigjoint.getTranslation( space='world' )
				posi = pm.nodetypes.ClosestPointOnSurface()
				ribbon.worldSpace >> posi.inputSurface
				posi.inPosition.set( p )
				u = min( max( posi.u.get(), 0.001 ), 0.999 )
				v = min( max( posi.v.get(), 0.001 ), 0.999 )

				pm.delete( posi )

				follicleshape = pm.nodetypes.Follicle()
				ribbon.local >> follicleshape.inputSurface
				ribbon.worldMatrix[0] >> follicleshape.inputWorldMatrix
				follicleshape.parameterU.set( u )
				follicleshape.parameterV.set( v )
				
				follicle = follicleshape.getParent()
				follicle.rename( utils.name_from_tags( rigjoint, 'follicle' ) )
				follicleshape.rename( follicle.name() + 'Shape' )

				follicleshape.outRotate >> follicle.rotate
				follicleshape.outTranslate >> follicle.translate

				# remove any constraints already on the joint
				pm.delete( rigjoint.getChildren( type='constraint' ) )

				pm.parentConstraint( [ follicle, rigjoint ], mo=True )
				

		return True