MEL scripts




Sir, you have given me what I asked for and much, much more! Thank you.


Error: Could not save file

i export my animation as a .anim file.

this is the error i get

Error: Could not save file

how can i fix it. btw i am using a maya mel script called dkanim


Can anybody help me on this?


This little tool extracts selected faces from a poly. Not really revolutionary (i’m sure it already exists), but it can be handy…

proc string [] JPL_FaceIndex (string $selFaces [])
	string $index [];

	for ($eachFace in $selFaces)
		string $buffer [];
		tokenize $eachFace "." $buffer;
		$index [size ($index)] = $buffer [(size ($buffer)-1)];
	return $index;

global proc JPL_ExtractFaces ()
	string $selObj[]=`ls -o -sl`;
	string $faces [] = `ls -sl`;
	string $selFaces[]=`filterExpand -sm 34 -ex true $faces`;
	string $firstObjFacesIndex [] = JPL_FaceIndex ($selFaces);

	if (size ($selObj) != 1)
		error "Select one object";

	if (size ($selFaces)==0)
		warning "select at least one face";
		changeSelectMode -object;

		string $newObj [] = `ls -sl`;

		delete $selFaces;

		select ($newObj [0] + ".f[" + "*" + "]");

		for ($i = 0 ; $i < size ($selFaces) ; $i++)
			select -d ($newObj [0] + "." + $firstObjFacesIndex [$i]);

		select -r $newObj [0];




forget this


Hi community,

I wanted to share three python scripts for mental ray.

-2D Motion Vector Pass
This script creates a 2d motion vector pass and will set the render settings in order to not offset the animation.

-UV pass + Material ID (Maya 2012 ASAP et Maya 2013)
Run the script to create the new UV pass with a material ID in the blue channel (Maya 2012 ASAP and Maya 2013)

-UV / PW / Material ID (Maya 2012 and before)
For the one who hasn’t the newest version of maya, this script will create buffers and render passes for Point World, UVs and Material ID.

Hope it will help someone !
If there is bug or request of improvements, you can email me at : abaudoin_vfx[@]


please I want mel script for save as video function


Here’s a little tool to create a dome light, to simulate a kind of ambient occlusion. You have already seen thousands of scripts like this since early 80’s? Me too! Done it just for the excercise, i’m not sure i will ever use it…

//this script simulates soft light - a kind of ambient occlusion - with a dome light.
//each parameter (except the number of lights) can be changed after the dome creation,
//within the main group (extra attributes or in the channel box).
//- save the script as "JPL_lightGlobe.mel" in your script folder
//- create a shelf button (or launch it in the script editor) with this code:
//		source "JPL_lightGlobe.mel";
//		JPL_lightGlobe ();
//or (for a quick test)
//- copy/paste this code in the script editor (new MEL tab)
//- add this line at the end:
//		JPL_lightGlobe ();
//- select all (ctrl+a or cmd+a)
//- execute (numPadEnter)

//this proc returns the lowest and highest values of the globe's bounding box
//used to calculate the relative position of each light
proc float [] JPL_GetValues ()
	string $globeName = `textFieldGrp -q -text LightGlobeName`;
	float $globeBBox [] = `xform -q -ws -bb $globeName`;
	float $bbox [] = {$globeBBox [1],$globeBBox [4]};
	return $bbox;

