Maya Python Temp

From bernie's
Jump to: navigation, search

list reference edits

import maya.cmds as cmds

for rl in cmds.ls(typ='renderLayer'):
    lc = cmds.listConnections(rl+'.adjustments', p=1, c=0);
    if lc:
        print('\n------------------------------\n'+rl+':\n------------------------------\n\t'+'\n\t'.join(lc))
    script = cmds.getAttr('%s.attributeOverrideScript' % rl)
    print script

Turn Deformers On/Off

#for now it's split in two
import maya.cmds as mc


envelopes = []

for o in mc.ls():
    if mc.attributeQuery('envelope', node=o, exists=True):
        if mc.getAttr(o+'.envelope',se=True):        
            envelopes.append([o,mc.getAttr(o+'.envelope')])
            mc.setAttr(o+'.envelope',0)
#-------------------------------------------------------------

for i in envelopes:
    mc.setAttr(i[0]+'.envelope',i[1])
envelopes = []

UI generation

import maya.cmds as mc

class buttonGenerator(object):
    
    def __init__(self):
        self.buildUI()
        
    def buttonPush(*args):
        mc.warning(args[0])

        
    def buildUI(self):
        mc.window('',title='UI',resizeToFitChildren=1,w=600)
        scrollLayout = mc.scrollLayout(horizontalScrollBarThickness=16,verticalScrollBarThickness=16)
        mc.columnLayout(adjustableColumn=True, columnAlign='center',rowSpacing=10)
        mc.rowLayout(numberOfColumns=3)
        mc.button(w=55,l="Refresh",c=self.buttonPush)

        mc.showWindow()
        
w = buttonGenerator()

super connection editor

from pymel.core import *

def buttonPressed(name):
    print "pressed %s!" % name
    
win = window(title="Super Connection Editor")
layout = horizontalLayout()
for i in range(5):
    button(label="button %s" % i,command = Callback( buttonPressed, i ) )
layout.redistribute()    # now will redistribute horizontally
win.show()

create prim from bounding box

import maya.cmds as mc




bbox = mc.xform(q=1,bb=1,ws=1)
bbox = mc.polyEvaluate(bc=1)
size = [(bbox[0][1]-bbox[0][0]),(bbox[1][1]-bbox[1][0]),(bbox[2][1]-bbox[2][0])]
center = [(bbox[0][1]+bbox[0][0])/2,(bbox[1][1]+bbox[1][0])/2,(bbox[2][1]+bbox[2][0])/2]


axises = [abs(size[2]-size[1]),abs(size[1]-size[0]),abs(size[2]-size[0])]

if

mc.polyCylinder(r=size[0])
mc.move(center[0],center[1],center[2])
sizes = [2 * x for x in center]

attach things to things ui

window = cmds.window( title="Attach stuff to stuff", iconName='Short Name', widthHeight=(150, 55),rtf=1 )
cmds.frameLayout(mh=10,mw=10,bv=0,l="")
cmds.columnLayout(adjustableColumn=True )
#cmds.rowLayout(adjustableColumn=True )
cmds.text( label='This script attaches objects to other\nobjects using follicles. Parent objects require\nnon-overlapping UVs.' )
cmds.text( label='\nObjects will be attached from their pivot\nto the closest point on parent mesh.\n In case of multiple parents, the script\nwill try to figure out which is the closest.\n' )
cmds.button( label='Set object(s) to attach' )
cmds.separator(st="none",h=10)
cmds.button( label='Set parent object(s) and apply', command=('cmds.deleteUI(\"' + window + '\", window=True)') )

#cmds.setParent( '..' )
cmds.showWindow( window )

counter animate

import maya.cmds as mc

#expects a poly face

#retrieve UV average

toUv =mc.polyListComponentConversion( tuv=True )
shp = mc.ls(sl=1,o=1)[0]
UVs = mc.polyEditUV(toUv, query=True )
U = V = 0.0
for i in range(len(UVs)/2):
    U += UVs[2*i]
    V += UVs[2*i+1]
U /= len(UVs)/2
V /= len(UVs)/2
 
#create follicle attach it

f = mc.createNode('follicle')
fObj = mc.listRelatives(f,p=1,f=1)[0]
mc.connectAttr(shp+".outMesh",f+".inputMesh")
mc.connectAttr(shp+".worldMatrix[0]",f+".inputWorldMatrix")
mc.connectAttr(f+".outTranslate",fObj+".translate")
mc.connectAttr(f+".outRotate",fObj+".rotate")
mc.setAttr(f+".parameterU", U)
mc.setAttr(f+".parameterV", V)


create curves on contact

import maya.cmds as mc


#### distance tooln, chopper les 2 objs ##########

mc.cycleCheck(c=1,e=0)                                                 #stop nag

obj = mc.ls(sl=1)[0]
targ = mc.ls(sl=1)[1]
objShp = mc.listRelatives(obj,s=1)[0]
targShp = mc.listRelatives(targ,s=1)[0]

objLoc = mc.spaceLocator()[0]
targLoc = mc.spaceLocator()[0]
objLocShp = mc.listRelatives(objLoc,s=1)[0]
targLocShp = mc.listRelatives(targLoc,s=1)[0]

cpom1 = mc.createNode('closestPointOnMesh')
mc.connectAttr(targShp+'.worldMesh[0]',cpom1+'.inMesh')
mc.connectAttr(targShp+'.worldMatrix[0]',cpom1+'.inputMatrix')
cpom2 = mc.createNode('closestPointOnMesh')
mc.connectAttr(objShp+'.worldMesh[0]',cpom2+'.inMesh')
mc.connectAttr(objShp+'.worldMatrix[0]',cpom2+'.inputMatrix')

mc.connectAttr(cpom1+'.result.position',objLoc+'.translate')
mc.connectAttr(cpom2+'.result.position',targLoc+'.translate')
mc.connectAttr(targLocShp+'.worldPosition',cpom1+'.inPosition')
mc.connectAttr(objLocShp+'.worldPosition',cpom2+'.inPosition')


