Tomigs - TTR



Start About Contact Reel


Maya Commands (Python) examples


Last updated 15/02/21


Examples of the use of Python inside Maya (calls to Maya Commands)
Application of coding (Python or MEL) Maya commands into several areas inside Maya:
GUIS, Transform operations, Object Duplications, Objects Creation, Texturing Objects, Rigging objects,
Lighting, Camera rig, etc.

Examples:

Bouncing Ball MayaCmdsBouncingBallGenerator01

Solar System MayaCmdsSolarSystem01
Rigging a Leg PROG_LegRigging







Bouncing Ball Creator, with GUI

MayaCmdsBouncingBallGenerator01



PROG_BouncingBallScript.png


import maya.cmds as cmds

gBallHeight = 3


def fCreateBall():
cmds.polySphere(r=3,name='BasketBall')
cmds.move(0,gBallHeight,0)

def fApplyTexture():
#Select the Ball object:
cmds.select('BasketBall')
object = cmds.ls(selection=True)
#selectedMenuItem = cmds.optionMenu('optionMenu', q=True, value=True)
cmds.sets(name='imageMaterialGroup', renderable=True, empty=True)
shaderNode = cmds.shadingNode('lambert', name='shaderNode', asShader=True)
fileNode = cmds.shadingNode('file', name='fileTexture', asTexture=True)
#folders:
lTextureFile = 'C:\TOMIGS\PROYS\PYTHON\MAYA\GUI-BouncingBallCreator\BasketBallTexture1200x1200.png'
cmds.setAttr('fileTexture'+'.fileTextureName', lTextureFile, type="string")
shadingGroup = cmds.sets(name='textureMaterialGroup', renderable=True, empty=True)
cmds.connectAttr('shaderNode'+'.outColor','textureMaterialGroup'+'.surfaceShader',force=True)
cmds.connectAttr('fileTexture'+'.outColor','shaderNode'+'.color',force=True)
cmds.surfaceShaderList('shaderNode', add='imageMaterialGroup')
cmds.sets(object, e=True, forceElement='imageMaterialGroup')

def fBounceYAxis(frames=30,highest_bounce=30):
cmds.select('BasketBall')
selected_objects = cmds.ls(selection = True)
print selected_objects
if len(selected_objects) < 1:
cmds.error("Must select one object")
anim_object = selected_objects[0]
print anim_object

bounce_height = highest_bounce
frame_time_count = 0
time_between_frames = 24
reduction_factor = 0.8

bounce_distance = highest_bounce/3.0
last_bounce_distance = 0
frame_time_count = 0
time_between_frames = 24


for frame in range(0,frames):
#move timeframe
print('Frame' + format(frame))
print('frame_time_count ' + format(frame_time_count))
print('time_between_frames ' + format(time_between_frames))
frame_time = frame_time_count + time_between_frames
print('frame_time ' + format(frame_time))
print(' ')
ball_distance = last_bounce_distance + bounce_distance

#ball_height = bounce_height
ball_height = bounce_height + gBallHeight
tangent_type = "spline"


'''every second bounce ball hits the ground, so y == 0'''
if frame % 2 == 0:
#ball_height = 0
ball_height = gBallHeight
tangent_type = "linear"
print('ball_height '+format(ball_height))
print('=====================')
'''set the keyframes'''
cmds.setKeyframe(anim_object+'.translateY',value=ball_height,time=frame_time,inTangentType=tangent_type,outTangentType=tangent_type)
#cmds.setKeyframe(anim_object+'.translateX',value=ball_height,time=frame_time,inTangentType=tangent_type,outTangentType=tangent_type)


'''reduce values for next bounce'''
frame_time_count += time_between_frames
time_between_frames = time_between_frames*reduction_factor
bounce_height = bounce_height*reduction_factor
#bounce_height = bounce_height*reduction_factor + gBallHeight

def fPlayStop():
#Play the animation
#cmds.play()
if cmds.play( q=True, state=True ):
cmds.play(state=False)
else:
cmds.play()


def fCreateCourt():
cmds.polyPlane(w=30,h=30,name='Court')
fApplyTexture_Court()