//this proc creates attributes on the group to modify the lights values.
//color values are easier to change in the attribute editor (Extra Attributes), since there is a
//color picker and only RGB float values in the channel box
proc JPL_addAttributesToGlobe (string $globe)
	//gets all the needed infos from the GUI
	float $topColor [] = `colorSliderGrp -q -rgb colorTopPicker`;
	float $bottomColor [] = `colorSliderGrp -q -rgb colorBottomPicker`;
	float $topIntensity = `floatSliderGrp -q -v topIntensitySlider`;
	float $bottomIntensity = `floatSliderGrp -q -v bottomIntensitySlider`;
	int $resolution = `intSliderGrp -q -v resolutionField`;
	int $filterSize = `intSliderGrp -q -v filterSizeField`;
	float $bias = `floatSliderGrp -q -v biasField`;
	float $shadowColor [] = `colorSliderGrp -q -rgb shadowColorPicker`;

	//adds all the attributes we'll need to modify the lights
	addAttr -longName TopColor -sn topC -usedAsColor -attributeType float3 $globe;
		addAttr -longName TopColorR -attributeType "float" -k true -parent TopColor;
		addAttr -longName TopColorG -attributeType "float" -k true -parent TopColor;
		addAttr -longName TopColorB -attributeType "float" -k true -parent TopColor;
	setAttr ($globe + ".TopColor") -type float3 $topColor [0] $topColor [1] $topColor [2];
	addAttr -longName BottomColor -sn bottomC -usedAsColor -attributeType float3 $globe;
		addAttr -longName BottomColorR -attributeType "float" -k true -parent BottomColor;
		addAttr -longName BottomColorG -attributeType "float" -k true -parent BottomColor;
		addAttr -longName BottomColorB -attributeType "float" -k true -parent BottomColor;
	setAttr ($globe + ".BottomColor") -type float3 $bottomColor [0] $bottomColor [1] $bottomColor [2];
	addAttr -longName TopIntensity -minValue 0.0 -maxValue 1.0 -dv $topIntensity -k true $globe;
	addAttr -longName BottomIntensity -minValue 0.0 -maxValue 1.0 -dv $bottomIntensity -k true $globe;
	addAttr -longName ShadowResolution -at long -minValue 16 -maxValue 8192 -dv $resolution -k true $globe;
	addAttr -longName ShadowFilterSize -at long -minValue 0 -maxValue 5 -dv $filterSize -k true $globe;
	addAttr -longName ShadowBias -minValue 0.0 -maxValue 1.0 -dv $bias -k true $globe;
	addAttr -longName ShadowColor -usedAsColor -attributeType float3 $globe;
		addAttr -longName ShadowColorR -attributeType "float" -k true -parent ShadowColor;
		addAttr -longName ShadowColorG -attributeType "float" -k true -parent ShadowColor;
		addAttr -longName ShadowColorB -attributeType "float" -k true -parent ShadowColor;
	setAttr ($globe + ".ShadowColor") -type float3 $shadowColor [0] $shadowColor [1] $shadowColor [2];

//this proc creates the globe and connects the light attributes to the group attributes
global proc JPL_CreateLightGlobe ()
	string $globeName = `textFieldGrp -q -text LightGlobeName`;
	rename lightGlobeSphere  $globeName;

	string $concatVertices [] = `ls ($globeName + ".vtx[" + "*" + "]")`;
	string $allVertices [] = `filterExpand -sm 31 $concatVertices`;//we'll create a light on each vertex
	string $globeName = `textFieldGrp -q -text LightGlobeName`;
	int $lightTypeInt = `radioButtonGrp -q -sl lightTypeRadio`;
	string $lightType = "pointLight";//default light type
	float $topIntensity = `floatSliderGrp -q -v topIntensitySlider`;
	float $bottomIntensity = `floatSliderGrp -q -v bottomIntensitySlider`;
	int $resolution = `intSliderGrp -q -v resolutionField`;
	int $filterSize = `intSliderGrp -q -v filterSizeField`;
	float $bias = `floatSliderGrp -q -v biasField`;
	float $topColor [] = `colorSliderGrp -q -rgb colorTopPicker`;
	float $bottomColor [] = `colorSliderGrp -q -rgb colorBottomPicker`;
	float $shadowColor [] = `colorSliderGrp -q -rgb shadowColorPicker`;

	float $BBoxGlobe [] = JPL_GetValues ();

	if (2 == $lightTypeInt)
		$lightType = "spotLight -coneAngle 60";
		spaceLocator -n JPLtarget;

	string $createLight = ($lightType + "-decayRate 0 -softShadow true -shadowSamples 1;");
	int $b = 0;//counter for lights' name iteration
	string $globe = `group -em -n ($globeName + "_grp")`;//lights' parent, will control their attributes

	JPL_addAttributesToGlobe ($globe);

	for ($vertex in $allVertices)
		string $a = $b;
		float $posVert [] = `xform -q -ws -t $vertex`;
		string $light = ($globeName + "Light" + $a);

		float $valueY = (($posVert [1] - $BBoxGlobe [0])/($BBoxGlobe [1] - $BBoxGlobe [0]));//returns the relative vertex position on the sphere's bbox (0 to 1)

		eval $createLight;
		rename $light;
		xform -ws -t $posVert [0] $posVert [1] $posVert [2] $light;
		//blendColors shadingNodes to blend colors and intensity from bottom to top
		shadingNode -asUtility blendColors -name ($light + "Color_BC");
		shadingNode -asUtility blendColors -name ($light + "Intensity_BC");
		setAttr ($light + "Color_BC.blender") $valueY;//$valueY (relative position) is the multiplyer for the blend
		setAttr ($light + "Intensity_BC.blender") $valueY;
		setAttr ($light + ".useDepthMapShadows") 1;
		setAttr ($light + ".emitSpecular") 0;
		setAttr ($light + ".shadowColor") -type double3 $shadowColor[0] $shadowColor[1] $shadowColor [2];

		//let's do some connections...
		connectAttr ($light + "Color_BC.output") ($light + ".color");
		connectAttr ($globe + ".TopColor") ($light + "Color_BC.color1");
		connectAttr ($globe + ".BottomColor") ($light + "Color_BC.color2");
		connectAttr ($globe + ".ShadowResolution") ($light + ".dmapResolution");
		connectAttr ($globe + ".ShadowFilterSize") ($light + ".dmapFilterSize");
		connectAttr ($globe + ".ShadowBias") ($light + ".dmapBias");
		connectAttr ($globe + ".ShadowColor") ($light + ".shadowColor");
		connectAttr ($light + "Intensity_BC.outputR") ($light + ".intensity");
		connectAttr ($globe + ".TopIntensity") ($light + "Intensity_BC.color1R");
		connectAttr ($globe + ".BottomIntensity") ($light + "Intensity_BC.color2R");
		if (2 == $lightTypeInt)
			aimConstraint -n tempTargetConstraint -o 0 -90 0 JPLtarget $light;
			delete -cn tempTargetConstraint;

		parent $light $globe;
	//cleaning up the scene
	delete $globeName;

	if (`objExists JPLtarget`)
		delete JPLtarget;

	deleteUI lightGlobe;