dd = mc.distanceDimension(sp=(0,0,0),ep=(0,0,0))
mc.connectAttr(cpom1+'.result.position',dd+'.startPoint',f=1)
mc.connectAttr(cpom2+'.result.position',dd+'.endPoint',f=1)



#### select loc to bake, change threshold ################################

threshold = .06
substeps = 2

wallLoc = mc.ls(sl=1)[0]
wallLocShp = mc.listRelatives(wallLoc,s=1)[0]

resultLoc = mc.spaceLocator()[0]

start = int(mc.playbackOptions(q=1,min=1))
end = int(mc.playbackOptions(q=1,max=1))



strokePointList = []


for i in xrange(start*substeps,end*substeps,1):
    time = i*1.0/substeps
    mc.currentTime(time)
    for i in range(3):                          #nasty hack to force cleaner closestPointOnMesh cycle
        mc.setAttr(wallLoc+'.rotateY', 0)        
    dist = mc.getAttr(dd+'.distance')
    pos = mc.getAttr(wallLocShp+'.worldPosition')[0]
    mc.setAttr(resultLoc+'.translate',pos[0],pos[1],pos[2],type='double3')      
    mc.setKeyframe(resultLoc, at='translate')
    if dist<threshold:
        strokePointList.append(pos)
    elif len(strokePointList) > 2:
        print 'newCurve'
        mc.curve(p=strokePointList,d=1)
        strokePointList = []
    else:
        strokePointList = []
        
        
mc.select(wallLocShp)

zCtrl

import maya.cmds as mc

def oneCurveGrid(rezx=10,rezy=10,scalex=1,scaley=1):
    
    points = []

    sx = 1.0/(rezx-1)
    sy = 1.0/(rezy-1)

    
    for i in range(rezx/2):
    
    
        for j in range(rezy):
            points.append( [ ( 2.0 * i * sx -.5 ) * scalex , ( j * sy -.5 ) * scaley ,0] )
        for j in reversed(range(rezy)):
            points.append( [ ( ( 2.0* i + 1) * sx -.5 ) * scalex ,( j * sy -.5 ) * scaley ,0])
            
    for i in range(rezy/2):  
        for j in reversed(range(rezx)):
            points.append( [ ( j * sx -.5 ) * scalex , ( i*2.0 * sy -.5 ) * scaley ,0])
        for j in range(rezx):
            points.append( [ ( j * sx -.5 ) * scalex , ( ( i*2.0+1) * sy -.5 ) * scaley ,0])
    
    for i in reversed(range(rezx)):
        points.append( [((i * sx -.5)*scalex) ,((i * sx -.5)*scaley), 0])

    return points
    

