Feeds:
Posts
Comments

Archive for January, 2008

Python + Maya – Part 2

Python + Maya
After some new training, here comes the second part of the Python + Maya Linil Tutorial. If you have no idea of what am I talking about in here, please feel free to check the first part of this tutorial Python + Maya – Part 1.

For you to get a grasp of what we’ll be building this time, take a look at the video from the final output.

Looks pretty better than the other time, huh? Let’s get started.

First of all, much of this new part is based on creating materials and changing their attributes, so before we turn into coding, it’s necessary to understand how Maya material system works.
In Maya, one material (let’s say, wood) is not applied directly to an object (let’s say, a table). It’s applied to a Shading Group and the objects are associated to the Shading Group. The purpose of this post is not to discuss this, but it’s very important for you to understand that. So, the chain is:
Material (wood) -> Shading Group -> Object (table)

Note We will get to coding now and I’ll be explaining just the procedure to create and animate only the balls that stand over the x axis, you’ll notice that animating the other ones (over the z axis) will be a matter of parameter setting. As WordPress has a lot of problems with syntax highlighting, you might think it’s better to follow the code through the original file. The link to the code without the z axis animation is: pythonMaya_xaxis.py and the link to the complete animation is: pythonMaya.py

Let’s get to coding now. As we’ll be creating lots of materials, we must define three functions in order to maintain the readability of the code.

def createMaterial( name, color, type ):

cmds.sets( renderable=True, noSurfaceShader=True, empty=True, name=name + ‘SG’ )
cmds.shadingNode( type, asShader=True, name=name )
cmds.setAttr( name+”.color”, color[0], color[1], color[2], type=’double3′)
cmds.connectAttr(name+”.outColor”, name+”SG.surfaceShader”)

The first line creates a Shading Group by calling the function sets, which returns nothing more than a set, in this case, an empty set for a while. The next line, creates a Material with the function shadingNode. Its first argument defines the type of material (lambert, blinn, anisotropic, etc), the second one is necessary for the system to understand it’s creating a real shading node, and the last one is the new material’s name.
After that, we set the color attribute. Notice that it doesn’t take a tuple for argument, but three different numbers and a fourth argument defining that the last three are a vector of 3 double integers. The last line connects the output color of the material we created to the surfaceShader of the Shading Group.

def assignMaterial (name, object):

cmds.sets(object, edit=True, forceElement=name+’SG’)

This one gets one object (the first argument) and assigns it to a correspondent Shading Group (the third argument and which must have already been created through createMaterial).

def assignNewMaterial( name, color, type, object):

createMaterial (name, color, type)
assignMaterial (name, object)

The third, and easiest of them, is just a way to call both others in one line.

After that and as you’ve seen in the movie, you’ll know the purpose of this time is to create some balls and then make them move in wave form. Before moving on to the balls, we need to create the ground plane (15×15).

cmds.polyPlane(name = ‘ground’, sw = 15, sh = 15, w = 15, h = 15)

To animate the balls, the easiest way is to set their vertical positions using a sinus function. We need to initialize the balls’ position and color and create a new material for each one of the plane’s faces that will have a ball on top:

for i in xrange(0,13):

cmds.polySphere(name = ‘ball’ + str(i), radius = 0.5)
pos = 2 + 1.5*sin( (1.6/pi)*(6-i) )
val = (1 + sin( (1.6/pi)*(6-i) ))/2
cmds.setAttr( ‘ball’ + str(i) + ‘.translateX’, 6-i)
cmds.setAttr( ‘ball’ + str(i) + ‘.translateY’, pos)
assignNewMaterial( ‘ballShader’ + str(i), (val, val, 1), ‘blinn’, ‘ball’ + str(i) )
assignNewMaterial( ‘ground’ + str(i), (1, 1, 1), ‘lambert’, ‘ground.f[‘ + str(118-i) + ‘]’ )

As we have 13 balls, we use a for from 0 to 12. In each step we:

  • Create a new Polygon Sphere with radius 0.5 and name ballX where X stands for an index from 0 to 12;
  • Calculate their vertical position using a sin function;
  • Calculate the color value which will be used ahead. The idea here is for the ball to be completely white (1,1,1) on it’s uppermost position and completely blue (0,0,1) on its downermost part;
  • Set the balls X position to coincide with each of the faces of our ground plane;
  • Assign the vertical value to the translateY attribute;
  • Create a new material for the ball;
  • Create a new material for the plane face (the faces of an object are accessed through an indexed list of faces, so the middle line will be like 7*15 + 1 = 106).

