PyQt4 camera presets Tool

Hi there. This post is going to be about building a Camera Presets Tool. Sure we can build on maya’s own presets button. But this way you can share it with your coworkers. If by the end of this post you feel confortable, change the code to introduce your own presets in there.

This time instead of using standard cmds to build the interface i used PyQt which is a much better solution for designing ui’s. It’s based on QT (a tech owned by nokia ). As far as my knowledge goes this would work on maya 2011+ due to its new QT interface integration. I’ve heard the about it working on older versions but you have to be a more experienced developer to make it work i guess.

here is the documentation for the all classes available in PyQT4

So let’s go!!

1. First Step is to get the PyQt installer. You can get it here. Thank’s Justin Israel for that.

2. Run this code in Maya. I’ve included all the necessary comments for you to follow along.

from PyQt4 import QtGui, QtCore
import maya.cmds as cmds

#data specs on the cameras name and sensor sizes [name,(width,height)]

camListSpecs = [ ["Arri Alexa", (0.935, 0.526)],
["Red Mysterium-X 4k", (0.870, 0.489) ],
["Red Mysterium-X 2k", (0.435, 0.244) ],
["Canon 5D MkII", (1.417, 0.799)],
["Canon 7D", (0.877, 0.492)],
["Phantom HD Gold 1080p", (0.944, 0.531)]
]

# camera creation function
def createCam():
    camName = str(cameraSel.currentText())
    index = cameraSel.currentIndex()
    focal = float(focalLengthInput.text())
    cmds.camera(name=camName, horizontalFilmAperture=camListSpecs[index][1][0],
    verticalFilmAperture=camListSpecs[index][1][1], focalLength=focal)
    mainWin.close()

#list to store only the camera names

camList = []

for i in range(len(camListSpecs)):
    camList.append(camListSpecs[i][0]) 

#SETUP PYQT WINDOW/WIDGETS

#setup mainwindow
mainWin = QtGui.QWidget()
mainWin.setGeometry(300, 300, 160, 200) #pos x,pos y,width,height
mainWin.setWindowTitle("Camera")

#camera Type combobox
cameraLabel = QtGui.QLabel("Camera Type", parent=mainWin)
cameraLabel.move(5, 5)
cameraSel = QtGui.QComboBox(parent=mainWin)
cameraSel.setGeometry(5, 25, 150, 20)

#add camera list to comboBox
cameraSel.addItems(camList)

#focalLenght field
focalLabel = QtGui.QLabel("Focal Length", parent=mainWin)
focalLabel.setGeometry(5, 50, 150, 20)
focalLengthInput = QtGui.QLineEdit(parent=mainWin)
focalLengthInput.setGeometry(75, 50, 50, 20)

focalLengthInput.setText("35")
mmLabel = QtGui.QLabel("mm", parent=mainWin)
mmLabel.setGeometry(130, 50, 50, 20)

#create camera button
createCambtn = QtGui.QPushButton("Create Camera", parent=mainWin)
createCambtn.setGeometry(5, 75, 150, 20)

#interface actions/signals
QtCore.QObject.connect(createCambtn, QtCore.SIGNAL("clicked()"), createCam)

#show QT window
mainWin.show()

.OBJ sequence importer for Maya

Hey there.
I’m aware that many artists don’t use OBJ sequences any more.
But now and then this may come in handy. Which happened to me.
And odd enough Maya doesn’t allow to import obj sequences. i used
it some years ago in max and it worked quite nicely.

So i took the time to write a python script for it. With a little help
from my Buddy John P. Neumann aka Arrantsquid here it is.

Hope it will help you. If not, you can still learn a bit from the code :)

Cheers

import maya.cmds as cmds

current_scene=cmds.ls(assemblies=True)

def selectDir():
	basicFilter = "*.obj"
	filename=cmds.fileDialog2(fileMode=4,ds=1, caption="Select Sequence",fileFilter=basicFilter)
	uniToStr=str(filename)
	global objList
	filePath=uniToStr.split("'")
	search=".obj"
	objList=[mesh for mesh in filePath if search in mesh]
	cmds.textScrollList(path, edit=True, append=objList)