def zControl():
    '''creates controllers to help with the focus distance. Plugs into 'focusDistance' of camera shape'''

    # choose cam 
    
    selection = mc.ls(sl=True)
    
    chosenCamera = False
    
    if len(selection) > 0:
        selShp = (selection[0],mc.listRelatives(selection[0],s=True))[mc.nodeType(selection[0])=='transform'] #gives us the shape
        if mc.nodeType(selShp) == 'camera':
            chosenCamera = selShp
    else:
        currentPanel = mc.getPanel(withFocus=True)
        if mc.getPanel(typeOf=currentPanel) == 'modelPanel':
            chosenCamera = mc.modelPanel(currentPanel,q=True,cam=True)
            chosenCamera = mc.listRelatives(chosenCamera,s=True)
            
    if not chosenCamera:
        mc.warning('Select camera or perspective view')    
    else:
        camObj = mc.listRelatives(chosenCamera,p=1)[0]
        camShape = chosenCamera[0]
        confirm  = mc.confirmDialog( title='Confirm', message='Create z-depth controller for "'+camObj+'" ?', button=['Yes','No'], defaultButton='Yes', cancelButton='No', dismissString='No' )
        if confirm == 'Yes':
    
            #spaghetti code below
            
            #floating locator system
            
            floatingZLoc = mc.curve(p=[[-0.319, -0.001, 0.0], [0.621, 0.94, 0.0], [-1.0, 0.94, 0.0], [-1.0, 1.06, 0.0], [1.392, 1.06, 0.0], [-0.608, -0.94, 0.0], [1.0, -0.94, 0.0], [1.0, -1.06, 0.0], [-1.379, -1.06, 0.0], [-0.319, -0.001, 0.0], [0.0, 0.0, 0.0], [-0.233, -0.233, -0.233], [0.233, 0.233, 0.233], [0.0, 0.0, 0.0], [-0.233, -0.233, 0.233], [0.233, 0.233, -0.233], [0.0, 0.0, 0.0], [-0.233, 0.233, -0.233], [0.233, -0.233, 0.233], [0.0, 0.0, 0.0], [0.233, -0.233, -0.233], [-0.233, 0.233, 0.233]],d=1,n=camObj+'_zDepth_FloatCtrl')
            projCurve = mc.curve(p=[[0,0,0],[0,0,1000]],d=1,n=camObj+'_longCurve')                    #create a curve to project our locator on
            pc = mc.parentConstraint(camObj,projCurve,mo=False)[0]                                    #curve follows camera
            mc.setAttr(pc+'.target[0].targetOffsetRotateY',180)
            cameraLocator = mc.spaceLocator(n=camObj+'_camLocator')[0]                                #locator on camera to get world position later
            mc.pointConstraint(camObj,cameraLocator,mo=False)
            floatingLocator = mc.spaceLocator(n=camObj+'_floatLocator')[0]                            #locator to get floating controller world pos
            mc.parent(floatingLocator,floatingZLoc)
            projectionLocator = mc.spaceLocator(n=camObj+'_projLocator')[0]                           #locator to project on curve
            
            nPoc = mc.createNode('nearestPointOnCurve')
            mc.connectAttr(mc.listRelatives(floatingLocator,s=True)[0]+'.worldPosition',nPoc+'.inPosition',f=True)
            mc.connectAttr(mc.listRelatives(projCurve,s=True)[0]+'.worldSpace',nPoc+'.inputCurve',f=True)
            mc.connectAttr(nPoc+'.position',projectionLocator+'.translate',f=True)
            
            db = mc.createNode('distanceBetween')
            mc.connectAttr(mc.listRelatives(projectionLocator,s=True)[0]+'.worldPosition',db+'.point1')
            mc.connectAttr(mc.listRelatives(cameraLocator,s=True)[0]+'.worldPosition',db+'.point2')
            
            #end result locator
            
            resultLocator = mc.spaceLocator(n=camObj+'resultLocator')[0]  
                  
            #camera based system
            
            cameraGrid = mc.curve(p=oneCurveGrid(18,10,4,2.25),d=1,n=camObj+'_zDepth_Ctrl')           #create a grid to visualize standard focus distance z
            cameraGridNull = mc.group(em=True,n=camObj+'_zDepth_Ctrl_ZERO')
            mc.parent(cameraGrid,cameraGridNull)
            mc.parent(resultLocator,cameraGridNull)
            pc2 = mc.parentConstraint(projCurve,cameraGridNull,mo=False)[0]
            mc.setAttr(cameraGrid+'.tz',mc.getAttr(camShape+'.focusDistance'))
    
            #choice system
            
            sr = mc.createNode('setRange')
            
            mc.setAttr(sr+'.oldMaxX',1)
            mc.setAttr(sr+'.oldMaxY',1)
            mc.setAttr(sr+'.maxY',0)
            mc.setAttr(sr+'.minY',1)
            mc.connectAttr(db+'.distance',sr+'.maxX',f=1)
            mc.connectAttr(cameraGrid+'.tz',sr+'.minX',f=1)           
            mc.connectAttr(sr+'.outValue.outValueX',resultLocator+'.tz',f=True)
            
                   
            arrow = mc.annotate(resultLocator,p=(0, 0, 0))
            arrowObj = mc.listRelatives(arrow,p=1)[0]
            arrowObj = mc.rename(arrowObj,camObj+'_zDistance')
            arrow = mc.listRelatives(arrowObj,s=1)[0]
            mc.parent(arrowObj,cameraGridNull,r=True)
            
            md = mc.createNode('multiplyDivide')                                                      #ridiculous hack to force annoation update
            mc.connectAttr(camObj+'.tx',md+'.input2.input2X')
            mc.connectAttr(sr+'.outValue.outValueX',md+'.input2.input2Y')
            mc.connectAttr(floatingZLoc+'.tx',md+'.input2.input2Z')
            mc.connectAttr(md+'.output',mc.listRelatives(arrow,p=1)[0]+'.translate')
            
            #mostly controls and cosmetic stuff
            
            for o in (projCurve,resultLocator,floatingLocator,projectionLocator,cameraLocator,pc2):
                mc.setAttr(o+'.visibility',False)
    
            for o in (cameraGrid,arrowObj):
                for p in ('tx','ty','tz','sx','sy','sz','rx','ry','rz'):
                    mc.setAttr(o+'.'+p,keyable=False,channelBox=False )
            mc.setAttr(cameraGrid+'.tz',keyable=True,channelBox=False )
            mc.setAttr(cameraGrid+'.tx',lock=True)
            mc.setAttr(cameraGrid+'.ty',lock=True)
    
    
            mc.addAttr(arrowObj,ln='focusDistance',attributeType='long')
            mc.setAttr(arrowObj+'.focusDistance',e=0,keyable=False,channelBox=True)
            mc.connectAttr(sr+'.outValue.outValueX',arrowObj+'.focusDistance',f=True)
            
            mc.addAttr(arrowObj,ln='useFloatingLocator',dv=0.0)
            mc.setAttr(arrowObj+'.useFloatingLocator',e=1,keyable=True,channelBox=False)
            mc.connectAttr(arrowObj+'.useFloatingLocator',sr+'.valueX',f=True)        
            mc.connectAttr(arrowObj+'.useFloatingLocator',sr+'.valueY',f=True)
    
    
            mc.setAttr(arrow+'.overrideEnabled',1)
            mc.setAttr(arrow+'.overrideColor',17)
            
            mc.setAttr(cameraGrid+'.overrideEnabled',1)
            mc.setAttr(cameraGrid+'.overrideColor',12)
            mc.setAttr(floatingZLoc+'.overrideEnabled',1)
            mc.setAttr(floatingZLoc+'.overrideColor',12)
            
    
            zFocusGroup = mc.group(em=True,n=camObj+'_zFocusGroup')
            mc.parent(cameraGridNull,floatingZLoc,projCurve,projectionLocator,cameraLocator,zFocusGroup)
            mc.connectAttr(resultLocator+'.tz',camShape+'.focusDistance',f=1)
            
            mc.select(arrowObj)
        
zControl()

locators on curve

import maya.cmds as mc
import maya.mel as mel
from random import uniform


def curveOnSurfaceFromCurve(curveObj,offsetDistance=0,offsetMove=[1,0,0]):
    offset1 = mc.offsetCurve(curveObj,ugn=0,d=offsetDistance)
    mc.setAttr(offset1[0]+".translate", offsetMove[0], offsetMove[1], offsetMove[2], type="double3")
    offset2 = mc.offsetCurve(curveObj,ugn=0,d=-offsetDistance)
    mc.setAttr(offset2[0]+".translate", -offsetMove[0], -offsetMove[1], -offsetMove[2], type="double3")
    loftObj = mc.loft(offset1,offset2,u=1,ch=1)[0]
    loftShp = mc.listRelatives(loftObj,s=1)[0]
    v = mc.getAttr(loftShp+'.minMaxRangeV.maxValueV')
    cOs = mc.curveOnSurface(loftObj,d=3,uv=((.5, 0),(0.5, 1*v/3), (0.5, 2*v/3), (0.5, v)))
    return cOs

