Monday, October 15, 2012

Selected Curve to Python Command

1 comments
In the process of making a control maker for python, I found it super annoying to manually figure out the command for a curve. This script will take the selected curve and return the command in python. SO MUCH EASIER.

Just run the script and type makePythonCommand("New Curve Name"). It should print out the commands for all curve types as well as transforms selected with multiple shapes under it.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import maya.cmds as mc

def makePythonCommand(name):
    try:
        curve = mc.ls(selection = True)[0]
        curveShapes = mc.listRelatives(curve, children = True, path= True, type = 'nurbsCurve')
    except:
        raise RuntimeError('Select a curve Please')    
    
    if name == '':
        name = 'What'
            
    for curveShape in curveShapes:
        #curveInfo    
        infoNode = mc.createNode('curveInfo')
        mc.connectAttr("%s.worldSpace[0]" %curveShape, "%s.inputCurve" %infoNode, force = True)
        
        #Find the knot values and get the numSpans,degree,form, and CVs
        knots = list(mc.getAttr('%s.knots' %infoNode)[0])
        numSpans = mc.getAttr('%s.spans' %curveShape)
        degree = mc.getAttr('%s.degree' %curveShape)
        form = mc.getAttr('%s.form' %curveShape)
        numCVs = numSpans + degree
        mc.delete(infoNode)
        
        if form == 2:
            numCVs -= degree
        
        cVs = mc.ls('%s.cv[0:%d]' %(curveShape, (numCVs-1)), flatten = True)        
        
        #For each cv get it's world position
        cvArray = [mc.xform(cv, q = True, ws = True, translation = True) for cv in cVs]
        
        if form == 2:
            cvArray.append(cvArray[0])
            cvArray.append(cvArray[1])
            cvArray.append(cvArray[2])
           
            pyCmd = 'mc.curve(name = "%s", per = True, d= %s,p= %s, k = %s)' %(name, degree, cvArray, knots)
            
        if degree == 1 and form !=2:
            pyCmd = 'mc.curve(name = "%s", d= 1,p= %s)' %(name, cvArray)
                            
        if degree >=2 and form !=2:     
            pyCmd = 'mc.curve(name = "%s", d= %s,p= %s, k = %s)' %(name, degree, cvArray, knots)
    
        print '\n%s' %pyCmd