def importer():
	objList.sort()
	for each in objList:
		loaded=cmds.file(each,i=True,dns=True)
	cmds.deleteUI('objwindow',window=True)
	getMeshes()

def loadWin():
	if cmds.window('objwindow',exists=True):
		cmds.deleteUI('objwindow',window=True)
	win=cmds.window('objwindow',title="Load Obj sequence",widthHeight=(250,450))
	cmds.columnLayout()
	cmds.text('Path to files')
	global path
	path=cmds.textScrollList(w=250)
	browseButton=cmds.button(label='browse',w=250,c='selectDir()')
	importButton=cmds.button(label='import',w=250,c='importer()')
	cmds.showWindow(win)

def getMeshes():
	newScene=cmds.ls(assemblies=True)
	meshList=[mesh for mesh in newScene if mesh not in current_scene]
	cmds.group(meshList,n="OBJ_GROUP")
	for i in range(len(meshList)):
		cmds.setKeyframe(meshList[i],attribute='visibility',value=0,t=0)
		cmds.setKeyframe(meshList[i],attribute='visibility',value=1,t=i+1)
		cmds.setKeyframe(meshList[i],attribute='visibility',value=0,t=i+2)

loadWin()

Import OS module example.

Hi there.
Here i explain a bit about the OS module functionality.
Basically it opens up the possibility for Maya to comunicate with
the OS. In this case we are going to create a simple folder called “Test_folder”

#first import the module
import os

#get the home directory through the environment variable 'HOME' and store in var dir
dir =os.getenv('HOME')

#join dir with "/Documents"
newdir=os.path.join(dir,'Documents')

#create a Test_folder inside "/documents"
makeDir=os.mkdir(os.path.join(newdir,'Test_folder'))

if you write dir(os) and execute, you can see all of its functionality printed on the console.

for instance ‘rmdir’ – removes a directory

write -> help(os.rmdir)
and you will see the help on each of them, in this case (rmdir) prints:
——————————-
rmdir(…)
rmdir(path)

Remove a directory.
——————————

Create shaders through Python

Here’s a quick script to create a simple shader via Python.

import maya.cmds as cmds
#create a shader
shader=cmds.shadingNode("blinn",asShader=True)
#a file texture node
file_node=cmds.shadingNode("file",asTexture=True)
# a shading group
shading_group= cmds.sets(renderable=True,noSurfaceShader=True,empty=True)
#connect shader to sg surface shader
cmds.connectAttr('%s.outColor' %shader ,'%s.surfaceShader' %shading_group)
#connect file texture node to shader's color
cmds.connectAttr('%s.outColor' %file_node, '%s.color' %shader)

Maya Script editor, text editor or ide

When you begin writing your first scripts, the natural way is to use maya script editor.
You can reach it by clicking the bottom right icon in your ui.

A few years ago with maya 2010 and bellow, this was a poor solution. No syntax coloring, code completion, or any other fancy handy stuff, so developers use to go for external text editors to manage and write their scripts. Advanced programmers still do it this way.
But since Maya 2011, the built in script editor has evolved and became very powerfull. Now has syntax highlighting, quick help,code completion, and all. Still missing python feedback instead of having to translate the mel it spits, to python, but with some experience you will naturally figure it out.

the other way

There are really fancy text editors out there with a lot of nice tools to work in maya python.
Some of them actually connect to Maya via “commandPort”.

Here is a list of some of them: (i haven’t try them all :) )

Sorry, i’m not a Windows so i only suggest mac and linux/unix editors. But some of them have win version.

- TextMate for Mac (paid): easy to learn, connects to Maya with an optional plugin/bundle.

- Eclipse (win,mac,linux) free and very powerful ide: It takes a few complicated steps to make it work with Maya and python/pymel but after a few headbangs it’s really power in your hands. Setup instructions here

