Maya Mel

From Antoine Vienne | Wiki
Jump to navigation Jump to search

Contents

Maya Mels Scripts

Octane Render Baking group id - Assign id to multiple objects shapes

// 0 is for Red, 2 for Green, 4 for Blue
// 3, 5 and 6 for Cyan, Magenta and Yellow
// Replace the number "0" by the number of your choice
// Baking group id is also avalaible in Attribute Spreadsheet Editor

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".octBakGrId") (0);
}

Maxwell Render - Particles sequence - Force .abc file

//This expression force Maya to reload an Alembic particles file at each frame - there is no other way in Maxwell Render to read a particles sequence in .abc

global int $current_frame;
$current_frame = `currentTime -query`;
print $current_frame;
{
setAttr -type "string" maxwellRFRKParticles1.file ("/YOUR_PATH/YOUR_FILE" + $current_frame + ".abc");
}

Maxwell Render - Specify object ID color

// Specify object ID color

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".mxSpecifyObjIdColor") (1);
    setAttr ($object + ".mxObjIdColor") -type "double3" 1 0 0;
}

Redshift - Add blend attribute and set random value for objects selection

// Useful for blending between colors with RedshiftUserDataScalar

for ( $object in `ls -sl -l` ) {
    print($object);
    addAttr -ln "blend" -at double  -min 0 -max 1 -dv 0 $object;
    setAttr ($object + ".blend") (rand(1));
}

Redshift - Set Primary visibility off for selection (layer override)

// Go in right render layer and select objects

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".rsEnableVisibilityOverrides") (1);
    editRenderLayerAdjustment ($object + ".rsPrimaryRayVisible");
    setAttr ($object + ".rsPrimaryRayVisible") (0);
}

Convert Motion trail to curve

// Select the motion trail first

{
$selected=`ls -dag -et snapshotShape`;
for ($obj in $selected){
$pts=(getAttr($obj+".pts"));
$size=size($pts);
$curve=`curve -d 1 -p $pts[0] $pts[1] $pts[2] -p $pts[4] $pts[5] $pts[6] -k 0 -k 1`;
for($i=8;$i<$size;$i+=4)
curve -os -a -p $pts[$i] $pts[$i+1] $pts[$i+2] $curve ;
}
}

Quantize keyframes for selection

// Snap keys on frames for objects selection

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    snapKey $object;
}

Loop image sequence for texture

// On File texture, check Image sequence, and edit expression

file1.frameExtension=((frame%8)+1);

Symmetrize - Duplicate & merge object

// Select half object first

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    xform -piv 0 0 0 $object;
    duplicate -rr;
    setAttr ($object + ".scaleX") (-1);
    select -add $object ;
    polyPerformAction polyUnite o 0;
    polyMergeVertex  -d 0.0001 -am 1 -ch 1;
    DeleteHistory;
    rename ($object);
}

Mirror object

// Select object first

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    DeleteHistory;
    makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 -pn 1;
    xform -piv 0 0 0 $object;
    duplicate -rr;
    setAttr ($object + ".scaleX") (-1);
    DeleteHistory;
}

Group each object and rename

// Select objects first

for ( $object in `ls -sl -l` ) {
    string $name = ($object);
    select $object ;
    doGroup 0 1 1;
    rename ($name + "_GRP");
}

Change path in an Attribute

// Here the Attribute is ".filePrefix" - Select objects first

for ( $object in `ls -sl -l` ) {
    string $path = getAttr ($object+".filePrefix");
    $path = `substitute "//OLD/PATH/" $path "//NEW/PATH/"`;
    setAttr -type "string" ($object+".filePrefix") ($path);
}

Change opacity mode on V-Ray shaders

// Select shaders first

for ( $object in `ls -sl -l` ) {
    if (attributeExists("omode",$object)) { //check if attribute exists
        CBunlockAttr ($object+".omode"); //unlock opacity mode
    }
    if (attributeExists("opacityMode",$object)) {
        setAttr ($object+".opacityMode") 1; //set opacity mode in Clip - 0 pour Normal
    }
}

// Alternative
for ( $object in `ls -sl -l` ) {
    if (attributeExists("opacityMode",$object)) {
        setAttr ($object+".opacityMode") -l false; //unlock attribute if locked
    }
    if (attributeExists("opacityMode",$object)) {
        setAttr ($object+".opacityMode") 2; //set opacity mode in Clip - 0 pour Normal
    }
}

