Posts

Showing posts with the label Python

Calling Python from Substance Painter

Here is a quick code snippet for calling a Python script from Substance Painter and parsing the results. The in/out is very simple, but serves as an example of using the alg.subprocess.check_output function to bridge the JS api and your own Python scripts. // This can be called from the QML UI, or elsewhere in the plugin code. function GetAllFilesInDirectory(root) { if (root == undefined) return; // I put my scripts in a relative path to keep my plugin tidy. var script_path = "Scripts/FileUtils.py"; // Gathering files var ret = "NOSTRING"; try { // The arguments are used as parameter inputs to the Python script. This requires some planning // and well communicated conventions, but works well enough. ret = alg.subprocess.check_output( [ pypath, // Absolute path to interpreter. script_path, // Relative path to the py script. "log_files_of_type", // sys.argv[1], in this case the python ...

Do you want to play a game?

Image
My Chrome browser split in half last night and asked me if I wanted to play a game. Saying yes turned my browser into a pseudo python console. Apparently Google has been tracking my search history and seen that, yeah, I like Python. Ok, having the browser window suddenly split open because someone is watching your search history is vaguely creepy, but what the hey, I do like Python! Why do they want to play a game with me? I don't know, its Google. Why did they make Google maps into Pac Man ? Its Google. They do stuff like that. The first challenge was to take an equation as a string and parse it into reverse polish notation. After thinking about it today I was able to write a passable parser that will probably make any real mathematician twitch- but it works and the code doesn't make me twitch. The challenge was, well, challenging, but fun! It reminds me a bit of the Project Euler challenges, except this one gives you a hopping bunny when you succeed. An animated ASCII hopping...

Check in- Pete's Been busy...

Image
Hello World, I've been busy, so busy that I've been neglecting to blog. Luckily, some of what I've been up to is worth blogging about, so it works out. At work, I've started a new position as a Senior Technical Environment Artist. If that seems like a long title, its because it is. I'm straddling a strange gap between grumbling about crappy tools and actually writing better ones. It's a great place to be, because I get to save myself tonnes of time and pat myself on the back about it at the same time. Outside of work it was my birthday and something strange and computer-ey fell into my lap in the shape of a Raspberry Pi. We quickly became friends and I decided to make it a home. Some Stuff about 3d Printing: My Pi's new case. Its my first attempt at industrial design! I created the case in Maya, based off of a CAD model of the Pi itself. I'm pretty  surprised  happy that the Raspberry Pi actually fits inside the case! Not only that, but it fits pretty da...

Maya: Animation Event Definition Tool

Image
I've been working on a new set of tools to define animation event data in Maya and export it into Unity for consumption by the AssetPostProcessor. This has been kind of a cool learning experience, because before now I really didn't have much to do with the Animation pipe, which has been an entirely manual process for the animators. Previously clips were cut up and events were defined by hand in Unity once the .fbx files had been exported from Maya. This wasn't such a bad thing, except that the tools in Unity for defining events were very un-intuitive. The aim of doing all this was to allow the animators the ability to work in a tool they were familiar with, and get the AssetPostProcessor to do most of the boring legwork on the Unity side. The Maya interface.  The Maya tool is pretty simple right now, and responsive enough that the animators don't hate me. Navigating to different clips or events will move to that time range on the slider. The event list is directly corre...

Perforce: Delete empty change lists using Python