wing IDE: Never used it, but a lot of people seem to like it.

Jedit: my first try at a Text Editor. It’s nice, but never got it to connect to Maya. It is possible, but i just couldn’t make it work.

 

And Now Some really heavy sh*t!!

Hardcore programmers use older texteditors that can take a while to learn. Myself am learning. Never though spending so much time understanding a text editor program. Acknowledge that a Text editor is not a Word processor !!

In this category i found two that are most used, both are free and come with mac and linux. don’t know about windows though.

VIM . Don’t be fooled by the screenshot, it’s really more powerful than it seems. There is a lot of plugins available in which you can find connecting to Maya.

It runs on the Terminal, but it can also run as standard app. See Gvim or Macvim

or

Emacs: which is kind of the same concept with different handling

There’s an active discussion on google groups about which editor everyone uses, check it here.

 

 

Remember that i’m not an expert or guru in the matter. My opinions are based on my experience which isn’t much.

Comments welcome!!

That is it. Have fun.

Maya Zoom/Pan Tools Script

Here goes another tool for productivity. No more scrolling in attr editor for pan/zoom :)

How to:
1. copy script to script editor in Python tab, select all text and then MM drag it to your shelf.
2. select a camera
3. hit the little icon with a looking glass over the viewport
4. press in your shelf button to launch
5. have fun


import maya.cmds as cmds

cam=cmds.ls(sl=True)
if len(cam)<1:
    cmds.confirmDialog(message="select a camera")
    camShape=cmds.listRelatives(cam)

def reset():
    cmds.panZoom(camShape,abs=True,z=1)
    cmds.panZoom(camShape,abs=True,l=0)
    cmds.panZoom(camShape,abs=True,d=0)
    cmds.floatSliderGrp(valZ, edit=True, value=1)
    cmds.floatSliderGrp(valX, edit=True, value=0)
    cmds.floatSliderGrp(valY, edit=True, value=0)

def paniZoom():
    zoomRate=cmds.floatSliderGrp(valZ, query=True, value=True)
    cmds.panZoom(camShape,abs=True,z=zoomRate)

    widthRate=cmds.floatSliderGrp(valX, query=True, value=True)
    cmds.panZoom(camShape,abs=True,l=widthRate)

    depthRate=cmds.floatSliderGrp(valY, query=True, value=True)
    cmds.panZoom(camShape,abs=True,d=depthRate)

windowZ=cmds.window(title="Zoom/pan",w=350,h=250)
cmds.columnLayout(w=150,adj=True)
valZ=cmds.floatSliderGrp(label="Zoom", field=True,dc="paniZoom()",value=1,min=-0.001,max=1,pre=3)
valY=cmds.floatSliderGrp(label="Vertical Pan", field=True,dc="paniZoom()",value=0,min=-1,max=1,pre=3)
valX=cmds.floatSliderGrp(label="Horizontal Pan", field=True,dc="paniZoom()",value=0,min=-1,max=1,pre=3)

resetButton=cmds.button(label="reset", c="reset()")
cmds.showWindow(windowZ)
cmds.panZoom(camShape,abs=True,z=10)

reset()

Inspiration for starting to code

I’m not a geek.
Never was. Probably never will. In fact, the first computer i owned was a Pentium III back in 2001. (Younger folks probably will think what is a Pentium III ?). Unlike my closest friends, i never had a ZXSpectrum, Amiga, Nintendo, Timex, Sega, Commodore or even a videoPack.

When the University of Kassel in Germany gave me an email account back in 1998, i was thinking: “what that hell do i do with this?”. Since then, internet changed my whole spectrum and gave me the opportunity to learn whatever i wanted to.

I always considered myself as an artist. Therefore, the coding in programs was always a 12 leg huge bug, that i would never have to face it. The maths, equations, functions and stuff were just too hard to understand, i thought.

What made me consider to start coding

One day at an OFFF conference, i saw the presentation of this very funny visual artist called Joshua Davis. If you never saw him giving a speech, i advise you to.