Change color space on selected fileTextures

// Useful to automatically convert Quixel Megascans by example from sRGB/Raw to ACES color spaces

string $object_selection[] = (`ls -sl`);
for ($object in $object_selection) {
    if(`getAttr ($object+".cs")` == "sRGB"){
        setAttr ($object + ".cs") -type "string" "Utility - sRGB - Texture";
    }
    if(`getAttr ($object+".cs")` == "Raw"){
        setAttr ($object + ".cs") -type "string" "Utility - Raw";
    }
}

Redshift - custom Tesselation on selected objects

// Select objects first

for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".rsMinTessellationLength") (0.1);
    setAttr ($object + ".rsMaxTessellationSubdivs") (2);
    setAttr ($object + ".rsOutOfFrustumTessellationFactor") (4);
}

Change color on selected shaders

// Select shaders first
for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".color") -l false;
    setAttr ($object + ".color") -type "double3" (0.18) (0.18) (0.18);
}

Change Filter Type on selected Files Textures

// Select files textures first - 0 means Off
for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".filterType") 0;
}

Clean Render Layers

// In MEL
fixRenderLayerOutAdjustmentErrors;

Change Filter Type on selected Files Textures

// Select files textures first - 0 means Off
for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".filterType") 0;
}

Select by name

// Select objects with "toto"
select -r "toto*";

Display color on shapes

// Select objects
for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".displayColors") 1;
    setDisplayColorChannelAttribute ($object + ".displayColorChannel");
    polyColorPerVertex -r 1 -g 0 -b 0 -a 1 -cdo;
}

Geometry Constraint on multiple selection

// Select objects to constrain
string $objectBase = "surfaceName";

for ( $object in `ls -sl -l` ) {
    select -cl;
    select $objectBase;
    select -add $object;
    geometryConstraint -weight 1;
    select -r "*Constraint*";
    doDelete;
}

=== Speed up smokes rendering with V-Ray ===
<pre>
// Select smokes first
for ( $object in `ls -sl -l` ) {
    print($object+"\n");
    setAttr ($object + ".rendStep") 160;
    setAttr ($object + ".shadowStep") 400;
}

Set bump multiplier on multiple V-Ray shaders

// Select shaders
for ( $object in `ls -sl -l` ) {
    if (attributeExists("bumpMult",$object)) {
        setAttr ($object + ".bumpMult") -1; //set bump multiplier at -1
    }
}

STOP/START viewport

// As seen on https://www.toadstorm.com/. - Put it in your shelf
paneLayout -e -manage false $gMainPane

paneLayout -e -manage true $gMainPane

Select curves by name

// Select objects first - Replace "toto" by what you are looking for

select `ls -type "nurbsCurve" "*toto*"`;

Noise expression

// Replace "pCube1"

pCube1.translateX=sin(time*20)*0.01*noise(time*10);
pCube1.translateY=sin(time*4)*0.01*noise(time*10);
pCube1.translateZ=sin(time*12)*0.01*noise(time*10);

V-ray - Make curves renderables

// Replace VRayLightMtl1 at the end by your material

$selected=`ls -dag -et curveShape`;
for ($object in $selected){
    // Add V-ray Extra attributes
    vray addAttributesFromGroup $object vray_nurbscurve_renderable 1;
    vrayAddAttr $object vraySeparator_vray_nurbscurve_renderable;
    vrayAddAttr $object vrayNurbsCurveRenderable;
    vrayAddAttr $object vrayNurbsCurveMaterial;
    vrayAddAttr $object vrayNurbsCurveTesselation;
    vrayAddAttr $object vrayNurbsCurveStartWidth;
    vrayAddAttr $object vrayNurbsCurveLockEndWidth;
    vrayAddAttr $object vrayNurbsCurveEndWidth;
    setUITemplate -pst attributeEditorTemplate;
// Activate renderable
setAttr ($object + ".vrayNurbsCurveRenderable") 1;
// Replace VRayLightMtl1 by your material
connectAttr -force VRayLightMtl1.outColor ($object + ".vrayNurbsCurveMaterial");
}

Get object type

