Example #1
0
def transferUVRigged(source, target, mode=3):
    shapes = pm.listRelatives(target, s=1, c=1, f=1)
    shapeOrig = None
    for shp in shapes:
        if pm.getAttr(shp + '.intermediateObject') and pm.listConnections(shp):
            shapeOrig = shp
    if shapeOrig:
        pm.setAttr(shapeOrig + '.intermediateObject', 0)
        pm.transferAttributes(source,
                              shapeOrig,
                              transferPositions=0,
                              transferNormals=0,
                              transferUVs=1,
                              transferColors=0,
                              sampleSpace=mode,
                              searchMethod=3,
                              flipUVs=0,
                              colorBorders=1)
        pm.delete(shapeOrig, ch=1)
        pm.setAttr(shapeOrig + '.intermediateObject', 1)
    else:
        pm.transferAttributes(source,
                              target,
                              transferPositions=0,
                              transferNormals=0,
                              transferUVs=1,
                              transferColors=0,
                              sampleSpace=mode,
                              searchMethod=3,
                              flipUVs=0,
                              colorBorders=1)
        pm.delete(target, ch=1)
    print 'transfer done!'
Example #2
0
def transfer_uv_skinned():
    # get selection
    selection = pm.ls(sl=True, transforms=True)
    shapes = selection[1].getShapes()

    # find "Orig" object on skinned mesh
    orig = None
    for shape in shapes:
        if shape.attr('intermediateObject').get():
            orig = shape
            orig.attr('intermediateObject').set(False)
            break

    # abort if no intermediate object was found
    if not orig:
        pm.warning("Could not find intermediate object on second transform.")
        return

    # transfer uvs from first object to base shape of the second
    pm.transferAttributes(selection[0],
                          orig,
                          transferPositions=0,
                          transferNormals=0,
                          transferUVs=2,
                          transferColors=0,
                          sampleSpace=5,
                          searchMethod=0,
                          flipUVs=0,
                          colorBorders=1)

    # delete history, so we can safely delete the second object afterwards
    pm.delete(orig, constructionHistory=True)
    orig.attr('intermediateObject').set(True)
Example #3
0
def TransferUvs():
    if len(pm.ls(selection=True)) < 2:

        pm.confirmDialog(message='Select Source and Select Targets',
                         title='Warning',
                         button='OK')

    else:

        Selection = pm.ls(selection=True)
        Source = Selection[0]
        Selection.pop(0)

        for object in Selection:
            pm.transferAttributes(Source,
                                  object,
                                  uvs=2,
                                  sampleSpace=4,
                                  sourceUvSpace="map1",
                                  targetUvSpace="map1",
                                  searchMethod=3,
                                  colorBorders=1)
            pm.select(clear=True)

        pm.inViewMessage(msg='<hl>Transfer_DONE</hl>.',
                         pos='midCenter',
                         fade=True)
Example #4
0
    def transfer_uvs(cls, sample_space=4):
        """transfer uvs between selected objects. It can search for
        hierarchies both in source and target sides.

        :parm sample_space: The sampling space:

          0: World
          1: Local
          2: UV
          3: Component
          4: Topology
        """
        selection = pm.ls(sl=1)
        pm.select(None)
        source = selection[0]
        target = selection[1]
        # auxiliary.transfer_shaders(source, target)
        # pm.select(selection)

        lut = auxiliary.match_hierarchy(source, target)

        for source, target in lut['match']:
            pm.transferAttributes(source,
                                  target,
                                  transferPositions=0,
                                  transferNormals=0,
                                  transferUVs=2,
                                  transferColors=2,
                                  sampleSpace=sample_space,
                                  sourceUvSpace='map1',
                                  searchMethod=3,
                                  flipUVs=0,
                                  colorBorders=1)
        # restore selection
        pm.select(selection)