After that, it’s time to animate. Keyframe setting comes inside two for loops. The first one, from 0 to 200 (the number of frames of our animation) and the other from 0 to 13 (the number of spheres on the x axis).

for itr in xrange(0,200):

for i in xrange(0,13):

name = ‘ball’ + str(i)
name2 = ‘ballShader’ + str(i)
pos = 2 + 1.5*sin( (1.6/pi)*(6-i) +itr/5.0 )
val = (1 + sin( (1.6/pi)*(6-i) +itr/5.0 ))/2
cmds.setKeyframe(name, attribute=’translateY’, value=pos, t=itr )
cmds.setAttr( name2 + ‘.color’, val, val, 1, type=’double3′ )
cmds.setKeyframe(name2, attribute = ‘color’, t=itr )
if(pos < 0.55):

cmds.setAttr( ‘ground’ + str(i) + ‘.color’, 0, 0, 1, type=’double3′ )
cmds.setKeyframe(‘ground’+str(i), attribute = ‘color’, t=itr )

else:

cmds.setAttr( ‘ground’ + str(i) + ‘.color’, 1, 1, 1, type=’double3′ )
cmds.setKeyframe(‘ground’+str(i), attribute = ‘color’, t=itr )

On the beginning of each loop, we set two names, the name of the ball to be animated (name) and the name of the shader to be animated (name2). Then we calculate the new position and color value the same way we did on our initialization. Then we set a keyframe for the ball’s position. To animate the material’s color, it’s needed to first set the attribute of it and then set a keyframe (we can’t use the value tag of the setKeyframe function but I don’t know why this happens yet, so expect some news in here).
After that, we analyze if the ball is sufficiently near the ground for us to set it’s face’s color. It’s done through the if and else statement.

So, you execute it and voilà! A new set of waving and color-changing balls! As I said, doing the z axis balls initialization and animation stands for homework for you all :D
Again, hope you enjoyed this new part (a lot more complicated than the first one but a lot more beautiful) and stay tuned for new parts.
Ah, don’t forget to comment and tell us your experience, doubts, impressions, etc.