def fApplyTexture_Court():
#Select the Ball object:
cmds.select( clear=True )
cmds.select('Court')
object = cmds.ls(selection=True)
cmds.sets(name='imageMaterialGroup2', renderable=True, empty=True)
shaderNode = cmds.shadingNode('lambert', name='shaderNode2', asShader=True)
fileNode = cmds.shadingNode('file', name='fileTexture2', asTexture=True)
#folders:
lTextureFile = 'C:\TOMIGS\PROYS\PYTHON\MAYA\GUI-BouncingBallCreator\CourtTexture1920x1200.jpg'
cmds.setAttr('fileTexture2'+'.fileTextureName', lTextureFile, type="string")
shadingGroup = cmds.sets(name='textureMaterialGroup2', renderable=True, empty=True)
cmds.connectAttr('shaderNode2'+'.outColor','textureMaterialGroup2'+'.surfaceShader',force=True)
cmds.connectAttr('fileTexture2'+'.outColor','shaderNode2'+'.color',force=True)
cmds.surfaceShaderList('shaderNode2', add='imageMaterialGroup2')
cmds.sets(object, e=True, forceElement='imageMaterialGroup2')


window = cmds.window(title = "Bouncing Ball Creator",widthHeight=(250,520))
#cmds.paneLayout()
cmds.columnLayout(adjustableColumn = True)
cmds.image( image='C:\TOMIGS\PROYS\PYTHON\MAYA\GUI-BouncingBallCreator\BBallBouncing285x250.jpg' )
#Button: create ball
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Create Ball',c="fCreateBall()")
#Button: Texturize
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Add Texture',c="fApplyTexture()")
#Button: Basket Court
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Add Court',c="fCreateCourt()")
#Button: Bounce
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Bounce along Y Axis',c="fBounceYAxis()")
#Button: Play
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Play / Stop',c="fPlayStop()")


cmds.showWindow(window)




Solar System Generator, with GUI

MayaCmdsSolarSystem01


Demo: on running the code, it will present with a GUI, with different controls:

- Textbox: you can type here a list of planets (comma separated). It is prepared for a maximum of 10 planets and one of them has to be called “Sun”
for the program to work well. By default will include the Solar System but the list can be edited.

- Sun’s Radius: specify the radius of the Sun, that is the biggest “planet”. The rest of planets will be created as a proportion of this “Sun”.

- Button “Create Planets”: will create a solar system based on the comma separated list of planets and the radius.

- Button “Texturize Planets”: will texturize the planets. It is based on the planets’ names, so texture files with the appropriate names have to exist.
Note: the path where the planets’ textures are is hardcoded, so this needs to be changed on the code.

- Button “Rotate Planet” and degrees slider: it will rotate all the planets by the specified degrees. By default 360 (that is no visible change).

- Button “Make Camera Rig”: will create a camera pointing to the Sun.

- Button “Create light Rig”: will create a set of lights surrounding the Sun.


Includes:
- GUI
- Modelling (create spheres of different radius in different positions aligned along the x axis)
- Texturing (applying different textures to each planet)
- Transform operations (rotating the planets)
- Camera rig (create a camera in a certain position)
- Light rig (create a set of lights surrounding the Sun)
- Looping through list of planets

MayaCmdsSolarSystem02


MayaCmdsSolarSystem03


MayaCmdsSolarSystem04


CODE:

import maya.cmds as cmds
 
gPlanetNames = []
gPlanetRadius = []
gPlanetDistances = []
 
def fGetPlanetNames():
global gPlanetNames
lPlanetNames = cmds.textField(gCtrlName, q=1, text=1)
gPlanetNames = lPlanetNames.split(',')
print lPlanetNames
print gPlanetNames
 
def fGetPlanetRadius():
global gPlanetRadius
lRadius = cmds.intSliderGrp(gRadiusCtrl,q=1,value=1)

if lRadius == 0:
print('Error: select a valid radius for the Sun')
gPlanetRadius.append(lRadius)
gPlanetRadius.append(lRadius*0.2)
gPlanetRadius.append(lRadius*0.3)
gPlanetRadius.append(lRadius*0.3)
gPlanetRadius.append(lRadius*0.3)
gPlanetRadius.append(lRadius*0.6)
gPlanetRadius.append(lRadius*0.5)
gPlanetRadius.append(lRadius*0.4)
gPlanetRadius.append(lRadius*0.4)
gPlanetRadius.append(lRadius*0.1)
gPlanetRadius.append(lRadius*0.1)
gPlanetRadius.append(lRadius*0.1)
gPlanetRadius.append(lRadius*0.1)
gPlanetRadius.append(lRadius*0.1)
print(gPlanetRadius)
 
