Work Specific Scripts

From bernie's
Jump to: navigation, search

Fixstudio excel plot to remap color values

import re

b = """0.0202020202    	0.0012355819
0.0303030303	0.0018490148
0.0404040404	0.0024572181
0.0505050505	0.0030584484
0.0606060606	0.0036509625
0.0707070707	0.0042330173
0.0808080808	0.0048028694
0.0909090909	0.0053587757"""


strg = "float $v[] = {"
lines = re.split(r'\n+', b)
for word in lines:
    for v in re.split(r'\t',word):
        strg = strg+str(float(v))+","

strg = strg + "1,1};"
print strg

copy paste str

float $v[] = {0.0202020202,0.0012355819,0.0303030303,0.0018490148,0.0404040404,0.0024572181,0.0505050505,0.0030584484,0.0606060606,0.0036509625,0.0707070707,0.0042330173,0.0808080808,0.0048028694,0.0909090909,0.0053587757,1,1};



for($i=0;$i<size($v);$i+=2){
    int $cur = $i+2;
    setAttr remapColor6.red[$cur].red_FloatValue ($v[$i+1]);
    setAttr remapColor6.red[$cur].red_Position ($v[$i]);
    setAttr remapColor6.red[$cur].red_Interp 1;
}

Fixstudio IES visualizer

7VjHuFP.png

//place in a scriptjob on frame change scene open; maxwell deosn't work with prerender mels

int $ti = `currentTime -q`;
string $filepath = "/prod/prod1/Projets/RESSOURCES/_LIB/3D/maya/scenes/LIGHTING/_ies/!preview/IESlist.txt";
string $readAllLines[] = `freadAllLines($filepath)`;
string $curfile = $readAllLines[$ti];
$filepart = `match "[^/\\]*$" $curfile`;
setAttr -type "string" maxwellRenderOptions.mxOverlayText $filepart;
setAttr -type "string" "maxwellEmitter21.iesFile" $curfile; //should be the emitter BSDF

Vray to Maxwell VDB placeholder

string $objs[] = `ls -sl`;
for($o in $objs){
    //$o = $objs[0];
    string $f = `getAttr($o+".inFile")`;
    string $range = `getAttr($o+".inCacheRange")`;
    $rangeArray = stringToStringArray($range, " - ");
    $maxVol = `createNode maxwellVolumetricObject`;
    setAttr ($maxVol+".useConstantDensity") 3;
    string $transforms[] = `listRelatives -p`;
    $tr = $transforms[0];
    
    //check if it's an animated VDB with vray's framerange, if it is, replace #### with 0000
    if(size($rangeArray)>0){
        if(getAttr($o+".inPlayAt")==1){
            setAttr ($o+".inPlayAt") 0;
            setAttr ($o+".inReadOffset") 0;
        }

        setAttr -type "string" ($maxVol+".file ") (substituteAllString($f, "####", "0000"));
        setAttr ($maxVol+".useCurrentFrame") 0;
    
        string $expr = "if("+$o+".inMode==0){\n"+$maxVol+".time = frame-"+$o+".inPlayAt;\n}else{\n"+$maxVol+".time = "+$o+".inIndex;\n};";
        $expr += "\n"+$tr+".visibility=("+$maxVol+".time>="+$rangeArray[0]+"&&"+$maxVol+".time<="+$rangeArray[1]+")?1:0;";
        expression -s $expr;
    }else{
        setAttr -type "string" ($maxVol+".file ") ($f);
    }
    parent $tr $o;
    makeIdentity $tr;
}

Random replace instance

global float $deletepercentage;

if(`objExists("instances_set")`){delete "instances_set";};
if(`objExists("replacingobjs_set")`){delete "replacingobjs_set";};

string $window = `window -menuBar true -title "Random replace"`;
columnLayout -adjustableColumn true;
$a = `button -label "Instance Objects"`;
button -e -command ("setSet(\"instances_set\",\""+$a+"\",\"Instance Objects\")") $a;
$b = `button -label "Objects To Replace"`;
button -e -command ("setSet(\"replacingobjs_set\",\""+$b+"\",\"Objects To Replace\")") $b;
$c = `button -label ("Random delete ("+$deletepercentage+"%)")`;
button -e -command ("setDelete(\""+$c+"\")") $c;
button -label "Go!" -command ("replaceWithInstances;deleteUI -window \""+$window+"\";");
showWindow $window;
proc setSet(string $name,string $button,string $buttonString){
    string $selectedElmts[] = `ls -sl -tr`;
    if(`objExists $name`){
        delete $name;
    }
    sets -n $name $selectedElmts;
    button -e -label ($buttonString+" ("+size($selectedElmts)+")") $button;
    select -cl;
}
proc setDelete(string $btn){
    global float $deletepercentage;
    string $text;
    string $result = `promptDialog
    -title "Delete random %"
    -message "Set chance of being deleted (0-100):"
    -button "OK" -button "Cancel"
    -defaultButton "OK" -cancelButton "Cancel"
    -dismissString "Cancel"`;
    
    if ($result == "OK") {
        $text = `promptDialog -query -text`;
        $deletepercentage = float($text);
        button -e -label ("Random delete("+$deletepercentage+"%)") $btn;
    }
}