Image
Some of the tools I've written allow a user to check out chains of files- like Maya files as well as any exported FBX files and their unity metadata etc, all in one nice pass. This is great, but it has one annoying side effect. If the user presses the button twice the files are added to another change list, but the one they were just in stays there, empty. Press it a number of times and suddenly you have an army of zombie phantom changelists whose only purpose is to clutter up your pending list and annoy you.  I have been using the P4Python API and found it to be... well... its kinda crap. It would be great if it had a 'delete all empty pending changelists' function, but it doesn't seem to. So I wrote one of my own.  Beware! If you don't like hacking output out of strings the following code will make you cringe...  There's my target... import subprocess """Get a list of changelists from the command line. Try to delete them (will delete if empty)...

Use Python to use JavaScript to get Photoshop to do stuff... and tell you about it!

Its been pretty well established that you can send a .jsx file to Photoshop using a subprocess call in Python. The tricky part is then getting Photoshop to send some information back. This is my awesome hacky method of passing information from Photoshop to Python. It relies on being able to write to a temporary text file from Photoshop and then reading that information back into Python. This method relies on actually being able to write data to disk... if that's a problem I suspect you could do the same to the console standard output and get the same results... somehow? Maybe? Because writing to the disk was not a problem in this situation, I went with a temp file solution. The only kinda tricky part was making my program wait for the return value to be passed. Subproces.call() returns a value of 1 or 0 from the shell, but this only indicates that the program successfully (or not) opened. Its highly likely that whatever script you passed to Photoshop as part of the Subprocess cal...

Texture Monkey: Starting to look like a real tool.

Image
Stuff is happening... After a little while in the field it came to be pretty apparent that the win32com module  can't  be relied upon to consistently work on everyone's machines. I spent a good amount of time trying to work out why , but came up with no solution that worked consistently on everyone's workstations. Errors like ('Member not found, None, None) would constantly pop up in their debug feedback, but not on mine. Talk about frustrating. So I got pretty annoyed and just ripped the win32com components out.  This was a pretty big undertaking, because apart from the GUI, win32com stuff made up about 80% of the remaining code. The P4 functionality wasn't touched, because its operating through it's own native API.  The solution: Photoshop Automation without win32com! The solution I went with was to write a wrapper around the JavaScript equivalent of what I was using the win32com module for. Each of these commands would be put into a list, which is then compi...

PSD Metadata and Real time GUI updates.

Image
It might not be the absolute best solution, but I have been able to put into practice my idea of storing the tool settings in the PSD metadata, and it actually works pretty well. The current setup works like this: On export, go through a dictionary of controls inside the GUI and check the settings.  Store each object name and it's setting as a text block with easily splittable characters. For this I chose to use ~ and | as neither of these are used for windows file or directory names.  Write this text block to the PSD metadata.  Meanwhile, in the export, use the GUI's current settings to determine output locations, formats and files to include.   To reload the settings: A background thread is constantly listening for any changes in the current active Photoshop document.  If the name of the document changes, it automatically kicks off a function that reads the metadata out of the active PSD and splits it into objectName, setting value pairs.  If no data is f...

Texture Monkey... version"some big number"

Image
We are now getting Perforce. Oh how I  missed thee Perforce! And what a fantastic opportunity to revisit my favorite pet project, Texture Monkey! Be be honest, I'm kinda sick of re-writing this tool, but I've got it to a point where it meets a couple of extra prerequisites that it was sucking at before, mainly: It's written at a point where I actually feel I can competently write functional and readable code.   It's UI uses the QT framework. Which it MUCH nicer to work with than the previous WX.  It's been built around the premise that it  should easily be portable across projects without having to change any of the source code- provided afew assumptions about project structure are met.  It does more than texture exporting, and now supports Perforce integration as well.  Most importantly, it is written in a modular fashion, and can be expanded upon or cut back without too much trouble.  Now with extra stuff! Behind the scenes: It stores and loads tool ...

Writing Metadata to a PSD file using Python

Image
I want to save some tool specific information about a PSD file, but I don't want to have another pesky metadata file floating about to bloat my source texture folder. Luckily, the PSD file format supports writing custom MetaData within it, which is perfect for what I want to do. In this particular example, I want my tool to be able to remember which folder the flattened image associated with this PSD will eventually be put into, the format the image will be in and the resolution. There are many fields you can write to, but I have chosen to write to the Instructions information, because that just makes the most sense. Usually in Photoshop, you can see this fields available by going to the file info panel and going to the advanced tab: In Python, we can access and write to the PSD's metadata very easily. import win32com.client.dynamic as w32dynamic w32 = w32dynamic.Dispatch psApp = w32('Photoshop.Application') doc = psApp.activeDocument # When I pull this info out of the ...

Model Monkey: Now with Configs!

Image
I've decided to use ini files to make it easier to port my Maya exporter across different projects with as little fuss as possible, using the standard Python ConfigParser module. The last time I really played around with .ini files was to mess with Command and Conquer Red Alert, and that was some time ago. It's really awesome that the .ini file format is still worth using today. There is a bug where you can add new file rules until the tool grows so long it is bigger than the screen. Time to add a scroll bar... Part of getting this to work includes creating a GUI interface to minimize the manual file editing that you might expect. Being my first major use of an .ini for a tool (I did use a teeny tiny .ini on Texture Monkey) I suddenly realized that I had to re-work a lot of my previous configuration code in order to make my tool flexible enough to be re-configurable without breaking into a million different lame parts. BUT! It's working now, whoo! A couple of things have to...

Maya Exporter: Tabs and Tools!

Image
I've been chipping away at my Maya Exporter and have a few Photoshop functions tied into it now, along side the original exporter functionality. Behind the scenes the Photoshop commands are built on Standard modules, using Subprocess and some string manipulation in order to get JavaScript commands to the Photoshop application. As the tool has expanded beyond it's initial export-only functionality, there has been a decent amount of clean up and re-factoring behind the scenes to make sure that it doesn't just turn into a mega-script. Maya-side functions and Photoshop functions have been split into separate classes and files from the GUI, which has made keeping track of the code a lot easier. The GUI is built using the Pyside QT Libraries, which comes standard with Maya 2014. Next on the list, adding the option to load different project environments.

Python Photoshop Automation without win32com- The Example

Image
So here is a working example of what I was talking about in my last blog post- making Photoshop automation possible without needing to use the win32com module. This specific example is not cross-platform compatible. It relies on getting the Photoshop application through it's registry entry, but the subprocess module is cross platform so it shouldn't be too hard to hammer this into a shape that can be used on Mac and PC. Or just Mac. Or whatever. Essentially there is no real magic going on here, just lots of string manipulation behind the scenes. Like I said in my last post, the biggest hole in this right now is the lack of feedback from Photoshop, but that's something I'm looking into when I get a few spare minutes here and there. Here is the example. When you run it, you should come up with something that looks like this: What an Amazing document.  And the code! This is a particularly long snippet. Hang in there! Essentially when the commands are called, like add_new_...

Python Photoshop Automation without win32com.

Clunky but kinda fun, its possible to automate Photoshop using Javascript files passed as arguments to the subprocess.  Although this essentially means you have to write your script in two languages (PS's native JS and Python for pipeline) the practical aspect of this is that it allows scripts to be written that do not require people to have the win32com/comtypes modules installed, and paves the way for cross platform scripts that aren't tied to windows only modules.  I've had some success with creating a dynamic JavaScript builder that wraps Python functions around Photoshop's native Javascript commands. When the list of commands is executed it is compiled into a jsx file and then passed on to the Photoshop subprocess as an argument. The only short coming right now is obtaining the output from Photoshop and making it into a two-way street. I have some ideas on how to do this, and will update with the solution I end up using. 

PySide and Maya2014

I've been working with PySide to make some tools for our Animation department. Part of that process involves a UI that is generated on the fly based on data read in from a spreadsheet. It was important that each UI component had a unique and predictable object name so that I could access the information it contained and save it out later. In case anyone else needs to do it, or has a better way, here is an example of the process I use.  Thanks to Nathan Horne and Chris Zurbrigg  for their very useful examples! # System # System import sys import os # GUI Modules from PySide import QtCore, QtGui import maya.OpenMayaUI as apiUI # Allows converting pointers to Python objects from shiboken import wrapInstance def maya_main_window(): main_win_ptr = apiUI.MQtUtil.mainWindow() return wrapInstance(long(main_win_ptr), QtGui.QWidget) # Create out Dialog class, inheriting from QDialog class Dialog(QtGui.QDialog): # Call the maya_main_window command to parent it def _...

Tooling around- Maya Photoshop Bridge

Image
My current little pet project to bridge Photoshop and Maya, from within the Maya environment. The tool is in very early development stage, but currently supports project configuration and opening a selected model's source PSD from within the Maya environment. Other neat time savers: Exporting a selected model's UV map and using it to create a new PSD. Calling Photoshop to export all of a model's maps from their source PSD.  Renaming shaders based on their diffuse texture name. linking associated known map types (eg- specular, gloss and normal)  The tool is written entirely in Python/Pymel and uses the win32com module as a bridge.  Various options to clean up scenes.  The current texture tools. More to come! Project options.

Sliced Py- Cheat sheet for Python Slicing

I'm constantly using slicing in my Python scripts, but I am also constantly scratching my head about exactly where to put the little colon to get the slice that I'm after. After consulting the stackoverflow gurus I wrote a little cheat sheet using a string as an example.   foo = "Monty Python's Flying Circus" #Print the middle of foo- slice from the 7th-1 character end at the 15th-1 character print foo[6:14] #Use a slice to get the first six characters print foo[:6] #>>> Monty #Slice after the first six characters of foo print foo[6:] #>>> Python's Flying Circus #Print everthing in foo print foo[:] #>>> Monty Python's Flying Circus #Every second character print foo[0:27:2] #>>> MnyPto' ligCru #The last character of foo print foo[-1] #>>> s #The last two characters of foo print foo[-2:] #>>> us #Everything but the last seven charachers of foo print foo[:-7] #>>> Monty Python's Flying

Maya, Python and Wings IDE

I've recently moved away from the Maya Script Editor for my Maya scripting and started using Wing IDE, which is great in that it has full code auto-complete, debugging support and can be rigged up to execute code in Maya straight from the IDE window using a simple server setup. Here are a couple of guides I found handy in getting Wings to work with my Maya install: To set up Auto Complete for MEL and Python. To execute code in Maya from the Wing IDE

Python, COM and windows 8

Recently I got myself a new laptop which came pre-installed with windows 8. Rather than instantly wiping it out and installing windows 7, I decided to give it a try. After getting over the initial shock, I installed all my usual python tools and started setting up my scripts... only to suddenly be stopped dead in my tracks when all my comtypes related scripts no longer worked, coming up with something along the lines of:                  TypeError : '_Dispatch' object is not callable Lame! Anyway, if anyone else encounters this, the solution turned out to be running the Python command line in XP compatibility mode. To set this up in windows 8, you can follow these steps: Go to your control panel. Click on the 'Programs'  category.  Click on 'Run programs made for previous versions of windows' Step through the troubleshooter, selecting your Python command line as the target program.  And it should all work again! 

PIL- Applying a threshold to an image's alpha

If you are using PIL (python imaging library) for batch processing textures you might find this useful. I used this little bit of code in one of my batch texture reduction scripts to apply a threshold to the alpha channel. This is to make sure it is still one bit after the size reduction, but also leaves the other channels intact. Here is the snippet: from PIL import Image fileName = r'C:\temp\test_image.tga' #Load the image try: img = Image.open(fileName) tempImg = img.load() del(tempImg) except IOError: print "*** IOError: %s\n" % sys.exc_info()[1].message #Test if the image actually *has* an alpha channel if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info): #create a threshold value threshold = 128 #Create a reference to the alpha channel using the split function alpha = img.split()[3] #Apply the threshold using the point function alpha = alpha.point(lambda p: p ...