def setLocs(*args):
    global pathAnims
    global curveObj
    global curveObjBase
    mini = mc.floatSliderGrp(args[0],q=1,v=1)
    maxi = mc.floatSliderGrp(args[1],q=1,v=1)
    rando = mc.floatSliderGrp(args[2],q=1,v=1)/50.0
    expr = 'float $v = '+curveObjBase+'.anim;\n'
    count = len(pathAnims)
    step = (maxi-mini)/float(count)
    for p in range(len(pathAnims)):
        expr = expr + pathAnims[p]+'.uValue = ($v + '+str(mini+step*float(p)+uniform(-rando,rando))+')%1;\n'
        print expr
    haveExp = mc.listConnections(curveObjBase+'.anim')
    if haveExp:
        mc.expression(haveExp[0],e=1,o=curveObjBase,  s=expr )
    else:
        mc.expression(o=curveObjBase, s=expr )

global curveObjBase
global curveObj
global pathAnims

curveObjBase = mc.ls(sl=1)[0]
curveObj = curveOnSurfaceFromCurve(curveObjBase)
curveShp = mc.listRelatives(curveObj,s=1)[0]
pathAnims = []

if mc.nodeType(curveShp) == 'nurbsCurve':
    result = mc.promptDialog(tx=10,message='Numb. of Locators:',button=['OK', 'Cancel'],defaultButton='OK',cancelButton='Cancel',dismissString='Cancel')
    if result == 'OK':
    	count = int(cmds.promptDialog(query=True, text=True))
        
                
        if mel.eval('attributeExists "anim" '+curveObjBase)==0:
            mc.addAttr(curveObjBase,ln="anim")
            mc.setAttr(curveObjBase+'.anim',e=1,k=1)
        for i in range(count):
            loc = mc.spaceLocator()
            pathA = mc.pathAnimation(loc[0],wut='normal',follow=True,fm=True,c=curveShp)
            #mc.pathAnimation(object,c=motionPathCurve,wut="normal",f=1,ua=customUpAxis,fa=customForwardAxis,fm=1,stu=mc.playbackOptions(q=1,minTime=1),etu=mc.playbackOptions(q=1,maxTime=1))
            #mc.setAttr(pathA+'.fractionMode',0)
            pathAnims.append(pathA)
            anim = mc.listConnections(pathA+'.uValue')[0] 
            mc.disconnectAttr(anim+'.output',pathA+'.uValue')
            mc.delete(pathA+'_uValue')
         
        window = mc.window(title='spacing')
        mc.columnLayout()
        a = mc.floatSliderGrp( label='start', field=True,cc=lambda _:setLocs(a,b,c) )
        b = mc.floatSliderGrp( label='end', field=True, value=1,cc=lambda _:setLocs(a,b,c) )
        c = mc.floatSliderGrp( label='random', field=True, value=0,cc=lambda _:setLocs(a,b,c) )
        mc.showWindow( window )
        setLocs(a,b,c)
        mc.select(curveObjBase)
    

attach 2-cv curves to other curves with cluster

from math import sqrt, fabs
import maya.cmds as mc

def mag(v1,v2):
    return sqrt(pow(v2[0]-v1[0],2) + pow(v2[1]-v1[1],2) + pow(v2[2]-v1[2],2))
    
#first make a selection of curves that will be parent (attached to) curves
stickToList = mc.ls(sl=1)

#####################################################################################
#####################################################################################
#####################################################################################
#####################################################################################


#for each selected curves, go through end and start cvs (this implies it's a 2 cv curve)
#get closest matching curve and its parm value, return it in a list
attachments = []
edges = mc.ls(sl=1)
for e in edges:
    for cv in range(2):
        pos = mc.xform(e+'.cv['+str(cv)+']',q=1,ws=1,t=1)
        #cv1 = mc.xform(e+'.cv[1]',q=1,ws=1,t=1)
        
        nearestDist = 99999.0
        selectedCurve = ''
        parm = -1
        npc = mc.createNode( 'nearestPointOnCurve')
        for item in stickToList:
            mc.connectAttr(mc.listRelatives(item,s=1)[0]+".worldSpace[0]", npc+".inputCurve", f=1)
            mc.setAttr(npc+".inPosition", pos[0], pos[1], pos[2], type="double3")
            nearPos =  mc.getAttr(npc+".position")[0]
            dist = mag(pos,nearPos)
            
            if dist < nearestDist:
                nearestDist = dist
                selectedCurve = item
                parm = mc.getAttr(npc+".parameter")
            #debug -- print(e+'.cv['+str(cv)+']'+' - '+str(item)+' : '+str(dist)+' ('+selectedCurve+')')
            
        mc.delete(npc)
        attachments.append([e+'.cv['+str(cv)+']',selectedCurve, parm])

#create clusters on each end attached to curves w/ motion path
for item in attachments:
    mc.select(item[0],r=1)
    cl = mc.cluster()
    pathAnim = mc.pathAnimation( cl, c=item[1] )
    inputs = mc.listConnections(pathAnim+".uValue", s=1)
    mc.disconnectAttr(inputs[0]+".output",pathAnim+".uValue")
    mc.setAttr(pathAnim+".uValue",item[2])



copy paste skin weights

import maya.cmds as mc
import maya.mel as mel

influences = []


def copySkinWeight():
    global influences
    vtx = mc.ls(sl=1,fl=1)
    obj = mc.ls(sl=1,o=1)[0]
    sc = mel.eval('findRelatedSkinCluster("'+obj+'")')
    
    values = mc.skinPercent(sc,str(vtx[0]),q=1,v=1,ib=0.0001)
    transforms = mc.skinPercent(sc,str(vtx[0]),q=1,t=None,ib=0.0001)
    influences = []
    for i in range(len(transforms)):
        influences.append((transforms[i],values[i]))

def pasteSkinWeight():
    global influences
    if len(influences) == 0:
        mc.warning('copy weights first')
    else:
        vtx = mc.ls(sl=1)
        mc.skinPercent(sc,vtx,tv=influences)


#add each def to shelf/function buttons
#copySkinWeight()
#pasteSkinWeight()

attach objects to closest objects