global proc replaceWithInstances(){
    global float $deletepercentage;
    string $instances[] = `listConnections -s 1 -d 0 -p 0 -c 0 "instances_set"`;
    string $objs[] = `listConnections -s 1 -d 0 -p 0 -c 0 "replacingobjs_set"`;
    int $end = size($objs)-1;
    global string $gMainProgressBar;  // This is defined on maya startup
    progressBar -edit -beginProgress -isInterruptable true -status "Replacing with instances" -maxValue $end $gMainProgressBar;
    refresh -su 1;
    for($i = 0;$i<=$end;$i++){
        if(`progressBar -query -isCancelled $gMainProgressBar`)
        break;
        if(`rand 1` > ($deletepercentage/100)){
            select -r $objs[$i] $instances[int(floor(rand(size($instances))))] ;
            replaceObjects 1 1 1 1;             
        }else{
            delete $objs[$i];
        }
        progressBar -edit -step 1 $gMainProgressBar;
    }
    progressBar -edit -endProgress $gMainProgressBar;    
        refresh -su 0;
}

Import vray proxies with vrmesh names

20neOkF.png

Override vray import procs to allow use of filenames as mesh names instead of the silly 'mesh' default name

proc string prepareStringArg(string $s) {
	string $subs = substitute("\"", $s, "\\\"");
	return "\"" + $subs + "\"";
}

proc string preparePathArg(string $s) {
	return prepareStringArg(fromNativePath($s));
}

proc vrayCreateProxyExisting(string $node, string $fileNameArray[], string $objectPath,int $useFileName) {
	global int $g_vrayImportProxy_animStart;
	global int $g_vrayImportProxy_animLength;
	global int $g_vrayImportProxy_hasFrameFilter;
	
	
	for($fileName in $fileNameArray) {
		string $anim = "";
		if ($g_vrayImportProxy_hasFrameFilter) {
			$anim = (" -animStart " + $g_vrayImportProxy_animStart
				 + " -animLength " + $g_vrayImportProxy_animLength);
		}
        //added by bernie
        if($useFileName){
            string $filepart = `match "[^/\\]*$" $fileName`;
            $node = `match "^[^\.]*" $filepart`; //i'm bad at regex
        }
		string $cmd = ("vrayCreateProxy"
			       + " -node " + prepareStringArg($node)
			       + " -dir "  + preparePathArg($fileName)
			       + " -existing "
			       + " -createProxyNode "
			       + $anim
			       + " -objectPath " + prepareStringArg($objectPath));
		eval $cmd;
	}
}

global proc vrayCreateProxyButtonProc(string $nodeNameCtrl, string $fileNameArray[], string $objectPathCtrl, string $singleModeCtrl, string $animLabelCtrl, string $browseModeUseFilename) {
    int $useFileName = `checkBox -q -value $browseModeUseFilename`;
	string $node = `textField -q -text $nodeNameCtrl`;
	string $objectPath = `textField -q -text $objectPathCtrl`;
	int $singleFileMode = `radioButton -q -select $singleModeCtrl`;
	// Before importing a proxy first trigger the execution of vrayProxyFilesAreReadable for single proxy mode only in order to re-evaluate 
	// the animation boundaries when frame formatting is inserted in the filename field without an action leading to the execution of its change command
	if ($singleFileMode)
		vrayProxyFilesAreReadable($fileNameArray, $animLabelCtrl);
	vrayCreateProxyExisting($node, $fileNameArray, $objectPath,$useFileName);
}