//this proc modifies the sphere
global proc JPL_ModifySphere (string $action)
	if ("density" == $action)
		int $density = `intSliderGrp -q -value densitySlider`;

		polySphere -e -subdivisionsX $density -subdivisionsY $density lightGlobeSphere;
	if ("radius" == $action)
		float $radius = `floatSliderGrp -q -value radiusSlider`;
		polySphere -e -radius $radius lightGlobeSphere;

global proc JPL_lightGlobe ()
	if (!`objExists lightGlobeSphere`)
		polySphere -r 100 -sx 5 -sy 5 -n lightGlobeSphere;
		if (`window -exists lightGlobe`)
			deleteUI lightGlobe;

		window -title "LightGlobe" lightGlobe;
			columnLayout -adj true;
				-label "Definition"
				-field true
				-minValue 5
				-maxValue 10
				-value 5
				-dc ("JPL_ModifySphere (\"density\");")
				-label "Radius"
				-field true
				-minValue 5
				-maxValue 2000
				-value 100
				-dc ("JPL_ModifySphere (\"radius\");")
				-numberOfRadioButtons 2
				-label "Light type" -labelArray2 "Point" "Spot"
				-sl 1
				-label "Top color"
				-rgb 1 1 1
				-label "Bottom color"
				-rgb 1 1 1
				-label "Top Intensity"
				-field true
				-precision 3
				-minValue 0
				-maxValue 1
				-value 0.1
				-label "Bottom Intensity"
				-field true
				-precision 3
				-minValue 0
				-maxValue 1
				-value 0.1
				-label "Shadow resolution"
				-field true
				-minValue 16
				-maxValue 8192
				-value 128
				-label "Shadow filter size"
				-field true
				-minValue 1
				-maxValue 5
				-value 5
				-label "Bias"
				-field true
				-precision 3
				-minValue 0
				-maxValue 1
				-value 0.001
				-label "Shadow Color"
				-rgb 0 0 0
				-label "Globe label"
				-text "MyLightGlobe"
			text -label "";
			button -label "Create" -c "JPL_CreateLightGlobe ();";
		showWindow lightGlobe;
		error "Object \"LightGlobeSphere\" already exists. Cleanup your scene.";


