Mel Temp

From bernie's
Jump to navigation Jump to search

Bake projected texture map to UVs

string $path = "Q:/PROJECT/PATH/TO/DIR/maya/images/"
string $projectionnode ="projection1.outColor";
string $els[] = `ls -sl`;
string $o = $els[0];
for($i=150;$i<350;$i=$i+3){
    $f = `currentTime -e $i`;
    $b = `convertSolidTx -antiAlias 1 -bm 1 -fts 1 -sp 0 -sh 0 -alpha 0 -doubleSided 0 -componentRange 0 -resolutionX 2048 -resolutionY 2048 -fileFormat "png"   -fin ($path+$o+"_proj_"+$i+".png") $projectionnode $o`;
    delete $b;
}

replace objects from one group to objects from another group

string $sel[] = `ls -sl`;
string $templateObject[] = ls($sel[0]+"|*");
string $objectsToReplace[] = ls($sel[1]+"|*");

for($o = 0;$o < size($objectsToReplace);$o++){
    int $rand = rand(size($templateObject));
    string $replacing = $objectsToReplace[$o];
    string $replacedBy = $templateObject[$rand];
    string $parents[] = `listRelatives -p $objectsToReplace[$o]`;
    float $rotate[] = `getAttr ($replacing+".r")`;    
    float $translate[] = `getAttr ($replacing+".t")`;    
    float $scale[] = `getAttr ($replacing+".s")`;    
    delete $replacing;
    string $duplicates[] = `duplicate $replacedBy`;
    string $newObj = $duplicates[0];
    parent $newObj $parents[0];
    
    setAttr ($newObj+".r") 	$rotate[0] $rotate[1] $rotate[2];
    setAttr ($newObj+".t") 	$translate[0] $translate[1] $translate[2];
    setAttr ($newObj+".s") 	$scale[0] $scale[1] $scale[2] ;
    rename $newObj $replacing;

}

polygon edges to curves

//select edges first
string $edges[];
for($e in `ls -sl -fl`){
    select -r $e;
    string $newEdges[] = `polyToCurve -form 2 -degree 3`;
    $edges[size($edges)] = $newEdges[0];
}
select -r $edges;

blender 2

{
    if (`window -exists blenderW`) deleteUI blenderW;
    if (`windowPref -exists blenderW`) windowPref -remove blenderW;
    string $window = `window -widthHeight 350 460 -title "Blender" blenderW `;
    columnLayout -columnAttach "both" 6 -rowSpacing 10 -columnWidth 350;
    text -ww 1 -l "\nBlends translates, rotates and scales of selection using \n transforms of 'start' and 'end'. \n\n Initial blend values set using distances \n";  
    checkBoxGrp -numberOfCheckBoxes 3 -vr -label "Attrs to blend " -en1 0 -va3 0 1 0 -labelArray3 "Translate" "Rotate" "Scale" cbg;
    checkBoxGrp -numberOfCheckBoxes 4 -vr -label "Options " -va4 0 1 1 1 -en2 0 -en3 0 -en4 0 -labelArray4 "Use constraints" "Keep offset" "Blend children elmts" "Don't blend last ('tail') elmts" cbg2;
    button -label "Set 'start' Selection" -command "selA" selAButton;
    button -label "Set 'end' Selection" -en 0 -command "selB" selBButton;

    button -label "Set blend selection (0)" -en 0 -command "selC" selCButton;
    button -label "Set ctrl obj (defaults to 1st start elmt)" -en 1 -command "setCtrl" ctrlButton;
    button -label "Apply blend" -command "blendAttr" -en 0 blendButton;
    button -label "Reset" -command "resetAll" resetButton;
    button -label "Cancel/close" -command "cancelpr";
    showWindow $window;
    global string $A[];
    global string $B[];
    global string $C[];
    global string $ctrl = "";
    proc selA(){
        string $objs[] = {};
        $objs = `ls -sl -l`;
        int $chCB = `checkBoxGrp -q -v3 "cbg2"`;
        int $endCB = `checkBoxGrp -q -v4 "cbg2"`;
        if(size($objs)!=0){
            if($chCB){
                string $tmp[] = `listRelatives -f -ad $objs[0]`;
                $tmp[size($tmp)] = $objs[0];
                $objs = $tmp;
            }
            int $noc = (size($objs)-$endCB)*$chCB + 1 * !$chCB;
            
            button -e -en 1 -label ("Set 'start' Selection ("+$noc+" elmts)") "selAButton";
            button -e -en 1 "selBButton";
            $A = {};
            if($endCB){
                for($i=1;$i<size($objs);$i++){
                    $A[size($A)] = $objs[$i];
                }
            }else{
                    $A = $objs;                
            }
            }
    }
    proc selB(){
        $objs = `ls -sl -l`;
        int $chCB = `checkBoxGrp -q -v3 "cbg2"`;
        int $endCB = `checkBoxGrp -q -v4 "cbg2"`;
        if(size($objs)!=0){
            if($chCB){
                string $tmp[] = `listRelatives -f -ad $objs[0]`;
                $tmp[size($tmp)] = $objs[0];
                $objs = $tmp;
            }
            int $noc = (size($objs)-$endCB)*$chCB + 1 * !$chCB;
            button -e -en 1 -label ("Set 'end' Selection ("+$noc+" elmts)") "selBButton";
            button -e -en 1 "selCButton";
            $B = {};
            if($endCB){
                for($i=1;$i<size($objs);$i++){
                    $B[size($B)] = $objs[$i];
                }
            }else{
                    $B = $objs;                
            }
            }
    }
    proc selC(){
        $objs = `ls -sl -l`;
        int $chCB = `checkBoxGrp -q -v3 "cbg2"`;
        int $endCB = `checkBoxGrp -q -v4 "cbg2"`;
        string $fullList[] = {};
        int $counterA = 0;
        int $counterB = 0;
        if(size($objs)!=0){
            for($o in $objs){
                $counterA++;
                if($chCB){
                    $tmp = `listRelatives -f -ad $o`;
                    
                    for($i = $endCB; $i<size($tmp); $i++){
                        $counterB++;
                        $fullList[size($fullList)] = $tmp[$i];
                    }
                    $fullList[size($fullList)] = $o;
                    $counterB++;
                }
            }
        }
            button -e -en 1 -label ("Set blend selection ("+$counterA+" x "+$counterB/$counterA+" elmts)") "selCButton";
            button -e -en 1 "blendButton";
            $C = $fullList;   
    }
    proc setCtrl(){
            string $sel[] = `ls -sl`;
            $ctrl = $sel[0];
            button -e -en 1 -label ("Set ctrl obj ("+$ctrl+")") "ctrlButton";        
    }
    proc blendAttr(){
        if($ctrl == ""){
            $ctrl = $A[size($A)-1];
        }
        int $doTranslate = `checkBoxGrp -q -v1 "cbg"`;
        int $doRotate = `checkBoxGrp -q -v2 "cbg"`;
        int $doScale = `checkBoxGrp -q -v3 "cbg"`;
        int $doConstraints = `checkBoxGrp -q -v1 "cbg2"`; 
        
        int $numBlends = size($C)/size($A);
        string $rootA = $A[size($A)-1];
        vector $rootAPos = `xform -q -ws -t $rootA`;
        string $rootB = $B[size($B)-1];
        vector $rootBPos = `xform -q -ws -t $rootB`;
        
        string $snA[] =  `ls -sn $rootA`;
        string $snB[] =  `ls -sn $rootB`;
        
        addAttr -ln (toupper($snA[0])+"_to_"+toupper($snB[0])) -at "enum" -en "  blends:" $ctrl;
            
        setAttr -e-channelBox true ($ctrl+"."+toupper($snA[0])+"_to_"+toupper($snB[0]));
            
        float $maxDistance = `mag($rootBPos-$rootAPos)`;
        


        string $connectExp = "//generated by script\n";
        
        for($i=0;$i<$numBlends;$i++){
            int $rootN = $i*size($A)+(size($C)/$numBlends-1);
            string $root = $C[$rootN];
            vector $center = `xform -q -ws -t $root`;
            float $distA = `mag($rootAPos-$center)`;
            float $distB = `mag($rootBPos-$center)`;
            float $ratio = .5;

            if($distA+$distB<=$maxDistance){
                $ratio = $distA/($distA+$distB);
            }
            string $names[] = `ls -sn $root`;
            string $ln = $snA[0]+"_"+$snB[0]+"_"+$names[0]+"_blend";
            
            addAttr -ln ($ln) -nn ($names[0]+"_blend") -defaultValue $ratio -minValue 0 -maxValue 1 $ctrl;         
            setAttr -e -keyable true ($ctrl+"."+$ln);
            
            for($j=0;$j<size($C)/$numBlends;$j++){
                string $curObj = $C[$i*size($A)+$j];
                //print("A"+$A[$j]+" -- B "+$B[$j]+" -- C "+$curObj+"\n");

                //oc
                if($doRotate){
                    if($doConstraints){
                        string $oc[] = `orientConstraint -mo -weight 1 $A[$j] $B[$j] $curObj`;
                        string $weightA[] = `listAttr -st "*W0" $oc[0]`;
                        string $weightB[] = `listAttr -st "*W1" $oc[0]`;
                        $connectExp += $oc[0]+"."+$weightA[size($weightA)-1]+" = 1-"+$ctrl+"."+$ln+";\n";
                        $connectExp += $oc[0]+"."+$weightB[size($weightB)-1]+" = "+$ctrl+"."+$ln+";\n";
                    }else{
                        $connectExp += $curObj+".rx = "+$B[$j]+".rx*"+$ln+" + "+$A[$j]+".rx*(1-"+$ln+");\n";
                        $connectExp += $curObj+".ry = "+$B[$j]+".ry*"+$ln+" + "+$A[$j]+".ry*(1-"+$ln+");\n";
                        $connectExp += $curObj+".rz = "+$B[$j]+".rz*"+$ln+" + "+$A[$j]+".rz*(1-"+$ln+");\n";
                    }
                }

                //$connectExp
                
                
            }

        }
        select -r $ctrl;
        expression -s $connectExp -o $ctrl;
    }
    proc resetAll(){
        $A = {""};
        $B = {""};
        $C = {""}; 
        $ctrl = ""; 
        button -e -en 1 -label ("Set 'start' Selection") "selAButton";
        button -e -en 0 -label ("Set 'end' Selection") "selBButton";
        button -e -en 0 -label ("Set blend selection (0)") "selCButton"; 
        button -e -en 1 -label ("Set ctrl obj (defaults to 1st start elmt)") "ctrlButton"; 
        
        button -e -en 0 "blendButton";
    }
    proc cancelpr(){
        $A = {""};
        $B = {""};
        $C = {""};
        deleteUI blenderW;
    }
}

bake vertex color map to texture

//export vertex color map from object
//if it doesn't work export 1 map by hand first

source artisanCallback;

string $sel[] = `ls -sl`;
$n = $sel[0];
proc string pad(float $n){return ($n<1000)? ( ($n<100)?( ($n<10)?"000"+$n:"00"+$n ):"0"+$n ) : $n+"";}

$tdir = (`workspace -q -rd` + "sourceimages\/" );

int $e = `playbackOptions -query -maxTime`;
int $s = `playbackOptions -query -minTime`;
$i = $s;

for($i = $s;$i<=$e;$i++){
currentTime ($i);
$path = ($tdir+$n+"."+pad($i)+".tif");
//select -r $n;
artExportAttrMapCB "artAttrPaintVertexCtx" $path "1";
}

remap with ramp

string $nodes[] = `ls -sl`;
string $source = "";
string $destination = "";
string $connection = "";

string $a[] = `listConnections -p 1 $nodes[0]`;
string $aNoPlugs[] = `listConnections $nodes[0]`;

string $b[] = `listConnections -p 1 $nodes[0]`;
string $bNoPlugs[] = `listConnections $nodes[0]`;

for($i = 0; $i<size($a);$i++){
    if($aNoPlugs[$i] == $nodes[1]){
        $connection = $b[$i];
        $ci = `connectionInfo -sfd $b[$i]`;
        if($ci == ""){ //destination
            $source = $b[$i];
            $connectionInfo = `connectionInfo -dfs $b[$i]`;
            $destination = $connectionInfo[0];
        }else{ //source
            $source = $ci;
            $destination = $b[$i];
        }
        break;
    }
}

$sn = `shadingNode -asTexture ramp`;
$pt = `shadingNode -asUtility place2dTexture`;
connectAttr ($pt+".outUV") ($sn+".uv");
connectAttr ($pt+".outUvFilterSize") ($sn+".uvFilterSize");

/*
to do: multiattr
if(`getAttr -s -type $source` == "float3"){
    source.
}*/

evalDeferred(`removeMultiInstance -break true ($sn+".colorEntryList[1]")`);
setAttr ($sn+".colorEntryList[0].color") -type double3 0 0 0 ;
setAttr ($sn+".colorEntryList[2].color") -type double3 1 1 1 ;
setAttr ($sn+".colorEntryList[2].position") 1;

disconnectAttr $source $destination;




connectAttr -f $source ($sn+".vCoord");
connectAttr -f ($sn+".outColor.outColorR") $destination;

select -r $sn;

color using userColor vray

int $colors[] = {16,221,255,64,232,2,255,189,15,232,50,34,101,7,255};
for($o in `ls -sl -l`){
    int $r = rand(0,5);
    print($r+"\n");
    vray addAttributesFromGroup $o vray_user_attributes 1;
    string $col = "rcolo="+($colors[$r*3]/255.0)+","+($colors[$r*3+1]/255.0)+","+($colors[$r*3+2]/255.0);
    setAttr -type "string" ($o+".vrayUserAttributes") $col;
}


select UV

//////////////////////////////
string $nullobjs[] = {};
for($o in `ls -sl`){
    if(size(`ls -fl ($o+".map[*]")`) < 2){
       $nullobjs[size($nullobjs)]  = $o;
    }
}
select -r $nullobjs;

////////////////////////
string $nullobjs[];
string $objs[] = `ls -sl`;
for($obj in $objs){
    select -r Structure_courts_389.map["*"]
    string $allUV[] = `polyUVSet -query -allUVSets $obj`;    
    if(size($allUV)>1){
        $nullobjs[size($nullobjs)] = $obj;
        print($obj+" ");
    }
}

far near clip edit

global string $n;
global string $f;
global string $checkbx;

$nc = `getAttr "perspShape.nearClipPlane"`;
$fc = `getAttr "perspShape.farClipPlane"`;

window -title "Set Near/Far Clip" -w 200;
columnLayout -adjustableColumn true;
separator -style "none" -h 3;
checkBox -label "include non default cams";
separator -style "none" -h 3;
rowLayout -numberOfColumns 2;
floatField -pre 4 -value $nc;
floatField -pre 0 -value $fc;
setParent..;
separator -style "none" -h 3;
columnLayout -adjustableColumn true;
floatSlider  -minValue (-5) -maxValue 5 -step 1 -value 0;
floatSlider -minValue (-5) -maxValue 5 -step 1 -value 0;
separator -style "none" -h 3;
showWindow;