Example #5
0
def uv_transfer():
    selection = pm.ls(os=True)
    if len(selection) == 2:
        obj_uv = selection[0]
        obj_destination = selection[1]
        relative = pm.listRelatives(obj_destination, children=True)
        logging.debug(relative)
        # get intermediate obj in relative.
        intermediate = pm.ls(relative, intermediateObjects=True)
        logging.debug(intermediate)
        len_inter = len(intermediate)
        logging.debug('Found {} intermediate objects.'.format(len_inter))
        for shape_orig in intermediate:
            shape_orig.intermediateObject.set(0)
            pm.transferAttributes(obj_uv,
                                  shape_orig,
                                  transferPositions=0,
                                  transferNormals=0,
                                  transferUVs=2,
                                  transferColors=0,
                                  sampleSpace=5,
                                  searchMethod=3,
                                  flipUVs=0,
                                  colorBorders=1)
            logging.info('UVs transfered.')
            pm.delete(shape_orig, ch=True)
            shape_orig.intermediateObject.set(1)
            logging.info('Operation successful.')

    else:
        # must select 2 objects.
        msg = 'Select object with UV, then select destination object.'
        raise Exception(msg)
Example #6
0
def transfer_uvs(*args):
    c = 0
    sel = pm.ls(selection=True)
    src_obj = sel[(len(sel) - 1)]
    sel.remove(src_obj)
    for m in sel:
        pm.select(clear=True)
        pm.select(src_obj)
        pm.select(sel[c], tgl=True)
        pm.transferAttributes(transferPositions=0,
                              transferNormals=0,
                              transferUVs=2,
                              transferColors=0,
                              sampleSpace=5,
                              sourceUvSpace='map1',
                              targetUvSpace='map1',
                              searchMethod=3,
                              flipUVs=0,
                              colorBorders=1)
        c += 1
    if pm.confirmDialog(m='Delete history on these?',
                        title='Delete history?',
                        button=['Yes', 'No'],
                        defaultButton='Yes',
                        cancelButton='No'):
        for m in sel:
            pm.delete(pm.PyNode(m), ch=True)
    pm.select(sel)
    pm.select(src_obj, tgl=True)
    pm.warning("Copied UVs from " + str(src_obj.name()) + " to " +
               str(len(sel)) + " meshes.")
 def snap(self):
     haircap = self.capName.getText()
     selected = pm.ls(sl =1, fl =1)
     if pm.objExists(haircap):
         for sel in selected:
             pm.transferAttributes(str(haircap), sel ,flipUVs=0, transferPositions=1, transferUVs=0, 
                 searchMethod=0, transferNormals=1, transferColors=0, sampleSpace=0)
     else: print 'define hair cap and add to script'
     pm.delete(selected, constructionHistory = 1)
Example #8
0
    def intersections(self, a, b):

        bDoutside = pm.duplicate(b, n="tmpBDoutside")[0]
        bDinside = pm.duplicate(b, n="tmpBDinside")[0]

        aCopyDupe = pm.duplicate(a, n="aCopyDupe")[0]

        dupes = [
            bDoutside,
            bDinside,
            aCopyDupe,
        ]

        for dupe in dupes:
            dupe.setParent(w=True)

        self.polygonVolume(bDinside, -.005)

        pm.polyColorPerVertex(bDinside, r=1, g=0, b=0, a=1, cdo=1)
        pm.polyColorPerVertex(bDoutside, r=0, g=0, b=0, a=1, cdo=1)
        bColoured = pm.polyUnite(bDoutside, bDinside, ch=False)[0]

        bColoured.setParent(w=True)
        pm.delete(bColoured, ch=True)

        pm.transferAttributes(bColoured,
                              aCopyDupe,
                              sourceColorSet="colorSet1",
                              targetColorSet="colorSet1",
                              transferColors=True,
                              sampleSpace=0,
                              colorBorders=1)

        pm.delete(aCopyDupe, ch=True)
        pm.delete(bColoured)
        aVerts = [
            str(a) + ".vtx[" + x.split("[")[-1].split("]")[0] + "]"
            for x in cmds.ls(str(aCopyDupe) + ".vtx[*]", fl=1)
            if cmds.polyColorPerVertex(x, q=1, rgb=1)[0] < .51
        ]
        #bVerts = [str(b)+".vtx["+x.split("[")[-1].split("]")[0]+"]" for x in cmds.ls(str(bCopyDupe)+".vtx[*]",fl=1) if cmds.polyColorPerVertex(x,q=1,rgb=1)[0] < .51]

        pm.delete(aCopyDupe)

        sel = pm.select(aVerts)
        selVerts = pm.ls(sl=True)
        pm.select(a)
        Verts = pm.select(pm.polyListComponentConversion(tv=True))
        allVerts = pm.ls(sl=True)
        pm.select(allVerts)
        pm.select(selVerts, d=True)
