Tải bản đầy đủ (.pdf) (592 trang)

Practical maya programming with python; unleash the power of python in maya and unlock your creativity

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (2.17 MB, 592 trang )


Practical Maya Programming with Python


Table of Contents
Practical Maya Programming with Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introspecting Maya, Python, and PyMEL
Creating your library
Using the interpreter
Finding a place for our library
Choosing a development root
Creating a function in your IDE



Reloading code changes
Exploring Maya and PyMEL
Creating an introspection function
Understanding Python and MEL types
Using the method resolution order
PyNodes all the way down
Understanding PyMEL data and math types
Leveraging the REPL
Building the pmhelp function
Creating a query string for a PyMEL object
Creating more tests
Adding support for modules
Adding support for types
Adding support for methods
Adding support for functions
Adding support for non-PyMEL objects
Designing with EAFP versus LBYL
Code is never complete
Opening help in a web browser
Summary
2. Writing Composable Code
Defining composability
Identifying anti-patterns of composability
Avoiding the use of Boolean flags
Evolving legacy code into composable code
Rewriting code for composability
Getting the first item in a sequence
Writing head and tail functions
Learning to use list comprehensions



Implementing is_exact_type
Saying goodbye to map and filter
Writing a skeleton converter library
Writing the docstring and pseudocode
Understanding docstrings and reStructured Text
Writing the first implementation
Breaking the first implementation
Understanding interface contracts
Extracting the safe_setparent utility function
Learning how to refactor
Simplifying the node to joint conversion
Learning how to use closures
Dealing with node connections
Dealing with namespaces
Wrapping up the skeleton converter
Writing a character creator
Stubbing out the character creator
Implementing convert_hierarchies_main
Implementing convert_hierarchies
Decomposing into composable functions
Implementing convert_hierarchy
Supporting inevitable modifications
Improving the performance of PyMEL
Defining performance
Refactoring for performance
Rewriting inner loops to use maya.cmds
Summary
3. Dealing with Errors

Understanding exceptions


Introducing exception types
Explaining try/catch/finally flow control
Explaining traceback objects
Explaining the exc_info tuple
Living with unhandled exceptions
Handling exceptions at the application level
Golden rules of error handling
Focus on the critical path
Keep the end user in mind
Only catch errors you can handle
Avoid partial mutations
Practical error handling in Maya
Dealing with expensive and mutable state
Leveraging undo blocks
Dealing with Maya's poor exception design
Leveraging the Maya application
Dealing with the Maya application
Leveraging Python, which is better than MEL
Building a high-level error handler
Understanding sys.excepthook
Using sys.excepthook in Maya
Creating an error handler
Improving the error handler
Inspecting Python code objects
Adding filtering based on filename
Assembling the contents of an error e-mail
Sending the error e-mail

Installing the error handler
Obeying the What If Two Programs Did This rule


Improving the error handler
Adding a user interface
Using a background thread to send the e-mail
Moving beyond e-mail
Capturing locals
Attaching log files
Summary
4. Leveraging Context Managers and Decorators in Maya
Inverting the subroutine
Introducing decorators
Explaining decorators
Wrapping an exporter with a decorator
Introducing context managers
Writing the undo_chunk context manager
Writing the undo_on_error context manager
Contrasting decorators and context managers
Context managers for changing scene state
Building the set_file_prompt context manager
Building the at_time context manager
Building the with_unit context manager
Building the set_renderlayer_active context manager
Building the set_namespace_active context manager
Improving on future versions of Maya
Creating the denormalized_skin context manager
Safely swapping vertex influences
Addressing performance concerns

Creating a decorator to record metrics
Getting a unique key
Recording duration


Reporting duration
Handling errors
Advanced decorator topics
Defining decorators with arguments
Decorating PyMEL attributes and methods
Stacking decorators
Using Python's decorator library
Doing decorators the right way
Summary
5. Building Graphical User Interfaces for Maya
Introducing Qt, PyQt, and PySide
Introducing Qt widgets
Introducing Qt layouts
Understanding Qt main windows and sorting
Introducing Qt signals
Establishing rules for crafting a GUI
Prefer pure PySide GUIs where possible
Use command-style UI building where necessary
Avoid the use of .ui files
Installing PySide
Supporting PySide and PyQt
Creating the hierarchy converter GUI
Creating the window
Running a Python file as a script
Introducing the QApplication class

Understanding the event loop
Running your GUI
Designing and building your GUI
Defining control, container, and window widgets


Adding the rest of the widgets
Hooking up the application to be effected by the GUI
Hooking up the GUI to be effected by the application
Simulating application events
Considering alternative implementations
Integrating the tool GUI with Maya
Opening the tool GUI from Maya
Getting the main Maya window as a QMainWindow
Making a Qt window the child of Maya's window
Using Python's reload function with GUIs
Emitting a signal from Maya
Connecting Maya to a signal
Verifying the hierarchy converter works
Working with menus
Creating a top-level menu
Getting the Qt object from a Maya path
Changing the font of a widget
Marking menus as new
Creating a test case
Adding a persistence registry
Verifying the new menu marker works
Using alternative methods to style widgets
Working with Maya shelves
Summary

6. Automating Maya from the Outside
Controlling Maya through request-reply
Using a Python client and Maya server
Controlling Python through exec and eval
Handling problems with IPC


Installing ZeroMQ
Demonstrating request-reply with ZeroMQ
Explaining connection strings, ports, bind, and connect
Designing the automation system
Pairing one client and one server
Bootstrapping the server from the client
The client-server handshake
Defining the server loop
Serializing requests and responses
Choosing what the server does
Handling exceptions between client and server
Understanding the Maya startup routine
Using batch mode versus GUI mode
Choosing a startup configuration mechanism
Using command line options
Using environment variables
Building the request-reply automation system
Creating a Python package
Launching Maya from Python
Automatically killing the server
Creating a basic Maya server
Running code at Maya startup
Understanding eval and exec