proc changeClip(){
    global string $n;
    global string $f;
    global string $checkbx;
       
}

hide stupid attribs maxwell

string $objs[] = `ls -sl`;
string $parms[] = {"mxem","bfc","hc","hs","hgi","hzc","soc","oo","ss","oid0","oid1","oid2"};
for($obj in $objs){
    for($parm in $parms){    
        catch(`setAttr -keyable false -channelBox false ($obj+"."+$parm)`);
        }
}

Align (match scale & position) according to vertices

global float $startVtxPos[];
global float $targetVtxPos[];
global float $oks[];
$oks = {};
if (`window -exists matchObjectsW`) deleteUI matchObjectsW;
if (`windowPref -exists matchObjectsW`) windowPref -remove matchObjectsW;
string $window = `window -widthHeight 250 250 -title "Object Align" matchObjectsW `;
columnLayout -columnAttach "both" 6 -rowSpacing 10 -columnWidth 250;
text -ww 1 -l "\nMatches the location of target from source\n\nSelect two vertices or one edge on each object, hit apply\n";  
button -label "Select components on target object" -command "selS" selSButton;
button -label "Select components on source object" -command "selT" selTButton;
button -label "Apply (no matching selection)" -command "matchObjects" -en 0 matchObjectsButton;
button -label "Close" -command "cancelMatchObjects";
showWindow $window;

proc cancelMatchObjects(){
    deleteUI matchObjectsW;
}

proc selS(){
    global float $oks[];
    global float $startVtxPos[];
    string $selection[] = `ls -sl`;
    string $vtx[] = `polyListComponentConversion -tv $selection`;
    if(size($vtx) != 2){
        warning "select an edge or two vertices";
        $oks[0] = 0;
    }else{
        $oks[0] = 1;
        $startVtxPos = `xform -q -ws -t $vtx`;
    }
    refreshMatchObjects;
}
proc selT(){
    global float $oks[];
    global float $targetVtxPos[];
    string $selection[] = `ls -sl`;
    string $vtx[] = `polyListComponentConversion -tv $selection`;
    if(size($vtx) != 2){
        warning "select an edge or two vertices";
        $oks[1] = 0;
    }else{
        $oks[1] = 1;
        $targetVtxPos = `xform -q -ws -t $vtx`;
    }
    refreshMatchObjects;
}
proc refreshMatchObjects(){
    global float $oks[];
    print($oks[0]+" "+$oks[1]);
    if($oks[0] && $oks[1]){
                
        button -e -en 1 -label ("Apply") "matchObjectsButton";       
    }else{
        button -e -en 0 -label ("Apply "+(($oks[0]+$oks[1]==1)?("(selected 1/2)"):("(no matching selection)"))) "matchObjectsButton";               
    }
}

set object pivot according to normals+locator

string $objs[] = `ls -sl`;
string $obj = `match "^[^\.]*" $objs[size($objs)-1]`;
setToolTo moveSuperContext; 
$manipMode = `manipMoveContext -q -mode Move`;
manipMoveContext -e -mode 9 Move;
vector $centerPos = `manipMoveContext -q -position Move`;
vector $centerRot = `manipMoveContext -q -oa Move`;
string $loca[] = `spaceLocator`;
setAttr ($loca[0]+".tx") ($centerPos.x);
setAttr ($loca[0]+".ty") ($centerPos.y);
setAttr ($loca[0]+".tz") ($centerPos.z);
setAttr ($loca[0]+".rx") (rad_to_deg($centerRot.x));
setAttr ($loca[0]+".ry") (rad_to_deg($centerRot.y));
setAttr ($loca[0]+".rz") (rad_to_deg($centerRot.z));
string $pivWindow = `window -title "Set Center"
       -iconName "Short Name"
       -widthHeight 180 110`;
columnLayout -adjustableColumn true;
       text -label "\nMove/rotate selected locator\nto set the pivot of your object\n";
       button -label "Done" -command ("pivProceed($pivWindow,$loca[0],$obj)");
       button -label "Cancel" -command ("deleteUI -window " + $pivWindow+";delete $loca[0]");
setParent ..;
showWindow $pivWindow;

select -r $loca[0];

proc pivProceed(string $w,string $loc, string $obj){
    string $parents[] = `listRelatives -parent $obj`;
    parent $obj $loc;
    makeIdentity -apply true -t 1 -r 1 -s 0 -n 0 $obj;
    if($parents[0] != ""){
        parent $obj $parents[0];
    }else{
        parent -w $obj;
    }
    delete $loc;    
    deleteUI -window $w;
}

manipMoveContext -e -mode $manipMode Move;

batch Maxwell FIRE rendering

global string $currentFrameFile;
global int $frameN;
global int $originalFrame;
global string $error;
global int $playblastActive;
$playblastActive = 0;
$currentFrameFile = $error = "";
$originalFrame = `currentTime -q`;
$frameN = 1;

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(){
    global string $error;
    global string $currentFrameFile;
//    "+`date -f "MMDD_hhmmss"`+"/
    $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;
    }else{
        $error = "No maxwell FIRE window found";
        firePBrefreshUI;
    }
    return "";
}
global proc firePlayblastUI(){
    global int $frameN;
    int $e = `playbackOptions -query -maxTime`;
    int $s = `playbackOptions -query -minTime`;
    $frameN = $s;
    if (`window -exists playblastFireWindow`) deleteUI playblastFireWindow;
    if (`windowPref -exists playblastFireWindow`) windowPref -remove playblastFireWindow;
    string $window = `window -menuBar true -title "Playblast Fire" playblastFireWindow`;
    string $vp = findLayout("MaxwellFIRE","maxwellViewport" );
    paneLayout -vis ($vp!="0");
    columnLayout -adjustableColumn true;
    progressBar -maxValue 10 -width 300 -vis 1 -en 0 UI_progress;
    textField -text  "'Seconds per frame' includes voxelisation" -en 0 -editable false UI_textfield;
    separator -h 18 -en 0;
    int $timeperframe = `optionVar -q "firePB_secondsperframe"`;
    $timeperframe = ($timeperframe!=0)?$timeperframe:15;
    intFieldGrp -numberOfFields 1 -label "Seconds per frame" -cc "firePBrefreshUI" -value1 $timeperframe UI_timePerF;
    separator -h 12 -en 0;
    intFieldGrp -numberOfFields 1 -label "Start frame" -cc "firePBrefreshUI" -value1 $s UI_startF;
    intFieldGrp -numberOfFields 1 -label "End frame" -cc "firePBrefreshUI" -value1 $e UI_endF;
    intFieldGrp -numberOfFields 1 -label "Frame increment" -cc "firePBrefreshUI" -value1 1 UI_incrF;
    int $firePBlaunchfcheck = (`optionVar -q "firePB_fcheck"`=="yes")?1:0;
    checkBoxGrp -numberOfCheckBoxes 1 -cat 1 "both" 90 -label1 "Launch fcheck" -cc "firePBrefreshUI" -value1 $firePBlaunchfcheck UI_fcheck;
    separator -h 12 -en 0;
    button -label "Playblast!" -command "firePythonThread(0)"  -h 40 UI_playblast;
    separator -h 3 -en 1 -st "none";
    button -label "Explore" -command "firePBOpenSequence(0)" UI_explore;
        separator -h 16 -en 1 -st "none";
    button -label "Close" -command "firePythonThread(1);deleteUI playblastFireWindow ";
        separator -h 5 -en 1 -st "none";
    setParent..;setParent..;
    paneLayout -vis ($vp=="0");
    columnLayout -adjustableColumn true;
    button -label "Launch maxwell FIRE first" -command "firePlayblastUI";
    showWindow $window;
}
global proc firePBTic(int $incr){
	global int $frameN;
    firePBrefreshUI;
    if(!$incr){
        print ".";
    }else{
		int $incrF = `intFieldGrp -q -value1 UI_incrF`;
        saveFireImage;
        currentTime -u 1 -e (`currentTime -q`+$incrF);
		$frameN = `currentTime -q`;
    }
}
global proc firePythonThread(int $kill){
    global int $originalFrame;
    global int $playblastActive;
    global string $error;
     
    python( "import threadProc;from threadProc import Timer;import maya.mel as mm" );
    if(!$kill){
		int $timePerF = `intFieldGrp -q -value1 UI_timePerF`;
        $playblastActive = 1;
        currentTime -u 1 -e (`intFieldGrp -q -value1 UI_startF`);
        python( "def tic():mm.eval('firePBTic(0)')");
        python( "def toc():mm.eval('firePBTic(1)')");
        python( "timerTic = Timer(1, tic, repeat=True);timerTic.start()");
        python( "timerToc = Timer("+$timePerF+", toc, repeat=True);timerToc.start()");
    }else{
        $playblastActive = 0;
		$error = "Playblasting stopped";
        python( "timerTic.stop();timerToc.stop()");
        currentTime -e $originalFrame;
		$launchFcheck = `checkBoxGrp -q -value1 UI_fcheck`;
		if($launchFcheck){
			firePBOpenSequence(1);
		}
firePBrefreshUI;		
    }
}
global proc firePBrefreshUI(){
    global string $error;
    global string $currentFrameFile;
    global int $playblastActive;
    
    int $startF = `intFieldGrp -q -value1 UI_startF`;
    int $endF = `intFieldGrp -q -value1 UI_endF`;
    int $incrF = `intFieldGrp -q -value1 UI_incrF`;
    string $textfieldText ="";
    if($playblastActive){
        $cur = `currentTime -q`;
        //$text = ($cur-$startF)/($endF - $startF)/$incrF;
	    $textfieldText = "Playblasting ("+$cur+"/"+$endF+")";
        //textField -e -text ( $text) -en 0 -editable false UI_textfield;
        button -e -label "Stop playblast" -command "firePythonThread(1)"  -h 40 UI_playblast;
    }else{
	    button -e -label "Playblast!" -command "firePythonThread(0)"  -h 40 UI_playblast;
        $incrF = ($incrF < 1)?1:$incrF;
        int $timePerF = `intFieldGrp -q -value1 UI_timePerF`;
		if($timePerF<3){
			$timePerF = 3;
			$error += "short frames times = crash";
		}
		intFieldGrp -e -value1 $timePerF UI_timePerF;
        optionVar -iv "firePB_secondsperframe" $timePerF;
        $launchFcheck = `checkBoxGrp -q -value1 UI_fcheck`;
        optionVar -sv "firePB_fcheck" (($launchFcheck)?"yes":"no");
        if($endF<$startF){
            intFieldGrp -e -value1 ($startF+1) UI_endF;
        }
        float $tte = (($endF-$startF)*1.0*$timePerF)/$incrF*1.0;
        string $seconds = pad(($tte%60.0));
        $textfieldText = floor($tte/60.0)+"'"+substring($seconds,3,4)+"\" necessary for playblast";

    }
    $textfieldText = ($error!="")?$error+"!":$textfieldText;
    textField -e -text ( $textfieldText) -en 0 -editable false UI_textfield;
    intFieldGrp -e -value1 ($incrF) UI_incrF;
    $error = "";
}
global proc firePBOpenSequence(int $fcheck){
    global string $currentFrameFile;
	global int $frameN;
    if($fcheck){
        int $startF = `intFieldGrp -q -value1 UI_startF`;
        int $endF = `intFieldGrp -q -value1 UI_endF`;
        int $incrF = `intFieldGrp -q -value1 UI_incrF`;
        fcheck  -F -n $startF ($frameN-1) $incrF (`substitute "[.*]([0-9]{4})[\.a-Z]" $currentFrameFile ".#."`);
    }else{
        string $dir = `match "^.*/" $currentFrameFile`;
        if(`about -win`){
            system("start explorer " + toNativePath($dir));
        }
    }
}

batch IPR rendering




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;
}

all nurbs to polys

string $nurbz[] = `lsType "nurbsSurface"`;
for($n in $nurbz){
    if($n!="<done>"){
    string $tr[] = `listRelatives -f -p $n`;
    string $pr[] = `listRelatives -f -p $tr[0]`;
    string $ntps[] = `nurbsToPoly -mnd 1  -ch 0 -f 2 -pt 1 -pc 200 -chr 0.9 -ft 0.01 -mel 0.001 -d 0.1 -ut 3 -un 3 -vt 3 -vn 3 -uch 0 -ucr 0 -cht 0.2 -es 0 -ntr 0 -mrt 1 -uss 1 -n ($tr[0]+"_poly") $n`;
    parent $ntps[0] $pr[0];
    delete $tr[0];
    }
}

Use edge loops


float $r[] = {};

//selectionner un edge loop au bord de l'objet et lancer ce code plein de fois (avec Entrée du clavier num.)

string $el[] = `pickWalk -d right -type edgeloop`;
$oldsize = $size = size($el);
setToolTo moveSuperContext; 
vector $centerPos = `manipMoveContext -q -position Move`;
$r[size($r)] = $centerPos.x;
$r[size($r)] = $centerPos.y;
$r[size($r)] = $centerPos.z;

//////////////
//quand c'est fini, lancer ce code 

$curv = "curve -d 1";
$ks = "";
for($i=0;$i<size($r)/3;$i++){
    $curv += " -p "+$r[$i*3+0]+" "+$r[$i*3+1]+" "+$r[$i*3+2];
    $ks += " -k "+$i;
}
$eval = $curv+$ks;
eval($eval);

Tracks

//makes tracks along a curve with single motionpaths nodes. Make sure to use a surface-to-curve to get the right normals -- no flips
int $dupl = 3;
string $objs[] = `ls -sl`;
if( (nodeType(`listRelatives -s $objs[1]`) == "nurbsCurve") && (nodeType(`listRelatives -s $objs[0]`) == "mesh") ){
    string $expression = "";
    string $curv = $objs[1];
    string $mesh = $objs[0];
    
    addAttr -ln "uSpeed"  -dv .5 -at double  $curv;
    setAttr -e-keyable true ($curv+".uSpeed"); 
    
    addAttr -ln "uSpread" -dv .1 -at double $curv;
    setAttr -e-keyable true ($curv+".uSpread"); 
    
    for($i = 0;$i<$dupl;$i++){
        string $dupObj[] = `duplicate $mesh`;
        string $mp = `pathAnimation -fractionMode true -follow true -followAxis x -upAxis y -worldUpType "normal" -inverseUp true -inverseFront false -bank false -curve $curv $dupObj[0]`;
        disconnectAttr ($mp+"_uValue.output") ($mp+".uValue");
        $expression += $mp+".uValue = ("+$curv+".uSpeed * time + "+$curv+".uSpread * "+$i+" )%1;\n";
    }
    expression -s $expression -o$curv -ae 1 -uc all;
    select -r $curv;
}else{
    warning "select an object and a curve";
}


Particles thingy

proc float[] mergeArray(float $a[], float $b[]){
    for($e in $b){
        $a[size($a)] = $e;
    }
    return $a;
};

proc float[] quad(float $v[], float $dist){
    $x = $v[0];
    $y = $v[1];
    $z = $v[2];
    float $list[] = {
        $x - $dist, $y - $dist, $z - $dist,
        $x + $dist, $y - $dist, $z - $dist,
        $x + $dist, $y - $dist, $z + $dist,
        $x - $dist, $y - $dist, $z + $dist,
        $x - $dist, $y + $dist, $z - $dist,
        $x + $dist, $y + $dist, $z - $dist,
        $x + $dist, $y + $dist, $z + $dist,
        $x - $dist, $y + $dist, $z + $dist
    };
    return $list;
}
proc quadDivide(){
    float $distance = 1;
    string $sel[] = `ls -sl`;
    float $l0[] = {};
    float $l1[] = {};
    
    if(size($sel)==0 || nodeType(`listRelatives -s $sel[0]`) != "particle"){
        $l0 = {0,0,0};
        $l1 = quad({0,0,0},$distance);
    }else{
        string $objs[] = `listRelatives -s $sel[0]`;
        $l0 = `getParticleAttr -a 1 -at position $objs[0]`;
        vector $v1 = <<$l0[0],$l0[1],$l0[2]>>;
        vector $v2 = <<$l0[3],$l0[4],$l0[5]>>;
        $distance = mag($v1-$v2)/4;
        print($distance);
        for($j = 0;$j<size($l0)/3;$j++){
            $l1 = mergeArray($l1,quad({$l0[$j*3],$l0[$j*3+1],$l0[$j*3+2]},$distance));
        }
    }

    float $l2[] = {};
    float $l3[] = {};

    for($i = 0;$i<size($l1)/3;$i++){
        $l2 = mergeArray($l2,quad({$l1[$i*3],$l1[$i*3+1],$l1[$i*3+2]},$distance/2));
    }
    for($j = 0;$j<size($l2)/3;$j++){
         $l3 = mergeArray($l3,quad({$l2[$j*3],$l2[$j*3+1],$l2[$j*3+2]},$distance/4));
    }

    $p1 = createParticle($l1,$distance);
    $p2 = createParticle($l2,$distance/2);
    $p3 = createParticle($l3,$distance/4);
    evalDeferred(print("done."));
}

proc string createParticle(float $list[], float $d){
    string $p = "particle ";
    for($i = 0;$i<size($list)/3;$i++){
        $p += " -p "+$list[$i*3]+" "+$list[$i*3+1]+" "+$list[$i*3+2];
    }
    string $pObj[] = eval($p);
    setAttr ($pObj[1]+".particleRenderType") 8;
    addAttr -is true -ln "radius" -at "float" -min 0 -max 20 -dv $d $pObj[1];
    return $pObj[1];
}
print("calculating, please wait..\n");
evalDeferred("quadDivide");

Super duplicate enhancement, has moved

proc int hasMoved(string $obj,float $threshold){
    int $t = `currentTime -q`;
    float $pN[] = `getAttr($obj+".translate")`;
    //float $rN[] = `getAttr($obj+".rotate")`;
    currentTime -e ($t - 1);
    float $pO[] = `getAttr($obj+".translate")`;
    //float $rO[] = `getAttr($obj+".rotate")`;
    currentTime -e $t;
    vector $diffT = <<$pO[0]-$pN[0],$pO[1]-$pN[1],$pO[2]-$pN[2]>>;

    if(mag($diffT)>$threshold){
        return true;
    }else{
        return false;
    }
}
string $o[] = `ls -sl`;
$v = 0;
for($i = 1;$i<400;$i++){
    currentTime -e $i;
    $v += hasMoved($o[0],0.001);
    //print $v;
}
print(floor(($v*1.0)/$i*10000)/100+"%");

UV texture


string $r = `createNode ramp`;
string $p = `createNode place2dTexture`;
setAttr ($p+".mirrorV") 1;
setAttr ($p+".repeatV") 2;
setAttr ($r+".interpolation") 0;
connectAttr ($p+".outUV") ($r+".uv");
connectAttr ($p+".outUvFilterSize") ($r+".uvFilterSize");

setAttr ($r+".colorEntryList[0].color") -type double3 1 .33 0;
setAttr ($r+".colorEntryList[0].position") .9166;
setAttr ($r+".colorEntryList[1].color") -type double3 1 1 0;
setAttr ($r+".colorEntryList[1].position") .75;
setAttr ($r+".colorEntryList[2].color") -type double3 0 1 0;
setAttr ($r+".colorEntryList[2].position") .5833;
setAttr ($r+".colorEntryList[3].color") -type double3 0 1 1;
setAttr ($r+".colorEntryList[3].position") .4166;
setAttr ($r+".colorEntryList[4].color") -type double3 0 0 1;
setAttr ($r+".colorEntryList[4].position") .25;
setAttr ($r+".colorEntryList[5].color") -type double3 1 0 1;
setAttr ($r+".colorEntryList[5].position") .0833;
setAttr ($r+".colorEntryList[6].color") -type double3 1 0 0;
setAttr ($r+".colorEntryList[6].position") 0;

string $r2 = `createNode ramp`;
string $p2 = `createNode place2dTexture`;
setAttr ($r2+".type") 1;
setAttr ($r2+".interpolation") 0;
for($i=0;$i<=11;$i++){
    setAttr ($r2+".colorEntryList["+$i+"].color") -type double3 (($i*2.0)/12) 0 0;
    setAttr ($r2+".colorEntryList["+$i+"].position") (($i*1.0)/12);
  
}
connectAttr -f ($r2+".outColorR") ($p+".offsetV");
connectAttr ($p2+".outUV") ($r2+".uv");
connectAttr ($p2+".outUvFilterSize") ($r2+".uvFilterSize");

$lamb = `shadingNode -asShader lambert -name lambertUVCheck`;
$lambSG = `sets -renderable true -noSurfaceShader true -empty -name lambertUVCheckSG`;
connectAttr -f ( $lamb + ".outColor" ) ( $lambSG + ".surfaceShader" );
connectAttr -force ($r+".outColor") ($lamb+".color");
addAttr -ln "tile"  -at double  -dv 1 $lamb;
setAttr -e-keyable true ($lamb+".tile");

$m = `createNode multiplyDivide`;
connectAttr -f ($lamb+".tile") ($m+".input1X");
connectAttr -f ($lamb+".tile") ($m+".input1Y");
setAttr ($m+".input2X") 2;
setAttr ($m+".input2Y") 1;
connectAttr -f ($m+".outputX") ($p+".repeatV");
connectAttr -f ($m+".outputY") ($p2+".repeatU");






small things rig

for($o in `ls -sl`){
select -r $o;
setToolTo moveSuperContext; 
vector $centerPos = `manipMoveContext -q -position Move`;
string $c[0] = `circle -nr 0 0 1 -c 0 0 0 -r 2 -ch 0 -n "DaimCtrl"`;
move -r -os -wd ($centerPos.x) ($centerPos.y) ($centerPos.z) ;
select $c[0] $o;
performParentConstraint 0;
performScaleConstraint 0;
select $c[0] ;
zero();
}

auto ribbon setup

string $jnts[] = `ls -sl`;
if(size($jnts)!=2){
    warning "select 2 joints";
}else{
    $startj = $jnts[0];
    $endj = $jnts[1];
    
}
float $sT[] = `xform -ws -q -t $startj`;
float $eT[] = `xform -ws -q -t $endj`;
float $trs[] = {abs($sT[0]-$eT[0]),abs($sT[1]-$eT[1]),abs($sT[2]-$eT[2])};

string $translate = ($trs[0]<$trs[1])?($trs[0]<$trs[2]):"";

string $elms[] = `ikHandle -sol ikSplineSolver -scv false -roc false -pcv false`;
$curve = $elms[2];
delete $elms[0] $elms[1];
setAttr "curve1.translateZ" -1.5;




Numericable fracture

$speedrand = 4;
$posrand = 1;
$startframe=110;
$endframe=126;
string $sel[] = `ls -sl`;
CenterPivot;
float $rand = 0;
float $bbox[] = `xform -q -ws -bb $sel[0]`;
float $pos[] = {};//`xform -q -ws -rp $sel[0]` ;
for($i=0;$i<size($sel);$i++){
    float $bboxtemp[] = `xform -q -ws -bb $sel[$i]`;
    $bbox = {min($bboxtemp[0],$bbox[0]),min($bboxtemp[1],$bbox[1]),min($bboxtemp[2],$bbox[2]),max($bboxtemp[3],$bbox[3]),max($bboxtemp[4],$bbox[4]),max($bboxtemp[5],$bbox[5])};
    float $postmp[] = `xform -q -ws -rp $sel[$i]` ;
    $pos = {$pos[0] + $postmp[0],$pos[1] + $postmp[1],$pos[2] + $postmp[2]};
}
$pos = {$pos[0]/$i,$pos[1]/$i,$pos[2]/$i};

float $x = ($bbox[3]-$bbox[0]);
$x = $rand*(rand($x)-$x/2);

float $y = ($bbox[4]-$bbox[1]);
$y = $rand*(rand($y)-$y/2);

float $z = ($bbox[5]-$bbox[2]);
$z = $rand*(rand($z)-$z/2);

print(($pos[0]+$x)+" "+($pos[1]+$y)+" "+($pos[2]+$z)+"\n");
string $items[] = {};
for($a in $sel){
    string $polyCutTool[] = `polyCut  -ef 1 -eo 0 0 0 -pc ($pos[0]+$x) ($pos[1]+$y) ($pos[2]+$z) -ro 0 90 90 -ch 1 $a`; //y
    polyCloseBorder -ch 1 $a;
    string $polyCutTool[] = `polyCut  -ef 1 -eo 0 0 0 -pc ($pos[0]+$x) ($pos[1]+$y) ($pos[2]+$z) -ro 90 90 90 -ch 1 $a`; //
    polyCloseBorder -ch 1 $a;
    string $polyCutTool[] = `polyCut  -ef 1 -eo 0 0 0 -pc ($pos[0]+$x) ($pos[1]+$y) ($pos[2]+$z) -ro 0 0 90 -ch 1 $a`;  //z
    polyCloseBorder -ch 1 $a;
    delete -ch $a;
    int $pieces[] = `polyEvaluate -s $a`;
    if($pieces[0] > 1){
        polySeparate -ch 0 $a;
        CenterPivot;       
    }
    appendStringArray($items,`ls -sl`, size(`ls -sl`));
}
for($it in $items){
    select -r $it;
    float $center[] = `xform -q -ws -rp $it`;
    vector $tr = <<$center[0]-$pos[0],$center[1]-$pos[1],$center[2]-$pos[2]>>;
    $tr = <<$tr.x*rand($speedrand),$tr.y*rand($speedrand),$tr.z*rand($speedrand)>>;
    $tr += <<rand(-$posrand,$posrand),rand(-$posrand,$posrand),rand(-$posrand,$posrand)>>;
    vector $rr = <<rand(-30,30),rand(-30,30),rand(-30,30)>>;

    setKeyframe -at translate  -t $startframe -t (($startframe+$endframe)/2) -t $endframe -v 0 $it;
    selectKey  -clear;
    selectKey -add -k -in 1 ($it+".translateX") ;
    keyframe -e -o move -vc  ($tr.x) -at ($it+".translateX");
    selectKey  -clear;
    selectKey -add -k -in 1 ($it+".translateY") ;
    keyframe -e -o move -vc  ($tr.y) -at ($it+".translateY");
    selectKey  -clear;
    selectKey -add -k -in 1 ($it+".translateZ") ;
    keyframe -e -o move -vc  ($tr.z) -at ($it+".translateZ");
    
    setKeyframe -at rotate -t $startframe -t (($startframe+$endframe)/2) -t $endframe -v 0 $it;
    selectKey  -clear;
    selectKey -add -k -in 1 ($it+".rotateX") ;
    keyframe -e -o move -vc  ($rr.x) -at ($it+".rotateX");
    selectKey  -clear;
    selectKey -add -k -in 1 ($it+".rotateY") ;
    keyframe -e -o move -vc  ($rr.y) -at ($it+".rotateY");
    selectKey  -clear;
    selectKey -add -k -in 1 ($it+".rotateZ") ;
    keyframe -e -o move -vc  ($rr.z) -at ($it+".rotateZ");
    selectKey  -clear;
    
   /* $ax = (abs($rr.x)<80)?0:(($rr.x>0)?360:-360);
    $ay = (abs($rr.y)<80)?0:(($rr.y>0)?360:-360);
    $az = (abs($rr.z)<80)?0:(($rr.z>0)?360:-360);
    
    selectKey -add -k -in 2 ($it+".rotateX") ;
    keyframe -e -o move -vc  ($ax) -at ($it+".rotateX");
    selectKey  -clear;
    selectKey -add -k -in 2 ($it+".rotateY") ;
    keyframe -e -o move -vc  ($ay) -at ($it+".rotateY");
    selectKey  -clear;
    selectKey -add -k -in 2 ($it+".rotateZ") ;
    keyframe -e -o move -vc  ($az) -at ($it+".rotateZ");*/

}

Instancer

$p = "particle";
string $sel[] = `ls -sl`;
string $rotations[];
for($o in $sel){
    float $xf[] = `xform -q -piv -ws $o`;
    $xf[3] = rad_to_deg($xf[3]);
    $xf[4] = rad_to_deg($xf[4]);
    $xf[5] = rad_to_deg($xf[5]);
    $rotations[size($rotations)] = $xf[3];
    $rotations[size($rotations)] = $xf[4];
    $rotations[size($rotations)] = $xf[5];        
    $p += " -p "+$xf[0]+" "+$xf[1]+" "+$xf[2];
}
string $particleObj[] = `eval $p`;




addAttr -ln rotationPP -dt vectorArray $particleObj[1];
addAttr -ln rotationPP0 -dt vectorArray $particleObj[1];
for($i = 0; $i < size($sel);$i++){
    select -r pobjectShape.pt[$r[$j]];
    string $pa = "targetPShape.pt["+$endPositions[$j]+"]";
    float $posi[] =  `getParticleAttr -a 1 -at initialPosition $pa`;
    setParticleAttr -vv $posi[0] $posi[1] $posi[2] -at targetPositionPP;
}
setParticleAttr -at rotationPP -fv $rotations -o $particleObj[1];
string $particleIns = eval("particleInstancer -r rotationPP -oi particleId -a -obj "+stringArrayToString($sel," -obj ")+" "+$particleObj[1]);