Example #9
0
def transfer_uvs(source, target):
	# TODO: Is there a way to detect which search methods to use in the command?
	# eg. sample random vertices to see if vtx numbering matches. If not, use world space.
	pm.transferAttributes (
		source, target,
		transferPositions=0,
		transferNormals=0,
		transferUVs=2,
		transferColors=0,
		sampleSpace=4, # 0 is world, 4 is component. 4 is best if topology hasn't changed
		sourceUvSpace='map1', targetUvSpace='map1',
		searchMethod=0, # 0 is closest along normal, 3 is closest to point
		flipUVs=0,
		colorBorders=1
	)
Example #10
0
def uv_transferHierarchy(space=4, searchMeth=3, deleteHistory=True, verbose=False):
    """Select two top groups and compare the entire hiearchy, where matches occur transfer UVs
	Args:
		space (int): transfer method 1-5, world=1, local=2, uv=3, component=4, topology=5
		searchMethod (int): determines closest point as default
		deleteHistory (boolean): deletes the history...
	Returns (boolean): True if success
	Usage:
		uv_transferHierarchy(space=1)
	"""
    sel = pm.ls(sl=True)
    sourceHierarchy = sel[0]
    targetHierarchy = sel[1]
    succeded = 0
    if len(sel) == 2:
        matches = cmph.hierarchyCompare(sourceHierarchy, targetHierarchy)
        for match in matches.keys():
            if pm.PyNode(match).getShape() and pm.PyNode(matches[match]).getShape():
                if (
                    pm.PyNode(match).getShape().type() == "mesh"
                    and pm.PyNode(matches[match]).getShape().type() == "mesh"
                ):
                    pm.transferAttributes(
                        match,
                        matches[match],
                        pos=False,
                        nml=False,
                        uvs=2,
                        col=False,
                        spa=space,
                        sus="map1",
                        tuv="map1",
                        searchMethod=searchMeth,
                        fuv=False,
                        clb=True,
                    )
                    if deleteHistory:
                        pm.delete(matches[match], ch=True)
                    succeded += 1
    else:
        pm.error("Must select 2 top nodes")
        return False
    print "A total of %d objects had their attributes transfered." % succeded
    if verbose:
        print repr(matches)
    pm.select(sel, r=True)
    return True
 def fill(self, times ):
     self.transform()
     selected = pm.ls(sl = 1)
     pm.select(cl = 1)
     if len(selected) >= 1:
         haircap = self.capName.getText()
         if len(selected) > 1:
             allNewHairs = []
             for n in range(len(selected)-1):
                 hair1 = selected[n]
                 hair2 = selected[n+1]
                 grp = pm.group(empty = True, name = 'HairGrp')
                 selfMatrix = selected[n].getMatrix()
                 hair2Matrix = selected[n+1].getMatrix()
                 grpMatrix = (selfMatrix + hair2Matrix)/2
                 grpMatrix = grpMatrix.homogenize()
                 grp.setMatrix(grpMatrix)
                 pm.parent([hair1, hair2], grp)
                 newHairs = []
                 for x in range(times-1):
                     newHair = pm.duplicate(hair1)[0]
                     newHair.setMatrix((selfMatrix*grpMatrix.inverse()).blend((hair2Matrix*grpMatrix.inverse()), weight = (x+1)*(1.0/times)))
                     #set blendshapes connecting new hair with the original hair
                     pm.blendShape(     hair1 ,newHair , w = (    0 , 1-(    (x+1)*(1.0/times)    )    )    )
                     #if hairs are the same connect the last one as well
                     if pm.polyEvaluate(hair1, v=1) == pm.polyEvaluate(hair2, v=1):
                         pm.blendShape(     hair2 ,newHair , w = (    0 , (x+1)*(1.0/times)    )    )
                     if pm.objExists(haircap) and self.transferCheckBox.getValue() == 1 :
                         pm.transferAttributes(haircap, newHair, sampleSpace=0,transferUVs=1, transferColors=0, sourceUvSet = 'map1',targetUvSet = 'map1')
                     newHairs.append(newHair)
                 pm.ungroup(grp)
                 allNewHairs.append(newHairs)
             if self.randSliderT.getValue() or self.randSliderR.getValue() > 0:
                 self.randomize(allNewHairs, transRot = 2)
             pm.select(allNewHairs)
         else:
             hair1 = selected[0]
             newHairs = []
             for x in range(times-1):
                 newHair = pm.duplicate(hair1)[0]
                 selfTrans = newHair.getTranslation()
                 selfRot = newHair.getRotation()
                 newHairs.append(newHair)
             if self.randSliderT.getValue() or self.randSliderR.getValue() > 0:
                 self.randomize(newHairs, transRot = 2)
             pm.select(newHairs)
     else: pm.error( "select something")