global proc vrayCreateImportProxyWindow()
{
	string $window = `window -rtf true -title "Import V-Ray proxy"`;
	formLayout -nd 100 cpwLyt;

	string $nodeNameLabel = `text -label "Node name: "`;
	string $fileNameLabel = `text -label "File(s):"`;
	string $objectPathLabel = `text -label "Object path:"`;
	string $animLabel = `text -l ""`;
	string $nodeNameCtrl = `textField -text "mesh" -w 190`;
	string $fileNameCtrl = `textField -w 190`;
	textField -e -annotation "Frame formatting is supported via <frameNN> to specify a sequence of proxy files." $fileNameCtrl;
	string $fileListCtrl = `scrollField -w 190 -h 120 -visible false -editable false`;
	string $objectPathCtrl = `textField -text "" -w 190`;
	string $cmdBrowse = "";

	string $browseModeRadioGrp = `radioCollection`;
	string $browseModeSingle = `radioButton -label "Single file (frame formatting is supported)" -select`;
	string $browseModeMultiple = `radioButton -label "Multiple files"`;
    
    //added by bernie
    string $browseModeUseFilename = `checkBox -label "Use filename as mesh name" -value false`;
   
	
	global float $g_mayaVersion;
	string $cmdGetProxyFiles = "vrayGetProxyFiles(\"" + $fileNameCtrl + "\",\"" + $fileListCtrl + "\", eval(\"radioButton -q -select " + $browseModeSingle + "\"))";
	string $cmdCreateProxy = "vrayCreateProxyButtonProc(\"" + $nodeNameCtrl + "\","+$cmdGetProxyFiles+",\""+$objectPathCtrl + "\",\""+$browseModeSingle+"\",\""+$animLabel+"\",\""+$browseModeUseFilename+"\");";
	$cmdCreateProxy += "deleteUI -window " + $window;
	string $createButton = `button -enable false -label "Create" -align "center" -c $cmdCreateProxy`;
	string $cmdFileNameChanged = "vrayImportProxyUpdateCreateBtn(\""+$createButton+"\", "+$cmdGetProxyFiles+", \""+$animLabel+"\")";
	textField -e -cc $cmdFileNameChanged -ec $cmdFileNameChanged  -rfc $cmdFileNameChanged $fileNameCtrl;
	scrollField -e -cc $cmdFileNameChanged -ec $cmdFileNameChanged $fileListCtrl;
	if ($g_mayaVersion >= 2011)
		$cmdBrowse = ("vrayImportProxyBrowseCmd(\"" + $fileNameCtrl + "\",\"" + $fileListCtrl + "\",true, \""+$createButton+"\", \""+$animLabel+"\")");
	else
		$cmdBrowse = "{textField -e -text `fileDialog -dm \"*.vrmesh *.abc\"` "+$fileNameCtrl+"; setFocus "+$fileNameCtrl+";}";
	string $browseButton = `symbolButton -image "navButtonBrowse.xpm" -c $cmdBrowse browser`;
	setFocus $nodeNameCtrl;
	string $cmdFileMode = "vrayProxySetFileMode(\"" + $window + "\",\"" + $fileNameCtrl + "\",\"" + $fileListCtrl + "\",\"";
	$cmdFileMode = $cmdFileMode + $animLabel + "\",\"browser\",\""+ $browseModeSingle + "\",\"" + $createButton;
	$cmdFileMode = $cmdFileMode + "\",\"" + $objectPathLabel + "\",\"" + $objectPathCtrl + "\");";
	radioButton -e -onCommand ($cmdFileMode) $browseModeSingle;
	radioButton -e -onCommand ($cmdFileMode) $browseModeMultiple;
	
    //added by bernie
    checkBox -e -onCommand ("textField -e -en 0 "+$nodeNameCtrl) $browseModeUseFilename;
    checkBox -e -offCommand ("textField -e -en 1 "+$nodeNameCtrl) $browseModeUseFilename;

	formLayout -e
		-af $browseModeSingle top 5
		-af $browseModeSingle left 5
		-ac $browseModeMultiple top 5 $browseModeSingle
		-af $browseModeMultiple left 5
		
        -ac $browseModeUseFilename top 5 $browseModeMultiple
		-af $browseModeUseFilename left 5
		
		-ac $nodeNameLabel top 10 $browseModeUseFilename
		-af $nodeNameLabel left 5
		-ac $fileNameLabel top 5 $nodeNameCtrl
		-af $fileNameLabel left 5
		-ac $nodeNameCtrl top 10 $browseModeUseFilename
		-ac $nodeNameCtrl left 5 $nodeNameLabel
		-af $nodeNameCtrl right 35
		
		-ac $fileNameCtrl top 5 $nodeNameCtrl
		-ac $fileNameCtrl left 5 $nodeNameLabel
		-af $fileNameCtrl right 35
		
		-ac $fileListCtrl top 0 $fileNameCtrl
		-ac $fileListCtrl left 5 $nodeNameLabel
		-af $fileListCtrl right 35
		-af $fileListCtrl bottom 80
		
		-ac $objectPathLabel top 5 $fileNameCtrl
		-af $objectPathLabel left 5
		-ac $objectPathCtrl top 5 $fileNameCtrl
		-ac $objectPathCtrl left 5 $nodeNameLabel
		-af $objectPathCtrl right 35

		-ac $animLabel top 5 $objectPathCtrl
		-aoc $animLabel left 0 $fileNameCtrl
		-ac $browseButton top 5 $nodeNameCtrl
		-ac $browseButton left 5 $nodeNameCtrl
		
		-ac $createButton top 25 $objectPathCtrl
		-af $createButton left 70
		-af $createButton right 35
		cpwLyt;

	// If we set it during creation, the size will be ignored, since Maya saves size/pos. for each window.
	global int $importProxyWndDefaultHeight;
	window -e -wh 305 $importProxyWndDefaultHeight -sizeable true $window;
	showWindow $window;
}