Merge particles systems

$pobj = "nParticle";
for($obj in `ls -sl`){
    $c = `particle -q -count $obj`;   
    $t = getAttr ($obj+".translate"); 
    float $m[] = `xform -query -matrix $obj`;
    $pos = `getParticleAttr -a 1 -at position $obj`;
    for($i=0;$i<size($pos);$i=$i+3){   
        float $p[] = {$pos[$i],$pos[$i+1],$pos[$i+2]};
        $p =  pointMatrixMult($p,$m);
        $pobj += " -p "+($p[0]+$t[0])+" "+($p[1]+$t[1])+" "+($p[2]+$t[2]);
    }
    
}
eval($pobj);

tmp:

//select particles and run
string $newP = "particle";
string $pa[] = `ls -sl`;
for($p in $pa){
   string $paSh[] = `listRelatives -s $p`;
   if(`nodeType $paSh[0]` != "particle"){
       warning "select particles only";
       break;
   }else{
       float $particlePos[] = `getParticleAttr -a 1 -at position $paSh[0]`;
       for($i=0;$i<size($particlePos)/3;$i++){
           $newP += " -p "+$particlePos[$i*3]+" "+$particlePos[$i*3+1]+" "+$particlePos[$i*3+2];
       }
   }
}
evalDeferred($newP);

matrix usage

float $m[] = `xform -query -matrix "nParticle1"`;
vector $p = `getParticleAttr -a 1 -at position nParticle1.pt[0]`;
$p =  pointMatrixMult($p,$m);
$p += getAttr ( "nParticle1.translate");
locator1.translateX = $p.x;
locator1.translateY = $p.y;
locator1.translateZ = $p.z;


Match closest particles wizz

//test 2 WIP
string $particles[] = `ls -sl`;

float $pos1[] =  `getParticleAttr -a 1 -at position $particles[0]`;
float $pos2[] =  `getParticleAttr -a 1 -at position $particles[1]`;
float $maxTries1[] = {};
float $maxTries2[] = {};
float $magns[] = {};
float $empties1[] = {};
float $empties2[] = {};
float $newOrd[] = {};

for($i=0;$i<size($pos1)/3;$i++){
    vector $pA1 = << $pos1[$i*3] , $pos1[$i*3+1] , $pos1[$i*3+2] >>;
    vector $pB1 = << $pos2[$i*3] , $pos2[$i*3+1] , $pos2[$i*3+2] >>;
    float $m1 = mag($pA1-$pB1);
    $magns[$i] = $m1;
}
for($i = 0; $i <= 10; $i++){
    int $a1 = rand(size($pos1)/3);
    int $a2 = $a1;
    while ($a1 == $a2){
        $a2 = rand(size($pos1)/3);        
    }
    int $b1 = rand(size($pos2)/3);
    int $b2 = $b1;
    while ($b1 == $b2){
        $b2 = rand(size($pos2)/3);        
    }
    vector $pA1 = << $pos1[$a1*3] , $pos1[$a1*3+1] , $pos1[$a1*3+2] >>;
    vector $pA2 = << $pos1[$a2*3] , $pos1[$a2*3+1] , $pos1[$a2*3+2] >>;
    vector $pB1 = << $pos2[$b1*3] , $pos2[$b1*3+1] , $pos2[$b1*3+2] >>;
    vector $pB2 = << $pos2[$b2*3] , $pos2[$b2*3+1] , $pos2[$b2*3+2] >>;

    float $m1 = mag($pA1-$pB1);
    float $m2 = mag($pA2-$pB2);
    
    float $m3 = mag($pA1-$pB2);
    float $m4 = mag($pA2-$pB1);
    
    if( ( $m3 + $m4 ) < ( $m1 + $m2 ) ){
        $magns[$a1] = $m1;
        $magns[$a2] = $m2;
        $newOrd[$a1] = $b1;
        $newOrd[$a2] = $b2;
    }else{
        
    }
    
}
print $newOrd;

/*
for($i=0;$i<size($pos1)/3;$i++){
    float $shortestdistance = 99999999;
    vector $p1 = << $pos1[$i] , $pos1[$i+1] , $pos1[$i+2] >>;
    int $id = -1;
    for($j=0;$j<size($pos2)/3;$j++){
        if($empties[$j] != 1){
            vector $p2 = << $pos2[$j] , $pos2[$j+1] , $pos2[$j+2] >>;
            float $distance = mag($p1-$p2);
            $shortestdistance = min($shortestdistance, $distance );
            if($shortestdistance==$distance){
                $id = $j;                
            }
        }   
    }
    if($id != -1){
        $newOrd[$i] = $id;
        $empties[$id] = 1;
    }
}
*/

for($i=0;$i<size($pos1)/3;$i++){
    int $index = $newOrd[$i];

    float $p[] = { $pos2[$index*3] , $pos2[$index*3+1] , $pos2[$index*3+2] };
    select -r ($particles[1]+".pt["+$i+"]");  
    setParticleAttr -vv $p[0] $p[1] $p[2] -at position;
    /*refresh -f;
    pause -sec 1;*/
}
select -r $particles;
string $selection[] = `ls -sl`;
float $r[] = {};
float $usedArray[] = {};
float $usedArrayFlag[] = {};
float $endPositions[] = {};

proc int inArray(float $v,float $thearray[]){
    int $flag = 0;
    for($item in $thearray){
        if($item == $v){
            $flag = 1;
            break;
        }
    }
    return $flag;
}
for($i = 0;$i < 500;$i++){
    $max = 1000;    
    $flag = true;
    int $t = rand(500);
    $count = 0;
    while(inArray($t,$r) && $count < $max){
        $count++;
        $t = rand(500);
        $flag = false;
    }
    if($flag || $count < $max ){
        $r[size($r)] = $t;
    }
}
for($i = 0;$i < 500;$i++){
    $max = 1000;    
    $flag = true;
    int $t = rand(500);
    $count = 0;
    while(inArray($t,$usedArray) && $count < $max){
        $count++;
        $t = rand(500);
        $flag = false;
    }
    if($flag || $count < $max ){
        $usedArray[size($usedArray)] = $t;
        $usedArrayFlag[size($usedArray)] = 0;
    }
}

float $rPositions[] = {};
float $usedArrayPosition[] = {};

for($particle in $r){
    string $pa = "pobjectShape.pt["+$particle+"]";
    float $posi[] =  `getParticleAttr -a 1 -at position $pa`;
    $rPositions[size($rPositions)] = $posi[0];
    $rPositions[size($rPositions)] = $posi[1];
    $rPositions[size($rPositions)] = $posi[2];
}
for($particle in $usedArray){
    string $pa = "targetPShape.pt["+$particle+"]";
    float $posi[] =  `getParticleAttr -a 1 -at position $pa`;
    $usedArrayPosition[size($usedArrayPosition)] = $posi[0];
    $usedArrayPosition[size($usedArrayPosition)] = $posi[1];
    $usedArrayPosition[size($usedArrayPosition)] = $posi[2];
}
//print(size($rPositions));
for($j = 0; $j < size($r) ; $j++ ){
    
    $failcount = 0;
    int $shortest;
    float $shortestdistance = 99999999;
    int $pid = $j * 3;
    vector $pPos = <<$rPositions[$pid],$rPositions[$pid+1],$rPositions[$pid+2]>>;
    for($i=0;$i<=1000;$i++){
        int $rand = rand(size($usedArray));
        if($usedArrayFlag[$rand]==0){


            vector $tPos = <<$usedArrayPosition[$rand*3],$usedArrayPosition[$rand*3+1],$usedArrayPosition[$rand*3+2]>>;
            $d = mag($pPos-$tPos);
            if(min($shortestdistance,$d)==$d){
                $shortestdistance = $d;
                $shortest = $rand;
            }
        }else{
            $failcount++;
        }
    }
    $usedArrayFlag[$shortest] = 1;
    $endPositions[$j] = $shortest;
}
for($j = 0; $j < size($r);$j++){
    select -r pobjectShape.pt[$r[$j]];
    string $pa = "targetPShape.pt["+$endPositions[$j]+"]";
    float $posi[] =  `getParticleAttr -a 1 -at initialPosition $pa`;
    setParticleAttr -vv $posi[0] $posi[1] $posi[2] -at targetPositionPP;
}
saveInitialState -atr targetPositionPP pobjectShape;
print("\nEnd");
select -r $selection;
 
 
 