// Replace toto with the object whose type you want to know

objectType toto;

Render layer override on specific object type

// Replace "Node" by the object type on which you want to act

$selected=`ls -type "Node"`;
for ($object in $selected){
    // Create layer override on Primary Visibility attribute on current renderLayer
    editRenderLayerAdjustment ($object + ".primaryVisibility");
    // Set Primary Visibility - 0 or 1
    setAttr ($object + ".primaryVisibility") 0;
}

V-ray - Make lights invisible

$selected=`ls -type "VRayLightRectShape"`;
for ($object in $selected){
    setAttr ($object + ".invisible") 1;
}

$selected=`ls -type "VRayLightSphereShape"`;
for ($object in $selected){
    setAttr ($object + ".invisible") 1;
}

$selected=`ls -type "VRayLightDomeShape"`;
for ($object in $selected){
    setAttr ($object + ".invisible") 1;
}

V-ray - Select Rect Light

select `ls -type "VRayLightRectShape"`;

V-ray - Rect Lights - Directional Preview - Always for all

$selected=`ls -type "VRayLightRectShape"`;
for ($object in $selected){
    setAttr ($object + ".directionalPreview") 1;
}

Randomize rotation on selected objects

// As posted on CGTalk by NaughtyNathan
// "just set the vector values to the maximum random x,y,z rotations you want to apply to the selected transforms."

vector $rndRot = << 0,0,90 >>;	// x,y,z rotations
for ($object in `ls -sl -tr`){
    rotate `rand ($rndRot.x)` `rand ($rndRot.y)` `rand ($rndRot.z)` $object;
}

Quit Maya

// Brute force method

$i = `getpid`; //application ID
    system("taskkill /PID "  + $i +" /f");

// In a gentle way

evalDeferred("quit -f");

V-ray - Import list of Alembics through Proxys Import

// List of Alembics files - Replace by the name of your Alembics
string $alembicsParts[] = {"part1","part2","part3"};

// Replace the PATH of your files - Scale by 100 for Houdini Alembics - <frame04> for sequences
for ($alembicsPart in $alembicsParts){
    vrayCreateProxy -node $alembicsPart -existing -dir ("C:/YOURPATH/"+$alembicsPart+".<frame04>.abc") -createProxyNode;
    setAttr ($alembicsPart+"_vraymesh.animType") 1;
    setAttr ($alembicsPart+".scaleZ") 100;
    setAttr ($alembicsPart+".scaleX") 100;
    setAttr ($alembicsPart+".scaleY") 100;
}

V-ray - Change path to VRayMesh for selected proxies

// Change path with your own .vrmesh
$selected=`ls -type "VRayMesh"`;
for ($object in $selected){
    setAttr -type "string" ($object + ".fileName2") "//DISK/PATH/YOUR_VRMESH.vrmesh";
}

// If you want to change Geometry type - 4 for GPU mesh - add following in the loop
//    setAttr ($object + ".geomType") 4;

Delete image planes

// Delete image plane if exists.
$selected=`ls -type "imagePlane"`;
select $selected;
for ($object in $selected){
    doDelete;
}

Merge alembic from set

// Select objects in a set called EXPORT_SET
select -r EXPORT_SET ;
timeControl -edit -forceRedraw $gPlayBackSlider;

// Create list of objects from EXPORT_SET
string $assetParts[] = `ls -sl`;
$assetPartsList = stringArrayToString($assetParts," ");

// Merge alembic with these objects
AbcImport -mode import -connect $assetPartsList "//DISK/PATH/alembic.abc";

Create Texture reference

// CREATE TEXTURE REFERENCE ON EXPORT SET

select -r YOUR_GROUP ;
CreateTextureReferenceObject;
select -cl  ;

// REMOVE REFERENCE OBJECTS FROM EXPORT SET
select -r YOUR_GROUP_reference ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
for ( $object in `ls -sl -l` ) {
    sets -rm EXPORT_SET $object;
}
select -cl  ;

Replace animated objects with V-Ray proxies

// First select animated objects to replace
// For each object create a proxy then constrain then bake simulation then delete constraint