vrayCreateImportProxyWindow;

Small: bake turtle maps with animation

haven't found a simpler way than call a batch multiple times

#maya-render-new is aliased to maya/bin/render
for i in {1..100}
do
	maya-render-new -preRender \"currentTime -e $i\" glass_normals_maker.mb
done

Small: vray ies library

import os
import os.path
import maya.cmds as mc
import ntpath


#get all IES and write to file
iesPath = '/u/mglib/IMAGES/VRAY_IES/'
target = open(iesPath+'IESlist.txt', 'w')

ieslist = []
for dirpath, dirnames, filenames in os.walk(iesPath):
    for filename in [f for f in filenames if f.endswith('.ies')]:
        ieslist.append(os.path.join(dirpath, filename))

target.write('All IES ---- auto generated\n')
target.write('\n'.join(ieslist))
target.close()

#create a vray light per item, set visibility keyframes, rename
count = 1
for ies in ieslist:
    light = mc.createNode('VRayLightIESShape')
    lightTransform = mc.listRelatives(light,parent=1)
    mc.setAttr(light+'.iesFile',ies,type='string')
    lightTransform = mc.rename(lightTransform,'ies_'+os.path.splitext(ntpath.basename(ies))[0])
    mc.setKeyframe( lightTransform,  attribute='visibility', t=[-1.0+count,1.0+count],v=0.0 )
    mc.setKeyframe( lightTransform,  attribute='visibility', t=[0.0+count],v=1.0 )
    count += 1

#render....




select all children but last ones (tails)

import maya.cmds as mc
selectAllbutEnd = []
l = mc.ls(sl=1)
for o in l:
   selectAllbutEnd.extend(mc.listRelatives(o,c=1,ad=1)[1:])
   selectAllbutEnd.append(o)
mc.select(selectAllbutEnd)

méca g grimbergen setup

stepped, requires loads of defs



############################################################### JNTS CREATION ##########################################



#single edge
edgeSelection = mc.ls(sl=1)
#mc.select(edgeSelection,r=1)




#for each selection, get edge loop and add it to list
edgeLoops = []
for edge in edgeSelection:
    mc.select(edge, r=1)
    mel.eval('SelectEdgeLoopSp')
    edgeLoop = mc.ls(sl=1, fl=1)
    edgeLoops.append(edgeLoop)

#create joint chain on each edge loop
joints = []    
for loop in edgeLoops:
    joints.append(bonesFromEdgeLoop(loop, 3, [0,0,4]))



boundJoints = []
flatList = []
for jntChain in joints:
    currentChain = []
    for i in range(len(jntChain)-1):
        currentChain.append(jntChain[i])
        flatList.append(jntChain[i])
    boundJoints.append(currentChain)

mc.select(flatList) #joints to skin with (boundjoints is a comprehensive list)


################ do skinning, with neighbours AND selected joints only #########
############################################################### AUTOMATIC WEIGHTS ##########################################




o = mc.ls(edgeLoops[0][0],o=1)
sc = mel.eval('findRelatedSkinCluster("'+str(o[0])+'")')


for i in range(len(edgeLoops)):
    #print i
    counter = i

    edgeLooptoFaces = mc.polyListComponentConversion(edgeLoops[counter],tf=True )
    face1 = mc.ls(edgeLooptoFaces,fl=1)[0]
    face1 = int(face1.split('[')[-1].split(']')[0])
    shell = mc.polySelect(o,ets=face1)
    shellVtx = mc.polyListComponentConversion(tv=1)
     
    antiList = flatList

    for jnt in boundJoints[counter]:
        antiList = [x for x in antiList if x != jnt]
    
    removeInfluences = []
    for jnt in antiList:
        removeInfluences.append((str(jnt),0))
    
    mc.skinPercent(sc,str(shellVtx[0]),tv=removeInfluences)
    
    
    

############################################################### AIM CONSTRAINTS ###########################################

    

attachCurve = u'curve1'
attachTopGeo = u'targetPlane'

sel = mc.ls(sl=1)
parents = []
for o in sel:
    d = mc.duplicate(o, po=1)
    d = mc.rename(d,str(o)+"_aimJnt")
    mc.parent(o,d)
    parents.append(d)

targetJoints = []
for o in parents:
    relatives = mc.listRelatives(o,c=1,ad=1)
    endJoint = relatives[0]
    targetJoint = mc.duplicate(endJoint)[0]
    mc.parent(targetJoint,endJoint)
    mc.setAttr(targetJoint+".tx",1)
    mc.setAttr(targetJoint+".displayHandle",1)
    targetJoints.append(targetJoint)
    

######  place target joints properly #########