#to do: clean follicles
def attachThingsToThings(objects,targets,keepHierachy=True):
    '''requires closestUV closestDistanceToMesh'''
    for o in objects:
        parents = mc.listRelatives(o,p=1,f=1)
        smallest = 99999.9
        closest = u''
        outPos = []
        #p = mc.xform(o,ws=1,q=1,t=1)
        p = mc.xform(o,ws=1,q=1,rotatePivot=True)
        for r in targets:
            dist = closestDistanceToMesh(p,r)
            if dist < smallest:
                smallest = dist
                closest = r
                outPos = p
        follicle = closestUV(outPos,closest,attachFollicle=1)
        
        eg = mc.group(em=1,n=o+'zero')
        mc.parent(eg,o)
        mc.makeIdentity(eg)
        mc.parent(eg,w=1)
        mc.parent(o,eg)
        mc.parentConstraint(follicle,eg,mo=1)
        
        if keepHierachy and parents != None:
            mc.parent(eg,parents[0])

def closestDistanceToMesh(position,target):
    cpom = mc.createNode( 'closestPointOnMesh')
    targetMesh = mc.listRelatives(target,s=1)[0]
    
    mc.connectAttr(targetMesh+".worldMesh[0]",cpom+".inMesh")
    mc.connectAttr(targetMesh+".worldMatrix[0]",cpom+".inputMatrix")
    mc.setAttr(cpom+".inPosition", position[0], position[1], position[2], type="double3")

    x = mc.getAttr(cpom+".result.position.positionX")
    y = mc.getAttr(cpom+".result.position.positionY")
    z = mc.getAttr(cpom+".result.position.positionZ")
    p2 = [x,y,z]
    mc.delete(cpom)
    return mag(position,p2)

projected point on mesh + UVs

def intersect(object,target,bidirectional=1):
    '''returns a position if there's an intersetction'''
    targetMesh = mc.listRelatives(target,s=1)[0]
    poly = mc.polyPlane(sx=2,sy=2,w=.01,h=.01)[0]
    mc.parent(poly,object)
    mc.makeIdentity(poly)
    centervtx = str(poly)+".vtx[4]";
    pos = mc.pointPosition(centervtx)
    mc.select(poly,target,r=1)
    wrap = mc.deformer(poly,type="shrinkWrap" )[0]
    mc.connectAttr(targetMesh+".worldMesh[0]",wrap+".targetGeom")
    mc.setAttr(wrap+".projection",3)
    mc.setAttr(wrap+".bidirectional",bidirectional)
    pos2 = mc.pointPosition(centervtx)
    mc.delete(wrap,poly)
    
    if pos==pos2:
        return False
    else:
        return pos2
        
def closestUV(position,target,attachFollicle=0):
    '''target geo MUST have its transforms frozen'''
    cpom = mc.createNode( 'closestPointOnMesh')
    targetMesh = mc.listRelatives(target,s=1,f=1)[0]
    
    mc.connectAttr(targetMesh+".worldMesh[0]",cpom+".inMesh")
    mc.connectAttr(targetMesh+".worldMatrix[0]",cpom+".inputMatrix")
    mc.setAttr(cpom+".inPosition", position[0], position[1], position[2], type="double3")

    getU = mc.getAttr(cpom+".result.parameterU")
    getV = mc.getAttr(cpom+".result.parameterV")
    mc.delete(cpom)
    if attachFollicle:
        follicle = mc.createNode('follicle')
        follicleObj = mc.listRelatives(follicle,p=1,f=1)[0]
        mc.connectAttr(targetMesh+".outMesh",follicle+".inputMesh")
        mc.connectAttr(targetMesh+".worldMatrix[0]",follicle+".inputWorldMatrix")
        mc.connectAttr(follicle+".outTranslate",follicleObj+".translate")
        mc.connectAttr(follicle+".outRotate",follicleObj+".rotate")
        mc.setAttr(follicle+".parameterU", getU)
        mc.setAttr(follicle+".parameterV", getV)
        return follicleObj
    else:
        return [getU,getV]
        
        
import maya.cmds as mc
from math import sqrt

create oriented joints from edge loop

import maya.cmds as mc
import maya.mel as mel
from math import pi, sqrt, fabs