proc int inArray(float $v,float $thearray[]){
    int $flag = 0;
    for($item in $thearray){
        if($item == $v){
            $flag = 1;
            break;
        }
    }
    return $flag;
}
float $r[] = {};
for($i = 0;$i < 500;$i++){
    $max = 1000;    
    $flag = true;
    int $t = rand(500);
    $count = 0;
    while(inArray($t,$r) && $count < $max){
        $count++;
        $t = rand(500);
        $flag = false;
    }
    if($flag || $count < $max ){
        $r[size($r)] = $t;
    }
}
size($r);
$max = 20;
$radius = 10;
for($i=0;$i<=$max;$i++){
    $side = rand($max/($i+1),$max/($i+2));
    vector $pos = sphrand($radius);
    polyCube -w $side -h $side -d $side -sx 1 -sy 1 -sz 1 -ax 0 1 0 -cuv 4 -ch 1;
    move -r ($pos.x) (abs($pos.y)) ($pos.z); 
    print isInsideCube()
}
proc isInsideCube(string $object, string $containerObject){
    vector $pos = getAttr($object+".translate");
    print($pos.x);
    
}
isInsideCube("pCube4","pCube1");
$ps = "particleShape1";
/*if(particleShape1.particleId==0){
particleShape1.position = sphrand(2);
particleShape1.radiusPP = rand(1,3);
}*/
for($i=0;$i<particleShape1.count;$i++){
	$j = 0;
	float $p[] = `getParticleAttr -at position -array true $ps`;
	vector $s[] = `getParticleAttr -at radiusPP -array true $ps`;
	$flag = false;
	vector $po;
	while(!flag){
		$po=sphrand(3);
		if(pow(mag($s),2)>$p[0]-
	};
}

locators on vertices bake

int $start = 0;
int $end = 10;
string $vertices[] = `ls -sl -fl`;
string $locators[];
for($v in $vertices){
    
    string $newLoc[] = `spaceLocator`;
    $locators[size($locators)] = $newLoc[0];
}
for($i=$start;$i<=$end;$i++){
    currentTime $i;
    for($j = 0; $j<size($vertices);$j++){
        float $pos[] = `xform -q -ws -t $vertices[$j]`;
        setAttr ($locators[$j]+".translate") $pos[0] $pos[1] $pos[2];
        setKeyframe ($locators[$j]+".translate");
    }
}

Clean Bevel

//requires selection
string $s[] = `ls -sl`;
string $groupz = `group -em`;
for($i = 0;$i<=size($s)-1;$i++){
    select -r $s[$i];
    string $obj[] = `bevelPlus -constructionHistory false  -normalsOutwards true  -range false  -polygon 1 -tolerance 0.01 -numberOfSides 3 -js true  -width 0 -depth 0 -extrudeDepth 0.2 -capSides 4 -bevelInside 0 -outerStyle 0 -innerStyle 0 -polyOutMethod 2 -polyOutCount 200 -polyOutExtrusionType 2 -polyOutExtrusionSamples 1 -polyOutCurveType 3 -polyOutCurveSamples 2 -polyOutUseChordHeightRatio 0`;
    parent $obj[0] $groupz;
}

Select sharp edges

global string $cursel[];
/*proc string selectAngle(){
    global string $cursel[];
    if(size(`ls -sl`)>0 || size($cursel)> 0){
        if(size(`ls -sl`)>0){
            $cursel = `ls -sl`;
        }
    }
    $v = `floatSliderGrp -q -v "flSlider"`;
    $softEdge = `polySoftEdge -angle 50 -ch 1 $cursel`;
    ConvertSelectionToEdges;
    polySelectConstraint -m 3 -type 32768 -sm 2;
    string $selectEdges[] = `ls -sl`;
    delete $softEdge;
    invertSelection;
    return 1;
}*/
global proc selectAngle(){
    global string $cursel[];
    select -r $cursel;
    $cursel = {};
}

string $window = `window -title "Select sharp edges"`;
columnLayout;
string $slid = `floatSliderGrp  -field true -label "Select Edge Angle" -min 0 -max 90 -dc "selectAngle()" "flSlider"`;
showWindow $window;

Save renderview image to desktop as png

catchQuiet(`saveRenderViewToDesktop`); //still pops up an error
global proc saveRenderViewToDesktop(){
    string $fileName = `file -q -sceneName`;
    string $scene = `match "[^/\\]*$" $fileName`;
    $scene = `match "^[^\.]*" $scene`;
    //string $path = $desktop+"/renderView/"+$scene+"/"+$scene+;
    //string $workspace = `workspace -q -fullName`;
    string $desktop = getenv("USERPROFILE")+"/Desktop";
    string $d = system("echo %DATE%-%TIME%");
    string $datetime = substring($d,9,10)+substring($d,4,5)+substring($d,1,2)+"_"+substring($d,12,13)+substring($d,15,16)+"_"+substring($d,18,18);
    //string $path = $desktop+"/renderView/"+$scene+"/"+$scene+;
    sysFile -makeDir ($desktop+"/renderView/"); // Windows
    string $path = $desktop+"/renderView/"+$scene+"-"+$datetime;
    //string $path = $desktop+"/"+$scene+"-"+$datetime;
    int $imf = `getAttr "defaultRenderGlobals.imageFormat"`;
    setAttr "defaultRenderGlobals.imageFormat" 32;
    renderWindowSaveImageCallback "renderView" $path "image";
    setAttr "defaultRenderGlobals.imageFormat" $imf;
}

loc on points

string $objs[] = `ls -sl`;
string $obj = `match "^[^\.]*" $objs[size($objs)-1]`;
setToolTo scaleSuperContext; 
manipScaleContext -e -mode 3 Scale;
vector $centerPos = `manipScaleContext -q -position Scale`;
vector $centerRot = `manipScaleContext -q -oa Scale`;
$centerRot = <<rad_to_deg($centerRot.x),rad_to_deg($centerRot.y),rad_to_deg($centerRot.z)>>;
string $loc[] = `spaceLocator -p 0 0 0`;
move -r ($centerPos.x) ($centerPos.y) ($centerPos.z);
select -r $objs;
select -add $loc[0];
//rotate -r -os ($centerRot.x) ($centerRot.y) ($centerRot.z);
//select -r $objs;
//string $cl[] = `newCluster " -envelope 1"`;
//parent $cl[1] $loc[0];

nClothCache green ticks

xu7xr.png

print "\n\n";
$ob = `ls -sl -l -o`;
string $s[] = `listRelatives -s $ob`;
$cache = "";
for($shp in $s){
print(`listConnections  -t "nClothShape" $shp`);
}

listConnections outputCloth2;
listRelatives -s nCloth2;
listConnections -t "nCache" nClothShape2; 


catchQuiet (`deleteAttr -attribute "cacheStart" $ob`);
catchQuiet (`deleteAttr -attribute "cacheEnd" $ob`);
addAttr -ln "cacheStart"  -at double  $ob;
setAttr -e-keyable true ($ob[0]+".cacheStart");
addAttr -ln "cacheEnd"  -at double  $ob;
setAttr -e-keyable true ($ob[0]+".cacheEnd");
setKeyframe -at "cacheStart" -t 1 $ob[0];
keyframe -e -at "cacheStart" -tds 1 $ob[0];
setKeyframe -at "cacheEnd" -t 10 $ob[0];
keyframe -e -at "cacheEnd" -tds 1 $ob[0];

softbodyFlatten

string $sel[] = `ls -sl`;
for($i = 0;$i<=100;$i+=2){
    currentTime $i;
    currentTime ($i+1);
    string $dupe[] = `duplicate $sel[0]`;
    $ch = `listRelatives -c $dupe[0]`;
    delete($dupe[0]+"|"+$ch[2]);
}

Advanced Skeleton Button Maker

makeButton("FKDrapSideE*_M",344,114,4,15,15,1);
//select s
makeButton("",684,14,4,15,15,1);
//turn mirror on, select t
select -r FKDrapSideF_R ;
select -tgl FKDrapSideF1_R ;
select -tgl FKDrapSideF2_R ;
select -tgl FKDrapSideF3_R ;
select -tgl FKDrapSideF4_R ;
select -tgl FKDrapSideF5_R ;
select -tgl FKDrapSideF6_R ;
select -tgl FKDrapSideF7_R ;
select -tgl FKDrapSideF8_R ;
makeButton("",344,215,4,15,15,1);


proc makeButton(string $sel, float $x, float $y, float $g, float $bw, float $bh, int $it){
    string $hardCodeSelector = "asSelectorDefault|columnLayout5|asSelectorDefaultFormLayout|asSelectorBGImage";
    string $hardCodeSelector2 = "asSelectorDefault|columnLayout5|asSelectorDefaultFormLayout|asSelectorBGImage";
    float $bigButtons[] = {};
    $p = 0;
    $gBuffStrArr[0]="1";    
    $i = 0;
    int $topbutton = 3;
    string $list[] = {""};
    if($sel == ""){
        $list = `ls -sl`;
    }else{
         $list = `ls $sel`;
    }
    for($obj in $list){
            $p = ($p<3)?$p+1:1;
            print($p+"\n\n");
            select -r $obj;
            $i += $it;
            print($i+"!!!!\n");
            //
            clear $gBuffStrArr;
            $gBuffStrArr[0] = ""+($x+$i*($bw+$g));
            $gBuffStrArr[1] = ""+$y;
            asSelectorDpc  $hardCodeSelector $hardCodeSelector $gBuffStrArr (($x+$i*($bw+$g))+$bw) ($y+$bh) 2;
            clear $gBuffStrArr;    
            select -cl;
            if($p == 1){
                $bigButtons[size($bigButtons)] = ($it!=-1)?($x+$i*($bw+$g)):(($x+$i*($bw+$g))+$bw);
            }
            if($p == 3 || $list[size($list)-1]==$obj){
                $bigButtons[size($bigButtons)] = ($it==-1)?($x+$i*($bw+$g)):(($x+$i*($bw+$g))+$bw);
            }
    }
    $i=0;
    for($a=0;$a<(size($list)+1);$a+=3){
        
        eval("select -r "+$list[$a]+" "+$list[$a+1]+" "+$list[$a+2]);
        string $s[] = `ls -sl`;
        print($a+": "+stringArrayToString($s," ")+"\n");
        //
        clear $gBuffStrArr;
        $gBuffStrArr[0] = ""+$bigButtons[$i];
        $gBuffStrArr[1] = ""+($y+$bh+$g*2);
        asSelectorDpc $hardCodeSelector $hardCodeSelector $gBuffStrArr $bigButtons[$i+1] ($y+2*$bh+$g*2-3) 2;
        clear $gBuffStrArr;    
        select -cl;
        $i+=2;
    }
}

Ajouter des attributs en masse

A finir....

// crée des attributs sur plusieurs objets en meme temps, et les affiches dans la channel box
// WIP ---- STRING & INT ne marchent pas (que 'sep' 'float' pr l'instant)

string $sel[]=`ls -sl`;
if(size($sel)>0){
	
	string $result = `promptDialog
	   -title "Create Attributes"
	   -message "type name default min max\n-> float Angle 0\n-> float Value 0 -10 10\n->sep\n-> sep sepName'"
	   -button "OK" -button "Cancel"
	   -defaultButton "OK" -cancelButton "Cancel"
	   -text "float "
	   -dismissString "Cancel"`;


	if ($result == "OK") {
		$text = `promptDialog -query -text`;
		string $opnts[] = stringToStringArray($text, " ");
		$type = $opnts[0];
		//string $attrs[] = `listAttr -r -s $obj`;
		//stringArrayContains($attrs,);
		$text = `promptDialog -query -text`;
		$ok = 0;
		$cmd = "";
		$setAttr = "";
		if($opnts[0] == "sep"){
			$nicename = "_______";
			if($opnts[1] != ""){
				$nicename = "__"+$opnts[1]+"__";
			}
			float $hack = rand(0,99999);
			$hack = floor($hack);
			$cmd = "addAttr -ln \"_sep"+$hack+"_\" -nn \""+$nicename+"\"  -at \"enum\"";
			$setAttr = "setAttr -e-channelBox true ";
			$ok = 1;
		}else{
			$type = ($opnts[0]=="int")?"int ":"double ";
			$name = $opnts[1];
			if($name == ""){
				warning "Need a var name!";
			}else{
				$ok = 1;
			}
			$def = ($opnts[2]=="")?0:$opnts[2];
			$min = ($opnts[3]=="")?"":"-min "+$opnts[3]+" ";
			$max = ($opnts[4]=="")?"":"-max "+$opnts[4]+" ";
			$cmd = "addAttr -ln \""+$name+"\" -at "+$type+""+$min+""+$max+"-dv "+$def+" ";
			$setAttr = "setAttr -e-keyable true";
		}
		if($ok){
			for($obj in $sel){
				eval($cmd+" "+$obj);
				string $listAttrs[] = `listAttr $obj`;
				string $lastAttr = $listAttrs[size($listAttrs)-1];
				eval($setAttr+" "+$obj+"."+$lastAttr);
			}
		}
	}
}else{
		warning "No objects selected";
}

Edge loops to bones

//select one edge part of an edge loop
string $parentjoint = "";
polySelectSp -ring;
for($edge in `ls -sl -fl`){
    select -r $edge;
    polySelectSp -loop;
    setToolTo moveSuperContext; 
    float $centerP[] = `manipMoveContext -q -position Move`;
    string $newjoint = `joint -p $centerP[0] $centerP[1] $centerP[2]`;
    if($parentjoint != ""){
        parent $newjoint $parentjoint;
        joint -e -zso -oj xyz -sao yup $parentjoint;     
    }else{
        parent -w;
    }
    $parentjoint = $newjoint;
}

Constraints

$obj = `ls -sl -o`;
//for($c in `listConnections -t "constraint" -d 0 $obj`){
for($c in `listConnections -p 1 -d 0 $obj`){
    print($c+" "+`nodeType $c`+"\n");
}
listConnections  -d 0 $obj

Bone Blender

//Bone blender
string $sel[] = `ls -sl`;
string $blend = "Chest_M.switch_r";

string $sn = `shadingNode -asUtility blendColors`;
connectAttr -f  $blend ($sn+".blender");
connectAttr -f ($sel[0]+".translate") ($sn+".color1");
connectAttr -f ($sel[1]+".translate") ($sn+".color2");
connectAttr -f ($sn+".output") ($sel[2]+".translate");

string $sn = `shadingNode -asUtility blendColors`;
connectAttr -f  $blend ($sn+".blender");
connectAttr -f ($sel[0]+".rotate") ($sn+".color1");
connectAttr -f ($sel[1]+".rotate") ($sn+".color2");
connectAttr -f ($sn+".output") ($sel[2]+".rotate");

string $sn = `shadingNode -asUtility blendColors`;
connectAttr -f  $blend ($sn+".blender");
connectAttr -f ($sel[0]+".scale") ($sn+".color1");
connectAttr -f ($sel[1]+".scale") ($sn+".color2");
connectAttr -f ($sn+".output") ($sel[2]+".scale");


Parallel/Corrective Blendshapes maker

//extremely dirty coding, but it works
{
    if (`window -exists corrBs`) deleteUI corrBs;
    if (`windowPref -exists corrBs`) windowPref -remove corrBs;
    string $window = `window -widthHeight 250 400 -title "Corrective Blendshapes" corrBs `;
    columnLayout -columnAttach "both" 5 -rowSpacing 10 -columnWidth 250;
    text -ww 1 -l "\nThis will create a shape that you can later feed into a parallel blendshape node manually, and control with SDKs. Make sure no other deformation than the base skinCluster is on.";  
    button -label "Select base mesh" -command "selBaseF" selBase;
    button -label "Select controller/bone at rest position" -command "controlA" -en false contrBase;
    button -label ">> Set in pose, click and sculpt" -command "sculptF" -en false sculptBut;
    
    button -label "Done ? >> Create the target" -command "doneF" -en false doneBut;
    button -label "Cancel/close" -command "cancel";
    showWindow $window;
    global string $objs[];
    global string $ctrls[];
    global float $ctrlsM[];
    global string $A[];
    global string $B[];
    proc selBaseF(){
        $objs = `ls -sl`;
        if(size($objs)!=0){
            print $objs[0];
            select -cl;
            button -e -en 1 "contrBase";
            button -e -en 0 -label ("Base: "+$objs[0]) "selBase";
            }
        }
    proc controlA(){
        $ctrls = `ls -sl`;
        if(size($ctrls)!=0){
            $ctrlsM[0] = `getAttr ($ctrls[0]+".translateX")`;
            $ctrlsM[1] = `getAttr ($ctrls[0]+".translateY")`;
            $ctrlsM[2] = `getAttr ($ctrls[0]+".translateZ")`;
            $ctrlsM[3] = `getAttr ($ctrls[0]+".rotateX")`;
            $ctrlsM[4] = `getAttr ($ctrls[0]+".rotateY")`;
            $ctrlsM[5] = `getAttr ($ctrls[0]+".rotateZ")`;
            $ctrlsM[6] = `getAttr ($ctrls[0]+".scaleX")`;
            $ctrlsM[7] = `getAttr ($ctrls[0]+".scaleY")`;
            $ctrlsM[8] = `getAttr ($ctrls[0]+".scaleZ")`;    
            button -e -en 0 -label ("Ctrl:"+$ctrls[0]) "contrBase";
            button -e -en 1 "sculptBut";
        }
    }
    proc sculptF(){
        select -cl;
        $A = `duplicate -n "base" $objs[0]`;
        $B = `duplicate -n "sculptme" $objs[0]`;
        move -r 8 0 0 $B[0];
        setAttr ($A[0]+".visibility") 0;
        catchQuiet(`parent -w $B[0]`);
        catchQuiet(`parent -w $A[0]`);
        select -r $B[0];
        button -e -en 0 "sculptBut";
        button -e -en 1 "doneBut";
    }
    proc doneF(){
        select -cl;
        select -r $B[0] $A[0] $objs[0];
        string $bs[] = `blendShape -par`;
        setAttr ($ctrls[0]+".translateX") $ctrlsM[0];
        setAttr ($ctrls[0]+".translateY") $ctrlsM[1];
        setAttr ($ctrls[0]+".translateZ") $ctrlsM[2];
        setAttr ($ctrls[0]+".rotateX") $ctrlsM[3];
        setAttr ($ctrls[0]+".rotateY") $ctrlsM[4];
        setAttr ($ctrls[0]+".rotateZ") $ctrlsM[5];
        setAttr ($ctrls[0]+".scaleX") $ctrlsM[6];
        setAttr ($ctrls[0]+".scaleY") $ctrlsM[7];
        setAttr ($ctrls[0]+".scaleZ") $ctrlsM[8]; 
        setAttr ($bs[0]+".weight[0]") 1;
        setAttr ($bs[0]+".weight[1]") -1;
        
        $name = "CorrectedMesh";    
        $result = `promptDialog -title "Name of correction" -message "Enter Name:" -button "OK" -button "Cancel" -defaultButton "OK" -cancelButton "Cancel" -dismissString "Cancel"`;
        if ($result == "OK") {
            $name = `promptDialog -query -text`;
        }
        string $newObj[] = `duplicate -n $name $objs[0]`;
        select -r $newObj[0];
        parent -w;
        
        string $parB[] = `listConnections ($bs[0]+".outputGeometry[0]")`;
        delete $parB; 

        catchQuiet(`delete $B[0]`);
        catchQuiet(`delete $A[0]`);
        button -e -en 1 -label "Select base mesh" "selBase";
        button -e -en 0 -label "Select controller/bone at rest position" "contrBase";
        button -e -en 0 "sculptBut";
        button -e -en 0 "doneBut";       
        select -r $newObj[0];
    }
    proc cancel(){
        catchQuiet(`delete $B[0]`);
        catchQuiet(`delete $A[0]`);
        print("Done");
        deleteUI corrBs;
    }
}

Reforger les connections vers les SSS

//SELECTIONNER DABORD LA TEXTURE MR (mentalRayTexture) ET PUIS LA LMAP (miss_fast_lmap)
string $files[] = `ls -sl`;
$texture = $files[0]+".message";
$lmap = $files[1]+".message";

for($mat in `lsType "misss_fast_skin_maya"`){
	if($mat != "<done>"){

		catchQuiet(`connectAttr -f $texture ($mat+".lightmap")`);
		string $bobo[] = `connectionInfo -dfs ($mat+".outValue")`;
		string $node = $bobo[0];
		string $SG = `match "^[^\.]*" $node`;
		//print($SG+"\n");
		catchQuiet(`connectAttr -f $lmap ($SG+".miLightMapShader")`);
	}
}

Joint flip

string $objs[] = `ls -sl`;
$parent = `listRelatives -p $objs[0]`;
string $flip = `addAttr -ln "FlipCorrect"  -at bool  $objs[0]`;
setAttr -e -keyable true ($objs[0]+".FlipCorrect");
$cond = `shadingNode -asUtility condition`;
setAttr ($cond+".secondTerm") 1;
setAttr ($cond+".colorIfTrueR") 180;
setAttr ($cond+".colorIfFalseR") 0;
connectAttr -f ($objs[0]+".FlipCorrect") ($cond+".firstTerm");
connectAttr -f ($cond+".outColorR") ($parent[0]+".rotateX");

Controller color selector

/*
ls -sl;
listRelatives -s;
overrideColor;


help -doc ls
*/

window;
//rowLayout -nc 2;
columnLayout;
colorIndexSliderGrp -label "Select Color" -min 0 -max 20 -value 10;
rowLayout -nc 2;
button -label "Apply" -command "Apply";
button -label "Cancel" -command "Cancel";
showWindow;

Jean texture to light intensity

animateLights;
global proc animateLights(){
    string $sele[] = `ls -sl`;
    string $selRel[] = `listRelatives -s $sele`;
    string $polys[] = `filterExpand -sm 12`;
    string $lights[] = `ls -lt $selRel`;
    if(size($sele) != size($polys)+size($lights) || size($polys)!=1){
        warning("Select lights and a poly object with a texture!");
    }else{
        string $shapes[] = `listRelatives -s $polys`;
        string $shape = $shapes[0];
        string $trans = $polys[0];
        
        string $SG[] = `listConnections -t shadingEngine $shape`;
        string $outcolor = `connectionInfo -sfd ($SG[0]+".surfaceShader")`;
        string $no_component = `match "^[^\.]*" $outcolor`;
        string $fileTexture[] = `listConnections -t file $no_component`;
        if(size($fileTexture)<1){
            warning("No file texture found with "+$shape);
        }else{
            string $lightSet = `sets -em -n "AffectedLightsSet"`;
            sets -in $lightSet $lights;
            string $ft = $fileTexture[0];
            string $cpom = `createNode closestPointOnMesh`;
            connectAttr -f ($shape+".outMesh") ($cpom+".inMesh");
            connectAttr -f ($trans+".matrix") ($cpom+".inputMatrix");
            
            //locator object
            $ctrlObjs = `spaceLocator -p 0 0 0 -n "LightsControlLoc"`;
            $ctrlObj = $ctrlObjs[0];
            $anot = `annotate -tx "Lights Control" -p 2 2 2 $ctrlObj`;
            parent (`listRelatives -p $anot`) $ctrlObj ;
            setAttr ($anot+".template") 1;
            addAttr -ln "________"  -at "enum" -en "________"  $ctrlObj;
            setAttr -e -keyable true ($ctrlObj+".________");
            addAttr -ln "activated" -at double -dv 1 $ctrlObj ;
            setAttr -e -keyable true ($ctrlObj+".activated");
            addAttr -ln "setkeys" -at double -dv 1 $ctrlObj ;
            setAttr -e -keyable true ($ctrlObj+".setkeys");
            addAttr -ln "multiplier" -at double -dv 100 $ctrlObj ;
            setAttr -e -keyable true ($ctrlObj+".multiplier");
            addAttr -ln "debug" -at double -dv 0 $ctrlObj ;
            setAttr -e -keyable true ($ctrlObj+".debug");
            
            //expression
           
            string $ex;
            $ex += "$ctrlObj = \""+$ctrlObj+"\";\nif(`getAttr ($ctrlObj+\".debug\")` == 1){\n$t = `currentTime -q`;\n\tprint(\"\\n----[\"+$t+\"]------------\\n\");\n}\n";
            $ex += "if(`getAttr ($ctrlObj+\".activated\")` == 1){\n    $multiplier = `getAttr ($ctrlObj+\".multiplier\")`;\n    $ft = \"file1\";\n    $cp = \""+$cpom+"\";\n";
            $ex += "    for($obj in `listConnections -s 1 -d 0 -p 0 -c 0 \""+$lightSet+"\"`){\n        $ws = `xform -worldSpace -query -translation $obj`;\n";
            $ex += "    \tsetAttr ($cp+\".inPosition\") $ws[0] $ws[1] $ws[2];\n    \t$u = `getAttr ($cp+\".parameterU\")`;\n    \t$v = `getAttr ($cp+\".parameterV\")`;\n";
            $ex += "        float $RGB[] = `colorAtPoint -o RGB -u $u -v $v $ft`;\n        $shp = `listRelatives -s $obj`;\n        setAttr ($shp[0]+\".intensity\") ($RGB[0]*$multiplier);\n";
            $ex += "        if(`getAttr ($ctrlObj+\".setkeys\")` == 1){\n          setKeyframe ($shp[0]+\".intensity\");\n        }\n        if(`getAttr ($ctrlObj+\".debug\")` == 1){\n";
            $ex += "          $pos = `getAttr ($cp+\".position\")`;\n          move -a $pos[0] $pos[1] $pos[2] $ctrlObj; \n          select -r $obj $ctrlObj;\n          print($obj+\": \"+($RGB[0]*$multiplier)+";
            $ex += "\" u: \"+$u+\" v:\"+$v+\"\\n\");\n          refresh -f;\n          pause -sec 1;\t\t\n        }\n    }\n}";
           
            expression -s $ex -o $ctrlObj -n "lightsExpression" -ae 1 -uc all ;
            select -r $ctrlObj;
    
        }    
    }
}


Del unused nodes

hyperShadePanelMenuCommand("hyperShadePanel1", "deleteUnusedNodes");


motion vector particles

string $panel = `getPanel -withFocus`;
$camera = `modelPanel -q -cam $panel`;

$pnts = `ls -sl -fl`;
float $pntLocalPositions[] = `xform -q -t -ws $pnts`;
vector $pntLocalPositionsVectors[] = <<$ptPosWs[0],$ptPosWs[1],$ptPosWs[2]>>;
float $a[] = getAttr($camera+".worldInverseMatrix");
matrix $cameraInverseMatrix[4][4] = <<$a[0],$a[1],$a[2],$a[3];$a[4],$a[5],$a[6],$a[7];$a[8],$a[9],$a[10],$a[11];$a[12],$a[13],$a[14],$a[15]>>;
float[] pointMatrixMult ( float $point[], float $matrix[] )

particle force

//particleforce
vector $force1 = inputForce[1];
vector $force2 = inputForce[2];
if( `mag $force1` != 0 || `mag $force2` != 0 )
		lifespanPP = 0;


fracture particles spread/gather

//voronois
global proc setVoronois(int $min,int $max){
float $polyVol = 0;
float $vmax = 0;
float $vmin = 0;
string $sele[] = `ls -sl`; 
string $shapes[] = `listRelatives -s -path $sele`; 
float $shapeVol[];
string $breakNode[];
for($i = 0;$i<size($sele);$i++){
	string $fxbreak[] = `listConnections($shapes[$i]+".inMesh")`;
	$breakNode[$i] = $fxbreak[0];
	select -d;
	select -r $sele[$i];
	$t = catchQuiet($polyVol = `computePolysetVolume`);
	$polyVol = abs($polyVol);
	$vmin = ($i == 0)?($polyVol):(min($vmin,$polyVol));
	$vmax = max($vmax,$polyVol);
	$shapeVol[$i] = $polyVol;
	//print("\n"+$sele[$i]+"("+$shapes[$i]+")   "+$breakNode[$i]+" "+size($fxbreak)+".\n");
}

select -r $sele;
for($a = 0;$a<size($sele);$a++){
$perc = ($shapeVol[$a]-$vmin)/($vmax-$vmin);
float $numPar = ceil(($max-$min)*$perc+$min);
print("\n"+$sele[$a]+"("+$shapes[$a]+") -> "+$breakNode[$a]+"    ["+$shapeVol[$a]+"] "+(floor($perc*100))+"% ("+($numPar)+")");
//setAttr "fxBreakGeometry4.numPoints" 10;
}
}
setVoronois(1,20);
string $particles[] = `ls -sl -fl`;
float $arr[] = `getParticleAttr -a 1 -at position $particles`;
float $avX = 0;
float $avY = 0;
float $avZ = 0;
int $b = 0;
for($b;$b<size($arr);$b+=3){
	$avX += $arr[$b];
	$avY += $arr[$b+1];
	$avZ += $arr[$b+2];
}
$avX = $avX/($b/3);
$avY = $avY/($b/3);
$avZ = $avZ/($b/3);
float $avG[] = {$avX,$avY,$avZ};

window -title "Push/Pull Particles";
columnLayout -adjustableColumn true;
$t = `floatSlider -min -100 -max 100 -value 0 -step 1 -cc "test($particles,$arr,$avG)" "particleSlider"`;
showWindow;

proc float[] newPositions(float $positions[], float $avG[], float $scale){
	int $b = 0;
	for($b;$b<size($positions);$b+=3){
		$positions[$b] = $positions[$b] + $scale*($avG[0]-$positions[$b]);
		$positions[$b+1] = $positions[$b+1] + $scale*($avG[1]-$positions[$b+1]);
		$positions[$b+2] = $positions[$b+2] + $scale*($avG[2]-$positions[$b+2]);
	}
return $positions;
}
proc moveParticles(string $particles[], float $positions[]){
	global string $gMainProgressBar;
	$len = `size($particles)`;
	progressBar -edit
	    -beginProgress
	    -isInterruptable true
	    -status "Moving Particles..."
	    -maxValue $len $gMainProgressBar;
	for($part in $particles){
		if(`progressBar -query -isCancelled $gMainProgressBar`)
		break;

		progressBar -edit -step 1 $gMainProgressBar;
		print($part+"\n");
	}
	progressBar -edit -endProgress $gMainProgressBar;
}
//moveParticles($particles,$arr);
proc test(string $particles[],float $positions[], float $average[]){
	$scale = `floatSlider -q -v "particleSlider"`;
	$scale = $scale/100;
	float $nuPositions[] = newPositions($positions,$average,0);
	print("-----\n"+$positions[0]+"\n--------\n");
}

3d to 2d 2

/// transform un point 3d en un point 2d (pour eviter a retracker derriere)

// Rob Bredow
// rob (at) 185vfx.com
// http://www.185vfx.com/
// Copyright 3/2002 Rob Bredow, All Rights Reserved

global string $hardpath = "E:";
global string $camera = "";
$w = `getAttr "defaultResolution.width"`;
$h = `getAttr "defaultResolution.height"`;

global string $firstline = "w="+$w+"|h="+$h;

// Get a matrix
proc matrix screenSpaceGetMatrix(string $attr){
  float $v[]=`getAttr $attr`;
  matrix $mat[4][4]=<<$v[0], $v[1], $v[2], $v[3];
             $v[4], $v[5], $v[6], $v[7];
             $v[8], $v[9], $v[10], $v[11];
             $v[12], $v[13], $v[14], $v[15]>>;
 return $mat;
}

// Multiply the vector v by the 4x4 matrix m, this is probably
// already in mel but I cant find it.
proc vector screenSpaceVecMult(vector $v, matrix $m){
  matrix $v1[1][4]=<<$v.x, $v.y, $v.z, 1>>;
  matrix $v2[1][4]=$v1*$m;
  return <<$v2[0][0], $v2[0][1],  $v2[0][2]>>;
}

global proc int screenSpace()
{
global string $camera;
global string $hardpath;
global string $textafteravant;
global string $textafterafter;

$w = `getAttr "defaultResolution.width"`;
$h = `getAttr "defaultResolution.height"`;

if($camera == ""){
	string $panel = `getPanel -withFocus`;
	$camera = `modelPanel -q -cam $panel`;
}

  // get the currently selected point
  string $dumpList[] = `ls -sl`;
  int $argc = size($dumpList);

  if ($argc != 1)
  {
    confirmDialog -t "screenSpace Usage" -m "To use, select a point on a geometry or a single object to write";
    return -1;
  }

  string $dumpPt = $dumpList[0];

  // Make $dumpPt a unix friendly name
  string $name = $dumpPt;
  while ( match("\\[",$name) != "" ) {
    $name = `substitute "\\[" $name "_"`;
  }
  while ( match("\\]",$name) != "" ) {
    $name = `substitute "\\]" $name ""`;
  }
  while ( match("\\.",$name) != "" ) {
    $name = `substitute "\\." $name "_"`;
  }

  // Find the frame range
  float $fs = `playbackOptions -q -min`;
  float $fe = `playbackOptions -q -max`;
  string $verify = "Will create " + $name + "_screenSpace.cmp\n" +
                   "For the frame range of " + $fs + "-" + $fe + "\n" +
                   "The camera used will be "+$camera+"\n";

  if (`confirmDialog -t "screenSpace Verify" -m $verify -b "Dump" -b "Cancel"` == "Cancel")
    return -2;

  print ("Dumping selection...\n");

  string $pointWsFile = $hardpath+"/"+$name+"_screenSpace.cmp";
  int $outFileId = fopen($pointWsFile,"w");

  if ($outFileId == 0) {
    print ("Could not open output file " + $pointWsFile);
    return -1;
  }

  string $line;

  int $f = 0;
  float $tx[],$ty[],$tz[];
fprint $outFileId $textafteravant;
  for ($f=$fs;$f<=$fe;$f++)	
  {
    currentTime $f;

    // get the world space position of the point into a vector
    float $ptPosWs[] = `xform -q -ws -t $dumpPt`;
    vector $ptVecWs = <<$ptPosWs[0],$ptPosWs[1],$ptPosWs[2]>>;

    // Grab the worldInverseMatrix from cam_main
    matrix $cam_mat[4][4] = screenSpaceGetMatrix($camera+".worldInverseMatrix");

    // Multiply the point by that matrix
    vector $ptVecCs = screenSpaceVecMult($ptVecWs,$cam_mat);

    // Adjust the point's position for the camera perspective
    float $hfv = `camera -q -hfv $camera`;
    float $ptx = (($ptVecCs.x/(-$ptVecCs.z))/tand($hfv/2))/2.0+.5;
    float $vfv = `camera -q -vfv $camera`;
    float $pty = (($ptVecCs.y/(-$ptVecCs.z))/tand($vfv/2))/2.0+.5;

    float $ptz = $ptVecCs.z;

	float $ww = ($ptx*$w*100);
	float $hh = ($pty*$h*100);

	$ww = `floor $ww`;
	$hh = `floor $hh`;
	
	$ww *= .01;
	$hh *= .01;

	$hh = $h - $hh;

	//hack to match in comp:

	$hh = ($hh-$h/2)*1.176+$h/2;
	
    $line = "\t"+$f+"\t"+$ww+ "\t" +$hh + "\t" + "0\n";
	//$text += $line;
    fprint $outFileId $line;
  }
	$textafter = "\n\n"+$textafterafter;
	fprint $outFileId $textafterafter;
  	fclose $outFileId;
	print("\n-------\n"+$pointWsFile+"\n---------\n");
	  return 1;
};

3d to 2d keys afx

/// transform un point 3d en un point 2d (pour eviter a retracker derriere)

// Rob Bredow
// rob (at) 185vfx.com
// http://www.185vfx.com/
// Copyright 3/2002 Rob Bredow, All Rights Reserved

global string $hardpath = "E:";
global string $camera = "";
$w = `getAttr "defaultResolution.width"`;
$h = `getAttr "defaultResolution.height"`;

global string $textafteravant;
$textafteravant = "Adobe After Effects 8.0 Keyframe Data\n\n\tUnits Per Second	25\n\tSource Width	"+$w+"\n\tSource Height	"+$h+"\n\tSource Pixel Aspect Ratio	1\n\tComp Pixel Aspect Ratio	1\n\nTransform	Position\n\tFrame	X pixels	Y pixels	Z pixels	\n";
global string $textafterafter = "End of Keyframe Data";



// Get a matrix
proc matrix screenSpaceGetMatrix(string $attr){
  float $v[]=`getAttr $attr`;
  matrix $mat[4][4]=<<$v[0], $v[1], $v[2], $v[3];
             $v[4], $v[5], $v[6], $v[7];
             $v[8], $v[9], $v[10], $v[11];
             $v[12], $v[13], $v[14], $v[15]>>;
 return $mat;
}

// Multiply the vector v by the 4x4 matrix m, this is probably
// already in mel but I cant find it.
proc vector screenSpaceVecMult(vector $v, matrix $m){
  matrix $v1[1][4]=<<$v.x, $v.y, $v.z, 1>>;
  matrix $v2[1][4]=$v1*$m;
  return <<$v2[0][0], $v2[0][1],  $v2[0][2]>>;
}

global proc int screenSpace()
{
global string $camera;
global string $hardpath;
global string $textafteravant;
global string $textafterafter;

$w = `getAttr "defaultResolution.width"`;
$h = `getAttr "defaultResolution.height"`;

if($camera == ""){
	string $panel = `getPanel -withFocus`;
	$camera = `modelPanel -q -cam $panel`;
}

  // get the currently selected point
  string $dumpList[] = `ls -sl`;
  int $argc = size($dumpList);

  if ($argc != 1)
  {
    confirmDialog -t "screenSpace Usage" -m "To use, select a point on a geometry or a single object to write";
    return -1;
  }

  string $dumpPt = $dumpList[0];

  // Make $dumpPt a unix friendly name
  string $name = $dumpPt;
  while ( match("\\[",$name) != "" ) {
    $name = `substitute "\\[" $name "_"`;
  }
  while ( match("\\]",$name) != "" ) {
    $name = `substitute "\\]" $name ""`;
  }
  while ( match("\\.",$name) != "" ) {
    $name = `substitute "\\." $name "_"`;
  }

  // Find the frame range
  float $fs = `playbackOptions -q -min`;
  float $fe = `playbackOptions -q -max`;
  string $verify = "Will create " + $name + "_screenSpace.cmp\n" +
                   "For the frame range of " + $fs + "-" + $fe + "\n" +
                   "The camera used will be "+$camera+"\n";

  if (`confirmDialog -t "screenSpace Verify" -m $verify -b "Dump" -b "Cancel"` == "Cancel")
    return -2;

  print ("Dumping selection...\n");

  string $pointWsFile = $hardpath+"/"+$name+"_screenSpace.cmp";
  int $outFileId = fopen($pointWsFile,"w");

  if ($outFileId == 0) {
    print ("Could not open output file " + $pointWsFile);
    return -1;
  }

  string $line;

  int $f = 0;
  float $tx[],$ty[],$tz[];
fprint $outFileId $textafteravant;
  for ($f=$fs;$f<=$fe;$f++)	
  {
    currentTime $f;

    // get the world space position of the point into a vector
    float $ptPosWs[] = `xform -q -ws -t $dumpPt`;
    vector $ptVecWs = <<$ptPosWs[0],$ptPosWs[1],$ptPosWs[2]>>;

    // Grab the worldInverseMatrix from cam_main
    matrix $cam_mat[4][4] = screenSpaceGetMatrix($camera+".worldInverseMatrix");

    // Multiply the point by that matrix
    vector $ptVecCs = screenSpaceVecMult($ptVecWs,$cam_mat);

    // Adjust the point's position for the camera perspective
    float $hfv = `camera -q -hfv $camera`;
    float $ptx = (($ptVecCs.x/(-$ptVecCs.z))/tand($hfv/2))/2.0+.5;
    float $vfv = `camera -q -vfv $camera`;
    float $pty = (($ptVecCs.y/(-$ptVecCs.z))/tand($vfv/2))/2.0+.5;

    float $ptz = $ptVecCs.z;

	float $ww = ($ptx*$w*100);
	float $hh = ($pty*$h*100);

	$ww = `floor $ww`;
	$hh = `floor $hh`;
	
	$ww *= .01;
	$hh *= .01;

	$hh = $h - $hh;

	//hack to match in comp:

	$hh = ($hh-$h/2)*1.176+$h/2;
	
    $line = "\t"+$f+"\t"+$ww+ "\t" +$hh + "\t" + "0\n";
	//$text += $line;
    fprint $outFileId $line;
  }
	$textafter = "\n\n"+$textafterafter;
	fprint $outFileId $textafterafter;
	//$text+= $textafterafter;
	//fprint $outFileId $text;
  	fclose $outFileId;
	print("\n-------\n"+$pointWsFile+"\n---------\n");
	//system("start \""+$pointWsFile+"\"");
	  return 1;
};

Kohen Ball Thing II

// cache tout ce qui est plus pres que la distance 'Clipdist' crée lors du premier lancement du script
// utilisation:
// hideInside 1;
// 1 - pose de clées sur la visibilité
// 0 - pose pas de clées
//
global proc hideInside(float $keyframe){
	string $sele[] = `ls -sl`;
	$target = $sele[size($sele)-1];

	if(!objExists ($target+".clipdist")){
		addAttr -ln "clipdist"  -at double $target;
		setAttr -e -keyable true {$target+".clipdist"};
		warning "Remplir l'attribut >> clipdist <<";
	}else{
		float $hidden = 0;
		float $minDist = `getAttr ($target+".clipdist")`;
		select -r $target;
		setToolTo moveSuperContext; 
		float $centerTarg[] = `manipMoveContext -q -position Move`;

		for($a=0;$a<size($sele)-1;$a++){
			//print("\n"+$a+" --- "+$sele[$a]);
			select -r $sele[$a];
			setToolTo moveSuperContext; 
			float $centerPosi[] = `manipMoveContext -q -position Move`;
			$vec = <<$centerTarg[0]-$centerPosi[0],$centerTarg[1]-$centerPosi[1],$centerTarg[2]-$centerPosi[2]>>;
			$dist = `mag $vec`;
			setAttr ($sele[$a]+".visibility") 1;
			if($dist-$minDist < 0){
				setAttr ($sele[$a]+".visibility") 0;
				$hidden++;
			}
			if($keyframe){
				setKeyframe ($sele[$a]+".visibility");
			}
		}
		print($hidden+" objets cachés");
	}
	select -r $sele;
}

Nodestate Locked>Normal

//Check si les nodeStates sont pas en normal:


for($obj in `ls`){
	$a = `getAttr($obj+".nodeState")`;
	if($a != 0){
		print("\n"+$obj+" "+$a);
	}
	//catchQuiet(`setAttr($obj+".nodeState") 0`);
}


Chernokid Manager

//ui interface based on http://www.axelgaertner.de/axcrack/AxCrack.mel thanks!

	global string $window="ChernokidsManager";
	global int $width=200;
	global string $location = "U:/CHERNOKID/PROD/TOOLS/MAYA/MANAGER";
	global string $locationB = "U:/CHERNOKID/PROD/BDD/FINAL";
	

	global string $extension = "txt";

	if (`window -exists $window`) deleteUI -window $window;

	window -tlc 210 390 -wh $width 300 -title ($window+" 0.1") -iconName "ckMan" $window;


	string $root = `formLayout`;
	string $parent = `tabLayout -scr true -cr true -imh 10 -imw 10 -parent $root`;
	formLayout -edit
   		-attachForm $parent "top"    5
  		-attachForm $parent "left"   5
   		-attachForm $parent "bottom" 5
 		-attachForm $parent "right"  5
     	$root;	

	// Create Tab01
	tabCharger($parent);
	// Create Tab02
	tabRefs($parent);


	showWindow $window;



global proc tabRefs(string $parent) {
	$extension = "ma";
	global string $locationB;
	$width=`tabLayout -q -w $parent`;
	string $MaxMasterFrame=`frameLayout -lv false -mw 10 -mh 10 -w $width -bv false -parent $parent "Refs"`;
	string $MasterFrame=`columnLayout -adj true -rs 7 -parent $MaxMasterFrame`;


	string $nvoFrm=`frameLayout -l "Décors" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $nvoCol=`rowColumnLayout -cw 1 350 -parent $nvoFrm`;
	separator -style "none" -height 17 -parent $nvoCol;
	refsDD("bob", "test", "",$nvoCol,$locationB+"/DECORS",$extension);

	separator -style "none" -height 17 -parent $nvoCol;
	button 
		-label "Charger en Ref" 
		-h 30 
		-c ("loadRef(getDropDownListValue(\"bob\"),$locationB+getDropDownListValue(\"bob\"))") 
		-parent   $nvoCol;
	popupMenu;
		menuItem -label "Ref Editor" -c "getDropDownListValue(\"bob\")";
		menuItem -label "Ouvrir la scène (!!)";
		menuItem -label "Ouvrir le dossier";

}

global proc tabCharger(string $parent) {

	global string $location;
	global string $extension;
	
	$width=`tabLayout -q -w $parent`;

	string $MaxMasterFrame=`frameLayout -lv false -mw 10 -mh 10 -w $width -bv false -parent $parent "Plans"`;
	string $MasterFrame=`columnLayout -adj true -rs 7 -parent $MaxMasterFrame`;
	string $chargerFrame=`frameLayout -l "Charger" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $chargerLay = `rowColumnLayout -cw 1 350 -cal 1 "center" -numberOfColumns 1 -parent $chargerFrame`;
	string $txtload =`columnLayout -parent  $chargerLay`;
	string $imgrow =`columnLayout -parent $chargerLay`;
	string $chrgp = `columnLayout -parent $chargerLay`;

	string $nvoFrm=`frameLayout -l "Nouveau" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $nvoCol=`rowColumnLayout -cw 1 350 -parent $nvoFrm`;
	string $Frame03=`frameLayout -l "Editer" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $Frame03Col=`columnLayout -adj true -parent $Frame03`;
				       
	$img = $location+"/images/none.png";
	text -l "- Plan: "-parent $txtload -al "right" -fn "smallBoldLabelFont" Plantexte;
	text -l "(...)" -parent $txtload -al "left";
	image
		-image $img
		-w 200
		-h 113
		-parent $imgrow
		Imagepreview;
	separator -style "none" -height 10 -parent $imgrow;
	optionMenuGrp 
		-label "Travail"
		-parent $imgrow
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ("updateSections(\""+$chrgp+"\")") typeXXX;
		mksections;
	separator -style "none" -height 10 -parent $chrgp;
	plansDropDown($chrgp,$location+"/plans/anim",$extension);
	separator -style "none" -height 17 -parent $chargerLay;
	button 
		-label "Charger" 
		-h 30 
		-c ExecuteExpandPieces 
		-parent $chargerLay	
		Chargebutton;
		popupMenu;
			menuItem -label "Charger le plus récent du dossier";
			menuItem -label "Ouvrir le dossier";
	optionMenuGrp 
		-label "Travail"
		-parent $nvoCol
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ("") typePlan;
		mksections;
	separator -style "none" -height 10 -parent $nvoCol;

	textFieldGrp
		-cal 1 "right" 
		-cw2 140 170 
       		-label "Plan (pXX)"
        		-text  "00"
		-parent $nvoCol 
		NvoPlan;
	separator -style "none" -height 17 -parent $nvoCol;
	button 
		-label "Nouveau" 
		-h 30 
		-c ExecuteExpandPieces 
		-parent $nvoCol;
	}
proc mksections(){
		menuItem -label "anim";
		menuItem -label "layout";
}
proc string remPre(string $string,string $pre){
	string $pre = $pre+"_";
	string $prev = `substitute $pre $string ""`;
	return $prev;
}
 
proc string remEx(string $file){
	string $node = $file;
	string $no_component = `match "^[^\.]*" $node`;
	return $no_component;
}


global proc updateSections(string $parent){
	global string $location;
	global string $extension;
	string $getFromap = `optionMenuGrp -q -v typeXXX`;
	plansDropDown($parent,$location+"/plans/"+$getFromap,$extension);
}

proc updatePlans(string $location,string $extension) {
	string $plan=`optionMenuGrp -q -v loadPlanXXX`;
	if($plan != "..."){
		$plan = $location+"/"+$plan+"."+$extension; 
		string $infos[] = flatTextToArray($plan);
		text -e -l $infos[0] Plantexte; 
		if($infos[1] != ""){
			image -e -image $infos[1] Imagepreview;
		}
	}
}
proc string[] flatTextToArray(string $textfile){
	$fileId=`fopen $textfile "r"`;
	string $nextLine = `fgetline $fileId`;
	string $rem = "\\\n";
	string $infos[] = {`substitute $rem $nextLine ""`};
	while ( size( $nextLine ) > 0 ) {
		//print ( $nextLine );
    		$nextLine = `fgetline $fileId`; 
		$infos[size($infos)] = `substitute $rem $nextLine ""`;
	}
	fclose $fileId;
	return $infos;
}
proc plansDropDown(string $parent, string $location,string $extension){
	if (`control -exists "loadPlanXXX"`) deleteUI "loadPlanXXX";
	optionMenuGrp 
		-label "Charger Plan"
		-parent $parent
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ("updatePlans(\""+$location+"\",\""+$extension+"\")") loadPlanXXX;
		menuItemFromFiles($location,$extension);
}
proc refsDD(string $name, string $label, string $function, string $parent, string $location, string $extension){
	if (`control -exists $name`) deleteUI $name;
	optionMenuGrp 
		-label $label
		-parent $parent
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ($function) $name;
		menuItemFromFiles($location,$extension);
}
proc menuItemFromFiles(string $location,string $extension){
		menuItem -label "...";
		$location+="/";
		$extension = "*."+$extension;
		string $filess[] = `getFileList -fs $extension -folder $location`;
		for($file in $filess){
			$file = remEx($file);
			menuItem -label $file;
		}
}
proc loadRef(string $name, string $where){
	file -r -type "mayaAscii" -gl -loadReferenceDepth "all" -namespace $name -options "v=0;p=17" $where;
}
proc getDropDownListValue(string $dd){
	$val = `optionMenuGrp -q -v $dd`;
	print $val;
}

Bones Scaler Redux

createNode animCurveUU -n "test";
setKeyframe -f 0 -v 0;
setKeyframe -f 1 -v 1;

Bones Scaler

constructionHistory -tgl off;
$objsA = `ls -sl`;
$a = $objsA;
$objsB = `duplicate -rr -rc $objsA`;
$b = $objsB;
$objsA = `listRelatives -ad -typ "joint" $objsA`;
$objsB = `listRelatives -ad -typ "joint" $objsB`;
$objsA[size($objsA)] = $a[0];
$objsB[size($objsB)] = $b[0];
pointConstraint -offset 0 0 0 -weight 1 $a[0] $b[0];

$empty_group = `group -em`;

$locators = `spaceLocator`;
$locator = $locators[0];

addAttr -ln "xtr_scaleX" -at "float" -min 0 -max 1 -dv 1 $locator;
$listAttr = `listAttr $locator`;
string $lastAttr = $listAttr[size($listAttr)-1];
setAttr -e-keyable true ($locator+"."+$lastAttr);
addAttr -ln "xtr_scaleY" -at "float" -min 0 -max 1 -dv 1 $locator;
$listAttr = `listAttr $locator`;
string $lastAttr = $listAttr[size($listAttr)-1];
setAttr -e-keyable true ($locator+"."+$lastAttr);
addAttr -ln "xtr_scaleZ" -at "float" -min 0 -max 1 -dv 1 $locator;
$listAttr = `listAttr $locator`;
string $lastAttr = $listAttr[size($listAttr)-1];
setAttr -e-keyable true ($locator+"."+$lastAttr);

$plusminus = `shadingNode -asUtility plusMinusAverage`;
setAttr ($plusminus+".operation") 3;

$count = 0;
for($obj in $objsA){
	$emptygrp = `group -em -n ($obj+"_group")`;
	pointConstraint -offset 0 0 0 -weight 1 $obj $emptygrp;
	parent $emptygrp $empty_group;
	$db = `shadingNode -asUtility distanceBetween`;
	connectAttr -f ($emptygrp+".translate") ($db+".point1");
	connectAttr -f ($locator+".translate") ($db+".point2");
	connectAttr -f ($db+".distance") ($plusminus+".input1D["+$count+"]");
	$multDiv = `shadingNode -asUtility multiplyDivide`;
	setAttr ($multDiv+".operation") 2;
	connectAttr -f ($db+".distance") ($multDiv+".input1X");
	connectAttr -f ($plusminus+".output1D") ($multDiv+".input2X");

	$reverse = `shadingNode -asUtility reverse`;
	connectAttr -f ($locator+".xtr_scaleX") ($reverse+".input.inputX");
	connectAttr -f ($locator+".xtr_scaleY") ($reverse+".input.inputY");
	connectAttr -f ($locator+".xtr_scaleZ") ($reverse+".input.inputZ");


	$multDivA = `shadingNode -asUtility multiplyDivide`;

	connectAttr -f ($multDiv+".outputX") ($multDivA +".input1.input1X");
	connectAttr -f ($multDiv+".outputX") ($multDivA +".input1.input1Y");
	connectAttr -f ($multDiv+".outputX") ($multDivA +".input1.input1Z");

	connectAttr -f ($locator+".xtr_scaleX") ($multDivA +".input2.input2X");
	connectAttr -f ($locator+".xtr_scaleY") ($multDivA +".input2.input2Y");
	connectAttr -f ($locator+".xtr_scaleZ") ($multDivA +".input2.input2Z");

	$plusminus2 = `shadingNode -asUtility plusMinusAverage`;
	connectAttr -f ($reverse+".output") ($plusminus2+".input3D[0]");
	connectAttr -f ($multDivA+".output") ($plusminus2+".input3D[1]");

	$multDivB = `shadingNode -asUtility multiplyDivide`;
	connectAttr -f ($plusminus2+".output3D") ($multDivB+".input1");
	connectAttr -f ($objsA[$count]+".scale") ($multDivB+".input2");

	addAttr -ln "xtscalex" -at "float" -dv 1 $objsB[$count];
	$listAttr = `listAttr $objsB[$count]`;
	string $lastAttrx = $listAttr[size($listAttr)-1];
	setAttr -e-keyable true ($objsB[$count]+"."+$lastAttrx);

	addAttr -ln "xtscaley" -at "float" -dv 1 $objsB[$count];
	$listAttr = `listAttr $objsB[$count]`;
	string $lastAttry = $listAttr[size($listAttr)-1];
	setAttr -e-keyable true ($objsB[$count]+"."+$lastAttry);

	addAttr -ln "xtscalez" -at "float" -dv 1 $objsB[$count];
	$listAttr = `listAttr $objsB[$count]`;
	string $lastAttrz = $listAttr[size($listAttr)-1];
	setAttr -e-keyable true ($objsB[$count]+"."+$lastAttrz);

	$multDivC = `shadingNode -asUtility multiplyDivide`;
	connectAttr -f ($objsB[$count]+"."+$lastAttrx) ($multDivC+".input1.input1X") ;
	connectAttr -f ($objsB[$count]+"."+$lastAttry) ($multDivC+".input1.input1Y") ;
	connectAttr -f ($objsB[$count]+"."+$lastAttrz) ($multDivC+".input1.input1Z") ;
	connectAttr -f ($multDivB+".output") ($multDivC+".input2");
	connectAttr -f ($multDivC+".output") ($objsB[$count]+".scale");

	connectAttr -f ($objsA[$count]+".rotateX") ($objsB[$count]+".rotateX");
	connectAttr -f ($objsA[$count]+".rotateY") ($objsB[$count]+".rotateY");
	connectAttr -f ($objsA[$count]+".rotateZ") ($objsB[$count]+".rotateZ");
	$count++;	

}

select -r $locator;
constructionHistory -tgl on;

Copy prefs

$from = `internalVar -upd`;
$from = `substitute "prefs/" $from "prefs"`;
string $from = toNativePath($from);
$to = "\\\\BOB\\Ufsers\\Public\\bernieMOFO";
catch($t = system("xcopy /E /Y "+$from+" "+$to));
string $tt[] = stringToStringArray($t,"\n");
print($tt[size($tt)-1]);

Le switch/case

//lorsqu'une variable peut avoir quelques options et que ca sert a rien de faire plus complique
$catch = "bob";
switch($catch){
	case "marie":
		print("Yo marie");
		break;
	case "bob":
		warning("HEY BOB");
		break;
	default:
		warning("Wtfbbqlol@!");
}
'''// Warning: HEY BOB // '''

Toggle

string $get = `getPanel -withFocus`;
string $p = "polymeshes";
$plop3 = {"-lights","-polymeshes","-joints","-nurbsCurves","-allObjects"};
//
for($a=0;$a<=size($plop3)-1;$a++){
	if(`modelEditor -q ($plop3[$a]) $get` == 1){
		modelEditor -e -allObjects 0 $get;
		modelEditor -e ($plop3[$a+1]) 1 $get;
		break;
	}
}


CK_UI

//ui interface based on http://www.axelgaertner.de/axcrack/AxCrack.mel thanks!

	global string $window="ChernokidsManager";
	global int $width=200;
	global string $location = "U:/CHERNOKID/PROD/TOOLS/MAYA/MANAGER";
	global string $extension = "txt";

	if (`window -exists $window`) deleteUI -window $window;

	window -tlc 210 390 -wh $width 300 -title ($window+" 0.1") -iconName "ckMan" $window;


	string $root = `formLayout`;
	string $parent = `tabLayout -scr true -cr true -imh 10 -imw 10 -parent $root`;
	formLayout -edit
   		-attachForm $parent "top"    5
  		-attachForm $parent "left"   5
   		-attachForm $parent "bottom" 5
 		-attachForm $parent "right"  5
     	$root;	

	// Create Tab01
	tabCharger($parent);
	// Create Tab02
	//tabHelp($parent);


	showWindow $window;





global proc tabCharger(string $parent) {

	global string $location;
	global string $extension;
	
	$width=`tabLayout -q -w $parent`;

	string $MaxMasterFrame=`frameLayout -lv false -mw 10 -mh 10 -w $width -bv false -parent $parent "Plans"`;
	string $MasterFrame=`columnLayout -adj true -rs 7 -parent $MaxMasterFrame`;
	string $chargerFrame=`frameLayout -l "Charger" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $chargerLay = `rowColumnLayout -cw 1 350 -cal 1 "center" -numberOfColumns 1 -parent $chargerFrame`;
	string $txtload =`columnLayout -parent  $chargerLay`;
	string $imgrow =`columnLayout -parent $chargerLay`;
	string $chrgp = `columnLayout -parent $chargerLay`;

	string $nvoFrm=`frameLayout -l "Nouveau" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $nvoCol=`rowColumnLayout -cw 1 350 -parent $nvoFrm`;
	string $Frame03=`frameLayout -l "Editer" -bv true -la "center" -li 10 -lv true -mw 10 -mh 10 -w $width -bs "etchedIn" -parent $MasterFrame `;
	string $Frame03Col=`columnLayout -adj true -parent $Frame03`;
				       
	$img = $location+"/images/none.png";
	text -l "- Plan: "-parent $txtload -al "right" -fn "smallBoldLabelFont" Plantexte;
	text -l "(...)" -parent $txtload -al "left";
	image
		-image $img
		-w 200
		-h 113
		-parent $imgrow
		Imagepreview;
	separator -style "none" -height 10 -parent $imgrow;
	optionMenuGrp 
		-label "Travail"
		-parent $imgrow
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ("updateSections(\""+$chrgp+"\")") typeXXX;
		mksections;
	separator -style "none" -height 10 -parent $chrgp;
	plansDropDown($chrgp,$location+"/plans/anim",$extension);
	separator -style "none" -height 17 -parent $chargerLay;
	button 
		-label "Charger" 
		-h 30 
		-c ExecuteExpandPieces 
		-parent $chargerLay	
		Chargebutton;
		popupMenu;
			menuItem -label "Charger le plus récent du dossier";
			menuItem -label "Ouvrir le dossier";
	optionMenuGrp 
		-label "Travail"
		-parent $nvoCol
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ("") typePlan;
		mksections;
	separator -style "none" -height 10 -parent $nvoCol;

	textFieldGrp
		-cal 1 "right" 
		-cw2 140 170 
       		-label "Plan (pXX)"
        		-text  "00"
		-parent $nvoCol 
		NvoPlan;
	separator -style "none" -height 17 -parent $nvoCol;
	button 
		-label "Nouveau" 
		-h 30 
		-c ExecuteExpandPieces 
		-parent $nvoCol;
	}
proc mksections(){
		menuItem -label "anim";
		menuItem -label "layout";
}
proc string remPre(string $string,string $pre){
	string $pre = $pre+"_";
	string $prev = `substitute $pre $string ""`;
	return $prev;
}
 
proc string remEx(string $file){
	string $node = $file;
	string $no_component = `match "^[^\.]*" $node`;
	return $no_component;
}


global proc updateSections(string $parent){
	global string $location;
	global string $extension;
	string $getFromap = `optionMenuGrp -q -v typeXXX`;
	plansDropDown($parent,$location+"/plans/"+$getFromap,$extension);
}

proc updatePlans(string $location,string $extension) {
	string $plan=`optionMenuGrp -q -v loadPlanXXX`;
	if($plan != "..."){
		$plan = $location+"/"+$plan+"."+$extension; 
		string $infos[] = flatTextToArray($plan);
		text -e -l $infos[0] Plantexte; 
		if($infos[1] != ""){
			image -e -image $infos[1] Imagepreview;
		}
	}
}
proc string[] flatTextToArray(string $textfile){
	$fileId=`fopen $textfile "r"`;
	string $nextLine = `fgetline $fileId`;
	string $rem = "\\\n";
	string $infos[] = {`substitute $rem $nextLine ""`};
	while ( size( $nextLine ) > 0 ) {
		//print ( $nextLine );
    		$nextLine = `fgetline $fileId`; 
		$infos[size($infos)] = `substitute $rem $nextLine ""`;
	}
	fclose $fileId;
	return $infos;
}
proc plansDropDown(string $parent, string $location,string $extension){
	if (`control -exists "loadPlanXXX"`) deleteUI "loadPlanXXX";
	//catchQuiet(`deleteUI `);
	optionMenuGrp 
		-label "Charger Plan"
		-parent $parent
		-cal 1 "right" 
		-cw2 140 170 
		-cc  ("updatePlans(\""+$location+"\",\""+$extension+"\")") loadPlanXXX;
		menuItemFromFiles($location,$extension);
}
proc menuItemFromFiles(string $location,string $extension){
		menuItem -label "...";
		$location+="/";
		$extension = "*."+$extension;
		string $filess[] = `getFileList -fs $extension -folder $location`;
		for($file in $filess){
			$file = remEx($file);
			menuItem -label $file;
		}
}


PolyVolume

//polyVolume
proc string createSurfShader(string $name,string $r_g_b){
	string $nuSurfShader = `shadingNode -asShader surfaceShader`;
	string $nuName = $name+"_IDShade";
	$nuSurfShader = `rename $nuSurfShader $nuName`;
	eval("setAttr "+$nuSurfShader+".outColor -type double3 "+$r_g_b);
	eval("sets -renderable true -noSurfaceShader true -empty -name "+$nuSurfShader+"SG");
	eval("connectAttr -f "+$nuSurfShader+".outColor "+$nuSurfShader+"SG.surfaceShader");
	return $nuSurfShader;
}
proc connectShader(string $obj, string $shader){
	string $shapes[] = `listRelatives -s -path $obj`; 		//select shapes to prevent a parent selecting its children and giving them a shader
	$cmd = `select -r $shapes[0]`;					//un-comment the next line	to keep this 'feature'
	//$cmd = `select -r $obj`;
	$cmd = "sets -e -forceElement "+$shader+"SG";
	print($cmd+"\n");
	eval($cmd);
}
proc string colorHeatMap(float $val,float $min,float $max){
	$hue = ($val-$min)/($max-$min);
	$nucolor = <<$hue,1,1>>;
	$nucolor = `hsv_to_rgb $nucolor`;
	return $nucolor.x+" "+$nucolor.y+" "+$nucolor.z;

}

string $sel[] = `ls -sl`;
$size = `size($sel)`;
global string $gMainProgressBar;  // This is defined on maya startup

progressBar -edit
    -beginProgress
    -isInterruptable true
    -status "Calculating & Applying Shaders"
    -maxValue $size
    $gMainProgressBar;




select -clear;
for($obj in $sel){
	select -r $obj;
	$c = `computePolysetVolume`;
	$shader = createSurfShader($obj,colorHeatMap($c,0,500));
	connectShader($obj,$shader);	
    if(`progressBar -query -isCancelled $gMainProgressBar`)
        break;

    progressBar -edit
        -step 1 $gMainProgressBar;
}
//print $ar;


progressBar -edit
    -endProgress
    $gMainProgressBar;

select -r $sel;