P.S.: I did some tweaking with the render in order to get that nice look, but this will be covered in other post! [=

Read Full Post »

Esse texto já esta na web há algum tempo, no entanto, muitos ainda não o leram. O texto fala sobre como os desenvolvedores Java costumam programar quando migram para a linguagem Python. O texto demonstra “erros” cometidos por esses programadores ao escrever uma aplicação, além disso contém várias dicas de como se evitar tais “erros” e tenta ensinar a pensar como programador Python. O texto original é em inglês mas recentemente foi traduzido e colocado a disposição no site do pythonbrasil.

De certa forma eu passei pela experiência de migrar do Java para a linguagem Python. Confesso que não gostava tanto de programar enquanto não conhecia essa nova linguagem. Desenvolver qualquer projeto pequeno para usufruir no meu próprio desktop em Java durava mais tempo que a minha empolgação.

O texto me foi bastante útil e por isso recomendo a leitura do mesmo. Minha experiência com Java veio por obrigação da faculdade, talvez se eu tivesse visto Python desde o começo do curso não tivesse achado as aulas tão enfadonhas. Migrar do Java pro Python, ao meu ver, é um caminho sem volta. A produtividade que se ganha é enorme, você vai conseguir terminar seus projetos antes do que você imaginava e isso vai lhe dar tempo para mais projetos ainda. Para ganhar tal produtividade é necessário que o programador deixe de pensar como fazia as coisas em Java e se pergunte como fazer essa mesma tarefa com os recursos do Python. Essa é a parte principal da migração para uma nova linguagem e do texto recomendado.

Read Full Post »

This video shows how to edit ID3 tags from your MP3 files using Emacs
keyboard macros and EMMS.

This link points to the high quality version in Ogg Video format.

Read Full Post »

Nokia acquires Trolltech

This morning, Trolltech announced on its site that they have made an agreement with Nokia that the Finland guys will make a public offer to buy the company.

Trolltech’s QT, a cross-platform software development framework which is used in popular software such as Skype, Google Earth, Adobe Photoshop Elements, Lucasfilm and by more than 5000 customers worldwide, will now be owned, supported and developed by Nokia.

The Finland Giant announced they will keep developing Trolltech products and supporting them.

For Nokia, it’s an amazing leap which will allow them to accelerate its cross-platform software strategy for mobile devices and desktop applications, and develop its Internet services business. With Trolltech, Nokia and third party developers will be able to develop applications that work in the Internet, across Nokia’s device portfolio and on PCs.

Source: Trolltech

Read Full Post »

GEdit

Já faz um tempo que eu tinha começado o projeto de desenvolver um plugin de auto-complete para Python no Gedit. A idéia surgiu após perceber que esse é um recurso desejado por muitos usuários desse editor. O plugin também é interesse do grupo que mantém o projeto e encontra-se na página deles como plugin desejado. Em breve, estarei inserindo uma entrada no wiki dos plugins do GEdit com o link para o plugin.

Certo dia resolvi olhar o código do VIm responsável pelo auto-complete de código python nesse editor. Para minha surpresa o código era também escrito em python. Depois de ler o código percebi que ele poderia ser portado para outros editores. Um dos motivos da escolha do GEdit é pela facilidade que ele proporciona aos desenvolvedores para escrever novos plugins. Recomendo a leitura do Python Plugin How to que ensina como desenvolver plugins nesse editor. Na página do projeto a escrita de plugins em python é ainda mais encorajada pela facilidade de desenvolvimento e manutenção do código proporcionada pela linguagem. Seguindo como base o plugin de completar palavras do Osmo Salomaa o trabalho exigido pelo auto-complete de código python ficou ainda mais fácil.

Em resumo o meu trabalho foi apenas juntar as duas partes: o código de auto-complete do VIm pertecente ao Aaron Griffin e o código do Osmo Salomaa. Aqui é um bom exemplo onde o software livre demonstra benefícios claramente, me proporcionando a facilidade de não ter que repetir o trabalho de ambos os autores, fazendo uso do código dos mesmo para prover a funcionalidade em outro editor.

Durante a jornada, a qual apesar de teoricamente simples acabou dando um certo trabalho, cometi a besteira de perder os códigos no antigo computador. Deixei o trabalho parado até encontrar ânimo de recomeçar novamente. O recomeço foi ainda melhor. O desenvolvimento foi muito mais ágil e tive a sorte de conseguir concertar os antigos erros mais rapidamente, alguns eu nem cheguei a esbarrar novamente.

O plugin funciona no Gedit através do atalho Ctrl+Alt+Space e permite completar código python em tempo real. Módulos do python também são suportados. Ele tem basicamente o mesmo funcionamento do auto-complete do VIm mas eu acabei fazendo alguns pequenos ajustes no código. O Aaron Griffin me alertou que o código continha alguns pequenos problemas conhecidos e que em breve ele poderia corrigir. Vou me manter informado para não deixar o plugin desatualizado. Talvez os meus pequenos ajustes tenham corrigido algum desses pequenos bugs que ele mencionou.

Essa é uma versão alpha, ainda não realizei grandes testes. Acredito que ela já possa ser usada, mas certamente bugs aparecerão. Estou disposto a auxiliar quem se interessar pelo plugin. Abaixo segue um conjunto de screenshots demonstrando o funcionamento do plugin. Atualmente o Gedit conta com diversos plugins para desenvolvimento de código Python, os quais o estão aproximando de um ambiente para desenvolvimento Python. Apesar de tudo eu ainda continuo usando o VIm.

A instalação do plugin é relativamente fácil. O usuário deve apenas descompactar o arquivo dentro do diretório .gnome2/gedit/plugins de sua home, reiniciar o gedit e ativar o plugin em editar -> preferências -> plugins. O plugin só funciona com código python, em outro formato de arquivo o atalho não terá funcionalidade alguma. Espero que o plugin conte com a ajuda da comunidade e se torne cada vez mais maduro.

Auto complete code in real time.Show doc strings

O código do plugin de auto completar código Python no Gedit esta disponível aqui.

UPDATE 18/05/08:

Peço desculpa à todos pela ausência, assim como pela falta de atualização do blog. Estamos nos programando para voltarmos com força total. Enfim, fazendo o mínimo o qual já deveria ter feito, adicionei o plugin no github e assim o acesso fica muito mais fácil. Também vou poder contar melhor com a colaboração dos interessados. Plugin disponível aqui.

Read Full Post »

Python + Maya – Part 1


First, what’s Maya?

Maya is a high end 3D computer graphics and 3D modeling software package originally developed by Alias Systems Corporation, but now owned by Autodesk as part of the Media and Entertainment division. Autodesk acquired the software in October 2005 upon purchasing Alias. Maya is used in the film and TV industry, as well as for computer and video games.Wikipedia on Autodesk Maya

On its 8th version, Maya introduced Python scripting as an alternative for their native scripting language, MEL (Maya Embedded Language) which was being used for quite a long time.
After spending some months learning Python, today started to study maya bindings to Python and decided to make a series of posts showing some of the things I learn on the process.

The idea is that Python and MEL are alternatives for a programmer as they provided similar functionalities. So one must choose between one each and start their program.

Inputing code to Maya might be done in a series of different ways:

  • On start Maya always runs a script named “userSetup.py” which must be located at:
    • Windows: <drive>:\Documents and Settings\<user>\My Documents\maya\<version>\scripts
    • Mac OS X: ~/Library/Preferences/Autodesk/maya/<version>/scripts
    • Linux: ~/maya/<version>/scripts

    So you can write anything you’d like Maya to do on its first moments of life at this file;

  • Command Line It’s possible to input simple commands through Maya command line on the bottom of the window, like some select command of a hard to click object;
  • Script Editor The best way to test and debug your script. Since 8th edition, the script editor has two tabs on its lower part: MEL and Python. Clicking Python part won’t change anything but the interpreter the script editor will use to interpret your code. It provides simple ways to test it, but could be better if there was some syntax highlight;
  • Code outside Maya One can write the whole code outside Maya using any editor he’d like. It’s probably the best alternative for big plugins since most editors are a lot better than Maya Script Editor itself.

After learning that, and jumping on to the API to see what it was capable i was pleasantly surprised (since I’ve never spent much time studying MEL’s API) to find out it was capable of many amazing things and they were all documented.

It’s possible to access every attribute of any of the nodes on the scene, to create key frames and make complete animations through one script and to access many of the tools provided throughout the menus.

One quick example is how to create a bouncing ball animation.

import maya.cmds as cmds
cmds.polySphere( name = ‘bouncing’, radius = 2 )
g = -0.04
v0y = 0.8
v0x = 0.1
pos0y = 2
pos0x = 0
for itr in xrange(0,6):
for tx in xrange(0,42):
posy = pos0y + v0y*(tx-1) + g*(tx-1)*(tx-1)/2
posx = pos0x + v0x*((itr*42) + tx-1)
cmds.setKeyframe( ‘bouncing’, attribute=’translateY’, value=posy, t=(itr*42) + tx )
cmds.setKeyframe( ‘bouncing’, attribute=’translateX’, value=posx, t=(itr*42) + tx )

Line 1 imports all the Maya Comands to cmds and line 2 creates a polygonal sphere named “bouncing” with 2 units radius.
Lines 3 to 7 set a few physical constants like gravity (g), initial speeds (v0x and v0y) and initial positions (pos0x and pos0y).
Then comes the keyframe creation. The ball will jump 6 times, so we have a for from 0 to 6. Each bounce will take 42 frames what explains the second for from 0 to 42. Inside the second for and through some basic physical equations we set new positions for both x and y axis, and then create keyframes for both attributes.

I’m still trying to figure out a way to create less keyframes (through this method, I ended up creating 252 keyframes) even though I know this doesn’t represent a real problem for Maya standards.

So, thanks for reading, hope you enjoyed it and, if you try this at home, please feel free to comment your experience. And don’t forget to check our next episode: Python + Maya – Part 2!!

Powered by ScribeFire.

Read Full Post »

EMMS Browser, o video :-)

Meu primeiro vídeo usando o recordmydesktop. Ele mostra o uso do
browser do EMMS, um gerenciador de mídias para o Emacs.
Link para baixar

Se preferir ver em qualidade inferior no google videos clique aqui.

Read Full Post »

Older Posts »

Follow

Get every new post delivered to your Inbox.