def bonesFromEdgeLoop(edgeLoop, numberOfBones = 4, front = [0,0,0]):
    '''creates a number of joints on edge loops, returns list of joints in the order'''
    numPoints = numberOfBones + 1
    edges = edgeLoop #expects an edge loop
    
    mc.setToolTo( 'moveSuperContext' )
    mmcMode = mc.manipMoveContext( 'Move', q=1, mode=1)
    mc.manipMoveContext( 'Move', e=1, mode=9) #set to normals avg
    
    #iteratate through edges, get normal and position, put locators
    locatorPositions = []
    locatorRotations = []
    locators = []
    for edge in edges:
        
        faces = mc.polyListComponentConversion(edge, tf=1)
        mc.select(faces,r=1)
        mmc = mc.manipMoveContext( 'Move', q=1, position=1, oa=1)
        
        loc = mc.spaceLocator()[0]
        
        locatorPositions.append([mmc[0],mmc[1],mmc[2]])
        locatorRotations.append([mmc[3],mmc[4],mmc[5]])
        
        mc.setAttr ( '%s.translate' % loc, mmc[0], mmc[1], mmc[2] )
        mc.setAttr ( '%s.rotate' % loc, deg(mmc[3]), deg(mmc[4]), deg(mmc[5]) )
       
        locators.append(loc)
    
    mc.manipMoveContext( 'Move', e=1, mode=mmcMode) #set it back
    
    
    mc.select(edges, r=1)
    edge = mel.eval('polyToCurve -form 2 -degree 1')[0]
    
    
    
    uParms = equidistantPoints(edge, numPoints , tolerance = 0.005)
    uPos = positionsFromParams(edge, uParms)
    
    edgeShape = mc.listRelatives(edge,s=1)[0]
    maxU = mc.getAttr(edgeShape+".maxValue")
    
    endA = mc.pointPosition( edge + '.u['+str(uParms[0])+']')
    endB = mc.pointPosition( edge + '.u['+str(uParms[-1])+']')
    
    curveStartOrigin = front                        # figuring out
    chooseStart = closest(curveStartOrigin,[endA,endB]) # which end is the start
    
    upLocators = []
    jointLocators = []
    joints = []
    
    for i in range(len(uParms)):
    
        n = len(uParms)-1-i if chooseStart else i
        pos = positionsFromParams( edge, [uParms[n]])[0]
     
        loc = mc.spaceLocator(p=[0,0,0])[0]
        jointLocators.append(loc)
    
        mc.setAttr(loc+".tx",pos[0])
        mc.setAttr(loc+".ty",pos[1])
        mc.setAttr(loc+".tz",pos[2])
        
        closestLoc = locators[closest(pos,locatorPositions)]
        upLoc = mc.duplicate(closestLoc)[0]
        upLocators.append(upLoc)
        mc.parent(upLoc,closestLoc)
        mc.setAttr(upLoc+".tx",.5)
        mc.parent(upLoc,w=1)
        
    
    for i in range(len(jointLocators)-1):
        
        ac = mc.aimConstraint( jointLocators[i+1], jointLocators[i], wut= 'object', wuo = upLocators[i] )
        mc.delete(ac)
    
    
    #set rot of last locator to the second to last
    
    r = list(mc.getAttr ( '%s.rotate' % jointLocators[-2] )[0])
    mc.setAttr ( '%s.rotate' % jointLocators[-1], r[0], r[1], r[2] )
    
    
    jointsList = []
    
    previousJnt = ""
    for i in range(len(jointLocators)):
        r = list(mc.getAttr ( '%s.rotate' % jointLocators[i] )[0])
        t = list(mc.getAttr ( '%s.translate' % jointLocators[i] )[0])
        mc.select(cl=1)
        jnt = mc.joint(p=t)
        mc.setAttr (jnt+'.jointOrientX', r[0])
        mc.setAttr (jnt+'.jointOrientY', r[1])
        mc.setAttr (jnt+'.jointOrientZ', r[2])
        if(previousJnt != ""):
            mc.parent(jnt,previousJnt)
        previousJnt = jnt
        if i == len(jointLocators)-1:
            jnt = mc.rename(jnt,jnt+'_end')
        jointsList.append(jnt)
        mc.select(cl=1)
    
    
    # tidy up
      
    mc.delete(upLocators,edge,locators,jointLocators)
    mc.select(jointsList[0],r=1)

    return jointsList






def deg(rad):
    return 180.0/pi*rad

def closest(point, list):
    index = -1
    min = 9999999.0
    for i in range(len(list)):
        dist = mag(list[i], point)
        if dist < min:
            min = dist
            index = i
    return index

def mag(v1,v2):
    return sqrt(pow(v2[0]-v1[0],2) + pow(v2[1]-v1[1],2) + pow(v2[2]-v1[2],2))

def cross(a, b):
    c = [a[1]*b[2] - a[2]*b[1],
         a[2]*b[0] - a[0]*b[2],
         a[0]*b[1] - a[1]*b[0]]

    return c

def positionsFromParams(curve, paramsList):
    pos = []
    for u in paramsList:
        pos.append(mc.pointPosition(curve+'.u['+str(u)+']' ))
    return pos

def equidistantPoints(curve, numPoints, tolerance = 0.005):
    '''plot equidistant points on a curve, return list of u params'''
    
    edgeShape = mc.listRelatives(curve,s=1)[0]
    maxU = mc.getAttr(edgeShape+".maxValue")
    
    ald = cmds.arcLengthDimension( curve+'.u['+str(maxU)+']')
    
    uParamsList = [0.0]
    curveTotalLength = mc.getAttr(ald+".arcLength")
    
    for i in range(numPoints-2):

        targetLength = curveTotalLength/(numPoints-1)*(i+1)
        uDelta = 1.0*maxU/2
        uparam = uDelta
        delta = tolerance + 1
        counter = 0
        
        while delta > tolerance:
         
            mc.setAttr(ald+".uParamValue", uparam )
            length = mc.getAttr(ald+".arcLength")
            
            delta = fabs(length-targetLength)
            uDelta /= 2
            
            if length>targetLength:
                uparam -= uDelta 
            else:
                uparam += uDelta
            #print(str(uparam)+" "+str(uDelta)+" "+str(counter)+" "+str(length))
        uParamsList.append(uparam)

    uParamsList.append(maxU)
    mc.delete(ald)
    return uParamsList

attach to curve with ribbon


import maya.cmds as mc
from math import sqrt


def attachToClosestPointOnCurve(useCurveOnSurface=True):
    #last element should be curve , no error checking - snaps to cloest point on mesh using motionPath
    
    sel = mc.ls(sl=1)
    curveObj = sel[len(sel)-1]
    sel.pop()

    if useCurveOnSurface:
        
        #positions = []
        #for ob in sel:
        #    positions.append(mc.xform(ob, q=1, ws=1, t=1))
        #curve = mc.curve( d=1, p=positions)

        bb = mc.xform(curveObj,ws=1,bb=1,q=1)
        size = sqrt(pow(bb[3]-bb[0],2) + pow(bb[4]-bb[1],2) + pow(bb[5]-bb[2],2)) / 150
        
        c1 = mc.offsetCurve(curveObj , d=(size))
        c2 = mc.offsetCurve(curveObj , d=(-size))
        spans = mc.getAttr(curveObj+".spans")
        
        lofted = mc.loft(c1, c2, d=1, po=0, ch=0, rn=True, ar=True, u=1, ss=1 )
        uvalue = mc.getAttr(lofted[0]+".minMaxRangeU.maxValueU")
        mc.delete(c1,c2)
        surfCurve = mc.curveOnSurface(lofted, d=3, uv= ((uvalue/2 , spans) , (uvalue/2 , spans-spans/3) , (uvalue/2 , spans-spans/3 * 2) , (uvalue/2 , 0)), k=(0,0,0,1,1,1) )
        curveObj = surfCurve

    npc = mc.createNode( 'nearestPointOnCurve')
    mc.connectAttr(mc.listRelatives(curveObj,s=1)[0]+".worldSpace[0]", npc+".inputCurve", f=1)
    
    for ob in sel:
        #parm = jc_closestPointOnCurve(mc.xform(ob, q=1, ws=1, t=1), curveObj)
        pos = mc.xform(ob, q=1, ws=1, t=1)
        mc.setAttr(npc+".inPosition", pos[0], pos[1], pos[2], type="double3")
        parm = mc.getAttr(npc+".parameter")
        #loc = mc.spaceLocator(n=ob+"_pointOnCurve")
        pathAnim = mc.pathAnimation( ob, c=curveObj )
        inputs = mc.listConnections(pathAnim+".uValue", s=1)
        mc.disconnectAttr(inputs[0]+".output",pathAnim+".uValue")
        mc.setAttr(pathAnim+".uValue",parm)
        
    mc.delete(npc)
    