for ( $object in `ls -sl -l` ) {
	vrayCreateProxy -node assetName -existing -dir ("//DISK/PATH/your_asset.vrmesh") -createProxyNode;
	select -r $object ;
	select -add assetName ;
	doCreateParentConstraintArgList 1 { "0","0","0","0","0","0","0","0","1","","1" };
	parentConstraint -weight 1;
	bakeResults -simulation true -t "1000:1100" -sampleBy 1 -oversamplingRate 1 -disableImplicitControl true -preserveOutsideKeys true -sparseAnimCurveBake false -removeBakedAttributeFromLayer false -removeBakedAnimFromLayer false -bakeOnOverrideLayer false -minimizeRotation true -controlPoints false -shape true {"assetName"};
	select `ls -type "constraint"`;
	select -add $object ;
	doDelete;
	select -cl  ;
	rename "assetName" $object;
}

Select all meshes in a group

// From cmadsenAniden on forums.autodesk.com
// Replace group1 by the name of your own group

select -r group1 ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;

Select shot camera

// CREATE VARIABLE FOR SHOT CAMERA AND SELECT IT

select `ls -type "camera"`;
select -d sideShape frontShape topShape perspShape;
$camerashot = `ls -sl`;
string $shotcamera = $camerashot[0];
print $shotcamera;
select $shotcamera;

Get list of frames with keys on all transform objects

$selected=`ls -dag -et transform`;

float $arrathy[] = `keyframe -query $selected`;

float $sorted[] = python("import pymel.core as pm; list(set((pm.getMelGlobal(\"float[]\", \"$arrathy\"))))");
print $sorted;

MULTI SNAP

// Replace a list of objects by another with bake of animation. Replace FSTART and FEND with your own padding.

///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/*
Type the command MS() in MEL form to open UI.
*/
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
source "generateChannelMenu.mel";

global proc MS ()
{
     global string $sourceObjects;
     global string $destinationObjects;



    // If the window exists already, delete it.
    if (`window -exists multiSnapWindow`)
    {
        deleteUI multiSnapWindow;
    }

    // Build the window.
    global string $man_window;
    string $man_window = `window -title " MULTI SNAP" -sizeable 0 -w 300 multiSnapWindow`;
    frameLayout -label "Snap source objects on destination objects.";
    rowLayout -width 540 -nc 2 -cw4 10 20 20 100;
    // Source objects section
    frameLayout -label "Source objects";
    $sourceObjects = `textScrollList -width 600 -height 300`;
    rowLayout -width 240 -nc 2 -cw2 120 120;
    button -label "Add selected" -command "MS_addObjects ();" -width 120;
    button -label "Remove selected" -command "MS_removeObjects ();" -width 120;
    setParent ..;
    rowLayout -width 240 -nc 2 -cw2 120 120;
    button -label "Remove All" -command "MS_clearObjects ();" -width 240;
    setParent ..;
    setParent ..;
    rowLayout -nc 3;
    button -label "Create" -command "VRAYCONNECDO() " -width 140 -align center;
    button -label "Close" -command "DAC_CloseUI() " -width 140 -align center;
    setParent ..;
    setParent ..;
    // Destination objects section
    frameLayout -label "Destination objects";
    $destinationObjects = `textScrollList -width 600 -height 300`;
    rowLayout -width 240 -nc 2 -cw2 120 120;
    button -label "Add selected" -command "MS_addMM ();" -width 120;
    button -label "Remove selected" -command "MS_removeMM ();" -width 120;
    setParent ..;
    setParent ..;
    rowLayout -nc 3;
    button -label "SNAP IT" -command "VRAYCONNECDO() " -width 140 -align center;
    button -label "Close" -command "DAC_CloseUI() " -width 140 -align center;
    setParent ..;
    setParent ..;

// Show the window.
showWindow multiSnapWindow;
}

global proc string[] getShaders(string $from)
{
// get the shapes from the input
string $shapes[] = ls("-o", "-dag", "-s", $from);
// give me the connected "shadingEngines"
string $shadingEngines[] = listConnections("-type","shadingEngine", $shapes);
// list the connected materials (shaders) from that
string $materials[] = ls("-mat", listConnections($shadingEngines));
// remove duplicate occurrences.
return (stringArrayRemoveDuplicates($materials));
}