Adding support for eval and exec
Adding support for exception handling
Adding support for timeouts
Adding support for the client-server handshake
Practical uses and improvements
Batch processing using Maya


Running a server in a Maya GUI session
Running automated tests in Maya
Adding support for logging
Supporting multiple languages and applications
Supporting control from a remote computer
Designing an object-oriented system
Evaluating other RPC frameworks
Summary
7. Taming the Maya API
Explaining types
Dicts all the way down
Using custom types to simplify code
Introducing inheritance by drawing shapes
Introducing Maya's API and architecture
Understanding the OpenMaya bindings
Navigating the Maya API Reference
Understanding MObjects and function sets
Learning the Maya Python API by example
Converting a name to an MObject node
Getting the name of an MObject
Getting the hash of a node
Building a mesh

Setting mesh normals
Using MScriptUtil to call a method
Using OpenMaya for callbacks
Comparing Maya Python API and PyMEL
Creating a Maya Python plugin
The life of a Python plugin
Creating the sound player library


Creating the plugin file
Reloading plugins
Adding a command flag
Comparing the OpenMaya and scripting solutions
Using PyMEL in a plugin that loads during startup
Summary
8. Unleashing the Maya API through Python
Understanding Dependency Graph plugins
Building a simple node plugin
Understanding plugin type IDs
Defining inputs, outputs, and the initializer
Creating the compute method
Taming the non-Pythonic Maya API
Demystifying Python metaprogramming
Rethinking type creation
Exploring the type function
The importance of being declarative
Designing the node factory
Designing plugin nodes
Designing the attribute specification
Designing the node type specification

Building the node factory
Specifying attributes
Creating attributes
Specifying a node
Using partial application to create attributes
Creating a node
Slaying the compute method
Extending the node factory


Supporting string and color attributes
Supporting enum attributes
Supporting transform nodes
Overriding MPxNode methods
Summary
9. Becoming a Part of the Python Community
Understanding Open Source Software
Differentiating OSS from script download sites
Defining what a third-party module is
Creating a site directory for third-party modules
Explaining the site directory
Creating a new site directory for Maya
Establishing the site directory at startup
Working with Python distributions in Maya
Using the Python Package Index
Adding a source distribution to Maya
Adding an egg or wheel to Maya
Using binary distributions on Windows
Using pip to install third-party modules
Contributing to the open source community

Designing Maya Python code for open source
Starting an open source project
Distributing your project
Engaging with the wider community
Summary
A. Python Best Practices
The args and kwargs parameters
String formatting
String concatenation


Raw strings and string literals
Path building and manipulation
Unicode strings
Using the doctest module
Adopting Test-Driven Development
Using the GitHub repository for this book
Index


Practical Maya Programming with Python


Practical Maya Programming with Python
Copyright © 2014 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a
retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged

to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.
First published: July 2014
Production reference: 1180714
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-472-8
www.packtpub.com


Cover image by Andrei Cosmin Cristea (<>)


Credits
Author
Robert Galanakis
Reviewers
Harry Boltz
Brian Escribano
Michael Tsai
Commissioning Editor
Akram Hussain
Acquisition Editor
Subho Gupta
Content Development Editor
Dayan Hyames

Technical Editors
Krishnaveni Haridas


Manal Pednekar
Copy Editors
Aditya Nair
Stuti Srivastava
Project Coordinator
Leena Purkait
Proofreaders
Stephen Copestake
Maria Gould
Paul Hindle
Indexers
Mariammal Chettiyar
Tejal Soni
Priya Subramani
Graphics
Sheetal Aute


Yuvraj Mannari
Abhinash Sahu
Production Coordinator
Pooja Chiplunkar
Cover Work
Pooja Chiplunkar



About the Author
Robert Galanakis is a technical artist cum programmer who has worked in various areas of game development. He
is the Technical Director of EVE Online at CCP Games, Iceland, where he focuses on Python, Lean, and Agile
training and evangelism. In 2008, Rob founded tech-artists.org, which is the largest and the most active community
focused on tech art on the Internet. He has spoken at Game Developers Conference several times and has also
written many articles about tools, pipelines, and culture. His blog can be found at www.robg3d.com. He lives in
Reykjavík, Iceland, with his wife Casady and their son Marcus.


About the Reviewers
Brian Escribano has over 11 years of experience working in the fields of education, TV, and games. He builds
world-class character rigs and animation pipelines for companies such as Nickelodeon, Mirada, and Spark
Unlimited. With his deep scripting knowledge in Python and MEL, Brian brings a wealth of expertise and
experience to any team he works with.
Michael Tsai attended the Academy of Art University at San Francisco to study Visual Effects. After college, he
worked on Fantastic Four 2 – Rise of the Silver Surfer, Red Cliff 2 – The Battle of Red Cliff, and the stereoscopic
version of G-Force. In 2012, Michael received his Master of Entertainment Technology degree (MET) from the
Entertainment Technology Center of Carnegie Mellon University. Elysium was another feature film he worked on
before he joined Schell Games in Pittsburgh as a full-time game artist.


www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You
can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount
on the eBook copy. Get in touch with us at <> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free
newsletters and receive exclusive discounts and offers on Packt books and eBooks.



Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can
access, read and search across Packt's entire library of books.


Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser


Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine
entirely free books. Simply use your login credentials for immediate access.


×