fails = []
follicles = []
for o in parents:
    topPos = intersect(o,attachTopGeo)
    
    if topPos == 0 :
        fails.append(o)
    else :
        follicle = closestUV(topPos,attachTopGeo,1)

        relatives = mc.listRelatives(o,c=1,ad=1)
        endJoint = relatives[0]
        endJointPos = mc.xform(endJoint,ws=1,t=1,q=1)
        loc = mc.spaceLocator()[0]
        mc.setAttr ( '%s.translate' % loc, endJointPos[0], endJointPos[1], endJointPos[2] )
        mc.select(loc,attachCurve,r=1)
        attachToClosestPointOnCurve(0)
        mc.aimConstraint(loc,o,wuo=str(follicle),wut="object",mo=1)
        mc.rename(loc,o+"_aimLoc")
        mc.delete(endJoint)
    
mc.select(fails) # if there's a selection, fix stuff
#fix stuff
#
jntsEnd = mc.ls(sl=1)
placement = []
for end in jntsEnd:
    t = mc.getAttr(end+".translate")
    placement.append([end,t])

#copy right to left
for i in range(len(placement)):
    
    ag = placement[i][0].replace('aile_d','aile_g')
    x =  placement[i][1][0][0]
    y =  placement[i][1][0][1]
    z =  -placement[i][1][0][2]
    mc.setAttr(ag+".tx",x)
    mc.setAttr(ag+".ty",y)
    mc.setAttr(ag+".tz",z)

add hdri ctrl

string $hdriCtrl = `createNode transform -n "hdriCtrl"`;
createNode nurbsCurve -n "hdriCtrlShape" -p "hdriCtrl";
	setAttr -k off ".v";
	setAttr ".cc" -type "nurbsCurve" 
		3 18 0 no 3	23 0 0 0 1 2 3 4 5 6 7 8 8 8 9 10 11 12 13 14 15 16 16 16 21
		3.1773138824361804 -0.098334400976111055 -0.0019187323799920489
		3.113926460204997 -1.0102159734494798 -0.0019187323799917117
		2.3575241134550451 -2.527169584847317 -0.0019187323799910387
		-0.010427481731231687 -3.3385769758437815 -0.0019187323799906781
		-2.2844758477551599 -2.2848481947115693 -0.0019187323799911471
		-3.1842745118033569 0.055871506457036514 -0.0019187323799921855
		-2.2040990750523348 2.3640878023122807 -0.001918732379993211
		0.10501572631038342 3.3385769758437815 -0.0019187323799936434
		2.443503170980458 2.4457986257314182 -0.0019187323799932476
		3.1470150388890095 0.90360414350370477 -0.0019187323799925633
		3.1842745118033569 0.009587422878553388 -0.0019187323799922265
		3.1470150388890095 -0.0019187323799924878 0.90360414350370555
		2.443503170980458 -0.0019187323799924878 2.4457986257314182
		0.10501572631038342 -0.0019187323799924878 3.3385769758437815
		-2.2040990750523348 -0.0019187323799924878 2.3640878023122815
		-3.1842745118033569 -0.0019187323799924878 0.055871506457036847
		-2.2844758477551599 -0.0019187323799924878 -2.2848481947115684
		-0.010427481731231687 -0.0019187323799924878 -3.3385769758437815
		2.3575241134550451 -0.0019187323799924878 -2.527169584847317
		3.113926460204997 -0.0019187323799924878 -1.0102159734494789
		3.1773138824361804 -0.0019187323799924061 -0.093784440343312514;

string $expr = "maxwellRenderOptions.environment[0].envOffsetU="+$hdriCtrl+".rotateY%360;maxwellRenderOptions.environment[0].envOffsetV="+$hdriCtrl+".rotateX%360;";
expression -s $expr;
setAttr -lock true ($hdriCtrl+".rz");
select -r $hdriCtrl;
setToolTo RotateSuperContext; 


evermotion cleaning

//to do: group according to mesh name (arch75_065_001+arch75_065_002 etc)


//set group name
string $objs[] = `ls -sl`;
for($o in $objs){
    string $buffer[] = {};
    string $r[] = `listRelatives $o`;
    $numTokens = `tokenize $r[0] "_" $buffer`;
    rename $o ($buffer[0]+"_"+$buffer[1]);
}

//rename shaders