//Add selected objects to list.
global proc MS_addObjects ()
{
      global string $sourceObjects;
      string $selectedshapes[] = `ls -sl -l`;
      //print $selectedshapes;
      int $count = 0;

if ($selectedshapes[0] != "")
{
   for ($i in $selectedshapes)
   {
     $count ++;
     textScrollList -edit -append $i $sourceObjects;
   }
}
}

//Add selected objects to list.
global proc MS_addMM ()
{
      global string $destinationObjects;
      string $selectedshapes[] = `ls -sl -l`;
      //print $selectedshapes;
      int $count = 0;

if ($selectedshapes[0] != "")
{
   for ($i in $selectedshapes)
   {
     $count ++;
     textScrollList -edit -append $i $destinationObjects;
   }
}
}

// Clear objects from list.
global proc MS_clearObjects ()
{
    global string $sourceObjects;
textScrollList -e -ra $sourceObjects;
}

// Remove selected object from list.
global proc MS_removeObjects ()
{
   global string $sourceObjects;

    int $index [] = `textScrollList -query -selectIndexedItem $sourceObjects`;
    if ($index [0] != 0)
    {
        textScrollList -edit -removeIndexedItem $index [0] $sourceObjects;
    }
   global string $sourceObjects;
}


global proc VRAYCONNECDO()
{
    // UI Elements
global string $sourceObjects;
global string $destinationObjects;
// Define user selected objects
string $selected_objects[] = `textScrollList -query -allItems $sourceObjects`;
string $meshMaterial[] = `textScrollList -query -allItems $destinationObjects`;
int $i = 0;



// SET PADDING
string $FSTART = "1";
string $FEND = "100";

print $FSTART;
print $FEND;

string $PADDING = $FSTART + ":" + $FEND;

//Progress bar
global string $gMainProgressBar;

// Start the progress bar and adjust its max value for this operation.
    int $steps = size($selected_objects);
    progressBar -edit -beginProgress -isInterruptable true -status "Connecting shaders to mesh material ..." -maxValue $steps $gMainProgressBar;
 
for ($i = 0; $i < size($selected_objects); $i ++)
{
        parentConstraint -n parentConstraintMS $selected_objects[$i] $meshMaterial[$i];
        select -r $meshMaterial[$i] ;
        bakeResults -simulation true -t $PADDING -sampleBy 1 -oversamplingRate 1 -disableImplicitControl true -preserveOutsideKeys true -sparseAnimCurveBake false -removeBakedAttributeFromLayer false -removeBakedAnimFromLayer false -bakeOnOverrideLayer false -minimizeRotation true -controlPoints false -shape true {$meshMaterial[$i]};
        select -cl  ;
        select -r "*parentConstraintMS*";
        doDelete;
// Update the progress bar.
progressBar -edit -step 1 $gMainProgressBar;
}
// End the progress.
progressBar -edit -endProgress $gMainProgressBar;
}

Delete hidden objects

// Select objects

for ( $object in `ls -sl` ) {
    $vis = getAttr ($object+".visibility");
    if ($vis == 0){
        select -r $object ;
        doDelete ;
    }
}

V-Ray - BAKE MATERIALS

// Made to work also with mayabatch.exe

////////////////////////////////////////////
// BAKE VRAY CUSTOM VARIABLES
////////////////////////////////////////////

// ASSET PATH
string $assetFileType = "mayaBinary";
string $assetPath = "C:/YOUR_PATH/YOUR_SURFACING_ASSET.mb";
string $assetName = "ASSET_NAME";

// LIGHT RIG PATH
string $lightRigFileType = "mayaAscii";
string $lightRigPath = "C:/YOUR_PATH/YOUR_LIGHT_RIG.mb";
string $lightRigName = "DAY_LIGHTING";

// BAKED TEXTURES PATH
string $bakedTexturesPath = ("C:/YOUR_PATH/BAKED_TEXTURES/" + $assetName + "_" + $lightRigName + "_Bake");
print $bakedTexturesPath;

// SET RESOLUTION FOR BAKED MAPS
$resWidth = 4096;
$resHeight = $resWidth;

// COLOR SPACE FOR FILE TEXTURES
string $fileColorSpace = "ACES - ACEScg";

////////////////////////////////////////////
// END OF CUSTOM VARIABLES
////////////////////////////////////////////



////////////////////////////////////////////
// RENDER SETTINGS

// Set File Name Prefix
setAttr -type "string" vraySettings.fileNamePrefix "<Scene>/<Layer>/<Camera>_<Layer>_<Scene>";

// Set resolution
$resWidthHalf = $resWidth/2;
$resHeightHalf = $resHeight/2;
setAttr "vraySettings.width" $resWidthHalf;
setAttr "vraySettings.height" $resHeightHalf;

// Set Persp camera renderable
setAttr "perspShape.renderable" 1;

// Set Image format
setAttr -type "string" "vraySettings.imageFormatStr" "exr (multichannel)";

// Set Animation type on Standard
setAttr "vraySettings.animType" 0;
setAttr "vraySettings.animBatchOnly" 1;

// Sampler type Bucket
setAttr "vraySettings.samplerType" 4;

// Min Shading Rate
//setAttr "vraySettings.minShadeRate" 4;
setAttr "vraySettings.minShadeRate" 7;

// Buckets subdivs
//setAttr "vraySettings.dmcMinSubdivs" 1;
//setAttr "vraySettings.dmcMaxSubdivs" 8;
//setAttr "vraySettings.dmcThreshold" 0.1;
setAttr "vraySettings.dmcMinSubdivs" 1;
setAttr "vraySettings.dmcMaxSubdivs" 15;
setAttr "vraySettings.dmcThreshold" 0.01;

// Color mapping Linear
setAttr "vraySettings.cmap_type" 0;

// GI on
setAttr "vraySettings.giOn" 1;
//setAttr "vraySettings.subdivs" 400;
setAttr "vraySettings.subdivs" 1000;

// Max subdivs
setAttr "vraySettings.ddisplac_maxSubdivs" 16;

// Cache geometry and bitmaps
setAttr "vraySettings.globopt_cache_geom_plugins" 1;
setAttr "vraySettings.globopt_cache_bitmaps" 1;

// Dynamic memory limit
setAttr "vraySettings.sys_rayc_dynMemLimit" 0;



////////////////////////////////////////////
// IMPORT

// IMPORT LIGHT RIG
file -import -type $lightRigFileType  -ignoreVersion -mergeNamespacesOnClash false -rpr ":" -options "v=0;" $lightRigPath;

// IMPORT ASSET
file -import -type $assetFileType  -ignoreVersion -mergeNamespacesOnClash false -rpr ":" -options "v=0;" $assetPath;



// CREATE SETS
select `ls -type "mesh"`;
sets -name "assetOriginal_Set" ;
duplicate -rr;
group -w -n ("GRP_" + $assetName + "_BAKE_" + `toupper $lightRigName`);
sets -name "assetBaked_Set" ;

// REMOVE BAKED PARTS FROM ORIGINAL PARTS SET
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
pickWalk -d down;
for ( $object in `ls -sl -l` ) {
    sets -rm assetOriginal_Set $object;
}
select -cl  ;

// DELETE HIDDEN OBJECTS
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
for ( $object in `ls -sl` ) {
    $vis = getAttr ($object+".visibility");
    if ($vis == 0){
        select -r $object ;
        doDelete ;
    }
}
select -cl  ;

// fixShapeName - Thanks to Pinkwerks
global proc
fixShapeName()
{
    string $me = "fixShapeName";
    string $shape;
    string $newShapeName;
    string $parent;
    string $tmpA[];
	string $selectedShapes[] = `ls -sl -l`;
    int $sizeOfShapes = `size $selectedShapes`;

    if ( $sizeOfShapes == 0 )
    	error($me + " : Nothing shapes to process!");

    for ( $shape in $selectedShapes )
    {
    	$tmpA = `listRelatives -p $shape`;
		$parent = $tmpA[0];
		$newShapeName = ($parent + "Shape");
		rename $shape $newShapeName;
    }
}

// APPLY FIXSHAPENAME TO BAKED ASSET PARTS
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
pickWalk -d down;
fixShapeName();
select -cl  ;

// DELETE OBJECTS WITHOUT UVS
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
for ( $object in `ls -sl` ) {
    int $vertexCount[] = `polyEvaluate -uv $object`;
    print $vertexCount;
    string $uvCount = $vertexCount[0];
    if ($uvCount == 0){
        select -r $object ;
        doDelete ;
    }
}

// CREATE VRAY BAKE OPTIONS
createNode "VRayBakeOptions" -n "vrayBakeOptions";
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
$selected=`ls -sl`;
for ($object in $selected){
    sets -edit -forceElement  vrayBakeOptions $object ;
}

// HIDE ORIGINAL ASSET
select -r assetOriginal_Set ;
pickWalk -d up;
hide `ls -sl`;



// BAKE VRAY OPTIONS
setAttr "vrayBakeOptions.udimBaking" 1;
setAttr "vrayBakeOptions.resolutionX" $resWidth;

optionVar -intValue "vrayBakeType" 2;
optionVar -intValue "vraySkipNodesWithoutBakeOptions" 1;
optionVar -intValue "vrayAssignBakedTextures" 1;
optionVar -stringValue "vrayBakeOutputPath" $bakedTexturesPath;
optionVar -intValue "vrayBakeProjectionBaking" 0;



// GO BAKE GO
select -cl  ;
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
select -r $polyGons;
for ( $object in `ls -sl -l` ) {
    vrayStartBake;
}
select -cl  ;

// UV TILING UDIM AND ACES CG FOR FILES
for ( $object in `ls -type "file"` ) {
    setAttr ($object + ".filterType") 0;
    setAttr ($object + ".uvTilingMode") 3;
    setAttr ($object + ".cs") -type "string" $fileColorSpace;
}

// CONNECT SHADERS
select -cl  ;
select -r assetBaked_Set ;
string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;
for ( $object in $polyGons ) {
    string $shadingGroupName = ($object + "Shape_bakedmtlSG");
    sets -e -forceElement $shadingGroupName $object;
}
select -cl  ;



///////////////////////////////////
// SAVE
file -rename ("C:/YOUR_PATH/BAKED_ASSETS/" + $assetName + "_" + $lightRigName + "_BAKE_DEBUG.mb");
file -f -save;

Arnold - Set all Standins display on Bouding box

$selected=`ls -type "aiStandIn"`;
for ($object in $selected){
    setAttr ($object + ".mode") 0;
}

Arnold - Set all Standins display on Point cloud

$selected=`ls -type "aiStandIn"`;
for ($object in $selected){
    setAttr ($object + ".mode") 4;
}

Alembic - Loop animation on all nodes

$selected=`ls -type "AlembicNode"`;
for ($object in $selected){
    setAttr ($object + ".cycleType") 1;
}

Mental Ray nodes error - Delete Mayatomr plugin

unknownPlugin -remove "Mayatomr";

Delete Unknown nodes

select -r `ls -type unknown`;
delete;

Write text

string $exampleFileName = ( "D:/yolo.bat" );
string $linesToWrite[] = {
    "youpi",
    "youhou"
    };
int $result = fwriteAllLines($exampleFileName,$linesToWrite);

Point Lock No Attach on selected follicles

for ( $object in `ls -sl -l` ) {
    setAttr ($object + ".pointLock") 0;
}

Convert .ma cameras from Reality Capture into .abc files

// List of assets
string $fileParts[] = {"asset_001", "asset_002"};

// Replace the PATH of your files
for ($filePart in $fileParts){
	string $fileName = $filePart + "_cam";
	string $filePath = "//DISK/PATH/" + $filePart + "/" + $filePart +"_cam.ma";
	file -import -type "mayaAscii"  -ignoreVersion -ra true -mergeNamespacesOnClash false -rpr $fileName -options "v=0;p=17;f=0"  -pr  -importFrameRate true  -importTimeRange "override" $filePath;
	select -cl;
	select `ls -type "imagePlane"`;
	pickWalk -d up;
	doDelete;
	select `ls -type "camera"`;
	pickWalk -d up;	
	string $abcPath = "//DISK/PATH/" + $filePart + "/" + $filePart +"_cam.abc";
	string $abcExp = "-frameRange 1 1 -uvWrite -worldSpace -dataFormat ogawa -root |* -file " + $abcPath;
	AbcExport -j $abcExp;
	select -all;
	doDelete;
}

Combine objects

// Select objects

polyPerformAction polyUnite o 0; 
DeleteHistory;
FreezeTransformations;
makeIdentity -apply true -t 1 -r 1 -s 1 -n 0 -pn 1;
CenterPivot;

Unitize UVs (one square UV by face)