attachToClosestPointOnCurve()
    



add kitten

import urllib2
import os
import maya.cmds as cmds
from random import randint


def kitten():
    tempDir = cmds.internalVar(userTmpDir=True)
    kitten = tempDir+'kitten.png';
    f = open(kitten,'wb')
    
    x = randint(200,600)
    y = randint(200,600)
    err = f.write(urllib2.urlopen('http://placekitten.com/g/'+str(x)+'/'+str(y)).read())
    f.close()
    
    window = cmds.window(t="miaow",widthHeight=(x,y))
    cmds.paneLayout()
    cmds.image( image=kitten,bgc=[.6,.6,.6] )
    cmds.showWindow( window )
    
kitten()

reload

import iprPlayblast
reload(iprPlayblast)

iprPlayblast.UI();

Ipr batch

//mel stuff

source bernie
whereIs RenderViewWindow


setAttr "defaultRenderGlobals.imageFormat" 7; //8 32;



RenderViewWindow;
renderWindowRender redoPreviousIprRender renderView;
stopIprRendering renderView;



proc string pad(float $n){return ($n<1000)? ( ($n<100)?( ($n<10)?"000"+$n:"00"+$n ):"0"+$n ) : $n+"";}
renderWindowRender redoPreviousIprRender renderView;
float $e = `playbackOptions -query -maxTime`;
float $s = `playbackOptions -query -minTime`;
for($i = $s;$i<$e;$i++){
    $startTime = `timerX`;
    while(`timerX -st $startTime`<5){
        //nothing
    }
    $frame = pad(`currentTime -q`);
    $dir = `internalVar -utd`;
    renderWindowEditor -e -writeImage ($dir+"/temp"+$frame) renderView;
    playButtonStepForward;
}




import maya.cmds as mc
import threading
import os


def test():
	print "test2"

widgets = {}	


def UI():
	if mc.window("iprPlayblast", exists = True):
		mc.deleteUI("iprPlayblast")
	
	widgets["window"] = mc.window("iprPlayblast", title = "Playblast IPR", mnb = False, mxb = False, resizeToFitChildren=1, w = 150, h = 100)
	mc.frameLayout( lv=0, borderStyle='etchedIn', mh=5, mw=5 )
	mc.checkBoxGrp(numberOfCheckBoxes=1, label='', label1='Force IPR restart on each frame' )
	mc.columnLayout()
	mc.intSliderGrp( label='Seconds per frame : ', field=True, minValue=0, fieldMaxValue=99999, value=30 )
	mc.textFieldButtonGrp( label='Test timing : ', text='use "Start IPR"...', editable = False, buttonLabel='Start IPR')
	mc.setParent( '..' )
	mc.separator( h=8 )

	
	workspaceDir = mc.internalVar(uwd=True)
	
	widgets["displayFilenameGrp"] = mc.textFieldGrp( label='', text='', editable=False )
	widgets["saveDirGrp"] = mc.textFieldButtonGrp( label='Save Dir : ', text=workspaceDir, buttonLabel='Browse', bc = UIgetDir)
	filename = os.path.splitext(os.path.basename(mc.file(q=True,sn=True)))[0]
	filename = ('temp',filename)[len(filename) != 0]
	widgets["saveFileGrp"] = mc.textFieldGrp( label='Filename : ', text=filename, editable=True, tcc = UIsetDisplayFilename )

	
	
	widgets["imageFormatGrp"] = mc.optionMenuGrp( label='Format : ', changeCommand=UIsetDisplayFilename )
	mc.menuItem( label='iff' )
	mc.menuItem( label='jpg' )
	mc.menuItem( label='png (not recommended)' )
	widgets["paddingGrp"] = mc.intFieldGrp( numberOfFields=1, label='Padding : ', value1=4, cc = UIsetDisplayFilename)
	mc.separator( h=8 )
	
	mc.intFieldGrp( numberOfFields=2, label='Start / End frame : ', value1= mc.playbackOptions(minTime=1,q=1), value2=mc.playbackOptions(maxTime=1,q=1))
	mc.checkBoxGrp(numberOfCheckBoxes=1, label='', label1='Play sequence when done' )
	mc.separator( h=8 )	
	mc.setParent( '..' )
	
	mc.rowLayout(nc = 1,adjustableColumn=1,columnAttach=[(1, 'both', 0)])
	mc.button(label="Playblast!", align='center',height=40 )
	mc.setParent( '..' )
	
	mc.rowLayout(  nc = 2,columnWidth2=(150, 150), adjustableColumn=1, columnAlign=(2, 'right'), columnAttach=[(1, 'both', 0), (2, 'both', 0)] )
	mc.button(label="Close", align='center' )
	mc.button(label="Help", align='center' )
	mc.setParent( '..' )
			
	
	mc.showWindow(widgets["window"])
	UIsetDisplayFilename()
	

def UIsetDisplayFilename(*args):
	dir =  mc.textFieldGrp(widgets["saveDirGrp"], query=True, text=True)
	file = mc.textFieldGrp(widgets["saveFileGrp"], query=True, text=True) 
	format = mc.optionMenuGrp(widgets["imageFormatGrp"],query=True, sl=True)
	formatList = ("iff","jpg","png")
	formatType = (7,8,32)
	
	
	
	format = formatList[format-1]
	padding = mc.intFieldGrp( widgets["paddingGrp"],query=True, value1=True)
	frame = str(int(mc.currentTime( query=True )))
	frame = frame.zfill(padding)
	
	mc.textFieldGrp(widgets["displayFilenameGrp"], edit = True, text=(dir+file+"."+frame+"."+format))

def UIsetFilename(*args):
	#widgets["saveFileGrp"].value
	print args[0]
	UIsetDisplayFilename()
	
def UIgetDir(*args):
	returnPath = mc.fileDialog2(fm = 3, fileFilter = None, ds = 1, okc = "Choose folder")
	mc.textFieldButtonGrp(widgets["saveDirGrp"],text = os.path.normcase(returnPath[0]), edit = True)
	UIsetDisplayFilename()
	


def UIgetSetFormat(*args)	:
	format = mc.optionMenuGrp(widgets["imageFormatGrp"],query=True, ils=True)
	
	
'''
timer code taken from Nathan Horne: http://nathanhorne.com/?p=116 
Usage:
def timerTest():
	print 'Hello World!'

#create and start a timer
timer = Timer(30, timerTest, repeat=True)
timer.start()

#To stop the timer
timer.stop()
'''


try:
	from maya.utils import executeInMainThreadWithResult
except:
	executeInMainThreadWithResult = None

class Timer(threading.Thread):
	def __init__(self, interval, function, args=[], kwargs={}, repeat=True):
		self.interval = interval
		self.function = function
		self.repeat = repeat
		self.args = args
		self.kwargs = kwargs
		self.event = threading.Event()
		threading.Thread.__init__(self)

	def run(self):
		def _mainLoop():
			self.event.wait(self.interval)
			if not self.event.isSet():
				if executeInMainThreadWithResult:
					executeInMainThreadWithResult(self.function, *self.args, **self.kwargs)
				else:
					self.function(*self.args, **self.kwargs)

		if self.repeat:
			while not self.event.isSet():
				_mainLoop()
		else:
			_mainLoop()
			self.stop()

	def start(self):
		self.event.clear()
		threading.Thread.start(self)

	def stop(self):
		self.event.set()
		threading.Thread.__init__(self)

Ref check wip

import maya.cmds as mc
import maya.mel as mel
from functools import partial
from os import listdir
from os.path import split, isfile, join, dirname
import subprocess

class refCheck(object):
    def __init__(self):
        self.UI()
    def buttonPush(*args):
        refPath = dirname(args[1])
        refPath	= refPath.replace('/', '\\')
        subprocess.Popen('explorer "%s"' % refPath)
    def UI(self):
        scene = mc.file(query=True,sn=True)
        allrefs = mc.file(query=True, list=True, withoutCopyNumber=True)
        fileRefs = sorted(list(set([item for item in allrefs if item.endswith('.ma') or item.endswith('.mb')])))
        mc.window(title='Check latest Refs',resizeToFitChildren=1)
        mc.columnLayout(adjustableColumn=True, columnAlign='center',rowSpacing=10)
        mc.rowLayout(numberOfColumns=1)
        cmds.text(w=460,l="\nCheck if each ref and sub-ref is the latest in its folder");
        cmds.setParent(upLevel=True)
        cmds.separator()
        for ref in fileRefs:
            if ref != scene:
                onlyfiles = [ f for f in listdir(split(ref)[0]) if isfile(join(split(ref)[0],f)) and f.endswith(('.mb','.ma')) ]
                #beautiful code below
                refFileName = ref.rpartition('/')[2]
                refStepName = ref.rpartition('/')[0].rpartition('/')[2];
                refChar = ref.rpartition('/')[0].rpartition('/')[0].rpartition('/')[0];
                refCharName = refChar.rpartition('/')[0].rpartition('/')[2]+" "+refChar.rpartition('/')[2];
                refCharName = refCharName.lower();
                latestRef = sorted(onlyfiles)[-1];
                col = [.3,.8,.3];
                if(refFileName!=latestRef):
                    col = [.9,.1,.1];
                
                mc.rowLayout(numberOfColumns=8)
                cmds.separator()
                cmds.button(w=50,l=refStepName,en=0)
                cmds.button(w=150,l=refCharName,bgc=col)
                cmds.text(w=270,l="  "+refFileName+" -> "+latestRef+" ")
    
                cmds.button(w=55,l="browse",c=partial(self.buttonPush, ref))
                cmds.button(w=65,l="load latest")
                cmds.checkBox(l="")
                cmds.separator()
                cmds.setParent(upLevel=True)
                cmds.separator()
                
        mc.rowColumnLayout(nc=2,cs=(2,5))
        cmds.button(w=85,l="load checked")
        cmds.button(w=85,l="close")
        cmds.setParent(upLevel=True)  

        mc.showWindow()
w = refCheck()


Upload Prefs to FTP wip

import maya.cmds as cmds
import zipfile, os

scriptDir = cmds.internalVar(usd=True)
prefDir = cmds.internalVar(upd=True)
presetDir = cmds.internalVar(ups=True)
tempDir = cmds.internalVar(utd=True)
#shelfDir = cmds.internalVar(ush=True)

zfilename = tempDir+"mayaprefs.zip"
zipf = zipfile.ZipFile(zfilename, "w", compression=zipfile.ZIP_DEFLATED )
path = prefDir
recursive_zip(zipf, path)
zipf.close()



def recursive_zip(zipf, directory, folder=None):
    nodes = os.listdir(directory)

    for item in nodes:
        if os.path.isfile(item):
            zipf.write(item, folder, zipfile.ZIP_DEFLATED)
        elif os.path.isdir(item):
            recursive_zip(zipf, os.path.join(directory, item), item)