def fGetPlanetDistances():
global gPlanetDistances
lRadius = cmds.intSliderGrp(gRadiusCtrl,q=1,value=1)
if lRadius == 0:
print('Error: select a valid radius for the Sun')
print('Updating planet distances...')
print(lRadius)
lDistance = 0
gPlanetDistances.append(lDistance) #Mercury
lDistance += 2*lRadius
gPlanetDistances.append(lDistance) #Venus
lDistance += lRadius
gPlanetDistances.append(lDistance) #Earth
lDistance += lRadius
gPlanetDistances.append(lDistance) #Mars
lDistance += lRadius
gPlanetDistances.append(lDistance) #Jupiter
lDistance += 2*lRadius
gPlanetDistances.append(lDistance) #Saturn
lDistance += 2*lRadius
gPlanetDistances.append(lDistance) #Uranus
lDistance += 2*lRadius
gPlanetDistances.append(lDistance) #Neptune
lDistance += 2*lRadius
gPlanetDistances.append(lDistance) #Pluto
lDistance += 2*lRadius
gPlanetDistances.append(lDistance)
lDistance += 2*lRadius
gPlanetDistances.append(lDistance)
lDistance += 2*lRadius
gPlanetDistances.append(lDistance)
lDistance += 2*lRadius
gPlanetDistances.append(lDistance)
lDistance += 2*lRadius
print(gPlanetDistances)
 
 
def fRotatePolygon(pPolygon,pDegrees):
#get the current angle
loc_CurrentAngle = cmds.getAttr(pPolygon+".rotateX")
print loc_CurrentAngle
#change the angle: rotate it by 360 degrees in the x axis
cmds.rotate(loc_CurrentAngle+pDegrees,0,0,pPolygon)
 
def fRotatePlanet(pPlanetName,pDegrees):
#lName = cmds.textField(gCtrlName,q=1,text=1)
lName = pPlanetName
print lName
cmds.select(lName)
object = cmds.ls(selection=True)
fRotatePolygon(lName,pDegrees)
 
def fRotateSolarSystem():
lDegrees = cmds.intSliderGrp(gDegreesCtrl,q=1,value=1)
fGetPlanetNames()
for planet in gPlanetNames:
fRotatePlanet(planet,lDegrees)
 

def fCreatePlanet(pRadius=3,pName="planet1"):
#lRadius = cmds.intSliderGrp(gRadiusCtrl,q=1,value=1)
#print(lRadius)
#lName = cmds.textField(gCtrlName, q=1, text=1)
#print(lName)
#cmds.polySphere(r=lRadius,name=lName)
lRadius = pRadius
cmds.polySphere(r=lRadius,name=pName)
 
def fCreateSolarSystem():
global gPlanetDistances
fGetPlanetNames()
fGetPlanetRadius()
fGetPlanetDistances()
print(gPlanetNames)
i = 0
for planet in gPlanetNames:
print planet
fCreatePlanet(pRadius = gPlanetRadius[i],pName = planet)
cmds.select(planet)
print('Moving planet ' + planet + ' distance ')
print(gPlanetDistances[i])
cmds.move(-gPlanetDistances[i],0,0)
i+=1

 
def fTexturizeSolarSystem():
for planet in gPlanetNames:
print(planet)
 
def fTexturizeSolarSystem():
fGetPlanetNames()
global gPlanetNames
for planet in gPlanetNames:
fTexturizePlanet(planet)