string $objs[] = `ls -sl`;
for($o in $objs){
    

    string $sh[] = `listRelatives -s $o`;
    string $lc[] = `listConnections $sh[0]`;
    
    if(`nodeType $lc[0]` == "shadingEngine"){
        string $buffer[] = {};
        string $shd[] = `listConnections ($lc[0]+".surfaceShader")`;
        //$numTokens = `tokenize $sh[0] "_" $buffer`;
        rename $lc[0] ($o+"_matSG");
        rename $shd[0] ($o+"_mat");
        
    }
    
}
//reload file textures
for($t in `lsType "file"`){
    AEfileTextureReloadCmd ($t+".fileTextureName");
}
//reassign fileTextures so there are no duplicates
string $fileTextures[] = `lsType "file"`;
string $files[] = {};
string $shader[] = {};
for($t in $fileTextures){
        if($t != "<done>"){
        $files[size($files)] = `getAttr($t+".fileTextureName")`;
        string $con[] = `listConnections -s 0 -d 1 -p 1 $t`;    
        $shader[size($shader)] = $con[0];
    }
}
for($i=0;$i<size($files);$i++){
    for($j = $i+1;$j<size($files);$j++){
        if($files[$j] == $files[$i] && $files[$j] != "changed"){
            $files[$j] = "changed";
            print("connectAttr -f (\""+$fileTextures[$i]+".outColor\") (\""+$shader[$j]+"\");\n");
            //connectAttr -force ($fileTextures[$i]+".outColor") ($shader[$j]);
        }
    }
}

python

##############################################################
# Author: Zachary Cole
# Website: http://www.nzaneproductions.com
##############################################################
#
# Copyright: Creative Commons
#            Attribution-ShareAlike 3.0 Unported License
#
# This work is licensed under the 
# Creative Commons Attribution-ShareAlike 3.0 Unported License.
# To view a copy of this license,
# visit http://creativecommons.org/licenses/by-sa/3.0/ 
# or send a letter to 
# Creative Commons
# 444 Castro Street, Suite 900,
# Mountain View, California, 94041, USA.
#
# what does the above copyright mean? 
# give me credit, and share any modifications you make! thanks!
#
##############################################################
#
# what does this code snippet do?
#
# it relinks materials imported from a .vrscene to
# geometry imported from a .fbx file when you wish
# to use a scene created for vray for 3dsmax in 
# a scene in vray for maya
#
##############################################################
# caveats?	please save backup copies of your work. 
#               I'm not responsible if it finds the 
#                   higgs boson or anything unexpected. 
#               the steps below assume you know how to do basic
#                   actions in both 3ds max and maya
# support?	are you paying for this? no. 
#               if you want to pay for it,
#                   then I'll try and support it.
# testing?	minimal testing in 3dsmax 2012 w/ vray 2
#                   and maya 2011 w/ vray 1.5 
# feedback?	post comments on my blog!! :-)
#
# assumptions?	I'm assuming that the named order is the
#                   same in both formats.
#                   i.e. the first brdf corresponds
#                   to the first phong. (seems to work)

##############################################################
# IMPORTANT steps:
# in 3ds max: 
#	select all the geometry you want to transfer
#	save selected as new scene
# 	open scene you just saved
#	export fbx
#	export .vrscene
# in maya:
# 	change renderer to vray
#	import fbx
#	import .vrscene
#	fix texture paths in hypershade
# 	run this script in the python window of the script editor
#
# wow i think these header comments are longer than my code. geeze.
##############################################################

import maya.cmds as cmds

def relinkVrayMaterials():

    # get em while they're hot
    mats = cmds.ls(materials=True)
    
    phongs = []
    materials = []
    submaterials = []

    
    print "#### searching through materials..."
    # cycle through all materials
    for mat in mats:

        # look for shaders that match the naming
        # when you bring them in from .fbx
        if cmds.nodeType(mat) == "phong":
            phongs.append(mat)

        # look for shaders that match the naming
        #  when you bring them in from .vrscene
        elif mat.find("brdf") == 0 or mat.find("material") == 0:
            if mat not in submaterials:
                materials.append(mat)

            # layered shaders are special cases
            # the connected shaders will not match up to the
            # phong shaders from the fbx
            if cmds.nodeType(mat) == "layeredShader":
                # get the connected attrs
                arr = cmds.listAttr(mat + ".inputs", m=True)
                for a in arr:
                    # we only care about the color inputs
                    if a[-6:] == ".color":
                        # get the connected nodes
                        conn = cmds.listConnections(mat + "." + a)
                        # add them to the ignored submaterials list
                        for c in conn:
                            submaterials.append(c)
	
    print "#### replacing material assigments..."
    # cycle through all phong materials
    for i in range(0, len(phongs)):
        pho = phongs[i]
        mat = materials[i]
        # these vray materials don't have shader groups when
        # they are imported from .vrscenes, so let's make one for each
        matSG = cmds.sets( renderable=True, 
                           noSurfaceShader=True,
                           empty=True,
                           name=mat+'SG' );
        cmds.connectAttr( mat+".outColor",
                          mat+"SG.surfaceShader", 
                          force=True)    
        # get the objects assigned to the phong
        objs = cmds.hyperShade(objects=pho)
        # assign new material to selected objects
        cmds.hyperShade(assign=mat)
        print "#### assigned %s to %s assigned objects" % (mat, pho)

    print "#### done"