Example #12
0
def transferUV(source, destination):
    source = pm.ls(source)[-1]
    destination = pm.ls(destination)[-1]

    pm.select(source)
    pm.select(destination, add=True)

    pm.transferAttributes(transferPositions=0,
                          transferNormals=0,
                          transferUVs=2,
                          transferColors=2,
                          sampleSpace=0,
                          searchMethod=3,
                          flipUVs=0,
                          colorBorders=1,
                          sourceUvSpace="map1",
                          targetUvSpace="map1")
 def transfer(self):
     haircap = self.capName.getText()
     oldSel = pm.ls(sl = 1)
     pm.select(pm.ls(o=1, sl=1))
     selected = pm.ls(sl = 1)
     pm.select(cl = 1)
     myCurrentUvSet =  pm.polyUVSet(selected[0], q = True , currentUVSet = True )[0]
     if pm.objExists(haircap) and self.transferCheckBox.getValue() == 1:
         for object in selected:
             pm.transferAttributes(haircap, object, sampleSpace=0,transferUVs=1, transferColors=0, sourceUvSet = 'map1',targetUvSet = 'map1')
     elif len(selected) > 1 and self.transferCheckBox.getValue() == 0:
         last = selected.pop(-1)
         for object in selected:
             if pm.polyEvaluate(object, v = 1) ==  pm.polyEvaluate(last, v = 1):
                 pm.select([last, object])
                 pm.transferAttributes(sampleSpace=5,transferUVs=1, transferColors=0,sourceUvSet = myCurrentUvSet, targetUvSet = myCurrentUvSet )
     else: pm.error( "assign hair cap geo, or select more than one object with same topology")
     pm.select(oldSel)
Example #14
0
def reverseNormalsAndPreserveUVs(mesh):
    '''
    reverse normals but keep the uvs the same
    (don't change from blue to red, etc) 
    
    this will break uv seams!!!
    '''
    # duplicate the mesh to keep a copy of the correct uvs
    dupMesh = pm.duplicate(mesh)
    
    # reverse normals on the mesh
    pm.polyNormal(mesh, nm=0, ch=0)
    
    # transfer correct uvs back to mesh 
    pm.transferAttributes(dupMesh, mesh, uvs=2, spa=4)
    pm.delete(mesh, ch=True)
    
    # cleanup
    pm.delete(dupMesh)
    