// Select objects

for ( $object in `ls -sl -l` ) {
    select -r ($object+".e[*]");
    hilite ($object+".e[*]") ;
    polyMapCut -ch 1 ($object+".e[*]");
    polyForceUV -unitize $object;
    select $object;
    DeleteHistory;
}

ONE-CLICK Unfold UVs

// Select seams edges first

invertSelection;
string $selectedEdges [] = `ls -sl`;

string $selectedObject [] = `ls -selection -objectsOnly`;

select -r ($selectedObject[0]+".e[*]");
hilite ($selectedObject[0]+".e[*]") ;
polyMapCut -ch 1 ($selectedObject[0]+".e[*]");
polyForceUV -unitize $selectedObject[0];

select $selectedObject[0];
polyMapSewMove -nf 10 -lps 0 -ch 1 $selectedEdges;
select -r ($selectedObject[0]+".map[*]");
u3dUnfold -ite 1 -p 0 -bi 1 -tf 1 -ms 1024 -rs 0 ($selectedObject[0]+".map[*]");
u3dLayout -res 256 -scl 1 -spc 0.001 -mar 0.01 -box 0 1 0 1 $selectedObject[0];
select $selectedObject[0];

Create Texture Reference on all shapes from a group

// Select top group first

string $selection[] = `ls -sl`;
string $polyGons[] = `filterExpand -sm 12 $selection`;

for ($i = 0; $i < size($polyGons); $i ++)
{
    select -r $polyGons[$i] ;
    CreateTextureReferenceObject;
}

select -r $selection;

Search and select by name

// If you want to select every object containing "tree"
// From NaughtyNathan on CGTalk

select -r "*tree*";

// And if you want to select only transforms containing "tree"

select `ls -type "transform" "*tree*"`;

// And if you are using namespace, you need:

select -r `ls -r 1 "*tree*"`;

Search and select UI

window -t "Search and Select";
columnLayout;


frameLayout -mh 10 -mw 10 -l "" ;

textField  -text TOTO -w 200 "requestTransform";

proc searchSelectTransform() {
    string $what = ("*" + `textField -q -text "requestTransform"` + "*");
    select -r `ls -type "transform" -r 1 $what`;
}

button -label "Search and select Transforms" -command "searchSelectTransform";
setParent..;


frameLayout -mh 10 -mw 10 -l "" ;

textField  -text TOTO -w 200 "requestShape";
		
proc searchSelectShape() {
    string $what = ("*" + `textField -q -text "requestShape"` + "*");
    select -r `ls -type "shape" -r 1 $what`;
}

button -label "Search and select Shapes" -command "searchSelectShape";
setParent..;


frameLayout -mh 10 -mw 10 -l "" ;

textField  -text TOTO -w 200 "requestAny";
		
proc searchSelectAny() {
    string $what = ("*" + `textField -q -text "requestAny"` + "*");
    select -r `ls -r 1 $what`;
}

button -label "Search and select any type" -command "searchSelectAny";
setParent..;


frameLayout -mh 10 -mw 10 -l "" ;

textField  -text TOTO -w 200 "requestCtrls";
		
proc searchSelectCtrls() {
    string $what = ("*" + `textField -q -text "requestCtrls"` + "*");
    select -r `ls -type "nurbsCurve" -r 1 $what`;
}

button -label "Search and select Ctrls" -command "searchSelectCtrls";
setParent..;


frameLayout -mh 10 -mw 10 -l "" ;

textField  -text TOTO -w 200 "requestJoints";
		
proc searchSelectJoints() {
    string $what = ("*" + `textField -q -text "requestJoints"` + "*");
    select -r `ls -type "joint" -r 1 $what`;
}

button -label "Search and select Joints" -command "searchSelectJoints";
setParent..;


showWindow;

Constrain Parent and Scale on a selection of objects

// Select objects

for ( $object in `ls -sl -l` ) {
    select -r pCube1 ;
    select -add $object ;
    doCreateParentConstraintArgList 1 { "1","0","0","0","0","0","0","0","1","","1" };
    parentConstraint -mo -weight 1;
    doCreateScaleConstraintArgList 1 { "0","1","1","1","0","0","0","1","","1" };
    scaleConstraint -offset 1 1 1 -weight 1;
}