Search code examples
pythonmayapymel

rename result node based on parent node


I'm writing a script that duplicates curves from a selected mesh.

Once it has created the curve, I want it to rename the result based on the name of the original mesh that it used to create the curve with a suffix. Eg.: 'meshName_Crv' or something like that.

import pymel.core as pm

#Select meshes to use as a source for copying the curves.
tarlist = pm.ls(selection=True, fl=True)

#Select an edge within the selected meshes
edgelist = pm.ls(selection=True, fl=True)

alledgelist = []

for i in edgelist:
    index = i.index()

for tar in tarlist:
    tarpy = pm.PyNode(tar)
    alledgelist.append(tarpy.e[index])

for edges in alledgelist:
    pm.select(edges)
    pm.mel.eval('SelectEdgeLoop;')
    pm.mel.eval('polyToCurve -form 2 -degree 3;')

Currently it is creating curves with the default name 'polyToCurve'. But I need to rename based on the original source mesh.

I know that me code is not perfect so far... I'd appreciate any advice and help.


Solution

  • Lots of command are documented : https://help.autodesk.com/cloudhelp/2018/CHS/Maya-Tech-Docs/CommandsPython/polySelect.html

    Lots of example for each command and also some flags like : -name

    if a command doesn't appear in this documentation, you can type in mel :

    whatIs commandName;
    

    it will give you the path of the module

    Also I like to use regex so I have inlcuded one here but you can remove it as I gave you an alternative line 22 (it just feels less cleaner but it works)

    import maya.cmds as cmds
    # if using regex
    import re
    #Select meshes to use as a source for copying the curves.
    # pSphere3 pSphere2 pSphere1
    tarlist = cmds.ls(selection=True, fl=True)
    
    #Select an edge within the selected meshes
    # pSphere3.e[636]
    edgelist = cmds.ls(selection=True, fl=True)
    
    # Result: [u'e[636]'] # 
    indexes = [i.split('.')[-1] for i in edgelist]
    
    # Result: [u'pSphere3.e[636]', u'pSphere2.e[636]', u'pSphere1.e[636]'] # 
    alledgelist = [t+'.'+i for i in indexes for t in tarlist]
    
    # regex = `anyString`.e[`anyDigit`] \\ capture what is in ``
    p = re.compile('(\w+).e\[(\d+)\]')
    for e in alledgelist:
        # without regex
        name, id = e.replace('e[', '')[:-1].split('.')
        # with regex
        name, id = p.search(e).group(1), p.search(e).group(2)
        edgeLoop = cmds.polySelect(name, el=int(id))
        cmds.polyToCurve(form=2, degree=3, name='edgeLoop_{}_{}'.format(name, id))