Joshua at that time presented us with a series of illustrations he made procedurally. By Procedurally, i mean computer generated through a series of equations and math. Joshua isn’t really a computer scientist with thick googles, he is a skater, tattooed, rock n roll style guy.

He showed a series of hugely complex illustrations, all vector based, and asked the audience: “Go draw that by hand! i dare you!”

But the most important phrase that i heard from him was:

“Hey, if i can do math, so can you!”

I say the same thing to you.

cheers.

Light Values Script

Here goes one simple script for you guys to chew. It basically sets up a window UI to change Intensity and color of the Lights in the scene. Just copy it from the script editor to your shelf. It loads all your lights in the scene to the list. Then select the lights you want to change settings (it allows multiple selection).

Later i will introduce specular,diffuse, depth map shadows and raytrace shadow options.

in the meantime, enjoy it.

cheers

import maya.cmds as cmds

initiallightList=cmds.ls(type="light")
lightArray=[]

def Lighter():
    for o in lightArray:
        print lightArray
        iniVal= cmds.getAttr(o+".intensity")
        iniRGB = cmds.getAttr(o+".color")
        value=cmds.floatSliderGrp(newVal,query=True,value=True)
        colorRGB=cmds.colorSliderGrp (RGB, query=True, rgbValue=True)
        cmds.setAttr(o+".intensity",value)
        cmds.setAttr(o+".colorR",colorRGB[0])
        cmds.setAttr(o+".colorG",colorRGB[1])
        cmds.setAttr(o+".colorB",colorRGB[2])

def index():
    indexl=cmds.textScrollList(lista, q=True,si=True)
    del lightArray[:]
    for i in range(len(indexl)):
        lightArray.append(indexl[i])
        cmds.select(indexl[i])

#window UI
LightWindow=cmds.window(title="Light Values",w=150)
cmds.columnLayout(w=150,adj=True)
lista=cmds.textScrollList(height=150, ams=True, da=True,sc="index()")
for each in initiallightList:
    cmds.textScrollList(lista,edit=True,append=each)

cmds.frameLayout(label="Adjust Settings for selected Lights",w=150)
newVal=cmds.floatSliderGrp(label="Intensity",w=150,cal=(1,"left"),pre=2,adj=1,field=True)
RGB=cmds.colorSliderGrp(label="color RGB",cal=(1,"left"),adj=True)
cmds.setParent('..')
cmds.rowLayout()
cmds.setParent('..')
cmds.button(label="Apply",c="Lighter()")
cmds.button(label="Close", c="cmds.deleteUI(LightWindow)")
cmds.setParent('..')

cmds.showWindow(LightWindow)

First Book

This was my first reading. Definitely a must have. Although a quarter away in the book i had to abandon. The problem is that i started to know pretty things about Python, but nothing about how to use in Maya. I’ll get back to it for sure in the future.

The Second resource i found was Chad Vernon’s website. Great material in there.

There is also the Python for Maya google group, but hey!!!,  those discussions are still way too advanced for me.

After these, i found this Technical Artist on twitter who has a nice blog about Python, his name is John Neumann. check here.

 

Introduction

Who should read this:

Hello Maya artists, this is going to be place where i will post my learning experience with Python in Maya. There will be small scripts and hopefully one day, great ones. I will also post my experience and problems i may encounter. It will be a great reading for newcomers in Maya Python, but experienced TA’s and TD’s will certainly have a laugh reading it.(go on, i encorage you to comment my post with TD jokes. More than welcome!! :) ).

Inspiration

I started learning Python one day, after a chat session with my Tutor Lee Danskin at escape studios, advised me to learn Python. I was at the time starting to learn MEL (Maya Embed Language) and i so excited with it. Lee Danskin said that MEL is great but Python or Pymel is the way to go. That and some Linux skills.

Book


Maya Python for Games and Film: A Complete Reference for Maya Python and the Maya Python API
This is the book that i’m reading as i go. check it here.

Online Learning

Also watching Justin Israel video about Python for Maya in CMIVFX