relinkVrayMaterials()

clean fucked up vertices

string $objs[] = `ls -sl`;
for($o in $objs){
    string $pp[] = `polyPlane -w 1 -h 1 -sx 1 -sy 1 -ax 0 1 0 -cuv 2 -ch 0`;
    string $pu[] = `polyUnite -ch 0 -mergeUVSets 1 $pp[0] $o`;
    select -r ($pu[0]+".f[0]");
    doDelete;
    rename $pu[0] $o;
}


rapid rig mirror controllers

//if it's buggy, it's because bernie
global string $cb;
window -t "mirror controllers rrig";
columnLayout;
separator -style "none" -h 5;
rowLayout -nc 2;
    separator -style "none" -w 10;
    $cb = `checkBox -label "use mirror ( check if buggy )"`;
    setParent..;
separator -style "none" -h 5;
rowLayout -nc 5;
    separator -style "none" -w 10;
    button -label " Left >> Right " -command "rapidRigMirrorControllers 0";
    separator -style "none" -w 10;
    button -label " Left << Right " -command "rapidRigMirrorControllers 1";
    separator -style "none" -w 10;
    setParent..;
separator -style "none" -h 10;
showWindow;

proc rapidRigMirrorControllers(int $side){
    global string $cb;
    string $objs[] = `ls -sl -l`;
    
    //if it's a vertex/cp, select object
    string $no_component = `match "^[^\.]*" $objs[0]`;
    if($no_component != $objs[0]){
        $objs = {};
        $objs = `ls -l $no_component`;
    }

    //loop through each object, check if there's a symmetry, hardcoded as _r and _l
    for($o in $objs){
        string $oSym = ($side)?(substituteAllString($o,"_r","_l")):(substituteAllString($o,"_l","_r"));
        if(`objExists $oSym` && ($oSym!=$o)){
            string $cps[] = `ls -fl ($o+".cp[*]")`;
            int $sizeCP = size($cps);
              for($i=0;$i<$sizeCP;$i++){
                int $mirroring = (`checkBox -q -v $cb`)?-1:1;
                
                $x = `getAttr($o+".controlPoints["+$i+"].xValue")`;
                $y = `getAttr($o+".controlPoints["+$i+"].yValue")`;
                $z = `getAttr($o+".controlPoints["+$i+"].zValue")`;
                setAttr ($oSym+".controlPoints["+$i+"].xValue") ($mirroring*$x);
                setAttr ($oSym+".controlPoints["+$i+"].yValue") ($mirroring*$y);
                setAttr ($oSym+".controlPoints["+$i+"].zValue") ($mirroring*$z);

                /*setAttr ($oSym+".controlPoints["+($sizeCP-$i)+"].xValue") ($x);
                setAttr ($oSym+".controlPoints["+($sizeCP-$i)+"].yValue") ($y);
                setAttr ($oSym+".controlPoints["+($sizeCP-$i)+"].zValue") ($z);*/
              }
        }else{
            warning("no "+(($side)?"left":"right")+" side found for "+$o);
        }
    }
}

maxwell lock alphain gain bug

//sometimes maxwell is loaded in another scene (vray/arnold/mr) and fucks up the alpha gain (puts it at .5). So lock the alpha gainz
for($t in `ls -typ "file"`){
    print(catch(`setAttr -l true ($t+".ag")`));
}

maxwell shelf

global string $currentFrameFile;
global string $error;

$playblastActive = 0;
$currentFrameFile = $error = "";

global proc firePlayblast(){
	firePlayblastUI;
}
proc string findLayout( string $windowUI,string $name )
{//from bryan ewert
  string $controls[] = `lsUI -l -controlLayouts`;
  string $pattern = $windowUI + "*";
  string $layout = "";

  for ( $ui in $controls )
  {
    if ( `gmatch $ui $pattern` )
    {
      string $tokens[];
      int $numTokens = `tokenize $ui "|" $tokens`;
      if ( $numTokens > 1 )
      {
        $layout = $tokens[0] + "|" + $tokens[1];
          string $ca[] = `layout -q -ca $layout`;  
          for ( $c in $ca )
          {      
            return ($layout + "|" + $c);
            break;
          }
        break;
      }
    }
  }
  return false;
}
global proc string pad(float $n){return ($n<1000)? ( ($n<100 )?( ($n<10 )?"000"+$n:"00"+$n ):"0"+$n ) : $n+"";}
global proc string getImagePath(string $extraPath,int $extension){ 
    setAttr "defaultRenderGlobals.outFormatControl" 0;
    setAttr "defaultRenderGlobals.animation" 1;
    setAttr "defaultRenderGlobals.putFrameBeforeExt" 1;
    setAttr "defaultRenderGlobals.extensionPadding" 4;
    string $image = pad(`currentTime -q`);    
    string $tof[] = `renderSettings -gin $image -fp`;
    string $dir = `match "^.*/" $tof[0]`;
    string $filepart = `match "[^/\\]*$" $tof[0]`;
    $filepart = (!$extension)?`match "(.*)[^\.a-z]" $filepart`:$filepart;
    return $dir+$extraPath+$filepart;
}
global proc string saveFireImage(int $openExplorer){
    global string $error;
    global string $currentFrameFile;
    string $r;
    $filePath = getImagePath("maxwellFirePlayblasts/",0)+".png";
    $mkdir = `sysFile -makeDir (match("^.*/",$filePath))`;
    string $vp = findLayout("MaxwellFIRE","maxwellViewport" );
    if($mkdir && $vp != "0"){
        maxwellViewport -e -saveIRImg ($filePath) $vp;
        $currentFrameFile = $filePath;
        $r = `toNativePath(match("^.*/",$filePath))`;
        if($openExplorer){
            system("start explorer " + $r);
        }else{
            maxwellSendIrImageToRV $vp;
            renderWindowMenuCommand keepImageInRenderView renderView;
        }
    }else{      
        $error = "No maxwell FIRE window found";
        $r = $error;
    }
    return $r;      
}
saveFireImage(0);