def fTexturizePlanet(pPlanetName):
#lName = cmds.textField(gCtrlName,q=1,text=1)
lName = pPlanetName
print lName
cmds.select(lName)
object = cmds.ls(selection=True)
lImageMaterialGroupName = 'imageMaterialGroup'+lName
cmds.sets(name=lImageMaterialGroupName, renderable=True, empty=True)
lShaderNodeName = lName + 'ShaderNode'
shaderNode = cmds.shadingNode('lambert', name=lShaderNodeName, asShader=True)
lFileTextureName = 'fileTexture'+lName
fileNode = cmds.shadingNode('file', name=lFileTextureName, asTexture=True)
#folders:
lTextureFile = 'C:\\TOMIGS\\PROYS\\PYTHON\\MAYA\\CA-SolarSystem\\Planet_textures-20190501\\'
lTextureFile += lName
lTextureFile += '.jpg'
print lTextureFile
cmds.setAttr(lFileTextureName+'.fileTextureName', lTextureFile, type="string")
shadingGroup = cmds.sets(name='textureMaterialGroup', renderable=True, empty=True)
cmds.connectAttr(lShaderNodeName+'.outColor','textureMaterialGroup'+'.surfaceShader',force=True)
cmds.connectAttr(lFileTextureName+'.outColor',lShaderNodeName+'.color',force=True)
cmds.surfaceShaderList(lShaderNodeName, add=lImageMaterialGroupName)
cmds.sets(object, e=True, forceElement=lImageMaterialGroupName)

 
def fMakeCameraRig():
aimLoc = cmds.spaceLocator()
newCam = cmds.camera()
#cmds.viewPlace(newCam[0], eye=(5,6,8), lookAt=(0, 2, 0))
x_target = cmds.getAttr("Sun"+".translateX")
y_target = cmds.getAttr("Sun"+".translateY")
z_target = cmds.getAttr("Sun"+".translateZ")
cmds.viewPlace(newCam[0], eye=(18,21,29), lookAt=(x_target,y_target,z_target))
 
def fMakeLightRig():
offsetAmount = 10
lightRotation = 30
newLight = cmds.spotLight(rgb=(1, 1, 1), name="KeyLight")
lightTransform = cmds.listRelatives(newLight, parent=True)
keyLight = lightTransform[0]
newLight = cmds.spotLight(rgb=(0.8, 0.8, 0.8), name="FillLight")
lightTransform = cmds.listRelatives(newLight, parent=True)
fillLight = lightTransform[0]
newLight = cmds.directionalLight(rgb=(0.2, 0.2, 0.2),name="BackLight")
lightTransform = cmds.listRelatives(newLight, parent=True)
backLight = lightTransform[0]
cmds.move(0, 0, offsetAmount, keyLight)
cmds.move(0, 0, 0, keyLight + ".rotatePivot")
cmds.rotate(-lightRotation, lightRotation, 0, keyLight)
cmds.move(0, 0, offsetAmount, fillLight)
cmds.move(0, 0, 0, fillLight + ".rotatePivot")
cmds.rotate(-lightRotation, -lightRotation, 0, fillLight)
cmds.move(0, 0, offsetAmount, backLight)
cmds.move(0, 0, 0, backLight + ".rotatePivot")
cmds.rotate(180 + lightRotation, 0, 0, backLight)
rigNode = cmds.group(empty=True, name="LightRig")
cmds.parent(keyLight, rigNode)
cmds.parent(fillLight, rigNode)
cmds.parent(backLight, rigNode)
cmds.select(rigNode, replace=True)
 
 
'''
RUN!!!
'''
 
window = cmds.window(title = "Solar System Generator",widthHeight=(320,700))
cmds.columnLayout(adjustableColumn = True)
cmds.image(image = "C:\TOMIGS\PROYS\PYTHON\MAYA\CA-SolarSystem\SolarSystem.jpg")
 
cmds.separator(style='in', h=20)
cmds.text(label="Name the planets, separated by commas")
gCtrlName = cmds.textField()
lPlanetNames = cmds.textField(gCtrlName, e=1, text="Sun,Mercury,Venus,Earth,Mars,Jupiter,Saturn,Uranus,Neptune,Pluto")
 
cmds.separator(style='in', h=20)
gRadiusCtrl = cmds.intSliderGrp(l="Radius",min=1,max=50,f=True)
 
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Create Planets',c="fCreateSolarSystem()")

cmds.separator(style='in', h=20)
cmds.button(h=30,label='Texturize Planets',c="fTexturizeSolarSystem()")

cmds.separator(style='in', h=20)
gDegreesCtrl = cmds.intSliderGrp(l="Degrees",min=0,max=360,f=True)
cmds.intSliderGrp(gDegreesCtrl, e=1, value=360)
cmds.button(h=30,label='Rotate Planets',c="fRotateSolarSystem()")

cmds.separator(style='in', h=20)
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Make Camera Rig',c="fMakeCameraRig()")
 
cmds.separator(style='in', h=20)
cmds.button(h=30,label='Create Light Rig',c="fMakeLightRig()")
 
 
cmds.showWindow(window)




Leg Rigging

Creates legs and locks and hides all the attributes on all the joints of every leg instance.

PROG_LegRigging



PROG_LegRigging02



PROG_LegRigScript