Hello! Is there way in MEL to save ALL animation from the maya scene into the text file… With other script restore only the values at the every frame i need from this text file, and apply to the all objects (without animation, just the value of the keyable attributes at the specific frame) in exactly the same scene?
I need it to remove all animation from the file but place all objects ( in every frame i choose ) as it was in the file with animation.


Good evening!
Just created this python script as a friendly helper for Maya scripters which executes a python command for each selected object, or for each selected pair/triple/… of objects using a renaming scheme with placeholders like this:

    orientContraint("%1", "%2")
   Note all "%1's" have to be selected consecutively, then all "%2's" (Not pairwise %1 %2 %1 %2..)
   Some extra features:
     1. Editable presets
  1. Any number of placeholders (%1, %2,…) - make sure # selected object is multiple of # of placeholders
    3. A script preview function
    4. Placeholder for iteration count (%i)
    5. Placeholder for total count (%t)
    6. Form data persisting over app restarts

   import maya.cmds as cmds
import subprocess

strPresets_init = '\
# nurbsCircleShape1 => joints, set joints draw style to node
cmds.parent("nurbsCircleShape1", "%1", r=True, s=True, add=True)
cmds.setAttr("%1.drawStyle", 2)
# Orient Constraint w/maintainOffset
cmds.orientConstraint("%1", "%2", maintainOffset=True)
# Orient Constraint 
cmds.orientConstraint("%1", "%2")
# Point contraint w/maintainOffset
cmds.pointConstraint("%1", "%2"), maintainOffset=True)
# Point contraint
cmds.pointConstraint("%1", "%2")
# Parent
cmds.parent("%1", "%2", r=True, s=True)
# Connect Rotate and Translate
cmds.connectAttr("%1.rotate", "%2.rotate", force=True)
cmds.connectAttr("%1.translate", "%2.translate", force=True)
# Connect Scale
cmds.connectAttr("%1.scale", "%2.scale", force=True)
# Match Rotation
# Match Translation

def countPlaceholders(elText):
	i = 0
	while elText.find('%' + str(i+1)) >= 0:
		i = i + 1
	return i