rolex

auto trotteuse

# utilisation: chopper un (ou plusieurs) objet ou un controlleur
# eventuellement renommer attr= "rotateY" avec un autre axe
# par defaut le tour se fait dans le sens des aiguilles d'une montre =), changer rotateDirection en 1.0 pour avoir l'inverse

# 'offset' et 'cadence' modifiable sur lobjet

import maya.cmds as mc

attr = 'rotateY'
rotateDirection = -1.0

for o in mc.ls(sl=1):
    mc.addAttr(o,longName='offsetSecondes', defaultValue=0.0)
    mc.setAttr(o+'.offsetSecondes', keyable=1)
    mc.addAttr(o,longName='cadenceHertz', defaultValue=8)
    mc.setAttr(o+'.cadenceHertz', keyable=1)
    expressionString = o+'.'+attr+' = '+str(rotateDirection)+'*('+o+'.offsetSecondes + floor(time*'+o+'.cadenceHertz)/'+o+'.cadenceHertz) * 6';
    mc.expression(o+'.'+attr,s=expressionString)


misc


$ct = `currentTime -q`;
currentTime -e 0;

source channelBoxCommand;

CBdeleteConnection "_montre_Submariner:MOD_verre1.tx";
CBdeleteConnection "_montre_Submariner:MOD_verre1.ty";
CBdeleteConnection "_montre_Submariner:MOD_verre1.tz";
CBdeleteConnection "_montre_Submariner:MOD_verre1.rx";
CBdeleteConnection "_montre_Submariner:MOD_verre1.ry";
CBdeleteConnection "_montre_Submariner:MOD_verre1.rz";

CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.tx";
CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.ty";
CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.tz";
CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.rx";
CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.ry";
CBdeleteConnection "_montre_Submariner:MOD__montre_Submariner_submarine_obj31.rz";

CBdeleteConnection "_montre_Submariner:MOD_trottinette.tx";
CBdeleteConnection "_montre_Submariner:MOD_trottinette.ty";
CBdeleteConnection "_montre_Submariner:MOD_trottinette.tz";

parentConstraint -mo -weight 1 _montre_Submariner:MOD_trottinette _montre_Submariner:MOD_verre1;
parentConstraint -mo -weight 1 _montre_Submariner:MOD_trottinette _montre_Submariner:MOD__montre_Submariner_submarine_obj31;

currentTime -e $ct;

select -r "_montre_Submariner:MOD__montre_Submariner_submarine_obj31" "_montre_Submariner:MOD_verre1";



string $kf[] = `select -r "*:MOD_trottinette_rotateY"`;
for($o in `ls -sl`){
    $fc = `keyframe -query -keyframeCount $o`;   
    $s = `keyframe -in 0 -q -tc $o`;
    $sV = `keyframe -in 0 -q -vc $o`;
    $e = `keyframe -in ($fc-1) -q -tc $o`;
    $eV = `keyframe -in ($fc-1) -q -vc $o`;
  
    int $start = $s[0];
    int $end = $e[0];
    float $base = $sV[0];
    float $range = $eV[0]-$sV[0];
    
    for($i=$start;$i<=$end;$i++){

        float $step = $i - $start;
        float $totalTime = $end - $start;
        float $progression = (floor($step/3.125)*3.125) / $totalTime;
        float $kv =  $base + $range * $progression;

        keyframe -e -a -vc $kv -t $i $o;
    }
}

select -r "_montre_Submariner:MOD__montre_Submariner_submarine_obj31" "_montre_Submariner:MOD_verre1" "*:MOD_trottinette";