Example #15
0
def yetitransfer(yetimeshsrs, yetimeshtrs):
    try:
        yetishapesrs = yetimeshsrs.getShape()
        yetishapetrs = yetimeshtrs.getShape()
    except:
        yetishapesrs = []
        yetishapetrs = []
        cmds.warning(str(yetishapesrs) + "'s shapeNode is not exists!!")
    #sruvset = pm.polyUVSet(yetishapesrs,q=1,currentUVSet=1)[0]
    #truvset = pm.polyUVSet(yetishapetrs,q=1,currentUVSet=1)[0]
    pm.transferAttributes(yetishapetrs,
                          yetishapesrs,
                          transferPositions=1,
                          transferNormals=1,
                          transferUVs=0,
                          transferColors=0,
                          sampleSpace=3,
                          sourceUvSpace='map1',
                          targetUvSpace='map1',
                          searchMethod=3,
                          flipUVs=0,
                          colorBorders=1)
    yetinodecol = yeticonnectAttr("pgYetiMaya", yetishapesrs, yetishapetrs)
    grmsels = yetishapesrs.listConnections(s=0, type="pgYetiGroom")
    grmcols = grmrebuild(grmsels, yetishapetrs)
    pm.select(yetimeshtrs, r=1)
    if pm.objExists(yetimeshtrs + "_reference") == True:
        pm.delete(yetimeshtrs + "_reference")
    try:
        mel.eval("CreateTextureReferenceObject")
    except:
        pass
    refmesh = cmds.listConnections(yetishapetrs + ".referenceObject",
                                   d=0,
                                   type="mesh")
    pm.group(yetinodecol,
             grmcols,
             refmesh,
             name=str(yetimeshtrs.split(":")[-1]) + "_yeti_G")
Example #16
0
def copyUV(objs=None):

    if not objs:
        objs = pm.ls(sl=True)
    else:
        objs = pm.ls(objs)

    if len(objs) < 2:
        return None

    for i in range(len(objs) - 1):
        pm.select(objs[-1])
        pm.select(objs[i], add=True)
        pm.transferAttributes(transferPositions=0,
                              transferNormals=0,
                              transferUVs=2,
                              transferColors=2,
                              sampleSpace=4,
                              sourceUvSpace="map1",
                              targetUvSpace="map1",
                              searchMethod=3,
                              flipUVs=0,
                              colorBorders=1)
Example #17
0
def copyUV( objs=None ):
	
	if not objs:
		objs = pm.ls( sl=True )
	else:
		objs = pm.ls( objs )
	
	if len( objs ) < 2:
		return None
	
	for i in range( len( objs )-1 ):
		pm.select( objs[-1] )
		pm.select( objs[i], add=True )
		pm.transferAttributes(
				transferPositions= 0 
				,transferNormals=0 
				,transferUVs=2 
				,transferColors=2 
				,sampleSpace=4 
				,sourceUvSpace="map1" 
				,targetUvSpace="map1" 
				,searchMethod=3
				,flipUVs=0 
				,colorBorders=1 )
Example #18
0
def relax():
    # check the selection
    selection = pm.ls(sl=1)
    if not selection:
        return

    # convert the selection to vertices
    verts = pm.ls(pm.polyListComponentConversion(tv=1))

    if not verts:
        return

    shape = verts[0].node()

    # duplicate the geometry
    dup = shape.duplicate()[0]
    dup_shape = dup.getShape()

    # now relax the selected vertices of the original shape
    pm.polyAverageVertex(verts, i=1, ch=0)

    # now transfer point positions using transferAttributes
    ta_node = pm.transferAttributes(
        dup,
        verts,
        transferPositions=True,
        transferNormals=False,
        transferUVs=False,
        transferColors=False,
        sampleSpace=0,
        searchMethod=0,
        flipUVs=False,
        colorBorders=1,
    )
    # delete history
    pm.delete(shape, ch=1)

    # delete the duplicate surface
    pm.delete(dup)

    # reselect selection
    pm.select(selection)
Example #19
0
def relax():
    # check the selection
    selection = pm.ls(sl=1)
    if not selection:
        return

    # convert the selection to vertices
    verts = pm.ls(pm.polyListComponentConversion(tv=1))

    if not verts:
        return

    shape = verts[0].node()

    # duplicate the geometry
    dup = shape.duplicate()[0]
    dup_shape = dup.getShape()

    # now relax the selected vertices of the original shape
    pm.polyAverageVertex(verts, i=1, ch=0)

    # now transfer point positions using transferAttributes
    ta_node = pm.transferAttributes(
        dup,
        verts,
        transferPositions=True,
        transferNormals=False,
        transferUVs=False,
        transferColors=False,
        sampleSpace=0,
        searchMethod=0,
        flipUVs=False,
        colorBorders=1,
    )
    # delete history
    pm.delete(shape, ch=1)

    # delete the duplicate surface
    pm.delete(dup)

    # reselect selection
    pm.select(selection)
Example #20
0
def _buildMorphTargets(mesh_type, figure):
    pm.importFile(figure.files[mesh_type], namespace=mesh_type+'Geo')
    tgt_mesh = pm.ls(mesh_type+'Geo:Mesh')[0]

    # Transfer existing blendshapes on imported mesh
    if tgt_mesh.inMesh.listConnections(type='blendShape'):
        dup_mesh = duplicateClean(tgt_mesh, name='TMP_'+figure.mesh.name())
        bs_node = tgt_mesh.inMesh.listConnections(type='blendShape')[0]

        # Transfer new shape to dup_mesh
        pm.transferAttributes(
            figure.mesh, dup_mesh, transferPositions=True, sampleSpace=3, targetUvSpace='UVOrig')
        pm.delete(dup_mesh, ch=True)
        # Add as target to tgt_mesh
        pm.blendShape(bs_node, edit=True, target=(
            tgt_mesh, len(bs_node.listAliases()), dup_mesh, 1.0))
        # Set new shape and lock
        bs_node.setAttr(dup_mesh.name(), 1.0, lock=True)

        new_shapes = transferShapes(
            bs_node, dup_mesh, tgt_prefix=mesh_type+'Geo:NEW_')

        # Delete existing blendshape targets
        for shp in bs_node.inputTarget.listConnections():
            pm.delete(shp)

        for shp in new_shapes:
            pm.rename(shp, shp.name().replace('NEW_', ''))

        pm.delete(tgt_mesh, ch=True)

    # Transfer new figure shape to base geo
    pm.transferAttributes(
        figure.mesh, tgt_mesh, transferPositions=True, sampleSpace=3, targetUvSpace='UVOrig')
    pm.delete(tgt_mesh, ch=True)

    target_lists = {
        'Head': pm.ls(('POS_*', 'SHP_*'), type='transform') + pm.ls(['JCM*' + limb + '*' for limb in ['Collar', 'Neck', 'Shldr']], type='transform'),
        'Body': pm.ls(('JCM_*', 'SHP_*'), type='transform')
    }

    # Create morph target meshes
    for src_mesh in target_lists[mesh_type]:
        new_mesh = duplicateClean(
            tgt_mesh, name=mesh_type+'Geo:'+src_mesh.name())
        pm.transferAttributes(
            src_mesh, new_mesh, transferPositions=True, sampleSpace=3, targetUvSpace='UVOrig')
        pm.delete(new_mesh, ch=True)
Example #21
0
uvmap = []

slSz=len(sl)

sc=sl[0]
tg=sl[1:]
i = 0
for i in xrange(len(tg)):
	sh=FindShMesh(sl[i])
	uvmap=pm.polyUVSet(sh, q=1, cuv=1)
	orig=FindOrigMesh(sl[0])
	if orig == "None":
		orig=FindShMesh(sl[0])
		pm.select(orig,tg[i])
		
		pm.transferAttributes(fuv=0, uvs=2, pos=0, clb=1, sus=str(uvmap[0]), sm=3, spa=1, nml=0, col=2)
		pm.delete(tg[i],ch=1)
		
	
	else:
		pm.setAttr((orig + ".intermediateObject"), 
			0)
		pm.select(sl[i])
		pm.select(orig, add=1)
		pm.transferAttributes(fuv=0, uvs=2, pos=0, clb=1, sus=uvs[0], sm=3, spa=1, nml=0, col=2)
		pm.delete(orig,ch=1)
		pm.setAttr((orig + ".intermediateObject"), 
			1)
		
	
def skrink_wrap(geo, proxy):
    print "skirink wrapping %s to %s" % (proxy, geo)
    pm.transferAttributes(geo, proxy, transferPositions=1, sampleSpace=0, searchMethod=3)