def batchEval():
	global window, tf, txt, OVbatchEval_presets, fullnameFromLabel
	if not cmds.optionVar( exists='batchEval_preset' ):
		cmds.optionVar( stringValue=('batchEval_preset', "setAttr(\"%1.rotateX\", 0)"))

	if not cmds.optionVar( exists='batchEval_presets' ):
		cmds.optionVar( stringValue=('batchEval_presets', strPresets_init))

	OVbatchEval_preset = cmds.optionVar( q='batchEval_preset' )
	OVbatchEval_presets = cmds.optionVar( q='batchEval_presets' )

	window	= cmds.window( title="Python Batch", iconName='Python Batch', widthHeight=(720, 225) )
	form	= cmds.formLayout( numberOfDivisions = 100 )
	tf		= cmds.scrollField( editable=True, wordWrap=False, text=OVbatchEval_preset )
	om		= cmds.optionMenu( label='Presets:', width=520, changeCommand=onChangedPreset )
	b0		= cmds.button( label='Edit Presets', command=onClickEdit, width=132, height=24 )
	txt		= cmds.text( font="tinyBoldLabelFont", label = "Enter Python commands. Use %1, %2, ... as name placeholders, %i as iteration counter, %t as total." )

	cmds.menuItem( label='', enable = False )
	fullnameFromLabel = {}
	for preset in OVbatchEval_presets.split('
		if preset[0:2]=="# ":
			strLabel = preset[2:preset.find("
")] # in case there's a comment in first line, use that as label
			strLabel = preset.replace("
", " ")
		while fullnameFromLabel.get(strLabel, False):
			strLabel = strLabel+"(1)"
		fullnameFromLabel[strLabel] = cmds.menuItem( label = strLabel, annotation = preset )
	b1	= cmds.button( label='Execute', command=onClickExecute, width=132, height=24 )
	b1b	= cmds.button( label='Execute and Close', command=onClickExecuteAndClose, width=142, height=24 )
	b1c	= cmds.button( label='Preview Script', command=onClickPreview, width=142, height=24 )
	b2	= cmds.button( label='Close', command=onClickClose, width=132, height=24 )

	cmds.formLayout( form, edit=True,
		attachForm=[(b0, 'right', 8), (b0, 'top', 5), (txt, 'left', 8), (om, 'top', 5), (om, 'left', 5), (tf, 'left', 5), (tf, 'right', 5), (b1, 'bottom', 12), (b1, 'left', 12), (b1b, 'bottom', 12), (b1c, 'bottom', 12), (b2, 'bottom', 12), (b2, 'right', 12)],
		attachControl=[(txt, 'top', 10, om), (tf, 'top', 6, txt), (tf, 'bottom', 12, b1), (b1b, 'left', 8, b1), (b1c, 'left', 8, b1b)] )
	cmds.showWindow( window )

def onClickClose(arg):
	global window, tf
	strCmd = cmds.scrollField( tf, q=True, text=True )
	cmds.optionVar( stringValue=('batchEval_preset', strCmd))
	cmds.deleteUI(window, window=True)

def onClickEdit(arg):
	global e_window, OVbatchEval_presets, e_tf
	e_window = cmds.window( title="Python Batch Preset Editor", widthHeight=(720,720) )
	e_form = cmds.formLayout(numberOfDivisions=100)
	e_txt = cmds.text( font="tinyBoldLabelFont", label = "Use --- to separate list entries. Entries with multiple lines are ok." )
	e_tf = cmds.scrollField( editable=True, wordWrap=False, text=OVbatchEval_presets )
	e_b1 = cmds.button( label='Save', command=onClickSave, width=132, height=24 )
	e_b2 = cmds.button( label='Cancel', command=('cmds.deleteUI(\"' + e_window + '\", window=True)'), width=132, height=24 )
	cmds.formLayout( e_form, edit=True,
		attachForm=[(e_txt, 'top', 8), (e_txt, 'left', 8), (e_tf, 'left', 8), (e_tf,'right',8), (e_b1, 'left', 12), (e_b1, 'bottom', 12), (e_b2, 'right', 12), (e_b2, 'bottom', 12)],
		attachControl=[(e_tf, 'top', 8, e_txt), (e_tf, 'bottom', 10, e_b1)] )
	cmds.showWindow( e_window )

def onClickSave(arg):
	global window, e_window, OVbatchEval_presets, e_tf, tf
	OVbatchEval_presets = cmds.scrollField( e_tf, q=True, text=True )
	cmds.optionVar( stringValue=('batchEval_presets', OVbatchEval_presets))
	strCmd = cmds.scrollField( tf, q=True, text=True )
	cmds.optionVar( stringValue=('batchEval_preset', strCmd))
	cmds.deleteUI(e_window, window=True)
	cmds.deleteUI(window, window=True)
	batchEval() #refresh
def onChangedPreset(label):
	global tf, fullnameFromLabel
	strPreset = cmds.menuItem( fullnameFromLabel[label], q=True, annotation=True)
	cmds.scrollField( tf, edit=True, text=strPreset )

def onExecute(bPreview):
	global window, tf, txt
	sl =
	nSel = len(sl)
	strCmd = cmds.scrollField( tf, q=True, text=True )
	cmds.optionVar( stringValue=('batchEval_preset', strCmd))
	resStr = ""

	nPh = countPlaceholders(strCmd)
	if (nSel / nPh)*nPh != nSel:
		cmds.text( txt, edit=True, label = "Number of objects selected no match to number of placeholders given ("+str(nPh)+" Placeholders, "+str(nSel)+" objects selected .. must be multiple of "+str(nPh)+")")
		return False
	if nSel == 0:
		cmds.text( txt, edit=True, label = "Nothing is selected!")
		return False

	for i in range(nSel / nPh):
		strCmd_resolved = strCmd
		for j in range(nPh):
			strCmd_resolved = strCmd_resolved.replace("%"+str(j+1), sl[i+(j*nSel/nPh)])
		strCmd_resolved = strCmd_resolved.replace("%i", str(i+1))
		strCmd_resolved = strCmd_resolved.replace("%t", str(nSel/nPh))
		if bPreview:
			resStr = resStr + strCmd_resolved + "
			print "executing: " + strCmd_resolved

	if bPreview:
		return resStr
		return True

def onClickExecute(arg):
	return onExecute(False)

def onClickPreview(arg):
	strPreview = onExecute(True) # True = Preview
	if strPreview == False:

	p_window = cmds.window( title="Python Batch Script Preview", widthHeight=(720, 720) )
	p_form = cmds.formLayout(numberOfDivisions=100)
	p_txt = cmds.text( font="tinyBoldLabelFont", label = "If something looks wrong, check selection order. Must be for example %1 %1, %2 %2, %3 %3... NOT %1 %2 %3, %1 %2 %3...!" )
	p_tf = cmds.scrollField( editable=True, wordWrap=False, text=strPreview )
	p_b2 = cmds.button( label='Close', command=('cmds.deleteUI(\"' + p_window + '\", window=True)'), width=132, height=24 )
	cmds.formLayout( p_form, edit=True,
		attachForm=[(p_txt, 'top', 8), (p_txt, 'left', 8), (p_tf, 'left', 8), (p_tf,'right',8), (p_b2, 'right', 12), (p_b2, 'bottom', 12)],
		attachControl=[(p_tf, 'top', 8, p_txt), (p_tf, 'bottom', 10, p_b2)] )
	cmds.showWindow( p_window )

def onClickExecuteAndClose(arg):
	if onClickExecute(arg):
		cmds.deleteUI(window, window=True)

   Let me know if sth like this aleady exists (I'm new to Maya)

** edit … That code tag inserts some extra spaces before each line for me :curious:. Bad for python. Sorry you’ll have to edit them away (or use the creativecrash script)


decided to release some of my python scripts.


Hello professionals,

My issue is not very complex so let me explane it with a simple example. I made a particleShape and instance it with a simple cube and set the AimDirection to velocity which make the cubes aim themselves on the surface that they emitted from. But i need them to rotate randomly on Y axis. But once i put my random rotation in Rotation`s field the Aim effect get lost. Some how them stay instead of each other i dont find a way to merge these together.

Thank you



sorry, maybe wrong place… but I didn’t know where to put it.

dynamics in Maya, always checks for initial penetration between objects, and most of the time It fails to calculate properly…

is there any kind of automatic way, Mel or plugin,… to help detect the penetration and maybe pull them out of each other to make a clean scene for dynamic?

thank you in advance


hey guys,

im not that clued up to mel but what i am trying to do is Make my particles return to there worldPosition over time.

basically i have particles that i have set there initial state and there is a field going though them and after the field has gone though i would like the particles to go back to there initial state position of time (over 50 frame for example).

i have seen this post but the particles dont go back over time, they just snap back in 1 frame…

if anyone can help it would be great… i am really stuck as my mel knowledge isnt great…



Welcome! I have small problem following DigitalTutors tutorial about rigging character in Maya. I’m trying to create Renaming Tool in MEL and everything seams to be ok with my script but I’m receiving such error:

// Error: Invalid object or value: -1 //

Maybe its easy to fix but i’m new to Maya so I’d be grateful if anyone could help me;)

Ps. This is my script:

//Renaming Tool

//Create the window

string $RNM_Win = window -t "Rename It!";

//Make the window a columnLayout and adjustable

columnLayout -adj 1;

//Query your selection

string $sel[] = ls -sl;

//for loop - so we can acess and apply the command to each selected object individually

for ($each in $sel) {

//Name field - acqure the name of selected objects and allow to rename them

nameField -o $each;


//Button on window for closing out our Renaming Tool

button -1 “CLOSE” -c “delete UI -window $RNM_Win”

//Shows our Renaming Window

showWindow $RNM_Win;


This is a little script that I wrote to create fast and easy Edge Loops in the geometry :wink:


Hey there, I didn’t try it in Maya but I think it’s because in the “button” command you have the label flag written as “-1” instead of “-l”.

One of the menus in the script editor has a “show line number in error” checkbox. Turn that on to make it easier to debug your code.

Hope that helps.


Please someone would help me with this.'s for a college work appreciate your help. thanks

Create a script that allows me to create the proxy of a helicopter (model of a helicopter in
very low poly)
 must include a general controller type Nurbs Circle function as father of all
 must create an expression that allows me to assess:
 If the helicopter is on the ground not moving propellers.
 If the helicopter rises must turn the propellers. :rolleyes: