code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
from entity import Entity
from apihandler import json_encode
class Directory(Entity):
_default_data = {
'id' : 0,
'type' : 'directory',
'name' : '',
}
def serialize(self):
data = self._data.copy()
#for file in data.files:
# file = file.serialize()
return data
def __str__(self):
return self._data['name']
def __unicode__(self):
return self._data['name']
| Python |
#-*- coding: utf-8 -*-
import json
import time
from entity import Entity
from apihandler import json_encode
class User (Entity):
_default_data = {
'id' : 0,
'name' : '',
'password' : '',
'sid' : '',
'regDate' : '',
'level' : 0,
}
def serialize(self):
"""
Сериализует данные в JSON для отправки пользователю.
"""
data = self._data.copy()
try:
data['regDate'] = str(int(time.mktime(data['regDate'].timetuple())))
except: pass
del data['password']
return data
@staticmethod
def unserialize(self, json):
return User()
| Python |
import sys
import baseSkeletonBuilder
from filesystem import Path
from baseSkeletonBuilder import *
__author__ = 'mel@macaronikazoo.com'
SKELETON_PART_SCRIPT_PREFIX = 'skeletonPart_'
_LOAD_ORDER = 'spine', 'head', 'arm', 'hand', 'leg'
def _iterSkeletonPartScripts():
for p in sys.path:
p = Path( p )
if 'maya' in p:
for f in p.files():
if f.hasExtension( 'py' ):
if f.name().startswith( SKELETON_PART_SCRIPT_PREFIX ):
yield f
partModuleNames = [ f.name() for f in _iterSkeletonPartScripts() ]
for name in reversed( _LOAD_ORDER ):
name = SKELETON_PART_SCRIPT_PREFIX + name
if name in partModuleNames:
partModuleNames.remove( name )
partModuleNames.insert( 0, name )
for modName in partModuleNames:
__import__( modName )
#import skeletonBuilderConversion
#skeletonBuilderConversion.convertOldParts()
#end
| Python |
'''
'''
def d_initCache(f):
def __init__(*args, **kwargs):
self = args[0]
self._CACHE_ = {}
return f(*args, **kwargs)
__init__.__name__ = f.__name__
__init__.__doc__ = f.__doc__
return __init__
initCache = d_initCache
def d_cacheValue(f):
def cachedRetValFunc(*args, **kwargs):
self = args[0]
try:
return self._CACHE_[ f ]
except KeyError:
val = f(*args, **kwargs)
self._CACHE_[ f ] = val
return val
#it may be a parent class has caching turned on, but the child class does not...
except AttributeError:
return f(*args, **kwargs)
cachedRetValFunc.__name__ = f.__name__
cachedRetValFunc.__doc__ = f.__doc__
return cachedRetValFunc
cacheValue = d_cacheValue
def d_cacheValueWithArgs(f):
def cachedRetValFunc(*args, **kwargs):
self = args[0]
funcArgsTuple = (f.__name__,)+tuple(args[1:])
try:
return self._CACHE_[funcArgsTuple]
except KeyError:
val = f(*args, **kwargs)
self._CACHE_[funcArgsTuple] = val
return val
except TypeError:
return f(*args, **kwargs)
except AttributeError:
return f(*args, **kwargs)
cachedRetValFunc.__name__ = f.__name__
cachedRetValFunc.__doc__ = f.__doc__
return cachedRetValFunc
cacheValueWithArgs = d_cacheValueWithArgs
def d_resetCache(f):
def resetCacheFunc(*args, **kwargs):
self = args[ 0 ]
retval = f(*args, **kwargs)
try:
self._CACHE_.clear()
return retval
except AttributeError:
return retval
resetCacheFunc.__name__ = f.__name__
resetCacheFunc.__doc__ = f.__doc__
return resetCacheFunc
resetCache = d_resetCache
#end | Python |
from baseMelUI import *
from changeIkFk import ChangeIkFkLayout
from changeParent import ChangeParentLayout
from changeRo import ChangeRoLayout
__author__ = 'hamish@valvesoftware.com'
class ChangeLayout(MelColumnLayout):
def __init__( self, parent ):
frame = MelFrameLayout( self, l='Change Ik/Fk', cll=True, cl=False )
ChangeIkFkLayout( frame )
frame = MelFrameLayout( self, l='Change Parent', cll=True, cl=True )
ChangeParentLayout( frame )
frame = MelFrameLayout( self, l='Change Rotation Order', cll=True, cl=True )
ChangeRoLayout( frame )
class ChangeWindow(BaseMelWindow):
WINDOW_NAME = 'changeTool'
WINDOW_TITLE = 'Change Tools'
DEFAULT_SIZE = 300, 250
DEFAULT_MENU = 'Help'
FORCE_DEFAULT_SIZE = True
HELP_MENU = 'ChangeTool', __author__, 'https://intranet.valvesoftware.com/wiki/index.php/Change_Tool'
def __init__( self ):
ChangeLayout( self )
self.show()
#end
| Python |
'''
provides console colouring - currently only NT is supported
'''
STD_OUTPUT_HANDLE = -11
FG_BLUE = 0x01
FG_GREEN = 0x02
FG_CYAN = 0x03
FG_RED = 0x04
FG_MAGENTA = 0x05
FG_YELLOW = 0x06
FG_WHITE = 0x07
BRIGHT = 0x08
BG_BLUE = 0x10
BG_GREEN = 0x20
BG_CYAN = 0x30
BG_RED = 0x40
BG_MAGENTA = 0x50
BG_YELLOW = 0x60
BG_BRIGHT = 0x80
import sys
try:
import ctypes
def setConsoleColour( colour ):
'''
sets the subsequent console spew to a given colour
eg. setConsoleColour(BRIGHT | FG_GREEN)
'''
std_out_handle = ctypes.windll.kernel32.GetStdHandle( STD_OUTPUT_HANDLE )
ctypes.windll.kernel32.SetConsoleTextAttribute( std_out_handle, colour )
except:
def setConsoleColour( colour ):
pass
class ColouredWriter:
def __init__( self, colour ):
self.colour = colour
def write( self, msg ):
setConsoleColour( self.colour )
sys.stdout.write( msg )
setConsoleColour( FG_WHITE )
def logInColour( msg, colour ):
print >> ColouredWriter( colour ), msg
'''
create some useful, common colouredWriter instances. an example for using these:
print >> Error, 'hello, im an error'
'''
Warn = ColouredWriter( BRIGHT | FG_YELLOW )
Error = ColouredWriter( BRIGHT | FG_RED )
Good = ColouredWriter( BRIGHT | FG_GREEN )
BigError = ColouredWriter( BRIGHT | FG_RED | BG_RED )
def logAsWarning( msg ):
print >> Warn, msg
def logAsError( msg ):
print >> Error, msg
#end
| Python |
from baseSkeletonBuilder import *
class Arm(SkeletonPart):
HAS_PARITY = True
@classmethod
def _build( cls, parent=None, buildClavicle=True, **kw ):
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
parent = getParent( parent )
allJoints = []
dirMult = idx.asMultiplier()
parityName = idx.asName()
if buildClavicle:
clavicle = createJoint( 'clavicle%s' % parityName )
cmd.parent( clavicle, parent, relative=True )
move( dirMult * partScale / 50.0, partScale / 10.0, partScale / 25.0, clavicle, r=True, ws=True )
allJoints.append( clavicle )
parent = clavicle
bicep = createJoint( 'bicep%s' % parityName )
cmd.parent( bicep, parent, relative=True )
move( dirMult * partScale / 10.0, 0, 0, bicep, r=True, ws=True )
elbow = createJoint( 'elbow%s' % parityName )
cmd.parent( elbow, bicep, relative=True )
move( dirMult * partScale / 5.0, 0, -partScale / 20.0, elbow, r=True, ws=True )
wrist = createJoint( 'wrist%s' % parityName )
cmd.parent( wrist, elbow, relative=True )
move( dirMult * partScale / 5.0, 0, partScale / 20.0, wrist, r=True, ws=True )
setAttr( '%s.rz' % bicep, dirMult * 45 )
jointSize( bicep, 2 )
jointSize( wrist, 2 )
return allJoints + [ bicep, elbow, wrist ]
def _buildPlacers( self ):
return []
def visualize( self ):
scale = self.getBuildScale() / 10.0
plane = polyCreateFacet( ch=False, tx=True, s=1, p=((0, 0, -scale), (0, 0, scale), (self.getParityMultiplier() * 2 * scale, 0, 0)) )
cmd.parent( plane, self.wrist, relative=True )
cmd.parent( listRelatives( plane, shapes=True, pa=True ), self.wrist, add=True, shape=True )
delete( plane )
@property
def clavicle( self ): return self[ 0 ] if len( self ) > 3 else None
@property
def bicep( self ): return self[ -3 ]
@property
def elbow( self ): return self[ -2 ]
@property
def wrist( self ): return self[ -1 ]
def _align( self, _initialAlign=False ):
parity = self.getParity()
normal = getPlaneNormalForObjects( self.bicep, self.elbow, self.wrist )
normal *= parity.asMultiplier()
if self.clavicle:
parent = getNodeParent( self.clavicle )
if parent: alignAimAtItem( self.clavicle, self.bicep, parity, upType='objectrotation', worldUpObject=parent, worldUpVector=MAYA_FWD )
alignAimAtItem( self.bicep, self.elbow, parity, worldUpVector=normal )
alignAimAtItem( self.elbow, self.wrist, parity, worldUpVector=normal )
if _initialAlign:
autoAlignItem( self.wrist, parity, worldUpVector=normal )
else:
alignPreserve( self.wrist )
for i in self.getOrphanJoints():
alignItemToLocal( i )
def getIkFkItems( self ):
return self.bicep, self.elbow, self.wrist
#end
| Python |
import exportManagerCore, filesystem, datetime, api
import maya.cmds as cmd
from filesystem import resolvePath
mel = api.mel
melecho = api.melecho
TOOL_NAME = 'visManager'
TOOL_VERSION = 1
EXTENSION = filesystem.DEFAULT_XTN
DEFAULT_LOCALE = filesystem.LOCAL
def exportPreset( presetName, visHierarchyTop, locale=DEFAULT_LOCALE ):
'''
exports a vis hierarchy preset file - this file contains a node hierarchy which represents a vis hierarchy.
each empty transform node in the group represents a set, and each volume in the structure represents a face
selection used to determine vis set membership
'''
exportDict = api.writeExportDict(TOOL_NAME, TOOL_VERSION)
#simply returns the
def getVolumesAndEmptyGroups( node ):
children = cmd.listRelatives(node, type='transform', path=True)
volumes = []
groups = []
for child in children:
shapes = cmd.listRelatives(child, shapes=True, type='nurbsSurface', path=True)
if shapes:
type = int( cmd.getAttr('%s.exportVolume' % child) )
pos = cmd.xform(child, q=True, ws=True, rp=True)
rot = cmd.xform(child, q=True, ws=True, ro=True)
scale = cmd.getAttr('%s.s' % child)[0]
volumes.append( (child, type, pos, rot, scale) )
else: groups.append( child )
return volumes, groups
topVolumes, topGroups = getVolumesAndEmptyGroups(visHierarchyTop)
parentQueue = [(visHierarchyTop, topGroups)]
#create the first entry
toExport = [(visHierarchyTop, None, topVolumes)]
while True:
try:
curNode = topGroups.pop(0)
curParent = cmd.listRelatives(curNode, p=True)[0]
curVolumes, curChildren = getVolumesAndEmptyGroups(curNode)
topGroups.extend(curChildren)
toExport.append( (curNode, curParent, curVolumes) )
except IndexError: break
exportDict['preset'] = toExport
thePreset = filesystem.Preset(locale, TOOL_NAME, presetName, EXTENSION)
thePreset.pickle(exportDict)
@api.d_showWaitCursor
def importPreset( presetName, locale=DEFAULT_LOCALE, createSets=True, deleteAfterImport=True ):
thePreset = filesystem.Preset(locale, TOOL_NAME, presetName, EXTENSION)
presetData = thePreset.unpickle()
volumesList = presetData['preset']
#if we're creating the vis sets, then we need to grab a list of meshes in the scene
allMeshes = set(cmd.ls(type='mesh'))
#this dict tracks what the names were when they were written out, vs what names they are
#after building them in scene - names can change due to clashes etc...
nodesDict = {}
#this dict tracks teh nodes and their corresponding set representation (should one exist...)
setDict = {}
for node, parent, volumesData in volumesList:
curNode = cmd.group(empty=True)
curNode = cmd.rename(curNode, node)
#if the parent exists in the node list (it should always exist except for the top node...
try: curNode = cmd.parent(curNode, nodesDict[parent])[0]
except KeyError: pass
nodesDict[node] = curNode
volumes = []
#build the volumes - place and parent them appropriately
for volume, type, pos, rot, scale in volumesData:
newVolume = exportManagerCore.createExportVolume( int(type) )
cmd.move(pos[0], pos[1], pos[2], newVolume, a=True, ws=True, rpr=True)
cmd.rotate(rot[0], rot[1], rot[2], newVolume, a=True, ws=True)
cmd.setAttr('%s.s' % newVolume, *scale)
newVolume = cmd.rename(newVolume, volume)
cmd.parent(newVolume, curNode)
volumes.append(newVolume)
if createSets:
items = []
setParent = ''
try: setParent = setDict[parent]
except KeyError: pass
for vol in volumes: items.extend( exportManagerCore.findFacesInVolumeForMaya(allMeshes, vol) )
newSet = mel.zooVisManCreateSet(setParent, node, items)
setDict[node] = newSet
if deleteAfterImport:
cmd.delete( nodesDict[ volumesList[0][0] ] )
#return the created volumes
return nodesDict.keys(),
#end | Python |
from rigPrim_curves import *
from spaceSwitching import build, NO_TRANSLATION, NO_ROTATION
class FkSpine(PrimaryRigPart):
__version__ = 0
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Spine' ), )
def _build( self, skeletonPart, translateControls=True, **kw ):
spineBase, spineEnd = skeletonPart.base, skeletonPart.end
partParent, rootControl = getParentAndRootControl( spineBase )
#build a list of all spine joints - start from the bottom of the heirarchy, and work up - a joint only has one parent
spines = [ spineEnd ]
if spineBase != spineEnd:
while True:
p = getNodeParent( spines[ -1 ] )
spines.append( p )
if p == spineBase: break
spines.reverse()
#try to figure out a sensible offset for the spine controls - this is basically just an average of the all offsets for all spine joints
spineOffset = AX_Z.asVector() * getAutoOffsetAmount( spines[ 0 ], spines )
#create the controls, and parent them
#determine what axis to draw the spine controls - assume they're all the same as the spine base
controlSpaces = []
controllers = []
startColour = ColourDesc( (1, 0.3, 0, 0.65) )
endColour = ColourDesc( (0.8, 1, 0, 0.65) )
spineColour = startColour
colourInc = (endColour - startColour) / float( len( spines ) )
for n, j in enumerate( spines ):
c = buildControl( "spine_%d_fkControl" % n, j, PivotModeDesc.BASE, ShapeDesc( 'pin', axis=AX_Z ), colour=spineColour, offset=spineOffset, scale=self.scale*1.5, niceName='Spine %d Control' % n )
cSpace = getNodeParent( c )
jParent = partParent
if n: jParent = controllers[ -1 ]
controllers.append( c )
controlSpaces.append( cSpace )
parent( cSpace, jParent )
spineColour += colourInc
setNiceName( controllers[ 0 ], 'Spine Base' )
setNiceName( controllers[ -1 ], 'Spine End' )
#create the space switching
for j, c in zip( spines, controllers ):
buildDefaultSpaceSwitching( j, c, **spaceSwitching.NO_TRANSLATION )
#create line of action commands
createLineOfActionMenu( spines, controllers )
#turn unwanted transforms off, so that they are locked, and no longer keyable
if not translateControls:
attrState( controllers, 't', *LOCK_HIDE )
return controllers, ()
class IKFKSpine(PrimaryRigPart):
__version__ = 0
PRIORITY = 10 #make this a lower priority than the simple FK spine rig
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Spine' ), )
@classmethod
def CanRigThisPart( cls, skeletonPart ):
return len( skeletonPart ) >= 3
def _build( self, skeletonPart, squish=True, **kw ):
objs = skeletonPart.items
parentControl, rootControl = getParentAndRootControl( objs[0] )
fittedCurve, linearCurve, proxies, fixedLengthProxies, controls, splineIkHandle, halfIdx = buildControls( objs, parentControl, name='spineControl', **kw )
buildDefaultSpaceSwitching( objs[0], controls[-1] )
parent( proxies, self.getPartsNode() )
parent( fittedCurve, linearCurve, self.getPartsNode() )
if splineIkHandle:
parent( splineIkHandle, self.getPartsNode() )
if fixedLengthProxies:
parent( fixedLengthProxies[0], self.getPartsNode() )
return controls, ()
#end
| Python |
from baseSkeletonBuilder import *
class Spine(SkeletonPart):
HAS_PARITY = False
@classmethod
def _build( cls, parent=None, count=3, direction='y', **kw ):
idx = kw[ 'idx' ]
partScale = kw[ 'partScale' ]
parent = getParent( parent )
directionAxis = Axis.FromName( direction )
allJoints = []
prevJoint = str( parent )
posInc = float( partScale ) / 2 / (count + 2)
moveList = list( directionAxis.asVector() * posInc )
for n in range( count ):
j = createJoint( 'spine%s%d' % ('' if idx == 0 else '%d_' % idx, n+1) )
cmd.parent( j, prevJoint, relative=True )
move( moveList[0], moveList[1], moveList[2], j, r=True, ws=True )
allJoints.append( j )
prevJoint = j
jointSize( j, 2 )
return allJoints
def _align( self, _initialAlign=False ):
for n, item in enumerate( self[ :-1 ] ):
alignAimAtItem( item, self[ n+1 ] )
#if there is a head part parented to this part, then use it as a look at for the end joint
childParts = self.getChildParts()
hasHeadPartAsChild = False
headPart = None
HeadCls = SkeletonPart.GetNamedSubclass( 'Head' ) or type( None )
for p in childParts:
if isinstance( p, HeadCls ):
headPart = p
break
if headPart is None:
autoAlignItem( self.end )
else:
alignAimAtItem( self.end, headPart.base )
#end
| Python |
'''
this module is simply a miscellaneous module for rigging support code - most of it is maya specific convenience code
for determining things like aimAxes, aimVectors, rotational offsets for controls etc...
'''
from maya.cmds import *
from vectors import *
import apiExtensions
import maya.cmds as cmd
import meshUtils
import api
import vectors
import random
from maya import OpenMaya
SPACES = SPACE_WORLD, SPACE_LOCAL, SPACE_OBJECT = range(3)
ENGINE_FWD = MAYA_SIDE = MAYA_X = Vector((1, 0, 0))
ENGINE_UP = MAYA_FWD = MAYA_Z = Vector((0, 0, 1))
ENGINE_SIDE = MAYA_UP = MAYA_Y = Vector((0, 1, 0))
#pull in some globals...
MPoint = OpenMaya.MPoint
MVector = OpenMaya.MVector
MMatrix = OpenMaya.MMatrix
MTransformationMatrix = OpenMaya.MTransformationMatrix
MBoundingBox = OpenMaya.MBoundingBox
MSpace = OpenMaya.MSpace
kWorld = MSpace.kWorld
kTransform = MSpace.kTransform
kObject = MSpace.kObject
Axis = vectors.Axis
AXES = Axis.BASE_AXES
#these are the enum values for the rotation orders for transform nodes in maya
MAYA_ROTATION_ORDERS = ROO_XYZ, ROO_YZX, ROO_ZXY, ROO_XZY, ROO_YXZ, ROO_ZYX = range( 6 )
MATRIX_ROTATION_ORDER_CONVERSIONS_FROM = Matrix.FromEulerXYZ, Matrix.FromEulerYZX, Matrix.FromEulerZXY, Matrix.FromEulerXZY, Matrix.FromEulerYXZ, Matrix.FromEulerZYX
MATRIX_ROTATION_ORDER_CONVERSIONS_TO = Matrix.ToEulerXYZ, Matrix.ToEulerYZX, Matrix.ToEulerZXY, Matrix.ToEulerXZY, Matrix.ToEulerYXZ, Matrix.ToEulerZYX
ROT_ORDER_STRS = 'xyz', 'yzx', 'zxy', 'xzy', 'yxz', 'zyx'
def alignFast( objToAlign, dest ):
if getAttr( '%s.t' % objToAlign, se=True ):
pos = xform( dest, q=True, ws=True, rp=True )
move( pos[0], pos[1], pos[2], objToAlign, a=True, ws=True, rpr=True )
if getAttr( '%s.r' % objToAlign, se=True ):
#rotation is a bit special because when querying the rotation we get back xyz world rotations - so we need to change the rotation order to xyz, set the global rotation then modify the rotation order while preserving orientation
initialRo = getAttr( '%s.ro' % objToAlign )
setAttr( '%s.ro' % objToAlign, 0 )
rot = xform( dest, q=True, ws=True, ro=True )
rotate( rot[0], rot[1], rot[2], objToAlign, a=True, ws=True )
xform( objToAlign, p=True, roo=ROT_ORDER_STRS[ initialRo ] )
def cleanDelete( node ):
'''
will disconnect all connections made to and from the given node before deleting it
'''
if not objExists( node ):
return
connections = listConnections( node, connections=True, plugs=True )
connectionsIter = iter( connections )
for srcConnection in connectionsIter:
tgtConnection = connectionsIter.next()
#we need to test if the connection is valid because a previous disconnection may have affected this one
if isConnected( srcConnection, tgtConnection ):
try:
#this may fail if the dest attr is locked - in which case just skip and hope deleting the node doesn't screw up the attribute value...
disconnectAttr( srcConnection, tgtConnection )
except RuntimeError: pass
cmd.delete( node )
def getObjectBasisVectors( obj ):
'''
returns 3 world space orthonormal basis vectors that represent the orientation of the given object
'''
worldMatrix = Matrix( cmd.getAttr( '%s.worldMatrix' % obj ), size=4 )
return Vector( worldMatrix[0][:3] ), Vector( worldMatrix[1][:3] ), Vector( worldMatrix[2][:3] )
def getLocalBasisVectors( obj ):
'''
returns 3 world space orthonormal basis vectors that represent the local coordinate system of the given object
'''
localMatrix = Matrix( cmd.getAttr( '%s.matrix' % obj ), size=4 )
return Vector( localMatrix[0][:3] ), Vector( localMatrix[1][:3] ), Vector( localMatrix[2][:3] )
def getPlaneNormalForObjects( objA, objB, objC, defaultVector=MAYA_UP ):
posA = Vector( xform( objA, q=True, ws=True, rp=True ) )
posB = Vector( xform( objB, q=True, ws=True, rp=True ) )
posC = Vector( xform( objC, q=True, ws=True, rp=True ) )
vecA, vecB = posA - posB, posA - posC
normal = vecA.cross( vecB )
#if the normal is too small, just return the given default axis
if normal.magnitude() < 1e-2:
normal = defaultVector
return normal.normalize()
def findPolePosition( end, mid=None, start=None, distanceMultiplier=1 ):
if not objExists( end ):
return Vector.Zero()
try:
if mid is None:
mid = listRelatives( end, p=True, pa=True )[0]
if start is None:
start = listRelatives( mid, p=True, pa=True )[0]
except TypeError:
return Vector.Zero()
joint0, joint1, joint2 = start, mid, end
pos0 = Vector( xform( joint0, q=True, ws=True, rp=True ) )
pos1 = Vector( xform( joint1, q=True, ws=True, rp=True ) )
pos2 = Vector( xform( joint2, q=True, ws=True, rp=True ) )
#this is the rough length of the presumably "limb" we're finding the pole vector position for
lengthFactor = (pos1-pos0).length() + (pos2-pos1).length()
#get the vectors from 0 to 1, and 0 to 2
vec0_1 = pos1 - pos0
vec0_2 = pos2 - pos0
#project vec0_1 on to vec0_2
projA_B = vec0_2.normalize() * ( (vec0_1 * vec0_2) / vec0_2.length() )
#get the vector from the projected vector above, to the mid pos
sub = vec0_1 - projA_B
#if the magnitude is really small just return the position of the mid object
if sub.length() < 1e-4:
return pos1
sub = sub.normalize()
polePos = pos0 + projA_B + (sub * lengthFactor)
return polePos
def largestT( obj ):
'''
returns the index of the translation axis with the highest absolute value
'''
pos = getAttr( '%s.t' % obj )[0]
idx = indexOfLargest( pos )
if pos[ idx ] < 0:
idx += 3
return idx
def indexOfLargest( iterable ):
'''
returns the index of the largest absolute valued component in an iterable
'''
iterable = [(x, n) for n, x in enumerate( map(abs, iterable) )]
iterable.sort()
return Axis( iterable[-1][1] )
def betweenVector( obj1, obj2 ):
'''
returns the vector between two objects
'''
posA = Vector( xform( obj1, q=True, ws=True, rp=True ) )
posB = Vector( xform( obj2, q=True, ws=True, rp=True ) )
return posB - posA
def getAimVector( obj ):
children = cmd.listRelatives( obj, path=True, typ='transform' ) or []
if len( children ) == 1:
return betweenVector(obj, children[0])
else:
axisIdx = largestT( obj )
axisVector = Axis( axisIdx ).asVector()
#now just return the axis vector in world space
mat = Matrix( cmd.getAttr( '%s.worldMatrix' % obj ) )
return multVectorMatrix( axisVector, mat )
def getObjectAxisInDirection( obj, compareVector, defaultAxis=Axis(0) ):
'''
returns the axis (an Axis instance) representing the closest object axis to
the given vector
the defaultAxis is returned if the compareVector is zero or too small to provide
meaningful directionality
'''
if not isinstance( compareVector, Vector ):
compareVector = Vector( compareVector )
xPrime, yPrime, zPrime = getObjectBasisVectors( obj )
try:
dots = compareVector.dot( xPrime, True ), compareVector.dot( yPrime, True ), compareVector.dot( zPrime, True )
except ZeroDivisionError:
return defaultAxis
idx = indexOfLargest( dots )
if dots[ idx ] < 0: idx += 3
return Axis( idx )
def getLocalAxisInDirection( obj, compareVector ):
xPrime, yPrime, zPrime = getLocalBasisVectors( obj )
dots = compareVector.dot( xPrime, True ), compareVector.dot( yPrime, True ), compareVector.dot( zPrime, True )
idx = indexOfLargest( dots )
if dots[ idx ] < 0: idx += 3
return Axis( idx )
def getAnkleToWorldRotation( obj, fwdAxisName='z', performRotate=False ):
'''
ankles are often not world aligned and cannot be world aligned on all axes, as the ankle needs to aim toward
toe joint. for the purposes of rigging however, we usually want the foot facing foward (or along one of the primary axes
'''
fwd = Vector.Axis( fwdAxisName )
fwdAxis = getObjectAxisInDirection( obj, fwd )
basisVectors = getObjectBasisVectors( obj )
fwdVector = basisVectors[ abs( fwdAxis ) ]
#determine the directionality of the rotation
direction = -1 if fwdAxis.isNegative() else 1
#flatten aim vector into the x-z plane
fwdVector[ AX_Y ] = 0
fwdVector = fwdVector.normalize() * direction
#now determine the rotation between the flattened aim vector, and the fwd axis
angle = fwdVector.dot( fwd )
angle = Angle( math.acos( angle ), radian=True ).degrees * -direction
#do the rotation...
if performRotate:
cmd.rotate(0, angle, 0, obj, r=True, ws=True)
return (0, angle, 0)
def getWristToWorldRotation( wrist, performRotate=False ):
'''
returns the world space rotation values to align the given object to world axes. If
performRotate is True the object will be rotated to this alignment. The rotation
values are returned as euler rotation values in degrees
'''
worldMatrix, worldScale = Matrix( getAttr( '%s.worldMatrix' % wrist ) ).decompose()
bases = x, y, z = map( Vector, worldMatrix.crop( 3 ) )
newBases = []
allAxes = range( 3 )
for basis in bases:
largestAxisValue = -2 #values will never be smaller than this, so the code below will always get run
largestAxis = 0
#find which world axis this basis vector best approximates - we want to world align the basis vectors
for n in range( 3 ):
absAxisValue = abs( basis[n] )
if absAxisValue > largestAxisValue:
largestAxisValue = absAxisValue
largestAxis = n+3 if basis[n] < 0 else n #if the dot is negative, shift the axis index by 3 (which makes it negative)
#track the largestAxisValue too - we want to use it as a measure of closeness
newBases.append( Axis( largestAxis ).asVector() )
newBases = map( list, newBases )
matrixValues = newBases[0] + newBases[1] + newBases[2]
worldRotMatrix = Matrix( matrixValues, 3 )
rots = worldRotMatrix.ToEulerXYZ( True )
if performRotate:
rotate( rots[0], rots[1], rots[2], wrist, a=True, ws=True )
return tuple( rots )
def isVisible( dag ):
'''
returns whether a dag item is visible or not - it walks up the hierarchy and checks both parent visibility
as well as layer visibility
'''
parent = dag
while True:
if not getAttr( '%s.v' % parent ):
return False
#check layer membership
layers = listConnections( parent, t='displayLayer' )
if layers is not None:
for l in layers:
if not getAttr( '%s.v' % l ):
return False
try:
parent = listRelatives( parent, p=True, pa=True )[0]
except TypeError:
break
return True
def areSameObj( objA, objB ):
'''
given two objects, returns whether they're the same object or not - object path names make this tricker than it seems
'''
try:
return cmd.ls( objA ) == cmd.ls( objB )
except TypeError:
return False
def getBounds( objs ):
minX, minY, minZ = [], [], []
maxX, maxY, maxZ = [], [], []
for obj in objs:
tempMN = cmd.getAttr( '%s.bbmn' % obj )[ 0 ]
tempMX = cmd.getAttr( '%s.bbmx' % obj )[ 0 ]
minX.append( tempMN[ 0 ] )
minY.append( tempMN[ 1 ] )
minZ.append( tempMN[ 2 ] )
maxX.append( tempMX[ 0 ] )
maxY.append( tempMX[ 1 ] )
maxZ.append( tempMX[ 2 ] )
minX.sort()
minY.sort()
minZ.sort()
maxX.sort()
maxY.sort()
maxZ.sort()
return minX[ 0 ], minY[ 0 ], minZ[ 0 ], maxX[ -1 ], maxY[ -1 ], maxZ[ -1 ]
def getTranslationExtents( objs ):
ts = [ xform( i, q=True, ws=True, rp=True ) for i in objs ]
xs, ys, zs = [ t[0] for t in ts ], [ t[1] for t in ts ], [ t[2] for t in ts ]
mnx, mxx = min( xs ), max( xs )
mny, mxy = min( ys ), max( ys )
mnz, mxz = min( zs ), max( zs )
return mnx, mny, mnz, mxx, mxy, mxz
def getObjsScale( objs ):
mnX, mnY, mnZ, mxX, mxY, mxZ = getBounds( objs )
x = abs( mxX - mnX )
y = abs( mxY - mnY )
z = abs( mxZ - mnZ )
return (x + y + z) / 3.0 * 0.75 #this is kinda arbitrary
def getJointBounds( joints, threshold=0.65, space=SPACE_OBJECT ):
'''
if the joints are skinned, then the influenced verts that have weights greater than the given
influenced are transformed into the space specified (if SPACE_OBJECT is used, the space of the
first joint is used), and the bounds of the verts in this space are returned as a 2-tuple of
bbMin, bbMax
'''
global MVector, MTransformationMatrix, Vector
if not isinstance( joints, (list, tuple) ):
joints = [ joints ]
theJoint = joints[ 0 ]
verts = []
for j in joints:
verts += meshUtils.jointVertsForMaya( j, threshold )
jointDag = api.getMDagPath( theJoint )
if space == SPACE_OBJECT:
jointMatrix = jointDag.inclusiveMatrix()
elif space == SPACE_LOCAL:
jointMatrix = jointDag.exclusiveMatrix()
elif space == SPACE_WORLD:
jointMatrix = OpenMaya.MMatrix()
else: raise TypeError( "Invalid space specified" )
vJointPos = MTransformationMatrix( jointMatrix ).rotatePivot( kWorld ) + MTransformationMatrix( jointMatrix ).getTranslation( kWorld )
vJointPos = Vector( [vJointPos.x, vJointPos.y, vJointPos.z] )
vJointBasisX = MVector(-1,0,0) * jointMatrix
vJointBasisY = MVector(0,-1,0) * jointMatrix
vJointBasisZ = MVector(0,0,-1) * jointMatrix
bbox = MBoundingBox()
for vert in verts:
#get the position relative to the joint in question
vPos = Vector( xform( vert, query=True, ws=True, t=True ) )
vPos = vJointPos - vPos
#now transform the joint relative position into the coordinate space of that joint
#we do this so we can get the width, height and depth of the bounds of the verts
#in the space oriented along the joint
vPosInJointSpace = Vector( vPos )
vPosInJointSpace = vPosInJointSpace.change_space( vJointBasisX, vJointBasisY, vJointBasisZ )
bbox.expand( MPoint( *vPosInJointSpace ) )
bbMin, bbMax = bbox.min(), bbox.max()
bbMin = Vector( [bbMin.x, bbMin.y, bbMin.z] )
bbMax = Vector( [bbMax.x, bbMax.y, bbMax.z] )
return bbMin, bbMax
def getJointSizeAndCentre( joints, threshold=0.65, space=SPACE_OBJECT, ignoreSkinning=False ):
if ignoreSkinning:
vec = Vector.Zero()
else:
minB, maxB = getJointBounds( joints, threshold, space )
vec = maxB - minB
#if the bounding box is a point then lets see if we can derive a useful size for the joint based on existing children
if not vec:
#make sure we're dealing with a list of joints...
if not isinstance( joints, (list, tuple) ):
joints = [ joints ]
children = listRelatives( joints, pa=True, typ='transform' ) or []
#if there are no children then we fall back on averaging the "radius" attribute for all given joints...
if not children:
radSum = sum( getAttr( '%s.radius' % j ) for j in joints )
s = float( radSum ) / len( joints ) * 5 #5 is an arbitrary number - tune it as required...
return Vector( (s, s, s) ), Vector( (0, 0, 0) )
theJoint = joints[ 0 ]
theJointPos = Vector( xform( theJoint, q=True, ws=True, rp=True ) )
#determine the basis vectors for <theJoint>. we want to transform the joint's size into the appropriate space
if space == SPACE_OBJECT:
theJointBasisVectors = getObjectBasisVectors( theJoint )
elif space == SPACE_LOCAL:
theJointBasisVectors = getLocalBasisVectors( theJoint )
elif space == SPACE_WORLD:
theJointBasisVectors = Vector( (1,0,0) ), Vector( (0,1,0) ), Vector( (0,0,1) )
else: raise TypeError( "Invalid space specified" )
bbox = MBoundingBox()
bbox.expand( MPoint( 0, 0, 0 ) ) #make sure zero is included in the bounding box - zero is the position of <theJoint>
for j in joints[ 1: ] + children:
pos = Vector( xform( j, q=True, ws=True, rp=True ) ) - theJointPos
pos = pos.change_space( *theJointBasisVectors )
bbox.expand( MPoint( *pos ) )
minB, maxB = bbox.min(), bbox.max()
minB = Vector( (minB.x, minB.y, minB.z) )
maxB = Vector( (maxB.x, maxB.y, maxB.z) )
vec = maxB - minB
centre = (minB + maxB) / 2.0
return Vector( map( abs, vec ) ), centre
getJointSizeAndCenter = getJointSizeAndCentre #for spelling n00bs
def getJointSize( joints, threshold=0.65, space=SPACE_OBJECT ):
return getJointSizeAndCentre( joints, threshold, space )[ 0 ]
def ikSpringSolver( start, end, **kw ):
'''
creates an ik spring solver - this is wrapped simply because its not default
maya functionality, and there is potential setup work that needs to be done
to ensure its possible to create an ik chain using the spring solver
'''
api.mel.ikSpringSolver()
kw[ 'solver' ] = 'ikSpringSolver'
handle, effector = cmd.ikHandle( '%s.rotatePivot' % start, '%s.rotatePivot' % end, **kw )
#now we want to ensure a sensible pole vector - so set that up
jointChain = getChain( start, end )
poleVectorAttrVal = xform( jointChain[1], q=True, ws=True, rp=True )
restPoleVector = betweenVector( jointChain[0], jointChain[1] )
setAttr( '%s.springRestPoleVector' % handle, *restPoleVector )
setAttr( '%s.poleVector' % handle, *poleVectorAttrVal )
return handle, effector
def resetSkinCluster( skinCluster ):
'''
splats the current pose of the skeleton into the skinCluster - ie whatever
the current pose is becomes the bindpose
'''
skinInputMatrices = listConnections( '%s.matrix' % skinCluster, plugs=True, connections=True, destination=False )
#this happens if the skinCluster is bogus - its possible for deformers to become orphaned in the scene
if skinInputMatrices is None:
return
#get a list of dag pose nodes connected to the skin cluster
dagPoseNodes = listConnections( skinCluster, d=False, type='dagPose' ) or []
iterInputMatrices = iter( skinInputMatrices )
for dest in iterInputMatrices:
src = iterInputMatrices.next()
srcNode = src.split( '.' )[ 0 ]
idx = dest[ dest.rfind( '[' )+1:-1 ]
matrixAsStr = ' '.join( map( str, cmd.getAttr( '%s.worldInverseMatrix' % srcNode ) ) )
melStr = 'setAttr -type "matrix" %s.bindPreMatrix[%s] %s' % (skinCluster, idx, matrixAsStr)
api.mel.eval( melStr )
#reset the stored pose in any dagposes that are conn
for dPose in dagPoseNodes:
dagPose( srcNode, reset=True, n=dPose )
def enableSkinClusters():
for c in ls( type='skinCluster' ):
resetSkinCluster( c )
setAttr( '%s.nodeState' % c, 0 )
def disableSkinClusters():
for c in ls( type='skinCluster' ):
setAttr( '%s.nodeState' % c, 1 )
def getSkinClusterEnableState():
for c in ls( type='skinCluster' ):
if getAttr( '%s.nodeState' % c ) == 1:
return False
return True
def buildMeasure( startNode, endNode ):
measure = createNode( 'distanceDimShape', n='%s_to_%s_measureShape#' % (startNode, endNode) )
measureT = listRelatives( measure, p=True, pa=True )[ 0 ]
locA = spaceLocator()[ 0 ]
locB = spaceLocator()[ 0 ]
cmd.parent( locA, startNode, r=True )
cmd.parent( locB, endNode, r=True )
locAShape = listRelatives( locA, s=True, pa=True )[ 0 ]
locBShape = listRelatives( locB, s=True, pa=True )[ 0 ]
connectAttr( '%s.worldPosition[ 0 ]' % locAShape, '%s.startPoint' % measure, f=True )
connectAttr( '%s.worldPosition[ 0 ]' % locBShape, '%s.endPoint' % measure, f=True )
return measureT, measure, locA, locB
def buildAnnotation( obj, text='' ):
'''
like the distance command above, this is a simple wrapper for creating annotation nodes,
and having the nodes you actually want returned to you. whoever wrote these commands
should be shot. with a large gun
returns a 3 tuple containing the start transform, end transform, and annotation shape node
'''
obj = str( obj ) #cast as string just in case we've been passed a PyNode instance
rand = random.randint
end = spaceLocator()[ 0 ]
shape = annotate( end, p=(rand(0, 1000000), rand(1000000, 2000000), 2364), tx=text )
start = listRelatives( shape, p=True, pa=True )[ 0 ]
endShape = listRelatives( end, s=True, pa=True )[ 0 ]
delete( parentConstraint( obj, end ) )
for ax in Axis.AXES[ :3 ]:
setAttr( '%s.t%s' % (start, ax), 0 )
setAttr( '%s.v' % endShape, 0 )
setAttr( '%s.v' % endShape, lock=True )
cmd.parent( end, obj )
return start, end, shape
def getChain( startNode, endNode ):
'''
returns a list of all the joints from the given start to the end inclusive
'''
chainNodes = [ endNode ]
for p in api.iterParents( endNode ):
if not p:
raise ValueError( "Chain terminated before reaching the end node!" )
chainNodes.append( p )
if apiExtensions.cmpNodes( p, startNode ): #cmpNodes is more reliable than just string comparing - cmpNodes casts to MObjects and compares object handles
break
chainNodes.reverse()
return chainNodes
def chainLength( startNode, endNode ):
'''
measures the length of the chain were it to be straightened out
'''
length = 0
curNode = endNode
for p in api.iterParents( endNode ):
curPos = Vector( xform( curNode, q=True, ws=True, rp=True ) )
parPos = Vector( xform( p, q=True, ws=True, rp=True ) )
dif = curPos - parPos
length += dif.get_magnitude()
if apiExtensions.cmpNodes( p, startNode ): #cmpNodes is more reliable than just string comparing - cmpNodes casts to MObjects and compares object handles
break
curNode = p
return length
def switchToFK( control, ikHandle=None, onCmd=None, offCmd=None ):
'''
this proc will align the bones controlled by an ik chain to the fk chain
ikHandle this flag specifies the name of the ikHandle to work on
onCmd this flag tells the script what command to run to turn the ik handle on - it is often left blank because its assumed we're already in ik mode
offCmd this flag holds the command to turn the ik handle off, and switch to fk mode
NOTE: if the offCmd isn't specified, it defaults to: lambda c, ik: setAttr( '%s.ikBlend' % c, 0 )
both on and off callbacks take 2 args - the control and the ikHandle
example:
switchToFK( ikHandle1, onCmd=lambda ctrl, ik: setAttr( '%s.ikBlend' % ik, 1 ), offCmd=lambda c, ik: setAttr( '%s.ikBlend' % ik, 0 ) )
'''
if ikHandle is None:
ikHandle = control
if onCmd is None:
onCmd = lambda c, ik: setAttr( '%s.ikBlend' % c, 0 )
if callable( onCmd ):
onCmd( control, ikHandle )
joints = cmd.ikHandle( ikHandle, q=True, jl=True )
effector = cmd.ikHandle( ikHandle, q=True, ee=True )
effectorCtrl = listConnections( '%s.tx' % effector, d=False )[ 0 ]
jRotations = [ getAttr( '%s.r' % j ) for j in joints ]
if callable( offCmd ):
offCmd( control, ikHandle )
for j, rot in zip( joints, jRotations ):
if getAttr( '%s.rx' % j, settable=True ): setAttr( '%s.rx' % j, rot[ 0 ] )
if getAttr( '%s.ry' % j, settable=True ): setAttr( '%s.ry' % j, rot[ 1 ] )
if getAttr( '%s.rz' % j, settable=True ): setAttr( '%s.rz' % j, rot[ 2 ] )
def switchToIK( control, ikHandle=None, poleControl=None, onCmd=None, offCmd=None ):
'''
this proc will align the IK controller to its fk chain
flags used:
-control this is the actual control being used to move the ikHandle - it is assumed to be the same object as the ikHandle, but if its different (ie if the ikHandle is constrained to a controller) use this flag
-pole tells the script the name of the pole controller - if there is no pole vector control, leave this flag out
-ikHandle this flag specifies the name of the ikHandle to work on
-onCmd this flag tells the script what command to run to turn the ik handle on - it is often left blank because its assumed we're already in ik mode
-offCmd this flag holds the command to turn the ik handle off, and switch to fk mode
NOTE: if the offCmd isn't specified, it defaults to: if( `getAttr -se ^.ikb` ) setAttr ^.ikb 1;
symbols to use in cmd strings:
^ refers to the ikHandle
# refers to the control object
example:
zooAlignIK "-control somObj -ikHandle ikHandle1 -offCmd setAttr #.fkMode 0";
'''
if ikHandle is None:
ikHandle = control
if callable( onCmd ):
onCmd( control, ikHandle, poleControl )
joints = cmd.ikHandle( ikHandle, q=True, jl=True )
effector = cmd.ikHandle( ikHandle, q=True, ee=True )
effectorCtrl = listConnections( '%s.tx' % effector, d=False )[ 0 ]
mel.zooAlign( "-src %s -tgt %s" % (effectorCtrl, control) )
if poleControl is not None and objExists( poleControl ):
pos = mel.zooFindPolePosition( "-start %s -mid %s -end %s" % (joints[ 0 ], joints[ 1 ], effectorCtrl) )
move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True )
if callable( offCmd ):
offCmd( control, ikHandle, poleControl )
def replaceConstraintTarget( constraint, newTarget, targetIndex=0 ):
'''
replaces the target at "targetIndex" with the new target
'''
newTarget = apiExtensions.asMObject( str( newTarget ) )
for attr in attributeQuery( 'target', node=constraint, listChildren=True ):
for connection in listConnections( '%s.target[%s].%s' % (constraint, targetIndex, attr), p=True, type='transform', d=False ) or []:
toks = connection.split( '.' )
node = toks[ 0 ]
if not apiExtensions.cmpNodes( node, newTarget ):
toks[ 0 ] = str( newTarget )
connectAttr( '.'.join( toks ), '%s.target[%s].%s' % (constraint, targetIndex, attr), f=True )
def replaceGivenConstraintTarget( constraint, targetToReplace, newTarget ):
'''
replaces targetToReplace transform on the given constraint with the newTarget transform
'''
targetToReplace = apiExtensions.asMObject( targetToReplace )
newTarget = apiExtensions.asMObject( newTarget )
#nothing to do if the nodes are the same...
if apiExtensions.cmpNodes( targetToReplace, newTarget ):
return
usedTargetIndices = getAttr( '%s.target' % constraint, multiIndices=True )
for idx in usedTargetIndices:
for attr in attributeQuery( 'target', node=constraint, listChildren=True ):
for connection in listConnections( '%s.target[%s].%s' % (constraint, idx, attr), p=True, type='transform', d=False ) or []:
toks = connection.split( '.' )
node = toks[ 0 ]
if apiExtensions.cmpNodes( node, targetToReplace ):
toks[ 0 ] = str( newTarget )
connectAttr( '.'.join( toks ), '%s.target[%s].%s' % (constraint, idx, attr), f=True )
def setupBaseLimbTwister( joint, aimObject, upObject, aimAxis ):
'''
Builds a bicep twist rig.
Bicep twist joints are basically joints that sit next to the bicep (humerous) in the hierarchy and take
all the weighting of the deltoid and upper triceps. Bicep twists don't rotate on their twist axis, but
aim at the elbow, so they basically do exactly as the humerous does but don't twist.
'''
if not isinstance( aimAxis, Axis ):
aimAxis = Axis.FromName( aimAxis )
upAxes = [ ax.asVector() for ax in aimAxis.otherAxes() ]
joint = apiExtensions.asMObject( joint )
upObject = apiExtensions.asMObject( upObject )
jWorldMatrix = joint.getWorldMatrix()
upVectorsWorld = [ ax * jWorldMatrix for ax in upAxes ]
upWorldInvMatrix = upObject.getWorldInverseMatrix()
#we want to transform the aimObject's two different axes into the space of the up object
upVectorsLocal = [ upVectorsWorld[0] * upWorldInvMatrix,
upVectorsWorld[1] * upWorldInvMatrix ]
matrixMult = createNode( 'pointMatrixMult', n='bicepTwister_primaryUpAxis' )
setAttr( '%s.inPoint' % matrixMult, *upVectorsLocal[0] )
setAttr( '%s.vectorMultiply' % matrixMult, True )
connectAttr( '%s.worldMatrix[0]' % upObject, '%s.inMatrix' % matrixMult )
vectorProduct = createNode( 'vectorProduct' )
connectAttr( '%s.output' % matrixMult, '%s.input1' % vectorProduct )
setAttr( '%s.operation' % vectorProduct, 1 )
aimNode = aimConstraint( aimObject, joint, aim=aimAxis.asVector(), wuo=upObject, wut='objectrotation' )[0]
addAttr( aimNode, ln='upAndAimDot', at='double' )
#create an expression to normalize the constraintVector attribute coming out of the aimConstraint node - its not normalized, and the vector product node doesn't normalize inputs (wtf?!)
expressionStr = '''float $mag = sqrt( (%(aimNode)s.constraintVectorX * %(aimNode)s.constraintVectorX) + (%(aimNode)s.constraintVectorY * %(aimNode)s.constraintVectorY) + (%(aimNode)s.constraintVectorZ * %(aimNode)s.constraintVectorZ) ) + 1;
float $normX = %(aimNode)s.constraintVectorX / $mag;
float $normY = %(aimNode)s.constraintVectorY / $mag;
float $normZ = %(aimNode)s.constraintVectorZ / $mag;
%(vectorProduct)s.input2X = %(matrixMult)s.outputX * $normX;
%(vectorProduct)s.input2Y = %(matrixMult)s.outputX * $normY;
%(vectorProduct)s.input2Z = %(matrixMult)s.outputX * $normZ;''' % locals()
expression( s=expressionStr )
sdkDriver = '%s.outputX' % vectorProduct
connectAttr( sdkDriver, '%s.upAndAimDot' % aimNode )
for upAxis, upVector, driverValues in zip( upAxes, upVectorsLocal, ((0, 0.1), (0.9, 1)) ):
for driverValue in driverValues:
for upAxisValue, upVectorValue, axisName in zip( upAxis, upVector, Axis.BASE_AXES ):
axisName = axisName.upper()
setDrivenKeyframe( '%s.upVector%s' % (aimNode, axisName), value=upAxisValue,
currentDriver=sdkDriver, driverValue=driverValue, itt='linear', ott='linear' )
setDrivenKeyframe( '%s.worldUpVector%s' % (aimNode, axisName), value=upVectorValue,
currentDriver=sdkDriver, driverValue=driverValue, itt='linear', ott='linear' )
for axisName in Axis.BASE_AXES:
axisName = axisName.upper()
setInfinity( '%s.upVector%s' % (aimNode, axisName), pri='oscillate', poi='oscillate' )
setInfinity( '%s.worldUpVector%s' % (aimNode, axisName), pri='oscillate', poi='oscillate' )
def reorderAttrs( obj, newAttribOrder ):
for attr in newAttribOrder:
objAttrpath = '%s.%s' % (obj, attr)
#if the attribute is locked, we'll need to unlock it to rename it
isAttrLocked = getAttr( objAttrpath, l=True )
if isAttrLocked:
setAttr( objAttrpath, l=False )
#rename the attribute to a temporary name. You can't rename it to its own name, so we need to rename it to a proxy name, and then back again
tempAttrname = '_temp__123xx'
while objExists( '%s.%s' % (obj, tempAttrname) ):
tempAttrname += '_1'
tempAttrib = renameAttr( objAttrpath, tempAttrname )
renameAttr( '%s.%s' % (obj, tempAttrname), attr )
#if the attribute WAS locked, lock it again, in order to maximise transparency
if isAttrLocked:
setAttr( objAttrpath, l=True )
def dumpNodeAttrs( node ):
'''
simple debug function - you can use this to dump out attributes for nodes, stick em in a text file and do a diff
can be useful for tracking down how various undocumented nodes mysteriously work
'''
attrs = listAttr( node )
for attr in attrs:
try:
print attr, getAttr( '%s.%s' % (node, attr) )
if attributeQuery( attr, n=node, multi=True ):
indices = getAttr( '%s.%s' % (node, attr), multiIndices=True ) or []
for idx in indices:
print '\t%d %s' % (idx, getAttr( '%s.%s[%d]' % (node, attr, idx) ))
except RuntimeError:
print attr
except TypeError:
print attr
del( control )
#end
| Python |
from filesystem import P4File, P4Change, removeDupes
from baseMelUI import *
from devTest import TEST_CASES, runTestCases
class DevTestLayout(MelVSingleStretchLayout):
def __init__( self, parent, *a, **kw ):
MelVSingleStretchLayout.__init__( self, parent, *a, **kw )
self.UI_tests = UI_tests = MelObjectScrollList( self, ams=True )
self.UI_run = UI_run = MelButton( self, l='Run Tests', c=self.on_test )
for testCls in TEST_CASES:
UI_tests.append( testCls )
self.setStretchWidget( UI_tests )
self.layout()
### EVENT HANDLERS ###
def on_test( self, *a ):
'''
run the selected tests - the modules are reloaded before running the tests so
its easy to iterate when writing the tests
'''
runTestCases( self.UI_tests.getSelectedItems() )
class DevTestWindow(BaseMelWindow):
WINDOW_NAME = 'devTestWindow'
WINDOW_TITLE = 'Maya Devtest Runner'
DEFAULT_MENU = None
DEFAULT_SIZE = 300, 300
FORCE_DEFAULT_SIZE = True
HELP_MENU = 'devTest', 'hamish@macaronikazoo.com', None
def __init__( self ):
BaseMelWindow.__init__( self )
DevTestLayout( self )
self.show()
#end
| Python |
from __future__ import with_statement
from maya import mel
from maya.cmds import *
from baseMelUI import *
from vectors import Vector, Colour
from common import printErrorStr, printWarningStr
from mayaDecorators import d_unifyUndo
from apiExtensions import asMObject, sortByHierarchy
from triggered import resolveCmdStr, Trigger
import re
import names
import colours
import presetsUI
eval = __builtins__[ 'eval' ] #otherwise this gets clobbered by the eval in maya.cmds
TOOL_NAME = 'zooPicker'
TOOL_EXTENSION = filesystem.presets.DEFAULT_XTN
TOOL_CMD_EXTENSION = 'cmdPreset'
VERSION = 0
MODIFIERS = SHIFT, CAPS, CTRL, ALT = 2**0, 2**1, 2**2, 2**3
ADDITIVE = CTRL | SHIFT
def isValidMayaNodeName( theStr ):
validChars = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
for char in theStr:
if char not in validChars:
return False
return True
def getLabelWidth( theString ):
'''
some guestimate code to determine the width of a given string when displayed as
text on a ButtonUI instance
'''
wideLetters = 'abcdeghkmnopqrsuvwxyz_ '
width = 0
for char in theString:
if char in wideLetters:
width += 7
else:
width += 3
return width
def removeRefEdits( objs, cmd=None ):
'''
removes reference edits from a list of objects. if the $cmd arg is an empty string
then ALL commands are removed. if $cmd is a valid reference edit command, only those
commands are removed from the list of objects supplied
'''
refNodeLoadStateDict = {}
for obj in objs:
if referenceQuery( obj, inr=True ):
refNode = referenceQuery( obj, rfn=True )
loadState = bool( referenceQuery( refNode, n=True ) )
refNodeLoadStateDict[ refNode ] = loadState
#now unload all references so we can remove edits
for node in refNodeLoadStateDict:
file( unloadReference=node )
#remove failed edits
for obj in objs:
referenceEdit( obj, failedEdits=True, successfulEdits=False, removeEdits=True )
#remove specified edits for the objects
for obj in objs:
if cmd is None:
referenceEdit( obj, failedEdits=True, successfulEdits=True, removeEdits=True )
else:
referenceEdit( obj, failedEdits=True, successfulEdits=True, editCommand=cmd, removeEdits=True )
#now set the refs to their initial load state
for node, loadState in refNodeLoadStateDict.iteritems():
if loadState:
file( loadReference=node )
select( objs )
def getTopPickerSet():
existing = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == TOOL_NAME ]
if existing:
return existing[ 0 ]
else:
pickerNode = createNode( 'objectSet', n='picker' )
sets( pickerNode, e=True, text=TOOL_NAME )
return pickerNode
class Button(object):
'''
A Button instance is a "container" for a button within a picker. To instantiate a button you need to pass the set node
that contains the button data. You can create a new set node using Button.Create.
A button, when pressed, by default selects the contents of the set based on the keyboard modifiers pressed. But a button
can also define its own press command. Button press commands are stored on the cmdStr string attribute on the set node
and can be most easily edited using the editor tab created by the PickerLayout UI.
'''
SELECTION_STATES = NONE, PARTIAL, COMPLETE = range( 3 )
CMD_MODES = MODE_SELECTION_FIRST, MODE_CMD_FIRST, MODE_CMD_ONLY = range( 3 )
CMD_MODES_NAMES = 'selection first', 'cmd first', 'cmd only'
MIN_SIZE, MAX_SIZE = 5, 100
DEFAULT_SIZE = 14, 14
DEFAULT_COLOUR = tuple( Colour( (0.25, 0.25, 0.3) ).asRGB() )
AUTO_COLOUR = None
COLOUR_PARTIAL, COLOUR_COMPLETE = (1, 0.6, 0.5), Colour( 'white' ).asRGB()
DEFAULT_ATTRS = ( { 'ln': 'posSize', 'dt': 'string' }, #stuff pos and size into a single str attr - so lazy...
{ 'ln': 'colour', 'dt': 'string' },
{ 'ln': 'label', 'dt': 'string' },
{ 'ln': 'cmdStr', 'dt': 'string' },
{ 'ln': 'cmdIsPython', 'at': 'bool', 'dv': False },
{ 'ln': 'cmdMode', 'at': 'enum', 'enumName': ':'.join( CMD_MODES_NAMES ), 'dv': MODE_SELECTION_FIRST }
)
@classmethod
def Create( cls, character, pos, size=DEFAULT_SIZE, colour=AUTO_COLOUR, label=None, objs=(), cmdStr=None, cmdIsPython=False ):
node = sets( em=True, text='zooPickerButton' )
sets( node, e=True, add=character.getNode() )
cls.ValidateNode( node )
self = cls( node )
self.setPosSize( pos, size )
self.setLabel( label )
self.setObjs( objs )
self.setCmdStr( cmdStr )
self.setCmdIsPython( cmdIsPython )
#if the colour is set to "AUTO_COLOUR" then try to determine the button colour based off the object's colour
if colour is cls.AUTO_COLOUR:
self.setColour( cls.DEFAULT_COLOUR )
self.setAutoColour()
else:
self.setColour( colour )
return self
@classmethod
def ValidateNode( cls, node ):
for addAttrKw in cls.DEFAULT_ATTRS:
if not objExists( '%s.%s' % (node, addAttrKw[ 'ln' ]) ):
addAttr( node, **addAttrKw )
def __init__( self, node ):
self.__node = asMObject( node )
def __repr__( self ):
return "%s( '%s' )" % (type( self ).__name__, self.getNode())
__str__ = __repr__
def __eq__( self, other ):
'''
two buttons are equal on if all their attributes are the same
'''
return self.getCharacter() == other.getCharacter() and \
self.getPos() == other.getPos() and \
self.getSize() == other.getSize() and \
self.getColour() == other.getColour() and \
self.getLabel() == other.getLabel() and \
self.getObjs() == other.getObjs() and \
self.getCmdStr() == other.getCmdStr() and \
self.getCmdIsPython() == other.getCmdIsPython()
def __ne__( self, other ):
return not self.__eq__( other )
def __hash__( self ):
return hash( self.getNode() )
def getNode( self ):
return unicode( self.__node )
def getCharacter( self ):
cons = listConnections( self.getNode(), type='objectSet', s=False )
if cons:
return Character( cons[0] )
def getPosSize( self ):
valStr = getAttr( '%s.posSize' % self.getNode() )
if valStr is None:
return Vector( (0,0,0) ), self.DEFAULT_SIZE
posStr, sizeStr = valStr.split( ';' )
pos = Vector( [ int( p ) for p in posStr.split( ',' ) ] )
size = Vector( [ int( p ) for p in sizeStr.split( ',' ) ] )
return pos, size
def getPos( self ): return self.getPosSize()[0]
def getSize( self ): return self.getPosSize()[1]
def getColour( self ):
rgbStr = getAttr( '%s.colour' % self.getNode() )
if rgbStr is None:
return self.DEFAULT_COLOUR
rgb = rgbStr.split( ',' )
rgb = map( float, rgb )
return Colour( rgb )
def getLabel( self ):
return getAttr( '%s.label' % self.getNode() )
def getNiceLabel( self ):
labelStr = self.getLabel()
#if there is no label AND the button has objects, communicate this to the user
if not labelStr:
if len( self.getObjs() ) > 1:
return '+'
return labelStr
def getObjs( self ):
return sets( self.getNode(), q=True ) or []
def getCmdStr( self ): return getAttr( '%s.cmdStr' % self.getNode() )
def getCmdIsPython( self ): return getAttr( '%s.cmdIsPython' % self.getNode() )
def getCmdMode( self ):
try:
return getAttr( '%s.cmdMode' % self.getNode() )
except TypeError:
self.ValidateNode( self.getNode() )
return getAttr( '%s.cmdMode' % self.getNode() )
def getResolvedCmdStr( self ):
cmdStr = self.getCmdStr()
if self.getCmdIsPython():
return cmdStr % locals()
else:
return resolveCmdStr( cmdStr, self.getNode(), self.getObjs() )
def setPosSize( self, pos, size ):
#make sure the pos/size values are ints...
pos = map( int, map( round, pos ) )
size = map( int, map( round, size ) )
posStr = ','.join( map( str, pos ) )
sizeStr = ','.join( map( str, size ) )
valStr = setAttr( '%s.posSize' % self.getNode(), '%s;%s' % (posStr, sizeStr), type='string' )
def setPos( self, val ):
if not isinstance( val, Vector ):
val = Vector( val )
p, s = self.getPosSize()
self.setPosSize( val, s )
def setSize( self, val ):
if not isinstance( val, Vector ):
val = Vector( val )
p, s = self.getPosSize()
self.setPosSize( p, val )
def setColour( self, val ):
if val is None:
val = self.DEFAULT_COLOUR
valStr = ','.join( map( str, val ) )
setAttr( '%s.colour' % self.getNode(), valStr, type='string' )
def setLabel( self, val ):
if val is None:
val = ''
setAttr( '%s.label' % self.getNode(), val, type='string' )
#rename the node to reflect the label
try:
if val and isValidMayaNodeName( val ):
rename( self.getNode(), val )
else:
objs = self.getObjs()
if objs:
rename( self.getNode(), '%s_picker' % objs[0] )
else:
rename( self.getNode(), 'picker' )
#this generally happens if the node is referenced... its no big deal if the rename fails - renaming just happens to make the sets slightly more comprehendible when outliner surfing
except RuntimeError: pass
def setObjs( self, val ):
if isinstance( val, basestring ):
val = [ val ]
if not val:
return
sets( e=True, clear=self.getNode() )
sets( val, e=True, add=self.getNode() )
def setCmdStr( self, val ):
if val is None:
val = ''
setAttr( '%s.cmdStr' % self.getNode(), val, type='string' )
def setCmdIsPython( self, val ):
setAttr( '%s.cmdIsPython' % self.getNode(), val )
def setCmdMode( self, val ):
setAttr( '%s.cmdMode' % self.getNode(), val )
def setAutoColour( self, defaultColour=None ):
objs = self.getObjs()
for obj in objs:
colour = colours.getObjColour( obj )
if colour:
self.setColour( colour )
return
if defaultColour is not None:
self.setColour( defaultColour )
def select( self, forceModifiers=None, executeCmd=True ):
'''
this is what happens when a user "clicks" or "selects" this button. It handles executing the button
command in the desired order and handling object selection
'''
cmdMode = self.getCmdMode()
#if we're executing the command only, execute it and bail
if cmdMode == self.MODE_CMD_ONLY:
if executeCmd:
self.executeCmd()
return
#if we're executing the command first - do it
if cmdMode == self.MODE_CMD_FIRST:
if executeCmd:
self.executeCmd()
if forceModifiers is None:
mods = getModifiers()
else:
mods = forceModifiers
objs = self.getObjs()
if objs:
if mods & SHIFT and mods & CTRL:
select( objs, add=True )
elif mods & SHIFT:
select( objs, toggle=True )
elif mods & CTRL:
select( objs, deselect=True )
else:
select( objs )
if cmdMode == self.MODE_SELECTION_FIRST:
if executeCmd:
self.executeCmd()
def selectedState( self ):
'''
returns whether this button is partially or fully selected - return values are one of the
values in self.SELECTION_STATES
'''
objs = self.getObjs()
sel = ls( objs, sl=True )
if not sel:
return self.NONE
elif len( objs ) == len( sel ):
return self.COMPLETE
return self.PARTIAL
def moveBy( self, offset ):
pos = self.getPos()
self.setPos( pos + offset )
def exists( self ):
return objExists( self.getNode() )
def isEmpty( self ):
return not bool( self.getObjs() )
def executeCmd( self ):
'''
executes the command string for this button
'''
cmdStr = self.getResolvedCmdStr()
if cmdStr:
try:
if self.getCmdIsPython():
return eval( cmdStr )
else:
return maya.mel.eval( "{%s;}" % cmdStr )
except:
printErrorStr( 'Executing command "%s" on button "%s"' % (cmdStr, self.getNode()) )
def duplicate( self ):
dupe = self.Create( self.getCharacter(), self.getPos(), self.getSize(),
self.getColour(), self.getLabel(), self.getObjs(),
self.getCmdStr(), self.getCmdIsPython() )
return dupe
def mirrorObjs( self ):
'''
replaces the objects in this button with their name based opposites - ie if this button contained the
object ctrl_L, this method would replace the objects with ctrl_R. It uses names.swapParity
'''
oppositeObjs = []
for obj in self.getObjs():
opposite = names.swapParity( obj )
if opposite:
oppositeObjs.append( opposite )
self.setObjs( oppositeObjs )
def delete( self ):
delete( self.getNode() )
class Character(object):
'''
A Character is made up of many Button instances to select the controls or groups of controls that
comprise a puppet rig. A Character is also stored as a set node in the scene. New Character nodes
can be created using Character.Create, or existing ones instantiated by passing the set node to
Character.
'''
DEFAULT_BG_IMAGE = 'pickerGrid.bmp'
@classmethod
def IterAll( cls ):
for node in ls( type='objectSet' ):
if sets( node, q=True, text=True ) == 'zooPickerCharacter':
yield cls( node )
@classmethod
def Create( cls, name ):
'''
creates a new character for the picker tool
'''
node = sets( em=True, text='zooPickerCharacter' )
node = rename( node, name )
sets( node, e=True, add=getTopPickerSet() )
addAttr( node, ln='version', at='long' )
addAttr( node, ln='name', dt='string' )
addAttr( node, ln='bgImage', dt='string' )
addAttr( node, ln='bgColour', dt='string' )
addAttr( node, ln='filepath', dt='string' )
setAttr( '%s.version' % node, VERSION )
setAttr( '%s.name' % node, name, type='string' )
setAttr( '%s.bgImage' % node, cls.DEFAULT_BG_IMAGE, type='string' )
setAttr( '%s.bgColour' % node, '0,0,0', type='string' )
#lock the node - this stops maya from auto-deleting it if all buttons are removed
lockNode( node )
self = cls( node )
allButton = self.createButton( (5, 5), (25, 14), (1, 0.65, 0.25), 'all', [], '%(self)s.getCharacter().selectAllButtonObjs()', True )
return self
def __init__( self, node ):
self.__node = asMObject( node )
def __repr__( self ):
return "%s( '%s' )" % (type( self ).__name__, self.getNode())
__str__ = __repr__
def __eq__( self, other ):
return self.getNode() == other.getNode()
def __ne__( self, other ):
return not self.__eq__( other )
def getNode( self ):
return unicode( self.__node )
def getButtons( self ):
buttonNodes = sets( self.getNode(), q=True ) or []
return [ Button( node ) for node in buttonNodes ]
def getName( self ):
return getAttr( '%s.name' % self.getNode() )
def getBgImage( self ):
return getAttr( '%s.bgImage' % self.getNode() )
def getBgColour( self ):
colStr = getAttr( '%s.bgColour' % self.getNode() )
return Colour( [ float( c ) for c in colStr.split( ',' ) ] ).asRGB()
def getFilepath( self ):
return getAttr( '%s.filepath' % self.getNode() )
def setName( self, val ):
setAttr( '%s.name' % self.getNode(), str( val ), type='string' )
lockNode( self.getNode(), lock=False )
rename( self.getNode(), val )
lockNode( self.getNode(), lock=True )
def setBgImage( self, val ):
setAttr( '%s.bgImage' % self.getNode(), val, type='string' )
def setBgColour( self, val ):
valStr = ','.join( map( str, val ) )
setAttr( '%s.bgColour' % self.getNode(), valStr, type='string' )
def setFilepath( self, filepath ):
setAttr( '%s.filepath' % self.getNode(), filepath, type='string' )
def createButton( self, pos, size, colour=None, label=None, objs=(), cmdStr=None, cmdIsPython=False ):
'''
appends a new button to the character - a new Button instance is returned
'''
return Button.Create( self, pos, size, colour, label, objs, cmdStr, cmdIsPython )
def removeButton( self, button, delete=True ):
'''
given a Button instance, will remove it from the character
'''
for aButton in self.getButtons():
if button == aButton:
sets( button.getNode(), e=True, remove=self.getNode() )
if delete:
button.delete()
return
def breakoutButton( self, button, direction, padding=5, colour=None ):
'''
doing a "breakout" on a button will basically take each object in the button and
create a new button for it in the given direction
'''
buttonPos, buttonSize = button.getPosSize()
colour = button.getColour()
posIncrement = Vector( direction ).normalize()
posIncrement[0] *= buttonSize[0] + padding
posIncrement[1] *= buttonSize[1] + padding
newButtons = []
objs = button.getObjs()
#figure out which axis to use to sort the objects - basically figure out which axis has the highest delta between smallest and largest
posObjs = [ (Vector( xform( obj, q=True, ws=True, rp=True ) ), obj) for obj in objs ]
bestDelta, bestSorting = 0, []
for n in range( 3 ):
sortedByN = [ (objPos[n], obj) for objPos, obj in posObjs ]
sortedByN.sort()
delta = abs( sortedByN[-1][0] - sortedByN[0][0] )
if delta > bestDelta:
bestDelta, bestSorting = delta, sortedByN
#now we've figured out which axis is the most appropriate axis and have the best sorting, build the buttons
objs = [ obj for objPosN, obj in bestSorting ]
#if the direction is positive (which is down the screen in the picker), then we want to breakout the buttons in ascending hierarchical fashion
ascending = True
if direction[0] < 0 or direction[1] < 0:
ascending = False
if ascending:
objs.reverse()
for obj in objs:
buttonPos += posIncrement
button = self.createButton( buttonPos, buttonSize, objs=[ obj ] )
button.setAutoColour( colour )
newButtons.append( button )
return newButtons
def selectAllButtonObjs( self ):
for button in self.getButtons():
button.select( ADDITIVE, False )
def isEmpty( self ):
if objExists( self.getNode() ):
return not self.getButtons()
return False
def delete( self ):
for button in self.getButtons():
button.delete()
node = self.getNode()
lockNode( node, lock=False )
delete( node )
def saveToPreset( self, filepath ):
'''
stores this picker character out to disk
'''
filepath = filesystem.Path( filepath )
if filepath.exists():
filepath.editoradd()
with open( filepath, 'w' ) as fOpen:
infoDict = {}
infoDict[ 'version' ] = VERSION
infoDict[ 'name' ] = self.getName()
infoDict[ 'bgImage' ] = self.getBgImage() or ''
infoDict[ 'bgColour' ] = tuple( self.getBgColour() )
fOpen.write( str( infoDict ) )
fOpen.write( '\n' )
#the preset just needs to contain a list of buttons
for button in self.getButtons():
buttonDict = {}
pos, size = button.getPosSize()
buttonDict[ 'pos' ] = tuple( pos )
buttonDict[ 'size' ] = tuple( size )
buttonDict[ 'colour' ] = tuple( button.getColour() )
buttonDict[ 'label' ] = button.getLabel()
buttonDict[ 'objs' ] = button.getObjs()
buttonDict[ 'cmdStr' ] = button.getCmdStr()
buttonDict[ 'cmdIsPython' ] = button.getCmdIsPython()
buttonDict[ 'cmdMode' ] = button.getCmdMode()
fOpen.write( str( buttonDict ) )
fOpen.write( '\n' )
#store the filepath on the character node
self.setFilepath( filepath.unresolved() )
@classmethod
def LoadFromPreset( cls, filepath, namespaceHint=None ):
'''
'''
filepath = filesystem.Path( filepath )
#make sure the namespaceHint - if we have one - doesn't end in a semi-colon
if namespaceHint:
if namespaceHint.endswith( ':' ):
namespaceHint = namespaceHint[ :-1 ]
buttonDicts = []
with open( filepath ) as fOpen:
lineIter = iter( fOpen )
try:
infoLine = lineIter.next()
infoDict = eval( infoLine.strip() )
while True:
buttonLine = lineIter.next()
buttonDict = eval( buttonLine.strip() )
buttonDicts.append( buttonDict )
except StopIteration: pass
version = infoDict.pop( 'version', 0 )
newCharacter = cls.Create( infoDict.pop( 'name', 'A Picker' ) )
newCharacter.setBgImage( infoDict.pop( 'bgImage', cls.DEFAULT_BG_IMAGE ) )
newCharacter.setBgColour( infoDict.pop( 'bgColour', (0, 0, 0) ) )
#if there is still data in the infoDict print a warning - perhaps new data was written to the file that was handled when loading the preset?
if infoDict:
printWarningStr( 'Not all info was loaded from %s on to the character: %s still remains un-handled' % (filepath, infoDict) )
for buttonDict in buttonDicts:
newButton = Button.Create( newCharacter, buttonDict.pop( 'pos' ),
buttonDict.pop( 'size' ),
buttonDict.pop( 'colour', Button.DEFAULT_COLOUR ),
buttonDict.pop( 'label', '' ) )
newButton.setCmdStr( buttonDict.pop( 'cmdStr', '' ) )
newButton.setCmdIsPython( buttonDict.pop( 'cmdIsPython', False ) )
newButton.setCmdMode( buttonDict.pop( 'cmdMode', Button.MODE_SELECTION_FIRST ) )
#now handle objects - this is about the only tricky part - we want to try to match the objects stored to file to objects in this scene as best we can
objs = buttonDict.pop( 'objs', [] )
realObjs = []
for obj in objs:
#does the exact object exist?
if objExists( obj ):
realObjs.append( obj )
continue
#how about inserting a namespace in-between any path tokens?
pathToks = obj.split( '|' )
if namespaceHint:
objNs = '|'.join( '%s:%s' % (namespaceHint, tok) for tok in pathToks )
if objExists( objNs ):
realObjs.append( objNs )
continue
#how about ANY matches on the leaf path token?
anyMatches = ls( pathToks[-1] )
if anyMatches:
realObjs.append( anyMatches[0] )
if not namespaceHint:
namespaceHint = ':'.join( anyMatches[0].split( ':' )[ :-1 ] )
newButton.setObjs( realObjs )
#print a warning if there is still data in the buttonDict - perhaps new data was written to the file that was handled when loading the preset?
if buttonDict:
printWarningStr( 'Not all info was loaded from %s on to the character: %s still remains un-handled' % (filepath, infoDict) )
return newCharacter
def _drag( *a ):
'''
passes the local coords the widget is being dragged from
'''
return [a[-3], a[-2]]
def _drop( src, tgt, msgs, x, y, mods ):
'''
this is the drop handler used by everything in this module
'''
src = BaseMelUI.FromStr( src )
tgt = BaseMelUI.FromStr( tgt )
#if dragging an existing button around on the form, interpret it as a move
if isinstance( src, ButtonUI ) and isinstance( tgt, DragDroppableFormLayout ):
srcX, srcY = map( int, msgs )
x -= srcX
y -= srcY
#figure out the delta moved
curX, curY = src.button.getPos()
delta = x - curX, y - curY
charUI = src.getParentOfType( CharacterUI )
buttonsToMove = charUI.getSelectedButtonUIs()
#if the button dragged isn't in the selection - add it to the selection
if src not in buttonsToMove:
buttonsToMove.insert( 0, src )
charUI.setSelectedButtonUIs( buttonsToMove )
#now move all the buttons by the given delta
for buttonUI in buttonsToMove:
buttonUI.button.moveBy( delta )
buttonUI.updateGeometry( False )
#finally, refresh the BG image
charUI.refreshImage()
#if dragging from the form to the form, or dragging from the creation button, interpret it as a create new button
elif isinstance( src, CreatePickerButton ) and isinstance( tgt, DragDroppableFormLayout ) or \
isinstance( src, DragDroppableFormLayout ) and isinstance( tgt, DragDroppableFormLayout ):
characterUI = tgt.getParentOfType( CharacterUI )
if characterUI:
newButton = characterUI.createButton( (x, y) )
class ButtonUI(MelIconButton):
def __init__( self, parent, button ):
MelIconButton.__init__( self, parent )
self.setColour( button.getColour() )
assert isinstance( button, Button )
self.button = button
self.state = Button.NONE
self( e=True, dgc=_drag, dpc=_drop, style='textOnly', c=self.on_press )
self.POP_menu = MelPopupMenu( self, pmc=self.buildMenu )
self._hashGeo = 0
self._hashApp = 0
self.update()
def buildMenu( self, *a ):
menu = self.POP_menu
isEditorOpen = EditorWindow.Exists()
menu.clear()
editButtonKwargs = { 'l': 'edit this button',
'c': self.on_edit,
'ann': 'opens the button editor which allows you to edit properties of this button - colour, size, position etc...' }
if isEditorOpen:
MelMenuItem( menu, l='ADD selection to button', c=self.on_add, ann='adds the selected scene objects to this button' )
MelMenuItem( menu, l='REPLACE button with selection', c=self.on_replace, ann="replaces this button's objects with the selected scene objects" )
MelMenuItem( menu, l='REMOVE selection from button', c=self.on_remove, ann='removes the selected scene objects from this button' )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='mirror duplicate button', c=self.on_mirrorDupe )
MelMenuItem( menu, l='move to mirror position', c=self.on_mirrorThis )
MelMenuItemDiv( menu )
MelMenuItem( menu, **editButtonKwargs )
MelMenuItem( menu, l='select highlighted buttons', c=self.on_selectHighlighted, ann='selects all buttons that are highlighted (ie are %s)' % Colour.ColourToName( Button.COLOUR_COMPLETE ) )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='breakout UP', c=self.on_breakoutUp, ann='for each object in this button, creates a button above this one' )
MelMenuItem( menu, l='breakout DOWN', c=self.on_breakoutDown, ann='for each object in this button, creates a button below this one' )
MelMenuItem( menu, l='<-- breakout LEFT', c=self.on_breakoutLeft, ann='for each object in this button, creates a button to the left of this one' )
MelMenuItem( menu, l='breakout RIGHT -->', c=self.on_breakoutRight, ann='for each object in this button, creates a button to the right of this one' )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='DELETE this button', c=self.on_delete, ann='deletes the button being right clicked on' )
MelMenuItem( menu, l='DELETE selected buttons', c=self.on_deleteSelected, ann='deletes all selected buttons. NOTE: this is not necessarily the highlighted buttons - look in the button editor for the list of buttons that are selected' )
else:
class Callback(object):
def __init__( self, func, *a ):
self.f = func
self.a = a
def __call__( self, *a ):
return self.f( *self.a )
buttonObjs = self.button.getObjs()
if len( buttonObjs ) == 1:
objTrigger = Trigger( buttonObjs[0] )
for slot, menuName, menuCmd in objTrigger.iterMenus( True ):
MelMenuItem( menu, l=menuName, c=Callback( mel.eval, menuCmd ) )
MelMenuItemDiv( menu )
MelMenuItem( menu, **editButtonKwargs )
def updateHighlightState( self ):
selectedState = self.button.selectedState()
if self.state == selectedState:
return
if selectedState == Button.PARTIAL:
self.setColour( Button.COLOUR_PARTIAL )
elif selectedState == Button.COMPLETE:
self.setColour( Button.COLOUR_COMPLETE )
else:
self.setColour( self.button.getColour() )
self.state = selectedState
def isButtonHighlighted( self ):
return self.button.selectedState()
def update( self ):
self.updateGeometry()
self.updateAppearance()
self.updateHighlightState()
def updateGeometry( self, refreshUI=True ):
posSize = pos, size = self.button.getPosSize()
x, y = pos
#check against the stored hash - early out if they match
if hash( posSize ) == self._hashGeo:
return
#clamp the pos to the size of the parent
parent = self.getParent()
maxX, maxY = parent.getSize()
#x = min( max( x, 0 ), maxX ) #NOTE: this is commented out because it seems maya reports the size of the parent to be 0, 0 until there are children...
#y = min( max( y, 0 ), maxY )
parent( e=True, ap=((self, 'top', y, 0), (self, 'left', x, 0)) )
self.setSize( size )
#store the hash - geo hashes are stored so that we can do lazy refreshes
self._hashGeo = hash( posSize )
if refreshUI:
self.sendEvent( 'refreshImage' )
def updateAppearance( self ):
niceLabel = self.button.getNiceLabel()
if hash( niceLabel ) == self._hashApp:
return
self.setLabel( niceLabel )
self._hashApp = hash( niceLabel )
def mirrorDuplicate( self ):
dupe = self.button.duplicate()
dupe.mirrorObjs()
dupe.setAutoColour( self.button.getColour() )
self.mirrorPosition( dupe )
#if the button has a label - see if it has a parity and if so, reverse it
label = self.button.getLabel()
if label:
newLabel = names.swapParity( label )
dupe.setLabel( newLabel )
self.sendEvent( 'appendButton', dupe, True )
def mirrorPosition( self, button=None ):
if button is None:
button = self.button
pickerLayout = self.getParentOfType( PickerLayout )
pickerWidth = pickerLayout( q=True, w=True )
pos, size = button.getPosSize()
buttonCenterX = pos.x + (size.x / 2)
newPosX = pickerWidth - buttonCenterX - size.x
newPosX = min( max( newPosX, 0 ), pickerWidth )
button.setPos( (newPosX, pos.y) )
### EVENT HANDLERS ###
def on_press( self, *a ):
self.button.select()
self.sendEvent( 'buttonSelected', self )
def on_add( self, *a ):
objs = self.button.getObjs()
objs += ls( sl=True ) or []
self.button.setObjs( objs )
def on_replace( self, *a ):
self.button.setObjs( ls( sl=True ) or [] )
def on_remove( self, *a ):
objs = self.button.getObjs()
objs += ls( sl=True ) or []
self.button.setObjs( objs )
def on_mirrorDupe( self, *a ):
self.mirrorDuplicate()
def on_mirrorThis( self, *a ):
self.mirrorPosition()
self.updateGeometry()
def on_edit( self, *a ):
self.sendEvent( 'buttonSelected', self )
self.sendEvent( 'on_showEditor' )
def on_selectHighlighted( self, *a ):
self.sendEvent( 'selectHighlightedButtons' )
def on_breakoutUp( self, *a ):
self.sendEvent( 'breakoutButton', self, (0, -1) )
def on_breakoutDown( self, *a ):
self.sendEvent( 'breakoutButton', self, (0, 1) )
def on_breakoutLeft( self, *a ):
self.sendEvent( 'breakoutButton', self, (-1, 0) )
def on_breakoutRight( self, *a ):
self.sendEvent( 'breakoutButton', self, (1, 0) )
def on_delete( self, *a ):
self.delete()
self.button.delete()
self.sendEvent( 'refreshImage' )
self.sendEvent( 'updateButtonList' )
def on_deleteSelected( self, *a ):
self.sendEvent( 'deleteSelectedButtons' )
class MelPicture(BaseMelWidget):
WIDGET_CMD = picture
def getImage( self ):
return self( q=True, i=True )
def setImage( self, image ):
self( e=True, i=image )
class DragDroppableFormLayout(MelFormLayout):
def __init__( self, parent, **kw ):
MelFormLayout.__init__( self, parent, **kw )
self( e=True, dgc=_drag, dpc=_drop )
class CharacterUI(MelHLayout):
def __init__( self, parent, character ):
self.character = character
self._selectedButtonUIs = []
self.UI_picker = MelPicture( self, en=False, dgc=_drag, dpc=_drop )
self.UI_picker.setImage( character.getBgImage() )
self.layout()
self.UI_buttonLayout = UI_buttonLayout = DragDroppableFormLayout( self )
self( e=True, af=((UI_buttonLayout, 'top', 0), (UI_buttonLayout, 'left', 0), (UI_buttonLayout, 'right', 0), (UI_buttonLayout, 'bottom', 0)) )
self.populate()
self.highlightButtons()
self.setDeletionCB( self.on_close )
def populate( self ):
for button in self.character.getButtons():
self.appendButton( button )
def updateEditor( self ):
self.sendEvent( 'updateEditor' )
def updateButtonList( self ):
self.sendEvent( 'updateButtonList' )
def createButton( self, pos, size=Button.DEFAULT_SIZE, colour=Button.AUTO_COLOUR, label='', objs=None ):
if objs is None:
objs = ls( sl=True, type='transform' )
newButton = Button.Create( self.character, pos, size, colour, label, objs )
#we want the drop position to be the centre of the button, not its edge - so we need to factor out the size, which we can only do after instantiating the button so we can query its size
sizeHalf = newButton.getSize() / 2.0
newButton.setPos( Vector( pos ) - sizeHalf )
self.appendButton( newButton, True )
#tell the editor to update the button list
self.sendEvent( 'updateButtonList' )
return newButton
def appendButton( self, button, select=False ):
ui = ButtonUI( self.UI_buttonLayout, button )
if select:
self.buttonSelected( ui )
self.updateButtonList()
return ui
def highlightButtons( self ):
for buttonUI in self.getButtonUIs():
buttonUI.updateHighlightState()
def getSelectedButtonUIs( self ):
selButtonUIs = []
for buttonUI in self._selectedButtonUIs:
if buttonUI.button.exists():
selButtonUIs.append( buttonUI )
return selButtonUIs
def setSelectedButtonUIs( self, buttonUIs ):
self._selectedButtonUIs = buttonUIs[:]
self.updateEditor()
def selectHighlightedButtons( self ):
currentSelection = []
for buttonUI in self.getButtonUIs():
if buttonUI.isButtonHighlighted() == Button.COMPLETE:
currentSelection.append( buttonUI )
self.setSelectedButtonUIs( currentSelection )
def breakoutButton( self, buttonUI, direction ):
buttons = self.character.breakoutButton( buttonUI.button, direction )
for button in buttons:
self.appendButton( button )
def refreshImage( self ):
self.UI_picker.setVisibility( False )
self.UI_picker.setVisibility( True )
self.updateEditor()
def buttonSelected( self, button ):
mods = getModifiers()
if mods & SHIFT and mods & CTRL:
if button not in self._selectedButtonUIs:
self._selectedButtonUIs.append( button )
elif mods & CTRL:
if button in self._selectedButtonUIs:
self._selectedButtonUIs.remove( button )
elif mods & SHIFT:
if button in self._selectedButtonUIs:
self._selectedButtonUIs.remove( button )
else:
self._selectedButtonUIs.append( button )
else:
self._selectedButtonUIs = [ button ]
self.updateEditor()
def getButtonUIs( self ):
return self.UI_buttonLayout.getChildren()
def clearEmptyButtons( self ):
needToRefresh = False
for buttonUI in self.getButtonUIs():
if buttonUI.button.isEmpty():
buttonUI.button.delete()
buttonUI.delete()
needToRefresh = True
if needToRefresh:
self.refreshImage()
def delete( self ):
self.character.delete()
MelHLayout.delete( self )
def deleteSelectedButtons( self ):
selectedButtonUIs = self.getSelectedButtonUIs()
for buttonUI in selectedButtonUIs:
buttonUI.button.delete()
buttonUI.delete()
self.refreshImage()
self.updateButtonList()
### EVENT HANDLERS ###
def on_close( self, *a ):
CmdEditorWindow.Close()
class CreatePickerButton(MelButton):
'''
this class exists purely so we can test for it instead of having to test against
a more generic "MelButton" instance when handling drop callbacks
'''
pass
class MelColourSlider(BaseMelWidget):
WIDGET_CMD = colorSliderGrp
KWARG_VALUE_NAME = 'rgb'
KWARG_VALUE_LONG_NAME = 'rgbValue'
class CmdEditorLayout(MelVSingleStretchLayout):
def __init__( self, parent, buttonUIs ):
self.UI_cmd = MelTextScrollField( self )
#add the popup menu to the cmd editor
MelPopupMenu( self.UI_cmd, pmc=self.buildMenu )
hLayout = MelHLayout( self )
self.UI_isPython = MelCheckBox( hLayout, l='Command is Python' )
self.UI_cmdMode = MelOptionMenu( hLayout, l='Command Mode' )
for modeStr in Button.CMD_MODES_NAMES:
self.UI_cmdMode.append( modeStr )
hLayout.layout()
hLayout = MelHLayout( self )
self.UI_save = MelButton( hLayout, l='Save and Close', c=self.on_saveClose )
self.UI_delete = MelButton( hLayout, l='Delete and Close', c=self.on_deleteClose )
self.UI_cancel = MelButton( hLayout, l='Cancel', c=self.on_cancel )
hLayout.layout()
self.setStretchWidget( self.UI_cmd )
self.layout()
self.setButtons( buttonUIs )
def buildMenu( self, menu, menuParent ):
cmd.menu( menu, e=True, dai=True )
MelMenuItem( menu, l='save preset', en=bool( self.UI_cmd.getValue() ), c=self.on_savePreset )
presetMenu = MelMenuItem( menu, l='load preset', sm=True )
presetManager = filesystem.PresetManager( TOOL_NAME, TOOL_CMD_EXTENSION )
for locale, presets in presetManager.listAllPresets().iteritems():
for p in presets:
MelMenuItem( presetMenu, l=p.name(), c=Callback( self.loadPreset, p ) )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='manage presets', c=lambda *a: presetsUI.load( TOOL_NAME, ext=TOOL_CMD_EXTENSION ) )
def loadPreset( self, preset, *a ):
cmdStrLines = filesystem.Path( preset ).read()
firstLine = cmdStrLines.pop( 0 )
cmdIsPython = 'python' in firstLine
self.UI_cmd.setValue( '\n'.join( cmdStrLines ) )
self.UI_isPython.setValue( cmdIsPython )
def savePreset( self ):
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
ret = promptDialog( t='Preset Name', m='Enter the preset name', b=BUTTONS, db=OK )
if ret == OK:
name = promptDialog( q=True, tx=True )
if name:
cmdStrLines = [ '//'+ ('python' if self.UI_isPython.getValue() else 'mel') ]
cmdStrLines.append( self.UI_cmd.getValue() )
preset = filesystem.Preset( filesystem.GLOBAL, TOOL_NAME, name, TOOL_CMD_EXTENSION )
preset.write( '\n'.join( cmdStrLines ) )
def setButtons( self, buttonUIs ):
self.buttonUIs = buttonUIs
self.update()
def update( self ):
button = self.buttonUIs[0].button
self.UI_cmd.setValue( button.getCmdStr() or '' )
self.UI_isPython.setValue( button.getCmdIsPython() )
self.UI_cmdMode.selectByIdx( button.getCmdMode() )
### EVENT HANDLERS ###
def on_savePreset( self, *a ):
self.savePreset()
@d_unifyUndo
def on_saveClose( self, *a ):
for buttonUI in self.buttonUIs:
buttonUI.button.setCmdStr( self.UI_cmd.getValue() )
buttonUI.button.setCmdIsPython( self.UI_isPython.getValue() )
buttonUI.button.setCmdMode( self.UI_cmdMode.getSelectedIdx() )
for ui in PickerLayout.IterInstances():
ui.updateEditor()
self.sendEvent( 'delete' )
@d_unifyUndo
def on_deleteClose( self, *a ):
for buttonUI in self.buttonUIs:
buttonUI.button.setCmdStr( None )
for ui in PickerLayout.IterInstances():
ui.updateEditor()
self.sendEvent( 'delete' )
def on_cancel( self, *a ):
self.sendEvent( 'delete' )
class CmdEditorWindow(BaseMelWindow):
WINDOW_NAME = 'PickerButtonCommandEditor'
WINDOW_TITLE = 'Command Editor'
DEFAULT_MENU = None
DEFAULT_SIZE = 450, 200
FORCE_DEFAULT_SIZE = True
def __init__( self, button ):
self.UI_editor = CmdEditorLayout( self, button )
self.show()
class ButtonList(MelObjectScrollList):
def itemAsStr( self, item ):
return item.button.getNode().split( ':' )[-1].split( '|' )[-1].replace( '_picker', '' )
class EditorLayout(MelVSingleStretchLayout):
DIRECTIONS = DIR_H, DIR_V = range( 2 )
def __init__( self, parent, pickerUI ):
self.pickerUI = pickerUI
self.expand = True
self.padding = 0
lblWidth = 40
self.UI_buttonLbl = MelLabel( self, align='center' )
self.UI_new = CreatePickerButton( self, l='Create Button: middle drag to place', dgc=_drag, dpc=_drop )
MelSeparator( self, h=16 )
hLayout = MelHSingleStretchLayout( self )
hLayout.expand = True
vLayout = MelVSingleStretchLayout( hLayout )
self.UI_buttons = ButtonList( vLayout, w=100, ams=True, sc=self.on_selectButtonFromList, dcc=self.on_doubleClickButton )
self.UI_selectHighlighted = MelButton( vLayout, l='select highlighted', c=self.on_selectHighlighted )
vLayout.padding = 0
vLayout.setStretchWidget( self.UI_buttons )
vLayout.layout()
selLayout = MelVSingleStretchLayout( hLayout )
selLayout.padding = 0
#UI for label
SZ_lblLabel = MelHSingleStretchLayout( selLayout )
lbl = MelLabel( SZ_lblLabel, l='label:', w=lblWidth )
SZ_label = MelHSingleStretchLayout( SZ_lblLabel )
self.UI_selectedLabel = MelTextField( SZ_label )
self.UI_autoSize = MelButton( SZ_label, l='fit to label', c=self.on_autoSize )
SZ_label.setStretchWidget( self.UI_selectedLabel )
SZ_label.layout()
SZ_lblLabel.setStretchWidget( SZ_label )
SZ_lblLabel.layout()
#UI for colour
self.UI_selectedColour = MelColourSlider( selLayout, label='colour:', cw=(1, lblWidth + 7), columnAttach=((1, 'left', 0), (2, 'left', 0), (3, 'left', 0)), adj=3 )
#UI for position
SZ_lblPos = MelHSingleStretchLayout( selLayout )
lbl = MelLabel( SZ_lblPos, l='pos:', w=lblWidth )
SZ_pos = MelHLayout( SZ_lblPos )
SZ_lblPos.setStretchWidget( SZ_pos )
SZ_lblPos.layout()
SZ_X = MelHSingleStretchLayout( SZ_pos )
self.UI_selectedPosX = MelIntField( SZ_X, min=0, max=640, step=1, cc=self.on_savePosX )
self.UI_selectedNudgeXL = MelButton( SZ_X, l='<', c=self.on_nudgeXL )
self.UI_selectedNudgeXR = MelButton( SZ_X, l='>', c=self.on_nudgeXR )
SZ_X.setStretchWidget( self.UI_selectedPosX )
SZ_Y = MelHSingleStretchLayout( SZ_pos )
self.UI_selectedPosY = MelIntField( SZ_Y, min=0, max=640, step=1, cc=self.on_savePosY )
self.UI_selectedNudgeYU = MelButton( SZ_Y, l='^', c=self.on_nudgeYU )
self.UI_selectedNudgeYD = MelButton( SZ_Y, l='v', c=self.on_nudgeYD )
SZ_Y.setStretchWidget( self.UI_selectedPosY )
SZ_X.padding = 0
SZ_Y.padding = 0
SZ_X.layout()
SZ_Y.layout()
SZ_pos.layout()
#UI for align buttons
thinButton = 18
SZ_lblAlignX = MelHSingleStretchLayout( selLayout )
MelLabel( SZ_lblAlignX, l='align:', w=lblWidth )
SZ_alignX = MelHLayout( SZ_lblAlignX )
SZ_lblAlignX.setStretchWidget( SZ_alignX )
SZ_lblAlignX.layout()
MelButton( SZ_alignX, l='horiz', h=thinButton, c=self.on_alignH )
MelButton( SZ_alignX, l='vert', h=thinButton, c=self.on_alignV )
SZ_alignX.layout()
#UI for size
SZ_lblSize = MelHSingleStretchLayout( selLayout )
lbl = MelLabel( SZ_lblSize, l='scale:', w=lblWidth )
SZ_size = MelHLayout( SZ_lblSize )
SZ_lblSize.setStretchWidget( SZ_size )
SZ_lblSize.layout()
self.UI_selectedScaleX = MelIntField( SZ_size, min=Button.MIN_SIZE, max=Button.MAX_SIZE, step=1, v=Button.MIN_SIZE, cc=self.on_saveScaleX )
self.UI_selectedScaleY = MelIntField( SZ_size, min=Button.MIN_SIZE, max=Button.MAX_SIZE, step=1, v=Button.MIN_SIZE, cc=self.on_saveScaleY )
SZ_size.layout()
#setup change callbacks
self.UI_selectedLabel.setChangeCB( self.on_saveLabel )
self.UI_selectedColour.setChangeCB( self.on_saveColour )
#add UI to edit the button set node
self.UI_selectedObjects = MelSetMemebershipList( selLayout, h=75 )
self.UI_selectedCmdButton = MelButton( selLayout, l='', c=self.on_editCmd )
hLayout.setStretchWidget( selLayout )
hLayout.layout()
selLayout.setStretchWidget( self.UI_selectedObjects )
selLayout.layout()
self.setStretchWidget( hLayout )
self.layout()
self.setDeletionCB( self.on_delete )
def getCurrentCharacterUI( self ):
return self.pickerUI.getCurrentCharacterUI()
def getSelectedButtonUIs( self ):
return self.pickerUI.getSelectedButtonUIs()
def updateButtonList( self ):
currentCharacterUI = self.getCurrentCharacterUI()
if currentCharacterUI is None:
return
self.UI_buttons.setItems( currentCharacterUI.getButtonUIs() )
def update( self, selectInList=True ):
currentCharacterUI = self.getCurrentCharacterUI()
if not currentCharacterUI:
self.UI_buttonLbl.setLabel( 'create a character first!' )
self.UI_new.setEnabled( False )
return
self.UI_new.setEnabled( True )
#make sure the selected buttons exist
selectedButtonUIs = self.getSelectedButtonUIs()
existingButtonUIs = []
for buttonUI in selectedButtonUIs:
if buttonUI.button.exists():
existingButtonUIs.append( buttonUI )
#if there buttons selected...
if existingButtonUIs:
button = existingButtonUIs[0].button
pos, size = button.getPosSize()
self.UI_buttonLbl.setLabel( 'editing button "%s"' % button.getNode() )
self.UI_selectedLabel.setValue( button.getLabel(), False )
self.UI_selectedPosX.setValue( pos.x, False )
self.UI_selectedPosY.setValue( pos.y, False )
self.UI_selectedScaleX.setValue( size.x, False )
self.UI_selectedScaleY.setValue( size.y, False )
self.UI_selectedColour.setValue( button.getColour(), False )
#set set editor edits sets for ALL selected buttons
self.UI_selectedObjects.setSets( [ b.button.getNode() for b in existingButtonUIs ] )
#update the auto size from label button
self.UI_autoSize.enable( bool( button.getLabel() ) )
#update the command editor button
self.UI_selectedCmdButton.setEnabled( bool( existingButtonUIs ) )
cmdStr = button.getCmdStr()
if cmdStr:
self.UI_selectedCmdButton.setLabel( '***EDIT*** Press Command' )
else:
self.UI_selectedCmdButton.setLabel( 'CREATE Press Command' )
#update the selected buttons lists
if selectInList:
self.UI_buttons.clearSelection()
self.UI_buttons.selectItems( existingButtonUIs )
else:
self.UI_buttonLbl.setLabel( 'no button selected!' )
def nudge( self, buttonUI, vectorIdx, direction=1 ):
mods = getModifiers()
increment = 5
if mods & SHIFT:
increment += 5
elif mods & CTRL:
increment = 5
elif mods & ALT:
increment = 1
pos = buttonUI.button.getPos()
pos[ vectorIdx ] += direction * increment
buttonUI.button.setPos( pos )
buttonUI.update()
def align( self, buttonUI, side=DIR_H ):
pos, size = buttonUI.button.getPosSize()
midHSide = pos[0] + (size[0] / 2.0)
midVSide = pos[1] + (size[1] / 2.0)
for b in self.getSelectedButtonUIs():
if b is buttonUI:
continue
if side == self.DIR_H:
pos, size = b.button.getPosSize()
pos[0] = midHSide - (size[0] / 2.0)
b.button.setPos( pos )
elif side == self.DIR_V:
pos, size = b.button.getPosSize()
pos[1] = midVSide - (size[1] / 2.0)
b.button.setPos( pos )
b.update()
### EVENT HANDLERS ###
def on_selectButtonFromList( self, *a ):
charUI = self.pickerUI.getCurrentCharacterUI()
if charUI:
selectedButtonUIs = self.UI_buttons.getSelectedItems()
self.pickerUI.getCurrentCharacterUI().setSelectedButtonUIs( selectedButtonUIs )
for buttonUI in selectedButtonUIs:
buttonUI.button.select( CTRL | SHIFT )
self.update( False )
charUI.highlightButtons()
@d_unifyUndo
def on_doubleClickButton( self, *a ):
pass
@d_unifyUndo
def on_selectHighlighted( self, *a ):
currentCharacterUI = self.getCurrentCharacterUI()
if currentCharacterUI:
currentCharacterUI.selectHighlightedButtons()
@d_unifyUndo
def on_autoSize( self, *a ):
minHeight = 14
extraPadding = 15
for buttonUI in self.getSelectedButtonUIs():
button = buttonUI.button
label = button.getLabel()
if label:
curSize = button.getSize()
width = getLabelWidth( label ) + extraPadding
height = max( minHeight, curSize[1] )
button.setSize( (width, height) )
buttonUI.updateGeometry()
self.update()
@d_unifyUndo
def on_nudgeXL( self, *a ):
for buttonUI in self.getSelectedButtonUIs():
self.nudge( buttonUI, 0, -1 )
@d_unifyUndo
def on_nudgeXR( self, *a ):
for buttonUI in self.getSelectedButtonUIs():
self.nudge( buttonUI, 0, 1 )
@d_unifyUndo
def on_nudgeYU( self, *a ):
for buttonUI in self.getSelectedButtonUIs():
self.nudge( buttonUI, 1, -1 )
@d_unifyUndo
def on_nudgeYD( self, *a ):
for buttonUI in self.getSelectedButtonUIs():
self.nudge( buttonUI, 1, 1 )
@d_unifyUndo
def on_alignH( self, *a ):
self.align( self.getSelectedButtonUIs()[0], self.DIR_H )
@d_unifyUndo
def on_alignV( self, *a ):
self.align( self.getSelectedButtonUIs()[0], self.DIR_V )
@d_unifyUndo
def on_saveLabel( self, *a ):
label = self.UI_selectedLabel.getValue()
for buttonUI in self.getSelectedButtonUIs():
buttonUI.button.setLabel( label )
buttonUI.update()
self.UI_buttons.update()
@d_unifyUndo
def on_saveColour( self, *a ):
colour = self.UI_selectedColour.getValue()
for buttonUI in self.getSelectedButtonUIs():
buttonUI.button.setColour( colour )
buttonUI.update()
@d_unifyUndo
def on_savePosX( self, *a ):
poxX = self.UI_selectedPosX.getValue()
for buttonUI in self.getSelectedButtonUIs():
pos = buttonUI.button.getPos()
pos[0] = poxX
buttonUI.button.setPos( pos )
buttonUI.update()
@d_unifyUndo
def on_savePosY( self, *a ):
posY = self.UI_selectedPosY.getValue()
for buttonUI in self.getSelectedButtonUIs():
pos = buttonUI.button.getPos()
pos[1] = posY
buttonUI.button.setPos( pos )
buttonUI.update()
@d_unifyUndo
def on_saveScaleX( self, *a ):
sizeX = self.UI_selectedScaleX.getValue()
for buttonUI in self.getSelectedButtonUIs():
size = buttonUI.button.getSize()
size[0] = sizeX
buttonUI.button.setSize( size )
buttonUI.update()
@d_unifyUndo
def on_saveScaleY( self, *a ):
sizeY = self.UI_selectedScaleY.getValue()
for buttonUI in self.getSelectedButtonUIs():
size = buttonUI.button.getSize()
size[1] = sizeY
buttonUI.button.setSize( size )
buttonUI.update()
def on_editCmd( self, *a ):
CmdEditorWindow( self.getSelectedButtonUIs() )
def on_delete( self, *a ):
CmdEditorWindow.Close()
class EditorWindow(BaseMelWindow):
WINDOW_NAME = 'pickerEditorWindow'
WINDOW_TITLE = 'Picker Editor'
DEFAULT_SIZE = 450, 400
DEFAULT_MENU = None
FORCE_DEFAULT_SIZE = True
def __init__( self, pickerUI ):
self.pickerUI = pickerUI
self.UI_editor = EditorLayout( self, pickerUI )
#kill the window when the scene changes
self.setSceneChangeCB( self.on_sceneChange )
self.show()
def update( self ):
self.UI_editor.update()
def updateButtonList( self ):
self.UI_editor.updateButtonList()
### EVENT HANDLERS ###
def on_sceneChange( self ):
self.close()
class PickerLayout(MelVSingleStretchLayout):
def __init__( self, parent ):
self.UI_tabs = tabs = MelTabLayout( self )
self.UI_tabs.setChangeCB( self.on_tabChange )
self.UI_showEditorButton = MelButton( self, l='Show Editor', c=self.on_showEditor )
self.padding = 0
self.setStretchWidget( tabs )
self.layout()
#build an editor - but keep it hidden
self.UI_editor = None
#setup up the UI
self.populate()
#update button state when the selection changes
self.setSelectionChangeCB( self.on_selectionChange )
#make sure the UI gets updated when the scene changes
self.setSceneChangeCB( self.on_sceneChange )
#hook up an undo callback to undo button changes and update the UI
self.setUndoCB( self.on_undo )
#hook up a deletion callback
self.setDeletionCB( self.on_delete )
def setUndoCbState( self, state ):
if state:
self.setUndoCB( self.on_undo )
else:
self.setUndoCB( None )
def populate( self ):
self.UI_tabs.clear()
for character in Character.IterAll():
self.appendCharacter( character )
def appendCharacter( self, character ):
idx = len( self.UI_tabs.getChildren() )
ui = CharacterUI( self.UI_tabs, character )
self.UI_tabs.setLabel( idx, character.getName() )
def getCurrentCharacterUI( self ):
selUI = self.UI_tabs.getSelectedTab()
if selUI:
return CharacterUI.FromStr( selUI )
return None
def getSelectedButtonUIs( self ):
selectedTab = self.UI_tabs.getSelectedTab()
if selectedTab:
currentCharacter = CharacterUI.FromStr( selectedTab )
if currentCharacter:
return currentCharacter.getSelectedButtonUIs()
return []
def selectCharacter( self, character ):
for idx, ui in enumerate( self.UI_tabs.getChildren() ):
if ui.character == character:
self.UI_tabs.setSelectedTabIdx( idx )
def isEditorOpen( self ):
if self.UI_editor is None:
return False
return self.UI_editor.exists()
def updateEditor( self ):
if self.isEditorOpen():
self.UI_editor.update()
def updateButtonList( self ):
if self.isEditorOpen():
self.UI_editor.updateButtonList()
def loadPreset( self, preset, *a ): #*a exists only because this gets directly called by a menuItem - and menuItem's always pass a bool arg for some reason... check state maybe?
namespaceHint = None
#if there is a selection, use any namespace on the selection as the namespace hint
sel = ls( sl=True, type='transform' )
if sel:
namespaceHint = sel[0].split( ':' )[0]
newCharacter = Character.LoadFromPreset( preset, namespaceHint )
if newCharacter:
self.appendCharacter( newCharacter )
else:
printWarningStr( 'No character was created!' )
def renameCurrentCharacter( self, newName ):
charUIStr = self.UI_tabs.getSelectedTab()
if charUIStr:
charUI = CharacterUI.FromStr( charUIStr )
if charUI:
charUI.character.setName( newName )
charUIIdx = self.UI_tabs.getSelectedTabIdx()
self.UI_tabs.setLabel( charUIIdx, charUI.character.getName() )
def clearEmptyButtons( self ):
charUI = self.getCurrentCharacterUI()
if charUI:
charUI.clearEmptyButtons()
### EVENT HANDLERS ###
def on_showEditor( self, *a ):
if not self.isEditorOpen():
self.UI_editor = EditorWindow( self )
self.updateButtonList()
self.updateEditor()
def on_tabChange( self, *a ):
if self.isEditorOpen():
self.UI_editor.updateButtonList()
self.on_selectionChange()
def on_sceneChange( self, *a ):
self.populate()
def on_selectionChange( self, *a ):
charUIStr = self.UI_tabs.getSelectedTab()
if charUIStr:
charUI = CharacterUI.FromStr( charUIStr )
charUI.highlightButtons()
def on_undo( self, *a ):
#check to see if the user only wants the undo to work if the editor is open
undoOnlyIfEditorOpen = optionVar( q='zooUndoOnlyIfEditorOpen' )
if undoOnlyIfEditorOpen:
if not self.isEditorOpen():
return
charUI = self.getCurrentCharacterUI()
if charUI:
self.updateEditor()
self.updateButtonList()
for buttonUI in charUI.getButtonUIs():
buttonUI.updateGeometry()
buttonUI.updateAppearance()
def on_delete( self, *a ):
EditorWindow.Close()
class PickerWindow(BaseMelWindow):
WINDOW_NAME = 'zooPicker'
WINDOW_TITLE = 'Picker Tool'
DEFAULT_SIZE = 275, 525
DEFAULT_MENU = 'File'
DEFAULT_MENU_IS_HELP = False
FORCE_DEFAULT_SIZE = True
HELP_MENU = 'hamish@macaronikazoo.com', TOOL_NAME, None
def __init__( self ):
fileMenu = self.getMenu( 'File' )
fileMenu( e=True, pmc=self.buildFileMenu )
self.UI_editor = PickerLayout( self )
self.show()
def buildFileMenu( self ):
menu = self.getMenu( 'File' )
menu.clear()
currentCharUI = self.UI_editor.getCurrentCharacterUI()
charSelected = bool( currentCharUI )
charSelectedIsReferenced = True
if charSelected:
charSelectedIsReferenced = referenceQuery( currentCharUI.character.getNode(), inr=True )
MelMenuItem( menu, l='New Picker Tab', c=self.on_create )
MelMenuItem( menu, en=charSelected, l='Rename Current Picker Tab', c=self.on_rename )
MelMenuItem( menu, en=not charSelectedIsReferenced, l='Remove Current Picker Tab', c=self.on_remove )
MelMenuItemDiv( menu )
MelMenuItem( menu, en=not charSelectedIsReferenced, l='Remove Empty Buttons', c=self.on_clearEmpty )
MelMenuItem( menu, en=charSelectedIsReferenced, l='Remove Edits To Referenced Picker', c=self.on_clearRefEdits )
MelMenuItemDiv( menu )
MelMenuItem( menu, en=charSelected, l='Save Picker Preset', c=self.on_save )
self.SUB_presets = MelMenuItem( menu, l='Load Picker Preset', sm=True, pmc=self.buildLoadablePresets )
undoOnlyIfEditorOpen = optionVar( q='zooUndoOnlyIfEditorOpen' )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='Only Refresh On Undo If Editor Open', cb=undoOnlyIfEditorOpen, c=self.on_undoPrefChange )
def buildLoadablePresets( self, *a ):
menu = self.SUB_presets
man = filesystem.PresetManager( TOOL_NAME, TOOL_EXTENSION )
presets = man.listAllPresets()
for loc, locPresets in presets.iteritems():
for p in locPresets:
pName = p.name()
MelMenuItem( menu, l=pName, c=Callback( self.UI_editor.loadPreset, p ) )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='manage presets', c=self.on_loadPresetManager )
### EVENT HANDLERS ###
def on_create( self, *a ):
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
defaultName = filesystem.Path( file( q=True, sn=True ) ).name()
ret = promptDialog( t='Create Picker Tab', m='Enter a name for the new picker tab:', text=defaultName, b=BUTTONS, db=OK )
if ret == OK:
name = promptDialog( q=True, text=True )
if name:
newCharacter = Character.Create( name )
self.UI_editor.populate()
self.UI_editor.selectCharacter( newCharacter )
self.UI_editor.on_showEditor()
def on_rename( self, *a ):
currentCharacterUI = self.UI_editor.getCurrentCharacterUI()
if currentCharacterUI:
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
ret = promptDialog( t='New Name', m='Enter the new name for the picker', tx=currentCharacterUI.character.getName(), b=BUTTONS, db=OK )
if ret == OK:
newName = promptDialog( q=True, tx=True )
if not newName:
printWarningStr( "You must enter a name!" )
return
self.UI_editor.renameCurrentCharacter( newName )
def on_remove( self, *a ):
currentCharacterUI = self.UI_editor.getCurrentCharacterUI()
if currentCharacterUI:
currentCharacterUI.delete()
def on_clearEmpty( self, *a ):
self.UI_editor.clearEmptyButtons()
def on_clearRefEdits( self, *a ):
currentCharacterUI = self.UI_editor.getCurrentCharacterUI()
if currentCharacterUI:
objs = [ currentCharacterUI.character.getNode() ]
objs += [ button.getNode() for button in currentCharacterUI.character.getButtons() ]
removeRefEdits( objs )
self.UI_editor.populate()
def on_save( self, *a ):
currentChar = self.UI_editor.getCurrentCharacterUI()
if currentChar:
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
ret = promptDialog( t='Preset Name', m='enter the name of the preset', tx=currentChar.character.getName(), b=BUTTONS, db=OK )
if ret == OK:
presetName = promptDialog( q=True, tx=True )
if presetName:
currentChar.character.saveToPreset( filesystem.Preset( filesystem.GLOBAL, TOOL_NAME, presetName, TOOL_EXTENSION ) )
def on_loadPresetManager( self, *a ):
presetsUI.load( TOOL_NAME, ext=TOOL_EXTENSION )
def on_undoPrefChange( self, *a ):
undoOnlyIfEditorOpen = optionVar( iv=('zooUndoOnlyIfEditorOpen', int( a[0] )) )
#end
| Python |
from maya.cmds import *
from names import Parity, Name, camelCaseToNice
from vectors import Vector, Colour
from control import attrState, NORMAL, HIDE, LOCK_HIDE, NO_KEY
from apiExtensions import asMObject, castToMObjects, cmpNodes
from mayaDecorators import d_unifyUndo
from maya.OpenMaya import MGlobal
from referenceUtils import ReferencedNode
import names
import filesystem
import typeFactories
import inspect
import meshUtils
import maya.cmds as cmd
import profileDecorators
#now do maya imports and maya specific assignments
import api
import maya.cmds as cmd
import rigUtils
from rigUtils import ENGINE_FWD, ENGINE_UP, ENGINE_SIDE
from rigUtils import MAYA_SIDE, MAYA_FWD, MAYA_UP
from rigUtils import Axis, resetSkinCluster
mel = api.mel
AXES = Axis.BASE_AXES
eval = __builtins__[ 'eval' ] #restore the eval function to point to python's eval
mayaVar = float( mel.eval( 'getApplicationVersionAsFloat()' ) )
TOOL_NAME = 'skeletonBuilder'
CHANNELS = ('x', 'y', 'z')
TYPICAL_HEIGHT = 70 #maya units
HUD_NAME = 'skeletonBuilderJointCountHUD'
#these are the symbols to use as standard rotation axes on bones...
BONE_AIM_VECTOR = ENGINE_FWD #this is the axis the joint should bank around, in general the axis the "aims" at the child joint
BONE_ROTATE_VECTOR = ENGINE_SIDE #this is the axis of "primary rotation" for the joint. for example, the elbow would rotate primarily in this axis, as would knees and fingers
BONE_AIM_AXIS = Axis.FromVector( BONE_AIM_VECTOR )
BONE_ROTATE_AXIS = Axis.FromVector( BONE_ROTATE_VECTOR )
_tmp = BONE_AIM_AXIS.otherAxes()
_tmp.remove( BONE_ROTATE_AXIS )
BONE_OTHER_AXIS = _tmp[0] #this is the "other" axis - ie the one thats not either BONE_AIM_AXIS or BONE_ROTATE_AXIS
BONE_OTHER_VECTOR = BONE_OTHER_AXIS.asVector()
del( _tmp )
getLocalAxisInDirection = rigUtils.getLocalAxisInDirection
getPlaneNormalForObjects = rigUtils.getPlaneNormalForObjects
#try to load the zooMirror.py plugin
try:
loadPlugin( 'zooMirror.py', quiet=True )
except:
import zooToolbox
zooToolbox.loadZooPlugin( 'zooMirror.py' )
def getScaleFromMeshes():
'''
determines a scale based on the visible meshes in the scene. If no visible
meshes are found, the TYPICAL_HEIGHT value is returend
'''
def isVisible( node ):
if not getAttr( '%s.v' % node ):
return False
for p in iterParents( node ):
if not getAttr( '%s.v' % p ): return False
return True
visibleMeshes = [ m for m in (ls( type='mesh' ) or []) if isVisible( m ) ]
if not visibleMeshes:
return TYPICAL_HEIGHT
return rigUtils.getObjsScale( visibleMeshes )
def getScaleFromSkeleton():
#lets see if there is a Root part already
scale = 0
for root in Root.IterAllParts():
t = Vector( getAttr( '%s.t' % root[0] )[0] )
scale = t.y
scale *= 1.75 #the root is roughly 4 head heights from the ground and the whole body is about 7 head heights - hence 1.75 (7/4)
#lets see if there is a spine part - between the root and the spine, we can get a
#pretty good idea of the scale for most anatomy types
scaleFromSpine = 0
spineCls = SkeletonPart.GetNamedSubclass( 'Spine' )
if spineCls is not None:
numSpines = 0
for spine in spineCls.IterAllParts():
items = spine.items
items.append( spine.getParent() )
mnx, mny, mnz, mxx, mxy, mxz = rigUtils.getTranslationExtents( items )
XYZ = mxx-mnx, mxy-mny, mxz-mnz
maxLen = max( XYZ ) * 1.5
scaleFromSpine += maxLen
numSpines += 1
#if there were spine parts found, average their scales, add them to the root scale and average them again
if numSpines:
scaleFromSpine /= float( numSpines )
scaleFromSpine *= 2.3 #ths spine is roughly 3 head heights, while the whole body is roughly 7 head heights - hence 2.3 (7/3)
scale += scaleFromSpine
scale /= 2.0
if not scale:
return getScaleFromMeshes()
return scale
def getItemScale( item ):
'''
returns the non-skinned "scale" of a joint (or skeleton part "item")
This scale uses a few metrics to determine the scale - first, the
bounds of any children are calculated and the max side of the bounding
box is found, and if non-zero returned. If the item has no children
then the radius of the joint is used (if it exists) otherwise the
magnitude of the joint translation is used.
If all the above tests fail, 1 is returned.
'''
scale = 0
children = listRelatives( item, type='transform' )
if children:
scales = []
bb = rigUtils.getTranslationExtents( children )
XYZ = bb[3]-bb[0], bb[4]-bb[1], bb[5]-bb[2]
scale = max( XYZ )
if not scale:
if objExists( '%s.radius' % item ):
scale = getAttr( '%s.radius' % item )
if not scale:
pos = Vector( getAttr( '%s.t' % item )[0] )
scale = pos.get_magnitude()
return scale or 1
def getNodeParent( obj ):
parent = listRelatives( obj, p=True, pa=True )
if parent is None:
return None
return parent[ 0 ]
def iterParents( obj, until=None ):
parent = getNodeParent( obj )
while parent is not None:
yield parent
if until is not None:
if parent == until:
return
parent = getNodeParent( parent )
def sortByHierarchy( objs ):
sortedObjs = []
for o in objs:
pCount = len( list( iterParents( o ) ) )
sortedObjs.append( (pCount, o) )
sortedObjs.sort()
return [ o[ 1 ] for o in sortedObjs ]
def getAlignSkipState( item ):
attrPath = '%s._skeletonPartSkipAlign' % item
if not objExists( attrPath ):
return False
return getAttr( attrPath )
def setAlignSkipState( item, state ):
'''
will flag a joint as user aligned - which means it will get skipped
by the alignment functions
'''
attrPath = '%s._skeletonPartSkipAlign' % item
if state:
if not objExists( attrPath ):
addAttr( item, ln='_skeletonPartSkipAlign', at='bool' )
setAttr( attrPath, True )
else:
deleteAttr( attrPath )
def d_restoreLocksAndNames(f):
'''
this decorator is for the alignment functions - it basically takes care of ensuring the children
are unparented before alignment happens, re-parented after the fact, channel unlocking and re-locking,
freezing transforms etc...
NOTE: this function gets called a lot. basically this decorator wraps all alignment functions, and
generally each joint in the skeleton has at least one alignment function run on it. Beware!
'''
def newF( item, *args, **kwargs ):
if getAlignSkipState( item ):
return
attrs = 't', 'r', 'ra'
#unparent and children in place, and store the original name, and lock
#states of attributes - we need to unlock attributes as this item will
#most likely change its orientation
children = castToMObjects( listRelatives( item, typ='transform', pa=True ) or [] ) #cast to mobjects as re-parenting can change and thus invalidate node name strings...
childrenPreStates = {}
for child in [ item ] + children:
lockStates = []
for a in attrs:
for c in CHANNELS:
attrPath = '%s.%s%s' % (child, a, c)
lockStates.append( (attrPath, getAttr( attrPath, lock=True )) )
try:
setAttr( attrPath, lock=False )
except: pass
originalChildName = str( child )
if not cmpNodes( child, item ):
child = cmd.parent( child, world=True )[0]
childrenPreStates[ child ] = originalChildName, lockStates
#make sure the rotation axis attribute is zeroed out - NOTE: we need to do this after children have been un-parented otherwise it could affect their positions
for c in CHANNELS:
setAttr( '%s.ra%s' % (item, c), 0 )
f( item, children=children, *args, **kwargs )
makeIdentity( item, a=True, r=True )
#now re-parent children
for child, (originalName, lockStates) in childrenPreStates.iteritems():
if child != item:
child = cmd.parent( child, item )[0]
child = rename( child, originalName.split( '|' )[-1] )
for attrPath, lockState in lockStates:
try:
setAttr( attrPath, lock=lockState )
except: pass
newF.__name__ = f.__name__
newF.__doc__ = f.__doc__
return newF
@d_restoreLocksAndNames
def autoAlignItem( item, invertAimAndUp=False, upVector=BONE_ROTATE_VECTOR, worldUpVector=MAYA_SIDE, worldUpObject='', upType='vector', children=None, debug=False ):
'''
for cases where there is no strong preference about how the item is aligned, this function will determine the best course of action
'''
numChildren = len( children )
#if there is more than one child, see if there is only one JOINT child...
childJoints = ls( children, type='joint' )
if len( childJoints ) == 1:
children = childJoints
#if there is only one child, aim the x-axis at said child, and aim the z-axis toward scene-up
### WARNING :: STILL NEED TO DEAL WITH CASE WHERE JOINT IS CLOSE TO AIMING AT SCENE UP
invertMult = -1 if invertAimAndUp else 1
if len( children ) == 1:
kw = { 'aimVector': BONE_AIM_VECTOR * invertMult,
'upVector': upVector * invertMult,
'worldUpVector': worldUpVector,
'worldUpType': upType }
if worldUpObject:
kw[ 'worldUpObject' ] = worldUpObject
c = aimConstraint( children[ 0 ], item, **kw )
if not debug: delete( c )
else:
for a in [ 'jo', 'r' ]:
for c in CHANNELS:
attrPath = '%s.%s%s' % (item, a, c)
if not getAttr( attrPath, settable=True ):
continue
setAttr( attrPath, 0 )
@d_restoreLocksAndNames
def alignAimAtItem( item, aimAtItem, invertAimAndUp=False, upVector=BONE_ROTATE_VECTOR, worldUpVector=MAYA_SIDE, worldUpObject='', upType='vector', children=None, debug=False ):
'''
aims the item at a specific transform in the scene. the aim axis is always BONE_AIM_VECTOR, but the up axis can be set to whatever is required
'''
invertMult = -1 if invertAimAndUp else 1
kw = { 'aimVector': BONE_AIM_VECTOR * invertMult,
'upVector': upVector * invertMult,
'worldUpVector': worldUpVector,
'worldUpType': upType }
if worldUpObject:
kw[ 'worldUpObject' ] = worldUpObject
c = aimConstraint( aimAtItem, item, **kw )
if debug: raise Exception
if not debug: delete( c )
@d_restoreLocksAndNames
def alignItemToWorld( item, children=None, skipX=False, skipY=False, skipZ=False ):
'''
aligns the item to world space axes, optionally skipping individual axes
'''
rotate( -90, -90, 0, item, a=True, ws=True )
if skipX: rotate( 0, 0, 0, item, a=True, os=True, rotateX=True )
if skipY: rotate( 0, 0, 0, item, a=True, os=True, rotateY=True )
if skipZ: rotate( 0, 0, 0, item, a=True, os=True, rotateZ=True )
@d_restoreLocksAndNames
def alignItemToLocal( item, children=None, skipX=False, skipY=False, skipZ=False ):
'''
aligns the item to local space axes, optionally skipping individual axes
'''
for skip, axis in zip( (skipX, skipY, skipZ), CHANNELS ):
if skipX:
setAttr( '%s.r%s' % (item, axis), 0 )
setAttr( '%s.jo%s' % (item, axis), 0 )
@d_restoreLocksAndNames
def alignPreserve( item, children=None ):
pass
def getCharacterMeshes():
'''
returns all "character meshes" found in the scene. These are basically defined as meshes that aren't
parented to a joint - where joints are
'''
meshes = ls( type='mesh', r=True )
meshes = set( listRelatives( meshes, p=True, pa=True ) ) #removes duplicates...
characterMeshes = set()
for mesh in meshes:
isUnderJoint = False
for parent in iterParents( mesh ):
if nodeType( parent ) == 'joint':
isUnderJoint = True
break
if not isUnderJoint:
characterMeshes.add( mesh )
return list( characterMeshes )
class SkeletonError(Exception): pass
class NotFinalizedError(SkeletonError): pass
class SceneNotSavedError(SkeletonError): pass
def getSkeletonSet():
'''
returns the "master" set used for storing skeleton parts in the scene - this isn't actually used for
anything but organizational purposes - ie the skeleton part sets are members of _this_ set, but at
no point does the existence or non-existence of this make any functional difference
'''
existing = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == TOOL_NAME ]
if existing:
return existing[ 0 ]
else:
skeletonParts = createNode( 'objectSet', n='skeletonParts' )
sets( skeletonParts, e=True, text=TOOL_NAME )
return skeletonParts
def createSkeletonPartContainer( name ):
'''
'''
theSet = sets( em=True, n=name, text='skeletonPrimitive' )
sets( theSet, e=True, add=getSkeletonSet() )
return theSet
def isSkeletonPartContainer( node ):
'''
tests whether the given node is a skeleton part container or not
'''
if objectType( node, isType='objectSet' ):
return sets( node, q=True, text=True ) == 'skeletonPrimitive'
return False
def getSkeletonPartContainers():
'''
returns a list of all skeleton part containers in the scene
'''
return [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == 'skeletonPrimitive' ]
def buildSkeletonPartContainer( typeClass, kwDict, items ):
'''
builds a container for the given skeleton part items, and tags it with the various attributes needed
to track the state for a skeleton part.
'''
#if typeClass is an instance, then set its container attribute, otherwise instantiate an instance and return it
if isinstance( typeClass, SkeletonPart ):
theInstance = typeClass
typeClass = type( typeClass )
#build the container, and add the special attribute to it to
if 'idx' in kwDict:
idx = kwDict[ 'idx' ]
else:
kwDict[ 'idx' ] = idx = typeClass.GetUniqueIdx()
theContainer = createSkeletonPartContainer( 'a%sPart_%s' % (typeClass.__name__, idx) )
addAttr( theContainer, ln='_skeletonPrimitive', attributeType='compound', numberOfChildren=7 )
addAttr( theContainer, ln='typeName', dt='string', parent='_skeletonPrimitive' )
addAttr( theContainer, ln='version', at='long', parent='_skeletonPrimitive' )
addAttr( theContainer, ln='script', dt='string', parent='_skeletonPrimitive' )
addAttr( theContainer, ln='buildKwargs', dt='string', parent='_skeletonPrimitive' ) #stores the kwarg dict used to build this part
addAttr( theContainer, ln='rigKwargs', dt='string', parent='_skeletonPrimitive' ) #stores the kwarg dict to pass to the rig method
addAttr( theContainer, ln='items',
multi=True,
indexMatters=False,
attributeType='message',
parent='_skeletonPrimitive' )
addAttr( theContainer, ln='placers',
multi=True,
indexMatters=False,
attributeType='message',
parent='_skeletonPrimitive' )
#now set the attribute values...
setAttr( '%s._skeletonPrimitive.typeName' % theContainer, typeClass.__name__, type='string' )
setAttr( '%s._skeletonPrimitive.version' % theContainer, typeClass.__version__ )
setAttr( '%s._skeletonPrimitive.script' % theContainer, inspect.getfile( typeClass ), type='string' )
setAttr( '%s._skeletonPrimitive.buildKwargs' % theContainer, str( kwDict ), type='string' )
#now add all the items
items = map( str, items )
for item in set( items ):
if nodeType( item ) == 'joint':
sets( item, e=True, add=theContainer )
#if the node is a rig part container add it to this container otherwise skip it
elif objectType( item, isAType='objectSet' ):
if isSkeletonPartContainer( item ):
sets( item, e=True, add=theContainer )
#and now hook up all the controls
for idx, item in enumerate( items ):
if item is None:
continue
connectAttr( '%s.message' % item, '%s._skeletonPrimitive.items[%d]' % (theContainer, idx), f=True )
return theContainer
def d_disconnectJointsFromSkinning( f ):
'''
Will unhook all skinning before performing the decorated method - and re-hooks it up after the
fact. Basically decorating anything with this function will allow you do perform operations
that would otherwise cause maya to complain about skin clusters being attached
'''
def new( *a, **kw ):
#for all skin clusters iterate through all their joints and detach them
#so we can freeze transforms - make sure to store initial state so we can
#restore connections afterward
skinClustersConnections = []
skinClusters = ls( typ='skinCluster' ) or []
for c in skinClusters:
cons = listConnections( c, destination=False, plugs=True, connections=True )
if cons is None:
print 'WARNING - no connections found on the skinCluster %s' % c
continue
conIter = iter( cons )
for tgtConnection in conIter:
srcConnection = conIter.next() #cons is a list of what should be tuples, but maya just returns a flat list - basically every first item is the destination plug, and every second is the source plug
#if the connection is originating from a joint delete the connection - otherwise leave it alone - we only want to disconnect joints from the skin cluster
node = srcConnection.split( '.' )[0]
if nodeType( node ) == 'joint':
disconnectAttr( srcConnection, tgtConnection )
skinClustersConnections.append( (srcConnection, tgtConnection) )
try:
f( *a, **kw )
#ALWAYS restore connections...
finally:
#re-connect all joints to skinClusters, and reset them
for srcConnection, tgtConnection in skinClustersConnections:
connectAttr( srcConnection, tgtConnection, f=True )
if skinClustersConnections:
for skinCluster in skinClusters:
resetSkinCluster( skinCluster )
new.__name__ = f.__name__
new.__doc__ = f.__doc__
return new
def d_disableDrivingRelationships( f ):
'''
tries to unhook all driver/driven relationships first, and re-hook them up afterwards
NOTE: needs to wrap a SkeletonPart method
'''
def new( self, *a, **kw ):
#store any driving or driven part, so when we're done we can restore the relationships
driver = self.getDriver()
drivenParts = self.getDriven()
#break driving relationships
self.breakDriver()
for part in drivenParts:
part.breakDriver()
try:
f( self, *a, **kw )
#restore driver/driven relationships...
finally:
#restore any up/downstream relationships if any...
if driver:
driver.driveOtherPart( self )
for part in drivenParts:
try:
self.driveOtherPart( part )
except AssertionError: continue #the parts may have changed size since the initial connection, so if they differ in size just ignore the assertion...
new.__name__ = f.__name__
new.__doc__ = f.__doc__
return new
def d_performInSkeletonPartScene( f ):
def new( self, *a, **kw ):
assert isinstance( self, SkeletonPart )
#if the part isn't referenced - nothing to do! execute the function as usual
if not self.isReferenced():
return f( self, *a, **kw )
partContainerFilepath = filesystem.Path( referenceQuery( self.getContainer(), filename=True ) )
curScene = filesystem.Path( file( q=True, sn=True ) )
if not curScene.exists():
raise TypeError( "This scene isn't saved! Please save this scene somewhere before executing the decorated method!" )
initialContainer = ReferencedNode( self.getContainer() )
self.setContainer( initialContainer.getUnreferencedNode() )
if not curScene.getWritable():
curScene.edit()
file( save=True, f=True )
file( partContainerFilepath, open=True, f=True )
try:
return f( self, *a, **kw )
finally:
self.setContainer( initialContainer.getNode() )
if not partContainerFilepath.getWritable():
partContainerFilepath.edit()
file( save=True, f=True )
file( curScene, open=True, f=True )
new.__name__ = f.__name__
new.__doc__ = f.__doc__
return new
class SkeletonPart(typeFactories.trackableClassFactory()):
__version__ = 0
#parity is "sided-ness" of the part. Ie if the part can exist on the left OR right side of the skeleton, the part has parity. the spine
#is an example of a part that has no parity, as is the head
HAS_PARITY = True
PART_SCALE = TYPICAL_HEIGHT
AUTO_NAME = True
AVAILABLE_IN_UI = True #determines whether this part should appear in the UI or not...
#some variables generally used by the auto volume creation methods
AUTO_VOLUME_SIDES = 8 #number of cylinder sides
#this list should be overridden for sub classes require named end placers such as feet
PLACER_NAMES = []
RigTypes = ()
def __new__( cls, partContainer ):
if cls is SkeletonPart:
clsName = getAttr( '%s._skeletonPrimitive.typeName' % partContainer )
cls = cls.GetNamedSubclass( clsName )
if cls is None:
raise TypeError( "Cannot determine the part class for the given part container!" )
return object.__new__( cls, partContainer )
def __init__( self, partContainer ):
if partContainer is not None:
assert isSkeletonPartContainer( partContainer ), "Must pass a valid skeleton part container! (received %s - a %s)" % (partContainer, nodeType( partContainer ))
self._container = partContainer
self._items = None
def __unicode__( self ):
return u"%s( %r )" % (self.__class__.__name__, self._container)
__str__ = __unicode__
def __repr__( self ):
return repr( unicode( self ) )
def __hash__( self ):
return hash( self._container )
def __eq__( self, other ):
return self._container == other.getContainer()
def __neq__( self, other ):
return not self == other
def __getitem__( self, idx ):
return self.getItems().__getitem__( idx )
def __getattr__( self, attr ):
if attr in self.__dict__:
return self.__dict__[ attr ]
if attr not in self.PLACER_NAMES:
raise AttributeError( "No such attribute %s" % attr )
idx = list( self.PLACER_NAMES ).index( attr )
cons = listConnections( '%s._skeletonPrimitive.placers[%d]' % (self.base, n), d=False )
if cons:
return cons[ 0 ]
return None
def __len__( self ):
return len( self.getItems() )
def __iter__( self ):
return iter( self.getItems() )
def getContainer( self ):
return self._container
def setContainer( self, container ):
self._container = container
self._items = None
def getItems( self ):
if self._items is not None:
return self._items[:]
self._items = items = []
idxs = getAttr( '%s._skeletonPrimitive.items' % self._container, multiIndices=True ) or []
for idx in idxs:
cons = listConnections( '%s._skeletonPrimitive.items[%d]' % (self._container, idx), d=False )
if cons:
assert len( cons ) == 1, "More than one joint was found!!!"
items.append( cons[ 0 ] )
#items = castToMObjects( items )
return items[:] #return a copy...
items = property( getItems )
@property
def version( self ):
try:
return getAttr( '%s._skeletonPrimitive.version' % self._container )
except: return None
def isDisabled( self ):
'''
returns whether the part has been disabled for rigging or not
'''
rigKwargs = self.getRigKwargs()
return 'disable' in rigKwargs
def getPlacers( self ):
placerAttrpath = '%s._skeletonPrimitive.placers' % self._container
if not objExists( placerAttrpath ):
return []
placers = []
placerIdxs = getAttr( placerAttrpath, multiIndices=True )
if placerIdxs:
for idx in placerIdxs:
cons = listConnections( '%s[%d]' % (placerAttrpath, idx), d=False )
if cons:
placers.append( cons[ 0 ] )
return placers
def verifyPart( self ):
'''
this is merely a "hook" that can be used to fix anything up should the way
skeleton parts are defined change
'''
#make sure all items have the appropriate attributes on them
baseItem = self[ 0 ]
for n, item in enumerate( self ):
delete( '%s.inverseScale' % item, icn=True ) #remove the inverse scale relationship...
setAttr( '%s.segmentScaleCompensate' % item, False )
if not objExists( '%s._skeletonPartName' % item ):
addAttr( item, ln='_skeletonPartName', dt='string' )
if not objExists( '%s._skeletonPartArgs' % item ):
addAttr( item, ln='_skeletonPartArgs', dt='string' )
if n:
if not isConnected( '%s._skeletonPartName' % baseItem, '%s._skeletonPartName' % item ):
connectAttr( '%s._skeletonPartName' % baseItem, '%s._skeletonPartName' % item, f=True )
if not isConnected( '%s._skeletonPartArgs' % baseItem, '%s._skeletonPartArgs' % item ):
connectAttr( '%s._skeletonPartArgs' % baseItem, '%s._skeletonPartArgs' % item, f=True )
def convert( self, buildKwargs ):
'''
called when joints built outside of skeleton builder are converted to a skeleton builder part
'''
if not buildKwargs:
for argName, value in self.GetDefaultBuildKwargList():
buildKwargs[ argName ] = value
if 'idx' not in buildKwargs:
idx = self.GetUniqueIdx()
buildKwargs[ 'idx' ] = idx
if 'parent' in buildKwargs:
buildKwargs.pop( 'parent' )
self.setBuildKwargs( buildKwargs )
#lock scale
attrState( self.items, ['s'], lock=True, keyable=False, show=True )
#lock rotate axis
attrState( self.items, ['rotateAxis'], lock=True, keyable=False, show=False )
#build placers...
self.buildPlacers()
def hasParity( self ):
return self.HAS_PARITY
def isReferenced( self ):
return referenceQuery( self._container, inr=True )
@classmethod
def ParityMultiplier( cls, idx ):
return Parity( idx ).asMultiplier()
@classmethod
def GetPartName( cls ):
'''
can be used to get a "nice" name for the part class
'''
return camelCaseToNice( cls.__name__ )
def getIdx( self ):
'''
returns the index of the part - all parts have a unique index associated
with them
'''
return self.getBuildKwargs()[ 'idx' ]
def getBuildScale( self ):
return self.getBuildKwargs().get( 'partScale', self.PART_SCALE )
def getParity( self ):
return Parity( self.getIdx() )
def getParityColour( self ):
parity = self.getParity()
if parity == Parity.LEFT:
return Colour( 'green' )
if parity == Parity.RIGHT:
return Colour( 'red' )
if parity == Parity.NONE:
return Colour( 'darkblue' )
return Colour( 'black' )
getParityColor = getParityColour
def getParityMultiplier( self ):
return self.getParity().asMultiplier()
def getOppositePart( self ):
'''
Finds the opposite part - if any - in the scene to this part. If no opposite part is found None is returned.
The opposite part is defined as the part that has opposite parity - the part with the closest index is
returned if there are multiple parts with opposite parity in the scene.
If this part has no parity None is returned.
'''
#is this a parity part? if not then there is no such thing as an opposite part...
if not self.hasParity():
return None
#get some data about this part
thisIdx = self.getIdx()
thisParity = self.getParity()
#is this a left or right parity part?
isLeft = thisIdx == Parity.LEFT
possibleMatches = []
for part in self.IterAllParts( True ):
parity = part.getParity()
if parity.isOpposite( thisParity ):
idx = part.getIdx()
#if "self" is a left part then its exact opposite will be self.getIdx() + 1, otherwise if "self" is a right
#sided part then its exact opposite will be self.getIdx() - 1. So figure out the "index delta" and use it
#as a sort metric to find the most appropriate match for the cases where there are multiple, non-ideal matches
idxDelta = 0
if isLeft:
idxDelta = idx - thisIdx
else:
idxDelta = thisIdx - idx
if idxDelta == 1:
return part
possibleMatches.append( (idxDelta, part) )
possibleMatches.sort()
if possibleMatches:
return possibleMatches[0][1]
return None
@property
def base( self ):
return self[ 0 ]
@property
def bases( self ):
'''
returns all the bases for this part - bases are joints with parents who don't belong to this part
'''
allItems = set( self )
bases = []
for item in self:
itemParent = getNodeParent( item )
if itemParent not in allItems:
bases.append( item )
return bases
@property
def end( self ):
return self[ -1 ]
@property
def ends( self ):
'''
returns all the ends for the part - ends are joints that either have no children, or have children
that don't belong to this part
'''
allItems = set( self )
ends = []
for item in self:
itemChildren = listRelatives( item, pa=True )
#so if the item has children, see if any of them are in allItems - if not, its an end
if itemChildren:
childrenInAllItems = allItems.intersection( set( itemChildren ) )
if not childrenInAllItems:
ends.append( item )
#if it has no children, its an end
else:
ends.append( item )
return ends
@property
def chains( self ):
'''
returns a list of hierarchy "chains" in the current part - parts that have
more than one base are comprised of "chains": ie hierarchies that don't have
a parent as a member of this part
For a hand part for example, this method will return a list of finger
hierarchies
NOTE: the chains are ordered hierarchically
'''
bases = set( self.bases )
chains = []
for end in self.ends:
currentChain = [ end ]
p = getNodeParent( end )
while p:
currentChain.append( p )
if p in bases:
break
p = getNodeParent( p )
currentChain.reverse()
chains.append( currentChain )
return chains
@property
def endPlacer( self ):
try:
return self.getPlacers()[ 0 ]
except IndexError:
return None
@classmethod
def GetIdxStr( cls, idx ):
'''
returns an "index string". For parts with parity this index string increments
with pairs (ie a left and a right) while non-parity parts always increment
'''
#/2 because parts are created in pairs so arm 2 and 3 are prefixed with "Arm1", and the first arm is simply "Arm"
if cls.HAS_PARITY:
return str( idx / 2 ) if idx > 1 else ''
return str( idx ) if idx else ''
def getBuildKwargs( self ):
'''
returns the kwarg dict that was used to create this particular part
'''
buildFunc = self.GetBuildFunction()
#get the default build kwargs for the part
argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc )
if defaults is None:
defaults = []
argNames = argNames[ 1: ] #strip the first arg - which is the class arg (usually cls)
kw = {}
for argName, default in zip( argNames, defaults ):
kw[ argName ] = default
#now update the default kwargs with the actual kwargs
argStr = getAttr( '%s._skeletonPrimitive.buildKwargs' % self._container )
kw.update( eval( argStr ) )
return kw
def setBuildKwargs( self, kwargs ):
'''
returns the kwarg dict that was used to create this particular part
'''
setAttr( '%s._skeletonPrimitive.buildKwargs' % self._container, str( kwargs ), type='string' )
def getRigKwargs( self ):
'''
returns the kwarg dict that should be used to create the rig for this part
'''
try:
argStr = getAttr( '%s._skeletonPrimitive.rigKwargs' % self._container )
except:
return {}
if argStr is None:
return {}
kw = eval( argStr )
return kw
def setRigKwargs( self, kwargs ):
setAttr( '%s._skeletonPrimitive.rigKwargs' % self._container, str( kwargs ), type='string' )
def updateRigKwargs( self, **kw ):
currentKwargs = self.getRigKwargs()
currentKwargs.update( kw )
self.setRigKwargs( currentKwargs )
def getPartName( self ):
idx = self.getIdx()
if self.hasParity():
parityStr = 'Left ' if self.getParity() == Parity.LEFT else 'Right '
idxStr = '' if idx < 2 else ' %d' % idx
else:
parityStr = ''
idxStr = ' %d' % idx if idx else ''
name = camelCaseToNice( self.getBuildKwargs().get( 'partName', '' ) )
clsName = camelCaseToNice( type( self ).__name__ )
return '%s%s %s%s' % (parityStr, name, clsName, idxStr)
def getActualScale( self ):
return rigUtils.getObjsScale( self )
def getParent( self ):
'''
returns the parent of the part - the actual node name. use getParentPart
to query the part this part is parented to (if any)
'''
return getNodeParent( self.base )
def setParent( self, parent ):
'''
parents the part to a new object in the scene - if parent is None, the
part is parented to the world
'''
if parent is None:
cmd.parent( self.base, w=True )
else:
cmd.parent( self.base, parent )
def getParentPart( self ):
'''
returns the part this part is parented to - if any. if this part isn't
parented to a part, None is returned.
NOTE: this part may be parented to something that isn't a member of a
part, so a result of None from this query doesn't mean the part has no
parent, just that its parent isn't a member of a part
'''
parent = self.getParent()
if parent is None:
return None
return self.InitFromItem( parent )
@classmethod
def GetBuildFunction( cls ):
'''
returns the build function for the part
'''
buildFunc = getattr( cls, '_build', None )
if buildFunc is None:
raise SkeletonError( 'no such part type' )
return buildFunc
@classmethod
def GetDefaultBuildKwargList( cls ):
'''
returns a list of 2 tuples: argName, defaultValue
'''
buildFunc = cls.GetBuildFunction()
spec = inspect.getargspec( buildFunc )
argNames = spec[ 0 ][ 1: ] #strip the first item because the _build method is a bound method - so the first item is always the class arg (usually called cls)
defaults = spec[ 3 ]
if defaults is None:
defaults = []
assert len( argNames ) == len( defaults ), "%s has no default value set for one of its args - this is not allowed" % cls
kwargList = []
for argName, default in zip( argNames, defaults ):
kwargList.append( (argName, default) )
return kwargList
@classmethod
def InitFromItem( cls, item ):
'''
will instantiate a SkeletonPart from an item of a previously built part.
if an item is given that isn't involved in a part None is returned
'''
if isSkeletonPartContainer( item ):
typeClassStr = getAttr( '%s._skeletonPrimitive.typeName' % item )
typeClass = SkeletonPart.GetNamedSubclass( typeClassStr )
return typeClass( item )
cons = listConnections( '%s.message' % item, s=False, type='objectSet' )
if not cons:
raise SkeletonError( "Cannot find a skeleton part container for %s" % item )
for con in cons:
if isSkeletonPartContainer( con ):
typeClassStr = getAttr( '%s._skeletonPrimitive.typeName' % con )
typeClass = SkeletonPart.GetNamedSubclass( typeClassStr )
return typeClass( con )
raise SkeletonError( "Cannot find a skeleton container for %s" % item )
### CREATION ###
def buildPlacers( self ):
'''
Don't override this method - instead override the _buildPlacers method. This method handles
connecting the placers to the part appropriately
'''
try:
buildPlacers = self._buildPlacers
except AttributeError: return []
placers = buildPlacers()
if not placers:
return
container = self._container
idx = self.getIdx()
idxStr = self.GetIdxStr( idx )
parityStr = Parity( idx % 2 ).asName() if self.hasParity() else ''
for n, placer in enumerate( placers ):
connectAttr( '%s.message' % placer, '%s._skeletonPrimitive.placers[%d]' % (container, n), f=True )
#name the placer appropriately
try:
placerName = self.PLACER_NAMES[ n ]
except IndexError:
proposedName = '%s%s_plc%d%s' % (type( self ).__name__, idxStr, idx, parityStr)
else:
proposedName = '%s%s_plc%d%s' % (placerName, idxStr, idx, parityStr)
if objExists( proposedName ):
proposedName = proposedName +'#'
placer = rename( placer, proposedName )
return placers
def _buildPlacers( self ):
'''
the default placer building method just creates a placer at teh end of every
joint chain in the part
'''
placers = []
for end in self.ends:
placer = buildEndPlacer()
setAttr( '%s.t' % placer, *getAttr( '%s.t' % end )[0] )
placer = parent( placer, end, r=True )[ 0 ]
placers.append( placer )
return placers
#NOTE!!! this method gets decorated below !!!
def Create( cls, *a, **kw ):
'''
this is the primary way to create a skeleton part. build functions are
defined outside the class and looked up by name. this method ensures
that all build methods (a build method is only required to return the
list of nodes that define it) register nodes properly, and encode data
about how the part was built into the part so that the part can be
re-instantiated at a later date
'''
partScale = kw.setdefault( 'partScale', cls.PART_SCALE )
#grab any kwargs out of the dict that shouldn't be there
visualize = kw.pop( 'visualize', True )
autoMirror = kw.pop( 'autoMirror', True )
#now turn the args passed in are a single kwargs dict
buildFunc = cls.GetBuildFunction()
argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc )
if defaults is None:
defaults = []
argNames = argNames[ 1: ] #strip the first arg - which is the class arg (usually cls)
if vArgs is not None:
raise SkeletonError( 'cannot have *a in skeleton build functions' )
for argName, value in zip( argNames, a ):
kw[ argName ] = value
#now explicitly add the defaults
for argName, default in zip( argNames, defaults ):
kw.setdefault( argName, default )
#generate an index for the part - each part must have a unique index
idx = cls.GetUniqueIdx()
kw[ 'idx' ] = idx
#run the build function and remove the parent from the kw dict - we don't need to serialize this...
items = buildFunc( **kw )
kw.pop( 'parent', None )
partContainer = buildSkeletonPartContainer( cls, kw, items )
#now rename all the joints appropriately if we're supposed to...
if cls.AUTO_NAME:
partName = kw.get( 'partName', cls.__name__ )
if not partName:
partName = cls.__name__
partName = partName[0].upper() + partName[ 1: ] #capitalize the first letter always...
kw[ 'partName' ] = partName
renamedItems = []
idxStr = cls.GetIdxStr( idx )
parityStr = Parity( idx % 2 ).asName() if cls.HAS_PARITY else ''
for n, item in enumerate( items ):
renamedItems.append( rename( item, '%s%s_%s%s' % (partName, idxStr, n, parityStr) ) )
items = renamedItems
#instantiate the part and align
newPart = cls( partContainer )
newPart.convert( kw )
newPart._align( _initialAlign=True )
#are we doing visualizations?
if visualize:
newPart.visualize()
return newPart
#in 2009 wrapping the Create with d_unifyUndo will crash maya... :(
if mayaVar >= 2011:
Create = classmethod( d_unifyUndo( Create ) )
else:
Create = classmethod( d_unifyUndo( Create ) )
def rebuild( self, **newBuildKwargs ):
'''
rebuilds the part by storing all the positions of the existing members,
re-creating the part with optionally changed build args, positioning
re-created joints as best as possible, and re-parenting child parts
'''
#grab the build kwargs used to create this part, and update it with the new kwargs passed in
buildKwargs = self.getBuildKwargs()
buildKwargs.update( newBuildKwargs )
buildKwargs[ 'parent' ] = getNodeParent( self )
self.unvisualize()
posRots = []
attrs = 't', 'r'
for item in self:
pos = xform( item, q=True, ws=True, rp=True )
rot = xform( item, q=True, ws=True, ro=True )
posRots.append( (item, pos, rot) )
childParts = self.getChildParts()
childParents = []
childPartDrivers = []
for part in childParts:
childParents.append( part.getParent() )
childPartDrivers.append( part.getDriver() )
part.breakDriver()
part.setParent( None )
orphans = self.getOrphanJoints()
orphanParents = []
for orphan in orphans:
orphanParents.append( getNodeParent( orphan ) )
cmd.parent( orphan, w=True )
delete( self.items )
newPart = self.Create( **buildKwargs )
oldToNewNameMapping = {}
for (oldItemName, pos, rot), item in zip( posRots, newPart.items ):
move( pos[ 0 ], pos[ 1 ], pos[ 2 ], item, ws=True, a=True, rpr=True )
rotate( rot[ 0 ], rot[ 1 ], rot[ 2 ], item, ws=True, a=True )
oldToNewNameMapping[ oldItemName ] = item
#reparent child parts
for childPart, childParent in zip( childParts, childParents ):
childParent = oldToNewNameMapping.get( childParent, childParent )
childPart.setParent( childParent )
#re-setup driver/driven relationships (should be done after re-parenting is done)
for childPart, childDriver in zip( childParts, childPartDrivers ):
if childDriver is not None:
childDriver.driveOtherPart( childPart )
#reparent orphans
for orphan, orphanParent in zip( orphans, orphanParents ):
orphanParent = oldToNewNameMapping.get( orphanParent, orphanParent )
cmd.parent( orphan, orphanParent )
newPart.visualize()
return newPart
### REDISCOVERY ###
@classmethod
def IterAllParts( cls, exactType=False ):
'''
iterates over all SkeletonParts in the current scene
'''
for partContainer in getSkeletonPartContainers():
thisPartCls = SkeletonPart.GetNamedSubclass( getAttr( '%s._skeletonPrimitive.typeName' % partContainer ) )
#if the user only wants the exact type then compare the classes - if they're not the same keep loopin
if exactType:
if cls is not thisPartCls:
continue
#otherwise test to see if this part's class is a subclass of
else:
if not issubclass( thisPartCls, cls ):
continue
yield thisPartCls( partContainer )
@classmethod
def IterAllPartsInOrder( cls ):
allParts = [ part for part in cls.IterAllParts() ]
allParts = sortPartsByHierarchy( allParts )
return iter( allParts )
@classmethod
def FindParts( cls, partClass, withKwargs=None ):
'''
given a part name and a kwargs dict (may be a partial dict) this method
will return all matching parts in the current scene. so if you wanted to
get a list of all the finger parts with 3 joints you would do:
SkeletonPart.FindParts( finger, { 'fingerJointCount': 3 } )
'''
withKwargs = withKwargs or {}
matches = []
for part in cls.IterAllParts( partClass ):
partKwargs = part.getBuildKwargs()
match = True
for argName, argValue in withKwargs.iteritems():
try:
if partKwargs[ argName ] != argValue:
match = False
break
except KeyError: continue
if match: matches.append( part )
return matches
@classmethod
def GetUniqueIdx( cls ):
'''
returns a unique index (unique against the universe of existing indices
in the scene) for the current part class
'''
allPartContainers = getSkeletonPartContainers()
thisTypeName = cls.__name__
existingIdxs = set()
for container in allPartContainers:
typeStr = getAttr( '%s._skeletonPrimitive.typeName' % container )
typeCls = SkeletonPart.GetNamedSubclass( typeStr )
if typeCls is cls:
attrPath = '%s._skeletonPrimitive.buildKwargs' % container
attrStr = getAttr( attrPath )
if attrStr:
buildArgs = eval( getAttr( attrPath ) )
existingIdxs.add( buildArgs[ 'idx' ] )
existingIdxs = list( sorted( existingIdxs ) )
#return the first, lowest, available index
for orderedIdx, existingIdx in enumerate( existingIdxs ):
if existingIdx != orderedIdx:
return orderedIdx
if existingIdxs:
return existingIdxs[ -1 ] + 1
return 0
@classmethod
def GetRigMethod( cls, methodName ):
for method in cls.RigTypes:
if method.__name__ == methodName:
return method
return None
def getChildParts( self ):
'''
returns a list of all the parts parented directly to a member of this part
'''
#first get a list of all the joints directly parented to a memeber of this part
selfItems = self.getItems() + self.getPlacers()
allChildren = listRelatives( selfItems, typ='transform', pa=True )
if not allChildren:
return
#subtract all the items of this part from the children - to give us all the children of this part that don't belong to this part
allChildren = set( allChildren ).difference( set( selfItems ) )
return getPartsFromObjects( allChildren )
def getOrphanJoints( self ):
'''
orphan joints are joints parented to a member of this part, but don't
belong to a part. orphan joints get aligned using the same alignment
method used by their parent part
'''
#first get a list of all the joints directly parented to a memeber of this part
allChildren = listRelatives( self, typ='joint', pa=True )
if not allChildren:
return []
childPartItems = []
for part in self.getChildParts():
childPartItems += list( part )
jointsInSomePart = set( childPartItems + self.items )
orphanChildren = set( allChildren ).difference( jointsInSomePart )
orphanChildren = list( orphanChildren )
childrenOfChildren = []
for i in orphanChildren:
iChildren = listRelatives( i, typ='joint', pa=True )
if not iChildren: continue
for c in iChildren:
if objExists( '%s._skeletonPartName' % c ): continue
childrenOfChildren.append( c )
return orphanChildren + childrenOfChildren
def selfAndOrphans( self ):
return list( self ) + self.getOrphanJoints()
@d_unifyUndo
def delete( self ):
if self.isRigged():
self.deleteRig()
for node in self.items:
rigUtils.cleanDelete( node )
if objExists( self._container ):
delete( self._container )
### ALIGNMENT ###
@d_unifyUndo
@d_disableDrivingRelationships
@d_disconnectJointsFromSkinning
def align( self, _initialAlign=False ):
self._align( _initialAlign )
def _align( self, _initialAlign=False ):
for item in self.selfAndOrphans():
autoAlignItem( item )
@d_unifyUndo
@d_disableDrivingRelationships
@d_disconnectJointsFromSkinning
def freeze( self ):
'''
freezes the transforms for all joints in this part
'''
makeIdentity( self.items, a=True, t=True, r=True )
### VISUALIZATION ###
@d_unifyUndo
def visualize( self ):
'''
can be used to create visualization for item orientation or whatever else.
NOTE: visualizations should never add joints, but can use any other node
machinery available.
'''
pass
@d_unifyUndo
def unvisualize( self ):
'''
removes any visualization on the part
'''
for i in self.selfAndOrphans():
children = listRelatives( i, shapes=True, pa=True ) or []
for c in children:
try:
if nodeType( c ) == 'joint': continue
delete( c )
#this can happen if the deletion of a previous child causes some other child to also be deleted - its a fringe case but possible (i think)
except TypeError: continue
### SYMMETRICAL SKELETON BUILDING ###
def driveOtherPart( self, otherPart ):
'''
drives the specified part with this part - meaning that all translations
and rotations of items in this part will drive the corresponding items in
the other part. attributes are hooked up for the most part using direct
connections, but some attributes are driven via an expression
'''
assert isinstance( otherPart, SkeletonPart ) #this is just for WING...
if type( self ) is not type( otherPart ):
raise SkeletonError( "Sorry, you cannot connect different types together" )
if len( self ) != len( otherPart ):
raise SkeletonError( "Sorry, seems the two parts are different sizes (%d, %d) - not sure what to do" % (len( self ), len( otherPart )) )
attrs = 't', 'r'
#first unlock trans and rot channels
attrState( otherPart.items, attrs, False )
#if the parts have parity AND differing parities, we may have to deal with mirroring differently
if self.hasParity() and self.getParity() != otherPart.getParity():
selfItems = self.items + self.getPlacers()
otherItems = otherPart.items + otherPart.getPlacers()
for thisItem, otherItem in zip( selfItems, otherItems ):
rotNode = cmd.rotationMirror( thisItem, otherItem, ax=BONE_AIM_AXIS.asName() ) #access via cmd namespace as the plugin may or may not have been loaded when all was imported from maya.cmds
#if the joints have the same parent, reverse position
if getNodeParent( thisItem ) == getNodeParent( otherItem ):
setAttr( '%s.mirrorTranslation' % rotNode, 2 )
else:
setAttr( '%s.mirrorTranslation' % rotNode, 1 )
#otherwise setting up the driven relationship is straight up attribute connections...
else:
for thisItem, otherItem in zip( self.items, otherPart.items ):
for attr in attrs:
for c in CHANNELS:
connectAttr( '%s.%s%s' % (thisItem, attr, c), '%s.%s%s' % (otherItem, attr, c), f=True )
def breakDriver( self ):
attrs = 't', 'r'
for item in (self.items + self.getPlacers()):
for a in attrs:
attrPaths = [ a ] + [ '%s%s' % (a, c) for c in CHANNELS ]
for attrPath in attrPaths:
attrPath = '%s.%s' % (item, attrPath)
isLocked = getAttr( attrPath, lock=True )
if isLocked:
setAttr( attrPath, lock=False ) #need to make sure attributes are unlocked before trying to break a connection - regardless of whether the attribute is the source or destination... 8-o
delete( attrPath, inputConnectionsAndNodes=True )
if isLocked:
setAttr( attrPath, lock=True )
def getDriver( self ):
'''
returns the part driving this part if any, otherwise None is returned
'''
attrs = 't', 'r'
for item in self:
for attr in attrs:
for c in CHANNELS:
cons = listConnections( '%s.%s%s' % (item, attr, c), destination=False, skipConversionNodes=True, t='joint' )
if cons:
for c in cons:
part = SkeletonPart.InitFromItem( c )
if part: return part
def getDriven( self ):
'''
returns a list of driven parts if any, otherwise an empty list is returned
'''
attrs = 't', 'r'
allOutConnections = []
for item in self:
for attr in attrs:
for c in CHANNELS:
allOutConnections += listConnections( '%s.%s%s' % (item, attr, c), source=False, skipConversionNodes=True, t='joint' ) or []
if allOutConnections:
allOutConnections = filesystem.removeDupes( allOutConnections )
return getPartsFromObjects( allOutConnections )
return []
### FINALIZATION ###
def generateItemHash( self, item ):
'''
creates a hash for the position and orientation of the joint so we can ensure
the state is still the same at a later date
'''
tHashAccum = 0
joHashAccum = 0
tChanValues = []
joChanValues = []
for c in CHANNELS:
#we hash the rounded string of the float to eliminate floating point error
t = getAttr( '%s.t%s' % (item, c) )
jo = getAttr( '%s.jo%s' % (item, c) )
val = '%0.4f %0.4f' % (t, jo)
tHashAccum += hash( val )
tChanValues.append( t )
joChanValues.append( jo )
iParent = getNodeParent( item )
return iParent, tHashAccum, tChanValues, joChanValues
@d_performInSkeletonPartScene
def finalize( self ):
'''
performs some finalization on the skeleton - ensures everything is aligned,
and then stores a has of the orientations into the skeleton so that we can
later compare the skeleton orientation with the stored state
'''
#early out if finalization is valid
if self.compareAgainstHash():
return
#make sure any driver relationship is broken
self.breakDriver()
#make sure the part has been aligned
self.align()
#remove any visualizations
self.unvisualize()
#unlock all channels and make keyable - we cannot change lock/keyability
#state once the skeleton is referenced into the rig, and we need them to
#be in such a state to build the rig
attrState( self.selfAndOrphans(), ('t', 'r'), False, True, True )
attrState( self.selfAndOrphans(), ('s', 'v'), False, False, True )
#create a hash for the position and orientation of the joint so we can ensure the state is still the same at a later date
for i in self.selfAndOrphans():
if not objExists( '%s._skeletonFinalizeHash' % i ):
addAttr( i, ln='_skeletonFinalizeHash', dt='string' )
setAttr( '%s._skeletonFinalizeHash' % i, str( self.generateItemHash( i ) ), type='string' )
def compareAgainstHash( self ):
'''
compares the current orientation of the partto the stored state hash when
the part was last finalized. if the part has differing
a bool indicating whether the current state matches the stored finalization
state is returned
'''
#if the part is rigged, then return True - if its been rigged then it should have been properly finalized so we should be good
if self.isRigged():
return True
#create a hash for the position and orientation of the joint so we can ensure the state is still the same at a later date
for i in self.selfAndOrphans():
#if the joint is marked with the align skip state, skip the finalization check
if getAlignSkipState( i ):
continue
#if it doesn't have the finalization hash attribute it can't possibly be finalized
if not objExists( '%s._skeletonFinalizeHash' % i ):
return False
#figure out what the hash should be and compare it to the one that is stored
iParent, xformHash, xxa, yya = self.generateItemHash( i )
try: storedParent, stored_xHash, xxb, yyb = eval( getAttr( '%s._skeletonFinalizeHash' % i ) )
except:
print 'stored hash differs from the current hashing routine - please re-finalize'
return False
#if the stored parent is different from the current parent, there may only be a namespace conflict - so strip namespace prefixes and redo the comparison
if iParent != storedParent:
if Name( iParent ).strip() != Name( storedParent ).strip():
print 'parenting mismatch on %s since finalization (%s vs %s)' % (i, iParent, storedParent)
return False
TOLERANCE = 1e-6 #tolerance used to compare floats
def doubleCheckValues( valuesA, valuesB ):
for va, vb in zip( valuesA, valuesB ):
va, vb = float( va ), float( vb )
if va - vb > TOLERANCE:
return False
return True
if xformHash != stored_xHash:
#so did we really fail? sometimes 0 gets stored as -0 or whatever, so make sure the values are actually different
if not doubleCheckValues( xxa, xxb ):
print 'the translation on %s changed since finalization (%s vs %s)' % (i, xxa, xxb)
return False
if not doubleCheckValues( yya, yyb ):
print 'joint orienatation on %s changed since finalization (%s vs %s)' % (i, yya, yyb)
return False
return True
### RIGGING ###
@d_unifyUndo
def rig( self, **kw ):
'''
constructs the rig for this part
'''
#check the skeleton part to see if it already has a rig
rigContainerAttrname = 'rigContainer'
rigContainerAttrpath = '%s.%s' % (self._container, rigContainerAttrname)
if not objExists( rigContainerAttrpath ):
addAttr( self._container, ln=rigContainerAttrname, at='message' )
#check to see if there is already a rig built
if listConnections( rigContainerAttrpath, d=False ):
print 'Rig already built for %s - skipping' % self
return
#update the kw dict for the part
rigKw = self.getBuildKwargs()
rigKw.update( self.getRigKwargs() )
rigKw.update( kw )
kw = rigKw
if kw.get( 'disable', False ):
print 'Rigging disabled for %s - skipping' % self
return
#pop the rig method name out of the kwarg dict, and look it up
try: rigMethodName = kw.pop( 'rigMethodName', self.RigTypes[ 0 ].__name__ )
except IndexError:
print "No rig method defined for %s" % self
return
#make sure to break drivers before we rig
self.breakDriver()
#discover the rigging method
rigType = self.GetRigMethod( rigMethodName )
if rigType is None:
print 'ERROR :: there is no such rig method with the name %s' % rigMethodName
return
#bulid the rig and connect it to the part
theRig = rigType.Create( self, **kw )
if theRig is None:
MGlobal.displayError( "Failed to create the rig for part %s" % self )
return
connectAttr( '%s.message' % theRig.getContainer(), '%s.rigContainer' % self._container, f=True )
def isRigged( self ):
'''
returns whether this skeleton part is rigged or not
'''
return self.getRigContainer() is not None
### VOLUME CREATION ###
def buildVolumes( self ):
'''
attempts to create volumes for the skeleton that reasonably tightly fits the character mesh. these
volumes can then be modified quickly using standard modelling tools, and can be then used to generate
a fairly good skinning solution for the character mesh
'''
#remove any visualization - this can confuse the volume removal code as it can't tell what is a volume mesh and what is a visualization mesh
self.unvisualize()
#remove any existing volumes
self.removeVolumes()
#get the list of character meshes
characterMeshes = getCharacterMeshes()
for item in self:
size, centre = rigUtils.getJointSizeAndCentre( item, ignoreSkinning=True )
#we just want to move the joint to the centre of the primary bone axis - not all axes...
otherAxes = BONE_AIM_AXIS.otherAxes()
centre[ otherAxes[0] ] = 0
centre[ otherAxes[1] ] = 0
volumes = self.buildItemVolume( item, size, centre )
for v in volumes:
v = rename( v, '%s__sbVolume#' % item )
makeIdentity( v, a=True, t=True, r=True, s=True )
shrinkWrap( v, characterMeshes )
def iterItemVolumes( self ):
'''
generator to yield a 2-tuple of each part item, and the list of volumes associated with it
'''
for item in self:
children = listRelatives( item, pa=True )
if children:
childMeshes = listRelatives( children, pa=True, type='mesh' )
if childMeshes:
meshParents = [ m for m in listRelatives( childMeshes, p=True, pa=True ) if nodeType( m ) != 'joint' ] #make sure not to remove joints...
yield item, meshParents
def removeVolumes( self ):
'''
handles removing any existing volumes on the skeleton
'''
for item, volumes in self.iterItemVolumes():
if volumes:
delete( volumes )
def buildItemVolume( self, item, size, centre ):
'''
handles creation of the actual volume - generally if you want control over volume creation for a part
you'll just need to override this method. It gets given the joint's "size" and its "centre" and you're
then free to build geometry accordingly
'''
sides = self.AUTO_VOLUME_SIDES
height = float( size[ BONE_AIM_AXIS ] )
geo = polyCylinder( h=height * 0.95, r=0.01, ax=BONE_AIM_VECTOR, sx=sides, sy=round( height/2.0 ), ch=False )[0]
parent( geo, item, r=True )
setAttr( '%s.t' % geo, *centre )
#finally remove the top and bottom cylinder caps - they're always the last 2 faces
numFaces = meshUtils.numFaces( geo )
delete( '%s.f[ %d:%d ]' % (geo, numFaces-2, numFaces-1) )
return [geo]
def createRotationCurves( theJoint ):
"""
create the UI widget for each rotGUI
"""
rotGuiOverRideColor = [ 13 , 14 , 6 ]
rotGuiCurves = []
c = curve( d=1, p=((0.000000, -0.000000, -1.000000),
(-0.000000, 0.500000, -0.866025),
(-0.000000, 0.866025, -0.500000),
(-0.000000, 1.000000, -0.000000),
(-0.000000, 0.350000, 0.000000),
(-0.116667, 0.116667, -0.116667),
(-0.000000, 0.000000, -0.350000),
(0.000000, -0.436239, -0.464331),
(0.000000, -0.866025, -0.350000),
(0.000000, -1.000000, 0.000000),
(0.000000, -0.866025, -0.500000),
(0.000000, -0.500000, -0.866025),
(0.000000, -0.000000, -1.000000)) )
rotGuiCurves.append( c )
c = curve( d=1, p=((0.000000, 0.000000, -1.000000),
(-0.500000, 0.000000, -0.866025),
(-0.866025, 0.000000, -0.500000),
(-1.000000, 0.000000, -0.000000),
(-0.350000, -0.000000, -0.000000),
(-0.116667, 0.116666, -0.116667),
(-0.000000, -0.000000, -0.350000),
(0.436239, -0.000000, -0.464331),
(0.866025, -0.000000, -0.350000),
(1.000000, -0.000000, 0.000000),
(0.866025, 0.000000, -0.500000),
(0.500000, 0.000000, -0.866025),
(0.000000, 0.000000, -1.000000)) )
rotGuiCurves.append( c )
c = curve( d=1, p=((0.000000, 1.000000, -0.000000),
(-0.500000, 0.866025, -0.000000),
(-0.866025, 0.500000, -0.000000),
(-1.000000, 0.000000, -0.000000),
(-0.350000, -0.000000, -0.000000),
(-0.116667, 0.116667, -0.116666),
(-0.000000, 0.350000, 0.000000),
(0.436239, 0.464331, -0.000000),
(0.866025, 0.350000, -0.000000),
(1.000000, -0.000000, 0.000000),
(0.866025, 0.500000, -0.000000),
(0.500000, 0.866025, -0.000000),
(0.000000, 1.000000, -0.000000)) )
rotGuiCurves.append( c )
for i, theCurve in enumerate( rotGuiCurves ):
theScale = 3
setAttr( '%s.sx' % theCurve, theScale )
setAttr( '%s.sy' % theCurve, theScale )
setAttr( '%s.sz' % theCurve, theScale )
makeIdentity( theCurve, a=True, s=True )
theCurveShape = listRelatives( theCurve, s=True, pa=True )[ 0 ]
setAttr( '%s.overrideEnabled' % theCurveShape, 1 )
setAttr( '%s.overrideDisplayType' % theCurveShape, 0 )
setAttr( '%s.overrideColor' % theCurveShape, rotGuiOverRideColor[i] )
parent( theCurveShape, theJoint, add=True, shape=True )
delete( theCurve )
def kwargsToOptionStr( kwargDict ):
toks = []
for k, v in kwargDict.iteritems():
if isinstance( v, (list, tuple) ):
v = ' '.join( v )
elif isinstance( v, bool ):
v = int( v )
toks.append( '-%s %s' % (k, v) )
return ' '.join( toks )
def createJoint( name=None ):
'''
simple wrapper to deal with joint creation - mainly provides a hook to control joint creation should that be needed
'''
if name:
if objExists( name ):
name = name +'#'
return createNode( 'joint', n=name )
return createNode( 'joint' )
def buildEndPlacer():
'''
builds a placer for the end of a chain. This is generally useful for aligning the last joint in a chain
but can also be useful for marking up interesting pivots on parts such as feet with foot edges etc...
'''
transform = createNode( 'transform' )
setAttr( '%s.displayHandle' % transform, True )
return transform
def jointSize( jointName, size ):
'''
convenience function to set the size of a joint
'''
setAttr( '%s.radius' % jointName, size )
def getRoot():
joints = ls( typ='joint' )
for j in joints:
if objExists( '%s.%s' % (j, TOOL_NAME) ):
return j
return None
class Root(SkeletonPart):
HAS_PARITY = False
@classmethod
def _build( cls, **kw ):
idx = kw[ 'idx' ]
partScale = kw[ 'partScale' ]
root = createJoint()
root = rename( root, 'root' )
move( 0, partScale / 1.75, 0, root, ws=True )
jointSize( root, 3 )
#tag the root joint with the tool name only if its the first root created - having multiple roots in a scene/skeleton is entirely valid
if idx == 0:
cmd.addAttr( ln=TOOL_NAME, at='message' )
#the root can only have a parent if its not the first root created
if idx:
move( 0, 0, -partScale / 2, root, r=True )
return [ root ]
def _buildPlacers( self ):
return []
def _align( self, _initialAlign=False ):
for i in self.selfAndOrphans():
alignItemToWorld( self[ 0 ] )
def finalize( self ):
#make sure the scale is unlocked on the base joint of the root part...
attrState( self.base, 's', False, False, True )
super( self.__class__, Root ).finalize( self )
def buildItemVolume( self, item, size, centre ):
height = size[2] / 3
width = max( size[0], size[1] ) / 3
geo = polyCube( w=width, h=height, d=width, sx=3, sy=3, sz=2, ax=(0, 0, 1), ch=True )[0]
parent( geo, item, r=True )
setAttr( '%s.t' % geo, *centre )
return [geo]
def getParent( parent=None ):
if parent is None:
#grab the selection and walk up till we find a joint
sel = ls( sl=True, type='transform' )
if sel:
obj = sel[0]
while nodeType( obj ) != 'joint':
obj = getNodeParent( obj )
if obj is None:
break
return obj
existingRoot = getRoot()
return existingRoot or Root.Create().base
if isinstance( parent, SkeletonPart ):
return parent.end
if objExists( parent ):
return parent
return getRoot() or Root.Create().base
def sortPartsByHierarchy( parts ):
'''
returns a list of the given parts in a list sorted by hierarchy
'''
sortedParts = sortByHierarchy( [ p.base for p in parts ] )
return [ SkeletonPart.InitFromItem( p ) for p in sortedParts ]
def getPartsFromObjects( objs ):
'''
returns a list of parts that have at least one of their items selected
'''
parts = []
for o in objs:
try:
parts.append( SkeletonPart.InitFromItem( o ) )
except SkeletonError: continue
selectedParts = filesystem.removeDupes( parts )
return selectedParts
@d_unifyUndo
@api.d_maintainSceneSelection
def realignSelectedParts():
'''
re-aligns all selected parts
'''
sel = ls( sl=True )
selectedParts = sortPartsByHierarchy( getPartsFromObjects( sel ) )
for part in selectedParts:
part.align()
@d_unifyUndo
@api.d_maintainSceneSelection
def realignAllParts():
'''
re-aligns all parts in the current scene
'''
for part in SkeletonPart.IterAllPartsInOrder():
try:
part.align()
except:
print 'ERROR: %s failed to align properly' % part
continue
@d_unifyUndo
@api.d_maintainSceneSelection
def finalizeAllParts():
#do a pre-pass on the skin clusters to remove un-used influences - this can speed up the speed of the alignment code
#is directly impacted by the number of joints involved in the skin cluster
skinClusters = ls( typ='skinCluster' )
for s in skinClusters:
skinCluster( s, e=True, removeUnusedInfluence=True )
failedParts = []
for part in sortPartsByHierarchy( part for part in SkeletonPart.IterAllParts() ):
part.breakDriver()
if not part.compareAgainstHash():
try:
part.finalize()
except:
failedParts.append( part )
if filesystem.IS_WING_DEBUG: raise
print 'ERROR: %s failed to finalize properly!' % part
continue
return failedParts
@d_unifyUndo
def freezeAllParts():
for part in SkeletonPart.IterAllParts():
part.freeze()
@d_unifyUndo
def setupAutoMirror():
partsInMirrorRelationship = set()
for part in SkeletonPart.IterAllParts():
if part in partsInMirrorRelationship:
continue
if part.hasParity():
idx = part.getIdx()
parity = part.getParity()
#if we have a left, look for a right
if parity == Parity.LEFT:
partToDrive = None
#try to find a matching part with the next index
for partOfType in part.IterAllParts():
if partOfType.getIdx() == idx + 1:
partToDrive = partOfType
break
#if we can't find a part with an incremented index, look for a part with the opposing parity
if not partToDrive:
for partOfType in part.IterAllParts():
if partOfType.getParity() == Parity.RIGHT:
partToDrive = partOfType
break
#if an appropriate part was found, setup the driven relationship
if partToDrive:
try:
part.driveOtherPart( partToDrive )
#if a skeleton error is thrown, ignore it (it means the parts are incompatible) but add the part to the partsInMirrorRelationship set
except SkeletonError: pass
partsInMirrorRelationship.add( part )
partsInMirrorRelationship.add( partToDrive )
def getNamespaceFromReferencing( node ):
'''
returns the namespace contribution from referencing. this is potentially
different from just querying the namespace directly from the node because the
node in question may have had a namespace before it was referenced
'''
if referenceQuery( node, isNodeReferenced=True ):
refNode = referenceQuery( node, referenceNode=True )
namespace = cmd.file( cmd.referenceQuery( refNode, filename=True ), q=True, namespace=True )
return '%s:' % namespace
return ''
@d_unifyUndo
@api.d_showWaitCursor
@api.d_maintainSceneSelection
def buildAllVolumes():
#align all parts first
for part in SkeletonPart.IterAllParts():
if not part.compareAgainstHash():
part.align()
for part in SkeletonPart.IterAllParts():
part.buildVolumes()
@d_unifyUndo
def removeAllVolumes():
for part in SkeletonPart.IterAllParts():
part.removeVolumes()
def shrinkWrap( obj, shrinkTo=None, performReverse=False ):
if shrinkTo is None:
shrinkTo = getCharacterMeshes()
if not isinstance( shrinkTo, (list, tuple) ):
shrinkTo = [ shrinkTo ]
from maya.OpenMaya import MFnMesh, MFloatPointArray, MFloatArray, MPoint, MFloatPoint, MVector, MFloatVector, MItMeshVertex, MDagPath, MSpace
kWorld = MSpace.kWorld
kTransform = MSpace.kTransform
obj = asMObject( obj )
shrinkTo = map( asMObject, shrinkTo )
#get the shape nodes...
dagObj = MDagPath.getAPathTo( obj )
dagObj.extendToShape()
#NOTE: we use the exclusive matrix because we want the object's parent - which is assumed to be the joint
dagWorldMatrix = dagObj.exclusiveMatrix()
dagWorldMatrixInv = dagObj.exclusiveMatrixInverse()
dagShinkTo = map( MDagPath.getAPathTo, shrinkTo )
for dag in dagShinkTo:
dag.extendToShape()
fnObj = MFnMesh( dagObj )
fnShrinkTo = map( MFnMesh, dagShinkTo )
aimIdx = BONE_AIM_AXIS
otherIdxs = idxA, idxB = BONE_AIM_AXIS.otherAxes()
#construct the MMeshIntersector instances
accellerators = []
for fnShrink in fnShrinkTo:
a = MFnMesh.autoUniformGridParams()
accellerators.append( a )
#now iterate over the verts in the obj, shoot rays outward in the direction of the normal and try to fit as best as
#possible to the given shrink meshes
itObjVerts = MItMeshVertex( dagObj )
vertPositions = []
while not itObjVerts.isDone():
intersects = []
pos = itObjVerts.position( kWorld )
actualPos = Vector( (pos.x, pos.y, pos.z) )
normal = MVector()
itObjVerts.getNormal( normal, kWorld )
#holy BAWLS maya is shite... MVector and MFloatVector are COMPLETELY different classes, and you can't construct one from the other?! What kind of retard wrote this API
pos = MFloatPoint( pos.x, pos.y, pos.z )
normal = MFloatVector( normal.x, normal.y, normal.z )
normal.normalize()
#now get ray intersections with the shrinkTo meshes
for fnShrinkMesh, accel in zip( fnShrinkTo, accellerators ):
hitPoints = MFloatPointArray()
def go( rev=False ):
fnShrinkMesh.allIntersections( pos, normal, #raySource, rayDirection
None, None, False, #faceIds, triIds, idsSorted
kWorld, 1000, rev, #space, maxParam, testBothDirs
accel, True, #accelParams, sortHits
hitPoints, #this is all we really care about...
None, None, None, None, None )
go()
if performReverse and not hitPoints.length():
go( performReverse )
for n in range( hitPoints.length() ):
p = hitPoints[ n ]
intersects.append( Vector( (p.x, p.y, p.z) ) ) #deal with native vectors for now...
#if there is just one intersection, easy peasy
if len( intersects ) == 1:
newPosition = intersects[0]
#otherwise we need to figure out which one is the best match...
elif intersects:
#first sort them by their distance to the vert - I think they should be sorted already, but...
sortByDist = [ ((p-actualPos).get_magnitude(), p) for p in intersects ]
sortByDist.sort()
#not sure how much guesswork to do here - so just use the closest...
newPosition = sortByDist[0][1]
#if there are no matches just use the actual vert position so we don't have to handle this case below...
else:
newPosition = actualPos
vertPositions.append( (actualPos, newPosition) )
vert = itObjVerts.next()
#now we have a list of vertex positions, figure out the average delta and clamp deltas that are too far away from this average
deltaSum = 0
numZeroDeltas = 0
for pos, newPos in vertPositions:
delta = (pos - newPos).get_magnitude()
if not delta:
numZeroDeltas += 1
deltaSum += delta
#if all deltas are zero, there is nothing to do... bail!
if len( vertPositions ) == numZeroDeltas:
return
deltaAverage = float( deltaSum ) / (len( vertPositions ) - numZeroDeltas) #don't count deltas that are zero...
clampedVertPositions = []
MAX_DIVERGENCE = 1.1 #the maximum allowable variance from the average delta
acceptableDelta = deltaAverage * MAX_DIVERGENCE
for pos, newPos in vertPositions:
if newPos is None:
clampedVertPositions.append( None )
continue
delta = (pos - newPos).get_magnitude()
#if the magnitude of the delta is too far from the average, scale down the magnitude
if delta > acceptableDelta:
deltaVector = newPos - pos
deltaVector = deltaVector * (acceptableDelta / delta)
clampedVertPositions.append( pos + deltaVector )
else:
clampedVertPositions.append( newPos )
#now set the vert positions
n = 0
itObjVerts.reset()
while not itObjVerts.isDone():
newPos = clampedVertPositions[ n ]
position = MPoint( *newPos )
itObjVerts.setPosition( position, kWorld )
n += 1
vert = itObjVerts.next()
def shrinkWrapSelection( shrinkTo=None ):
for obj in ls( sl=True, type=('mesh', 'transform') ):
makeIdentity( obj, a=True, t=True, r=True, s=True )
shrinkWrap( obj, shrinkTo )
def volumesToSkinning():
#first grab all the volumes and combine them into a single mesh, then generate weights from the original volumes (this should
#result in the duplicates being rigidly skinned to the skeleton) then transfer the weights from the combined mesh to the
#character meshes
allVolumes = []
for part in SkeletonPart.IterAllParts():
for item, volumes in part.iterItemVolumes():
allVolumes += volumes
#get the character meshes before we build the temp transfer surface
charMeshes = getCharacterMeshes()
import skinWeights
#combine them all
duplicateVolumes = duplicate( allVolumes, renameChildren=True )
makeIdentity( duplicateVolumes, a=True, t=True, r=True, s=True )
combinedVolumes = polyUnite( duplicateVolumes, ch=False )[0]
#generate weights
skinWeights.saveWeights( allVolumes )
skinWeights.loadWeights( [combinedVolumes], tolerance=2 )
#now transfer weights to the character meshes
for charMesh in charMeshes:
targetSkinCluster = skinWeights.transferSkinning( combinedVolumes, charMesh )
#now lets do a little smoothing
#skinCluster( targetSkinCluster, e=True, smoothWeights=0.65 )
"""
#JESUS!!! for some weird as piss reason maya doesn't like this python command: skinCluster( targetSkinCluster, q=True, smoothWeights=0.75 )
#nor this mel command: skinCluster -q -smoothWeights 0.75 targetSkinCluster
#you NEED to run this mel command: skinCluster -smoothWeights 0.75 -q targetSkinCluster
#which makes no goddamn sense - fuuuuuuuuuuuuuu alias!
#not to mention that the stupid as piss command returns vert indices, not components... what a bullshit api.
vertIdxs = mel.eval( "skinCluster -smoothWeights 0.5 -q %s" % targetSkinCluster )
baseStr = targetMesh +'.vtx[%d]'
select( [ baseStr % idx for idx in vertIdxs ] )
polySelectConstraint( pp=1, t=0x0001 ) #expand the selection
skinCluster( targetSkinCluster, e=True, smoothWeights=0.7, smoothWeightsMaxIterations=1 )
"""
#delete the combined meshes - we're done with them
delete( combinedVolumes )
def getSkeletonBuilderJointCount():
'''
returns a 2-tuple containing the total skeleton builder joint count, and the total number of
joints that are involved in a skin cluster
'''
#get the root joint and get a list of all joints under it
skeletonBuilderJoints = []
for rootPart in Root.IterAllParts():
skeletonBuilderJoints += rootPart.items
skeletonBuilderJoints += listRelatives( rootPart.items, ad=True, type='joint' ) or []
#generate a list of joints involved in skinning
skinnedJoints = []
for mesh in ls( type='mesh' ):
skinCluster = mel.findRelatedSkinCluster( mesh )
if skinCluster:
skinnedJoints += mel.eval( 'skinPercent -ib 0.001 -q -t %s "%s.vtx[*]"' % (skinCluster, mesh) )
#now get the intersection of the two lists - these are the joints on the character that are skinned
skinnedSkeletonBuilderJoints = set( skeletonBuilderJoints ).intersection( set( skinnedJoints ) )
return len( skeletonBuilderJoints ), len( skinnedSkeletonBuilderJoints )
def displaySkeletonBuilderJointCount():
totalJoints, skinnedJoints = getSkeletonBuilderJointCount()
return '%d skinned / %d total' % (skinnedJoints, totalJoints)
def setupSkeletonBuilderJointCountHUD():
if headsUpDisplay( HUD_NAME, ex=True ):
headsUpDisplay( HUD_NAME, rem=True )
else:
jointbb = headsUpDisplay( nfb=0 )
headsUpDisplay( HUD_NAME, section=0, block=jointbb, blockSize="small", label="Joint Count:", labelFontSize="small", command=displaySkeletonBuilderJointCount, event="SelectionChanged" ) #, nodeChanges="attributeChange"
#end
| Python |
from __future__ import with_statement
import os
import re
import sys
import time
import marshal
import datetime
import subprocess
import tempfile
import path
from path import *
from misc import iterBy
### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
### IMPORTANT: perforce is disabled by default - to enable call enablePerforce()
### !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
def getDefaultWorkingDir():
'''
perforce can be setup to use p4config files - if a user has done this, then setting the working
directory properly becomes critically important. This function gets called before spawning the
p4 processes to set the working directory. Implement the appropriate logic here for your
particular environment
'''
return None
class FinishedP4Operation(Exception): pass
class TimedOutP4Operation(Exception): pass
class P4Exception(Exception): pass
def _p4fast( *args ):
p = subprocess.Popen( 'p4 -G '+ ' '.join( args ), cwd=getDefaultWorkingDir(), shell=True, stdout=subprocess.PIPE )
results = []
try:
while True:
results.append( marshal.loads( p.stdout.read() ) )
except EOFError: pass
p.wait()
return results
class P4Output(dict):
EXIT_PREFIX = 'exit:'
ERROR_PREFIX = 'error:'
#
START_DIGITS = re.compile( '(^[0-9]+)(.*)' )
END_DIGITS = re.compile( '(.*)([0-9]+$)' )
def __init__( self, outStr, keysColonDelimited=False ):
EXIT_PREFIX = self.EXIT_PREFIX
ERROR_PREFIX = self.ERROR_PREFIX
self.errors = []
if isinstance( outStr, basestring ):
lines = outStr.split( '\n' )
elif isinstance( outStr, (list, tuple) ):
lines = outStr
else:
print outStr
raise P4Exception( "unsupported type (%s) given to %s" % (type( outStr ), self.__class__.__name__) )
delimiter = (' ', ':')[ keysColonDelimited ]
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith( EXIT_PREFIX ):
break
elif line.startswith( ERROR_PREFIX ):
self.errors.append( line )
continue
idx = line.find( delimiter )
if idx == -1:
prefix = line
data = True
else:
prefix = line[ :idx ].strip()
data = line[ idx + 1: ].strip()
if data.isdigit():
data = int( data )
if keysColonDelimited:
prefix = ''.join( [ (s, s.capitalize())[ n ] for n, s in enumerate( prefix.lower().split() ) ] )
else:
prefix = prefix[ 0 ].lower() + prefix[ 1: ]
self[ prefix ] = data
#finally, if there are prefixes which have a numeral at the end, strip it and pack the data into a list
multiKeys = {}
for k in self.keys():
m = self.END_DIGITS.search( k )
if m is None:
continue
prefix, idx = m.groups()
idx = int( idx )
data = self.pop( k )
try:
multiKeys[ prefix ].append( (idx, data) )
except KeyError:
multiKeys[ prefix ] = [ (idx, data) ]
for prefix, dataList in multiKeys.iteritems():
try:
self.pop( prefix )
except KeyError: pass
dataList.sort()
self[ prefix ] = [ d[ 1 ] for d in dataList ]
def __unicode__( self ):
return self.__str__()
def __getattr__( self, attr ):
return self[ attr ]
def asStr( self ):
if self.errors:
return '\n'.join( self.errors )
return '\n'.join( '%s: %s' % items for items in self.iteritems() )
INFO_PREFIX_RE = re.compile( '^info([0-9]*): ' )
def _p4run( *args ):
if not isPerforceEnabled():
return False
global INFO_PREFIX_RE
if '-s' not in args: #if the -s flag is in the global flags, perforce sends all data to the stdout, and prefixes all errors with "error:"
args = ('-s',) + args
cmdStr = 'p4 '+ ' '.join( map( str, args ) )
with tempfile.TemporaryFile() as tmpFile:
try:
p4Proc = subprocess.Popen( cmdStr, cwd=getDefaultWorkingDir(), shell=True, stdout=tmpFile.fileno() )
except OSError:
P4File.USE_P4 = False
return False
p4Proc.wait()
tmpFile.seek( 0 )
return [ INFO_PREFIX_RE.sub( '', line ) for line in tmpFile.readlines() ]
def p4run( *args, **kwargs ):
ret = _p4run( *args )
if ret is False:
return False
return P4Output( ret, **kwargs )
P4INFO = None
def p4Info():
global P4INFO
if P4INFO:
return P4INFO
P4INFO = p4run( 'info', keysColonDelimited=True )
if not P4INFO:
disablePerforce()
return P4INFO
def populateChange( change ):
changeNum = change[ 'change' ]
if isinstance( changeNum, int ) and changeNum:
fullChange = P4Change.FetchByNumber( changeNum )
for key, value in fullChange.iteritems():
change[ key ] = value
class P4Change(dict):
def __init__( self ):
self[ 'user' ] = ''
self[ 'change' ] = None
self[ 'description' ] = ''
self[ 'files' ] = []
self[ 'actions' ] = []
self[ 'revisions' ] = []
def __setattr__( self, attr, value ):
if isinstance( value, basestring ):
if value.isdigit():
value = int( value )
self[ attr ] = value
def __getattr__( self, attr ):
'''
if the value of an attribute is the populateChanges function (in the root namespace), then
the full changelist data is queried. This is useful for commands like the p4 changes command
(wrapped by the FetchChanges class method) which lists partial changelist data. The method
returns P4Change objects with partial data, and when more detailed data is required, a full
query can be made. This ensures minimal server interaction.
'''
value = self[ attr ]
if value is populateChange:
populateChange( self )
value = self[ attr ]
return value
def __str__( self ):
return str( self.change )
def __int__( self ):
return self[ 'change' ]
__hash__ = __int__
def __lt__( self, other ):
return self.change < other.change
def __le__( self, other ):
return self.change <= other.change
def __eq__( self, other ):
return self.change == other.change
def __ne__( self, other ):
return self.change != other.change
def __gt__( self, other ):
return self.change > other.change
def __ge__( self, other ):
return self.change >= other.change
def __len__( self ):
return len( self.files )
def __eq__( self, other ):
if isinstance( other, int ):
return self.change == other
elif isinstance( other, basestring ):
if other == 'default':
return self.change == 0
return self.change == other.change
def __iter__( self ):
return zip( self.files, self.revisions, self.actions )
@classmethod
def Create( cls, description, files=None ):
#clean the description line
description = '\n\t'.join( [ line.strip() for line in description.split( '\n' ) ] )
info = p4Info()
contents = '''Change:\tnew\n\nClient:\t%s\n\nUser:\t%s\n\nStatus:\tnew\n\nDescription:\n\t%s\n''' % (info.clientName, info.userName, description)
global INFO_PREFIX_RE
p4Proc = subprocess.Popen( 'p4 -s change -i', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
stdout, stderr = p4Proc.communicate( contents )
p4Proc.wait()
stdout = [ INFO_PREFIX_RE.sub( '', line ) for line in stdout.split( '\n' ) ]
output = P4Output( stdout )
changeNum = int( P4Output.START_DIGITS.match( output.change ).groups()[ 0 ] )
new = cls()
new.description = description
new.change = changeNum
if files is not None:
p4run( 'reopen -c', changeNum, *files )
return new
@classmethod
def FetchByNumber( cls, number ):
lines = _p4run( 'describe', number )
if not lines:
return None
change = cls()
change.change = number
toks = lines[ 0 ].split()
if 'by' in toks:
idx = toks.index( 'by' )
change.user = toks[ idx+1 ]
change.description = ''
lineIter = iter( lines[ 2: ] )
try:
prefix = 'text:'
PREFIX_LEN = len( prefix )
line = lineIter.next()
while line.startswith( prefix ):
line = line[ PREFIX_LEN: ].lstrip()
if line.startswith( 'Affected files ...' ):
break
change.description += line
line = lineIter.next()
lineIter.next()
line = lineIter.next()
while not line.startswith( prefix ):
idx = line.rfind( '#' )
depotFile = Path( line[ :idx ] )
revAndAct = line[ idx + 1: ].split()
rev = int( revAndAct[ 0 ] )
act = revAndAct[ 1 ]
change.files.append( depotFile )
change.actions.append( act )
change.revisions.append( rev )
line = lineIter.next()
except StopIteration:
pass
return change
@classmethod
def FetchByDescription( cls, description, createIfNotFound=False ):
'''
fetches a changelist based on a given description from the list of pending changelists
'''
cleanDesc = ''.join( [ s.strip() for s in description.lower().strip().split( '\n' ) ] )
for change in cls.IterPending():
thisDesc = ''.join( [ s.strip() for s in change.description.lower().strip().split( '\n' ) ] )
if thisDesc == cleanDesc:
return change
if createIfNotFound:
return cls.Create( description )
@classmethod
def FetchChanges( cls, *args ):
'''
effectively runs the command:
p4 changes -l *args
a list of P4Change objects is returned
'''
lines = _p4run( 'changes -l %s' % ' '.join( args ) )
changes = []
if lines:
lineIter = iter( lines )
curChange = None
try:
while True:
line = lineIter.next()
if line.startswith( 'Change' ):
curChange = cls()
changes.append( curChange )
toks = line.split()
curChange.change = int( toks[ 1 ] )
curChange.user = toks[ -1 ]
curChange.date = datetime.date( *list( map( int, toks[ 3 ].split( '/' ) ) ) )
curChange.description = ''
#setup triggers for other data in the changelist that doesn't get returned by the changes command - see the __getattr__ doc for more info
curChange.files = populateChange
curChange.actions = populateChange
curChange.revisions = populateChange
elif curChange is not None:
curChange.description += line
except StopIteration:
return changes
@classmethod
def IterPending( cls ):
'''
iterates over pending changelists
'''
info = p4Info()
for line in _p4run( 'changes -u %s -s pending -c %s' % (info.userName, info.clientName) ):
toks = line.split()
try:
changeNum = int( toks[ 1 ] )
except IndexError: continue
yield cls.FetchByNumber( changeNum )
#the number of the default changelist
P4Change.CHANGE_NUM_DEFAULT = P4Change()
P4Change.CHANGE_NUM_DEFAULT.change = 0
#the object to represent invalid changelist numbers
P4Change.CHANGE_NUM_INVALID = P4Change()
#all opened perforce files get added to a changelist with this description by default
DEFAULT_CHANGE = 'default auto-checkout'
#gets called when a perforce command takes too long (defined by P4File.TIMEOUT_PERIOD)
P4_LENGTHY_CALLBACK = None
#gets called when a lengthy perforce command finally returns
P4_RETURNED_CALLBACK = None
class P4File(Path):
'''
provides a more convenient way of interfacing with perforce. NOTE: where appropriate all actions
are added to the changelist with the description DEFAULT_CHANGE
'''
USE_P4 = False
#the default change description for instances
DEFAULT_CHANGE = DEFAULT_CHANGE
BINARY = 'binary'
XBINARY = 'xbinary'
TIMEOUT_PERIOD = 5
def run( self, *args, **kwargs ):
return p4run( *args, **kwargs )
def getFile( self, f=None ):
if f is None:
return self
return Path( f )
def getFileStr( self, f=None, allowMultiple=False, verifyExistence=True ):
if f is None:
return '"%s"' % self
if isinstance( f, (list, tuple) ):
if verifyExistence: return '"%s"' % '" "'.join( [ anF for anF in f if Path( anF ).exists() ] )
else: return '"%s"' % '" "'.join( f )
return '"%s"' % Path( f )
def getStatus( self, f=None ):
'''
returns the status dictionary for the instance. if the file isn't managed by perforce,
None is returned
'''
if not self.USE_P4:
return None
f = self.getFile( f )
try:
return self.run( 'fstat', f )
except Exception: return None
def isManaged( self, f=None ):
'''
returns True if the file is managed by perforce, otherwise False
'''
if not self.USE_P4:
return False
f = self.getFile( f )
stat = self.getStatus( f )
if stat:
#if the file IS managed - only return true if the head action isn't delete - which effectively means the file
#ISN'T managed...
try:
return stat[ 'headAction' ] != 'delete'
except KeyError:
#this can happen if the file is a new file and is opened for add
return True
return False
managed = isManaged
def isUnderClient( self, f=None ):
'''
returns whether the file is in the client's root
'''
if not self.USE_P4:
return False
f = self.getFile( f )
results = _p4fast( 'fstat', f )
if results:
fstatDict = results[0]
if 'code' in fstatDict:
if fstatDict[ 'code' ] == 'error':
phrases = [ "not in client view", "not under" ]
dataStr = fstatDict[ 'data' ].lower()
for ph in phrases:
if ph in dataStr:
return False
return True
def getAction( self, f=None ):
'''
returns the head "action" of the file - if the file isn't in perforce None is returned...
'''
if not self.USE_P4:
return None
f = self.getFile( f )
data = self.getStatus( f )
try:
return data.get( 'action', None )
except AttributeError: return None
action = property( getAction )
def getHaveHead( self, f=None ):
if not self.USE_P4:
return False
f = self.getFile( f )
data = self.getStatus( f )
try:
return data[ 'haveRev' ], data[ 'headRev' ]
except (AttributeError, TypeError, KeyError):
return None, None
def isEdit( self, f=None ):
if not self.USE_P4:
return False
editActions = [ 'add', 'edit' ]
action = self.getAction( f )
#if the action is none, the file may not be managed - check
if action is None:
if not self.getStatus( f ):
return None
return action in editActions
def isLatest( self, f=None ):
'''
returns True if the user has the latest version of the file, otherwise False
'''
#if no p4 integration, always say everything is the latest to prevent complaints from tools
if not self.USE_P4:
return True
status = self.getStatus( f )
if not status:
return None
#if there is any action on the file then always return True
if 'action' in status:
return True
#otherwise check revision numbers
try:
headRev, haveRev = status[ 'headRev' ], status[ 'haveRev' ]
return headRev == haveRev
except KeyError:
return False
def add( self, f=None, type=None ):
if not self.USE_P4:
return False
try:
args = [ 'add', '-c', self.getOrCreateChange() ]
except:
return False
#if the type has been specified, add it to the add args
if type is not None:
args += [ '-t', type ]
args.append( self.getFile( f ) )
ret = p4run( *args )
if ret.errors:
return False
return True
def edit( self, f=None ):
f = self.getFile( f )
if not isPerforceEnabled():
#if p4 is disabled but the file is read-only, set it to be writeable...
if not f.getWritable():
f.setWritable()
return False
#if the file is already writeable, assume its checked out already
if f.getWritable():
return True
try:
ret = p4run( 'edit', '-c', self.getOrCreateChange(), self.getFile( f ) )
except:
return False
if ret.errors:
return False
return True
def editoradd( self, f=None ):
if self.edit( f ):
return True
if self.add( f ):
return True
return False
def revert( self, f=None ):
if not self.USE_P4:
return False
return self.run( 'revert', self.getFile( f ) )
def sync( self, f=None, force=False, rev=None, change=None ):
'''
rev can be a negative number - if it is, it works as previous revisions - so rev=-1 syncs to
the version prior to the headRev. you can also specify the change number using the change arg.
if both a rev and a change are specified, the rev is used
'''
if not self.USE_P4:
return False
f = self.getFile( f )
#if file is a directory, then we want to sync to the dir
f = str( f.asfile() )
if not f.startswith( '//' ): #depot paths start with // - but windows will try to poll the network for a computer with the name, so if it starts with //, assume its a depot path
if os.path.isdir( f ):
f = '%s/...' % f
if rev is not None:
if rev == 0: f += '#none'
elif rev < 0:
status = self.getStatus()
headRev = status[ 'headRev' ]
rev += int( headRev )
if rev <= 0: rev = 'none'
f += '#%s' % rev
else: f += '#%s' % rev
elif change is not None:
f += '@%s' % change
if force: return self.run( 'sync', '-f', f )
else: return self.run( 'sync', f )
def delete( self, f=None ):
if not self.USE_P4:
return False
f = self.getFile( f )
action = self.getAction( f )
if action is None and self.managed( f ):
return self.run( 'delete', '-c', self.getOrCreateChange(), f )
def remove( self, f=None ):
if not self.USE_P4:
return False
self.sync( f, rev=0 )
def rename( self, newName, f=None ):
if not self.USE_P4:
return False
f = self.getFile( f )
try:
action = self.getAction( f )
if action is None and self.managed( f ):
self.run( 'integrate', '-c', self.getOrCreateChange(), f, str( newName ) )
return self.run( 'delete', '-c', self.getOrCreateChange(), f )
except Exception: pass
return False
def copy( self, newName, f=None ):
if not self.USE_P4:
return False
f = self.getFile( f )
newName = self.getFile( newName )
action = self.getAction( f )
if self.managed( f ):
return self.run( 'integrate', '-c', self.getOrCreateChange(), f, newName )
return False
def submit( self, change=None ):
if not self.USE_P4:
return
if change is None:
change = self.getChange().change
self.run( 'submit', '-c', change )
def getChange( self, f=None ):
if not self.USE_P4:
return P4Change.CHANGE_NUM_INVALID
f = self.getFile( f )
stat = self.getStatus( f )
try:
return stat.get( 'change', P4Change.CHANGE_NUM_DEFAULT )
except (AttributeError, ValueError): return P4Change.CHANGE_NUM_DEFAULT
def setChange( self, newChange=None, f=None ):
'''
sets the changelist the file belongs to. the changelist can be specified as either a changelist
number, a P4Change object, or a description. if a description is given, the existing pending
changelists are searched for a matching description. use 0 for the default changelist. if
None is passed, then the changelist as described by self.DEFAULT_CHANGE is used
'''
if not self.USE_P4:
return
if isinstance( newChange, (int, long) ):
change = newChange
elif isinstance( newChange, P4Change ):
change = newChange.change
else:
change = P4Change.FetchByDescription( newChange, True ).change
f = self.getFile( f )
self.run( 'reopen', '-c', change, f )
def getOtherOpen( self, f=None ):
f = self.getFile( f )
statusDict = self.getStatus( f )
try:
return statusDict[ 'otherOpen' ]
except (KeyError, TypeError):
return []
def getOrCreateChange( self, f=None ):
'''
if the file isn't already in a changelist, this will create one. returns the change number
'''
if not self.USE_P4:
return P4Change.CHANGE_NUM_INVALID
f = self.getFile( f )
ch = self.getChange( f )
if ch == P4Change.CHANGE_NUM_DEFAULT:
return P4Change.FetchByDescription( self.DEFAULT_CHANGE, True ).change
return ch
def getChangeNumFromDesc( self, description=None, createIfNotFound=True ):
if description is None:
description = self.DEFAULT_CHANGE
return P4Change.FetchByDescription( description, createIfNotFound ).change
def allPaths( self, f=None ):
'''
returns all perforce paths for the file (depot path, workspace path and disk path)
'''
if not self.USE_P4:
return None
f = self.getFile( f )
return toDepotAndDiskPaths( [f] )[ 0 ]
def toDepotPath( self, f=None ):
'''
returns the depot path to the file
'''
if not self.USE_P4:
return None
return self.allPaths( f )[ 0 ]
def toDiskPath( self, f=None ):
'''
returns the disk path to a depot file
'''
if not self.USE_P4:
return None
return self.allPaths( f )[ 1 ]
P4Data = P4File #used to be called P4Data - this is just for any legacy references...
path.P4File = P4File #insert the class into the path script... HACKY!
###--- Add Perforce Integration To Path Class ---###
def asP4( self ):
'''
returns self as a P4File instance - the instance is cached so repeated calls to this
method will result in the same P4File instance being returned.
NOTE: the caching is done within the method, it doesn't rely on the cache decorators
used elsewhere in this class, so it won't get blown away on cache flush
'''
try:
return self.p4
except AttributeError:
self.p4 = P4File(self)
return self.p4
def edit( self ):
'''
if the file exists and is in perforce, this will open it for edit - if the file isn't in perforce
AND exists then this will open the file for add, otherwise it does nothing
'''
if self.exists():
return self.asP4().editoradd()
return False
editoradd = edit
def add( self, type=None ):
return self.asP4().add()
def revert( self ):
return self.asP4().revert()
def asDepot( self ):
'''
returns this instance as a perforce depot path
'''
return self.asP4().toDepotPath()
#now wrap existing methods on the Path class - like write, delete, copy etc so that they work nicely with perforce
pathWrite = Path.write
def _p4write( filepath, contentsStr, doP4=True ):
'''
wraps Path.write: if doP4 is true, the file will be either checked out of p4 before writing or add to perforce
after writing if its not managed already
'''
assert isinstance( filepath, Path )
if doP4 and isPerforceEnabled():
hasBeenHandled = False
isUnderClient = P4File().isUnderClient( filepath )
if filepath.exists():
#assume if its writeable that its open for edit already
if not filepath.getWritable():
_p4fast( 'edit', filepath )
if not filepath.getWritable():
filepath.setWritable()
hasBeenHandled = True
ret = pathWrite( filepath, contentsStr )
if isUnderClient and not hasBeenHandled:
_p4fast( 'add', filepath )
return ret
return pathWrite( filepath, contentsStr )
pathPickle = Path.pickle
def _p4Pickle( filepath, toPickle, doP4=True ):
assert isinstance( filepath, Path )
if doP4 and isPerforceEnabled():
hasBeenHandled = False
isUnderClient = P4File().isUnderClient( filepath )
if filepath.exists():
if not filepath.getWritable():
_p4fast( 'edit', filepath )
if not filepath.getWritable():
filepath.setWritable()
hasBeenHandled = True
ret = pathPickle( filepath, toPickle )
if isUnderClient and not hasBeenHandled:
#need to explicitly add pickled files as binary type files, otherwise p4 mangles them
_p4fast( 'add -t binary', filepath )
return ret
return pathPickle( filepath, toPickle )
pathDelete = Path.delete
def _p4Delete( filepath, doP4=True ):
if doP4 and isPerforceEnabled():
try:
asP4 = P4File( filepath )
if asP4.managed():
if asP4.action is None:
asP4.delete()
if not filepath.exists():
return
else:
asP4.revert()
asP4.delete()
#only return if the file doesn't exist anymore - it may have been open for add in
#which case we still need to do a normal delete...
if not filepath.exists():
return
except Exception, e: pass
return pathDelete( filepath )
pathRename = Path.rename
def _p4Rename( filepath, newName, nameIsLeaf=False, doP4=True ):
'''
it is assumed newPath is a fullpath to the new dir OR file. if nameIsLeaf is True then
newName is taken to be a filename, not a filepath. the instance is modified in place.
if the file is in perforce, then a p4 rename (integrate/delete) is performed
'''
newPath = Path( newName )
if nameIsLeaf:
newPath = filepath.up() / newName
if filepath.isfile():
tgtExists = newPath.exists()
if doP4 and isPerforceEnabled():
reAdd = False
change = None
asP4 = P4File( filepath )
#if its open for add, revert - we're going to rename the file...
if asP4.action == 'add':
asP4.revert()
change = asP4.getChange()
reAdd = True
#so if we're managed by p4 - try a p4 rename, and return on success. if it
#fails however, then just do a normal rename...
if asP4.managed():
asP4.rename( newPath )
return newPath
#if the target exists and is managed by p4, make sure its open for edit
if tgtExists and asP4.managed( newPath ):
_p4fast( 'edit', newPath )
#now perform the rename
ret = pathRename( filepath, newName, nameIsLeaf )
if reAdd:
_p4fast( 'add', newPath )
asP4.setChange( change, newPath )
return ret
elif filepath.isdir():
raise NotImplementedError( 'dir renaming not implemented yet...' )
return pathRename( filepath, newName, nameIsLeaf )
pathCopy = Path.copy
def _p4Copy( filepath, target, nameIsLeaf=False, doP4=True ):
'''
same as rename - except for copying. returns the new target name
'''
if filepath.isfile():
target = Path( target )
if nameIsLeaf:
target = filepath.up() / target
if doP4 and isPerforceEnabled():
try:
asP4 = P4File( filepath )
tgtAsP4 = P4File( target )
if asP4.managed() and tgtAsP4.isUnderClient():
#so if we're managed by p4 - try a p4 rename, and return on success. if it
#fails however, then just do a normal rename...
asP4.copy( target )
return target
except: pass
return pathCopy( filepath )
def lsP4( queryStr, includeDeleted=False ):
'''
returns a list of dict's containing the clientFile, depotFile, headRev, headChange and headAction
'''
filesAndDicts = []
queryLines = _p4run( 'files', queryStr )
for line in queryLines:
fDict = {}
toks = line.split( ' ' )
#deal with error lines, or exit lines (an exit prefix may not actually mean the end of the data - the query may have been broken into batches)
if line.startswith( 'exit' ):
continue
if line.startswith( 'error' ):
continue
fData = toks[ 0 ]
idx = fData.index( '#' )
f = Path( fData[ :idx ] )
fDict[ 'depotPath' ] = f
rev = int( fData[ idx+1: ] )
fDict[ 'headRev' ] = rev
action = toks[ 2 ]
fDict[ 'headAction' ] = action
if action == 'delete' and not includeDeleted:
continue
fDict[ 'headChange' ] = toks[ 4 ]
filesAndDicts.append( (f, fDict) )
diskPaths = toDiskPaths( [f[0] for f in filesAndDicts] )
lsResult = []
for diskPath, (f, fDict) in zip( diskPaths, filesAndDicts ):
fDict[ 'clientFile' ] = diskPath
lsResult.append( fDict )
return lsResult
def toDepotAndDiskPaths( files ):
caseMatters = Path.DoesCaseMatter()
lines = []
for filesChunk in iterBy( files, 15 ):
lines += _p4run( 'where', *filesChunk )[ :-1 ] #last line is the "exit" line...
paths = []
for f, line in zip( map( Path, files ), lines ):
fName = f[ -1 ]
fNameLen = len( fName )
manipLine = line
if not caseMatters:
manipLine = line.lower()
fName = fName.lower()
#I'm not entirely sure this is bullet-proof... but basically the return string for this command
#is a simple space separated string, with three values. i guess I could try to match //HOSTNAME
#and the client's depot root to find the start of files, but for now its simply looking for the
#file name substring three times
depotNameIdx = manipLine.find( fName ) + fNameLen
depotName = P4File( line[ :depotNameIdx ], caseMatters )
workspaceNameIdx = manipLine.find( fName, depotNameIdx ) + fNameLen
#workspaceName = P4File( line[ depotNameIdx + 1:workspaceNameIdx ], caseMatters )
diskNameIdx = manipLine.find( fName, workspaceNameIdx ) + fNameLen
diskName = P4File( line[ workspaceNameIdx + 1:diskNameIdx ], caseMatters )
paths.append( (depotName, diskName) )
return paths
def toDepotPaths( files ):
'''
return the depot paths for the given list of disk paths
'''
return [ depot for depot, disk in toDepotAndDiskPaths( files ) ]
def toDiskPaths( files ):
'''
return the depot paths for the given list of disk paths
'''
return [ disk for depot, disk in toDepotAndDiskPaths( files ) ]
def isPerforceEnabled():
return P4File.USE_P4
def enablePerforce( state=True ):
'''
sets the enabled state of perforce
'''
P4File.USE_P4 = bool( state )
#hook up various convenience functions on the Path class, and plug in the overrides for operations
#such as write, delete, rename etc... This makes using perforce in conjunction with the Path class
#transparent to the programmer
if state:
Path.asP4 = asP4
Path.edit = edit
Path.editoradd = edit
Path.add = add
Path.revert = revert
Path.asDepot = asDepot
Path.write = _p4write
Path.pickle = _p4Pickle
Path.delete = _p4Delete
Path.rename = _p4Rename
Path.copy = _p4Copy
#restore the overridden methods on the Path class and delete any of the convenience methods added
else:
try:
del( Path.asP4 )
del( Path.edit )
del( Path.editoradd )
del( Path.add )
del( Path.revert )
del( Path.asDepot )
#if any of the above throw an Attribute error, presumably perforce hasn't been setup yet so assume none are present and just pass
except AttributeError: pass
#if perforce hasn't been setup already, doing this is harmless...
Path.write = pathWrite
Path.pickle = pathPickle
Path.delete = pathDelete
Path.rename = pathRename
Path.copy = pathCopy
def disablePerforce():
'''
alias for enablePerforce( False )
'''
enablePerforce( False )
def d_preserveDefaultChange(f):
'''
decorator to preserve the default changelist
'''
def newF( *a, **kw ):
global DEFAULT_CHANGE
preChange = DEFAULT_CHANGE
try: f( *a, **kw )
except:
DEFAULT_CHANGE = preChange
raise
DEFAULT_CHANGE = preChange
newF.__doc__ = f.__doc__
newF.__name__ = f.__name__
return newF
def syncFiles( files, force=False, rev=None, change=None ):
'''
syncs a given list of files to either the headRev (default) or a given changelist,
or a given revision number
'''
p4 = P4File()
if rev is not None:
ret = []
for f in files:
if force:
r = p4.sync( '-f', f, rev )
else:
r = p4.sync( f, rev )
ret.append( r )
return ret
elif change is not None:
args = [ 'sync' ]
if force:
args.append( '-f' )
args += [ '%s@%d' % (f, change) for f in files ]
return p4run( *args )
else:
args = files
if force:
args = [ '-f' ] + args
return p4.run( 'sync', *args )
def findStaleFiles( fileList ):
'''
given a list of files (can be string paths or Path instances) returns a list of "stale" files. stale files are simply
files that aren't at head revision
'''
p4 = P4File()
stale = []
for f in fileList:
latest = p4.isLatest( f )
if latest is None:
continue
if not latest:
stale.append( f )
return stale
def gatherFilesIntoChange( files, change=None ):
'''
gathers the list of files into a single changelist - if no change is specified, then the
default change is used
'''
p4 = P4File()
filesGathered = []
for f in files:
if not isinstance( f, Path ): f = Path( f )
try:
stat = p4.getStatus( f )
except IndexError: continue
if not stat:
try:
if not f.exists():
continue
except TypeError: continue
#in this case, the file isn't managed by perforce - so add it
print 'adding file:', f
p4.add( f )
p4.setChange(change, f)
filesGathered.append( f )
continue
#otherwise, see what the action is on the file - if there is no action then the user hasn't
#done anything to the file, so move on...
try:
action = stat[ 'action' ]
p4.setChange( change, f )
filesGathered.append( f )
except KeyError: continue
return filesGathered
def cleanEmptyChanges():
p4 = P4File()
for change in P4Change.IterPending():
deleteIt = False
try:
deleteIt = not change.files
except KeyError: deleteIt = True
if deleteIt:
p4run( 'change -d', str( change ) )
def findRedundantPYCs( rootDir=None, recursive=True ):
'''
lists all orphaned files under a given directory. it does this by looking at the pyc/pyo file and seeing if its corresponding
py file exists on disk, or in perforce in any form. if it does, it deletes the file...
'''
if rootDir is None:
rootDir = tools()
bytecodeExtensions = [ 'pyc', 'pyo' ]
exceptions = [ 'p4' ]
rootDir = Path( rootDir )
orphans = []
if rootDir.exists():
p4 = P4File()
files = rootDir.files( recursive=recursive )
bytecodeFiles = []
for f in files:
for byteXtn in bytecodeExtensions:
if f.hasExtension( byteXtn ):
if f.name().lower() in exceptions:
continue
bytecodeFiles.append( f )
for f in bytecodeFiles:
pyF = Path( f ).setExtension( 'py' )
#is there a corresponding py script for this file? if it does, the pyc is safe to delete - so delete it
if pyF.exists():
f.reason = 'corresponding py script found'
orphans.append( f )
continue
#if no corresponding py file exists for the pyc, then see if there is/was one in perforce... if the
#corresponding py file is in perforce in any way, shape or form, then delete the .pyc file - its derivative and
#can/will be re-generated when needed
stat = p4.getStatus( pyF )
if stat is None:
continue
f.reason = 'corresponding py file in perforce'
orphans.append( f )
return rootDir, orphans
def deleteRedundantPYCs( rootDir=None, recursive=True, echo=False ):
'''
does a delete on orphaned pyc/pyo files
'''
rootDir, orphans = findRedundantPYCs( rootDir, recursive )
for f in orphans:
if echo:
try:
print f - rootDir, f.reason
except AttributeError:
pass
f.delete()
| Python |
from path import *
from misc import removeDupes
LOCALES = LOCAL, GLOBAL = 'local', 'global'
DEFAULT_XTN = 'preset'
#define where the base directories are for presets
kLOCAL_BASE_DIR = Path('%HOME%/presets/')
kGLOBAL_BASE_DIR = Path( __file__ ).up( 2 )
class PresetException(Exception):
def __init__( self, *args ):
Exception.__init__(self, *args)
def getPresetDirs( locale, tool ):
'''
returns the base directory for a given tool's preset files
'''
if locale == LOCAL:
localDir = kLOCAL_BASE_DIR / tool
localDir.create()
return [localDir]
globalDir = kGLOBAL_BASE_DIR / tool
globalDir.create()
return [globalDir]
def presetPath( locale, tool, presetName, ext=DEFAULT_XTN ):
preset = getPresetDirs(locale, tool)[0] + scrubName(presetName, exceptions='./')
preset = preset.setExtension( ext )
return preset
def readPreset( locale, tool, presetName, ext=DEFAULT_XTN ):
'''
reads in a preset file if it exists, returning its contents
'''
file = getPresetPath(presetName, tool, ext, locale)
if file is not None:
return file.read()
return []
def savePreset( locale, tool, presetName, ext=DEFAULT_XTN, contentsStr='' ):
'''
given a contents string, this convenience method will store it to a preset file
'''
preset = Preset(locale, tool, presetName, ext)
preset.write( contentsStr )
return preset
def unpicklePreset( locale, tool, presetName, ext=DEFAULT_XTN ):
'''
same as readPreset except for pickled presets
'''
dirs = getPresetDirs(locale, tool)
for dir in dirs:
cur = dir/presetName
cur.extension = ext
if cur.exists: return cur.unpickle()
raise IOError("file doesn't exist!")
def picklePreset( locale, tool, presetName, ext=DEFAULT_XTN, contentsObj=None ):
preset = presetPath(locale, tool, presetName, ext)
preset.pickle(contentsObj, locale==GLOBAL)
def listPresets( locale, tool, ext=DEFAULT_XTN ):
'''
lists the presets in a given local for a given tool
'''
files = []
alreadyAdded = set()
for d in getPresetDirs(locale, tool):
if d.exists:
for f in d.files():
if f.name() in alreadyAdded: continue
if f.hasExtension( ext ):
files.append( f )
alreadyAdded.add( f.name() )
#remove duplicates
files = removeDupes( files )
files = [ Preset.FromFile( f ) for f in files ]
return files
def listAllPresets( tool, ext=DEFAULT_XTN, localTakesPrecedence=False ):
'''
lists all presets for a given tool and returns a dict with local and global keys. the dict
values are lists of Path instances to the preset files, and are unique - so a preset in the
global list will not appear in the local list by default. if localTakesPrecedence is True,
then this behaviour is reversed, and locals will trump global presets of the same name
'''
primaryLocale = GLOBAL
secondaryLocale = LOCAL
primary = listPresets(primaryLocale, tool, ext)
secondary = listPresets(secondaryLocale, tool, ext)
if localTakesPrecedence:
primary, secondary = secondary, primary
primaryLocale, secondaryLocale = secondaryLocale, primaryLocale
#so teh localTakesPrecedence determines which locale "wins" when there are leaf name clashes
#ie if there is a preset in both locales called "yesplease.preset", if localTakesPrecedence is
#False, then the global one gets included, otherwise the local one is listed
alreadyAdded = set()
locales = {LOCAL:[], GLOBAL:[]}
for p in primary:
locales[ primaryLocale ].append( p )
alreadyAdded.add( p.name() )
for p in secondary:
if p.name() in alreadyAdded: continue
locales[ secondaryLocale ].append( p )
return locales
def getPresetPath( presetName, tool, ext=DEFAULT_XTN, locale=GLOBAL ):
'''
given a preset name, this method will return a path to that preset if it exists. it respects the project's
mod hierarchy, so it may return a path to a file not under the current mod's actual preset directory...
'''
searchPreset = '%s.%s' % (presetName, ext)
dirs = getPresetDirs(locale, tool)
for dir in dirs:
presetPath = dir / searchPreset
if presetPath.exists:
return presetPath
def findPreset( presetName, tool, ext=DEFAULT_XTN, startLocale=LOCAL ):
'''
looks through all locales and all search mods for a given preset name. the startLocale simply dictates which
locale is searched first - so if a preset exists under both locales, then then one found in the startLocale
will get returned
'''
other = list( LOCALES ).remove( startLocale )
for loc in [ startLocale, other ]:
p = getPresetPath( presetName, tool, ext, loc )
if p is not None: return p
def dataFromPresetPath( path ):
'''
returns a tuple containing the locale, tool, name, extension for a given Path instance. a PresetException
is raised if the path given isn't an actual preset path
'''
locale, tool, name, ext = None, None, None, None
pathCopy = Path( path )
if pathCopy.isUnder( kGLOBAL_BASE_DIR ):
locale = GLOBAL
pathCopy -= kGLOBAL_BASE_DIR
elif pathCopy.isUnder( kLOCAL_BASE_DIR ):
locale = LOCAL
pathCopy -= kLOCAL_BASE_DIR
else:
raise PresetException("%s isn't under the local or the global preset dir" % file)
tool = pathCopy[ -2 ]
ext = pathCopy.getExtension()
name = pathCopy.name()
return locale, tool, name, ext
def scrubName( theStr, replaceChar='_', exceptions=None ):
invalidChars = """`~!@#$%^&*()-+=[]\\{}|;':"/?><., """
if exceptions:
for char in exceptions:
invalidChars = invalidChars.replace(char, '')
for char in invalidChars:
theStr = theStr.replace(char, '_')
return theStr
#these are a bunch of variables used for keys in the export dict. they're provided mainly for
#the sake of auto-completion...
kEXPORT_DICT_USER = 'user'
kEXPORT_DICT_MACHINE = 'machine'
kEXPORT_DICT_DATE = 'date'
kEXPORT_DICT_TIME = 'time'
kEXPORT_DICT_PROJECT = 'project'
kEXPORT_DICT_CONTENT = 'content'
kEXPORT_DICT_TOOL = 'tool_name'
kEXPORT_DICT_TOOL_VER = 'tool_version'
kEXPORT_DICT_SOURCE = 'scene' #the source of the file - if any
def writeExportDict( toolName=None, toolVersion=None, **kwargs ):
'''
returns a dictionary containing a bunch of common info to write when generating presets
or other such export type data
'''
d = {}
now = datetime.datetime.now()
d[ kEXPORT_DICT_DATE ], d[ kEXPORT_DICT_TIME ] = now.date(), now.time()
d[ kEXPORT_DICT_TOOL ] = toolName
d[ kEXPORT_DICT_TOOL_VER ] = toolVersion
#add the data in kwargs to the export dict - NOTE: this is done using setdefault so its not possible
#to clobber existing keys by specifying them as kwargs...
for key, value in kwargs.iteritems():
d.setdefault(key, value)
return d
class PresetManager(object):
def __init__( self, tool, ext=DEFAULT_XTN ):
self.tool = tool
self.extension = ext
def getPresetDirs( self, locale=GLOBAL ):
'''
returns the base directory for a given tool's preset files
'''
return getPresetDirs(locale, self.tool)
def presetPath( self, name, locale=GLOBAL ):
return Preset(locale, self.tool, name, self.extension)
def findPreset( self, name, startLocale=LOCAL ):
return Preset( *dataFromPresetPath( findPreset(name, self.tool, self.extension, startLocale) ) )
def listPresets( self, locale=GLOBAL ):
return listPresets(locale, self.tool, self.extension)
def listAllPresets( self, localTakesPrecedence=False ):
return listAllPresets(self.tool, self.extension, localTakesPrecedence)
class Preset(Path):
'''
provides a convenient way to write/read and otherwise handle preset files
'''
def __new__( cls, locale, tool, name, ext=DEFAULT_XTN ):
'''
locale should be one of either GLOBAL or LOCAL object references. tool is the toolname
used to refer to all presets of that kind, while ext is the file extension used to
differentiate between multiple preset types a tool may have
'''
name = scrubName(name, exceptions='./')
path = getPresetPath(name, tool, ext, locale)
if path is None:
path = presetPath(locale, tool, name, ext)
return Path.__new__( cls, path )
def __init__( self, locale, tool, name, ext=DEFAULT_XTN ):
self.locale = locale
self.tool = tool
@staticmethod
def FromFile( filepath ):
return Preset(*dataFromPresetPath(filepath))
FromPreset = FromFile
def up( self, levels=1 ):
return Path( self ).up( levels )
def other( self ):
'''
returns the "other" locale - ie if teh current instance points to a GLOBAL preset, other()
returns LOCAL
'''
if self.locale == GLOBAL:
return LOCAL
else: return GLOBAL
def copy( self ):
'''
copies the current instance from its current locale to the "other" locale. handles all
perforce operations when copying a file from one locale to the other. NOTE: the current
instance is not affected by a copy operation - a new Preset instance is returned
'''
other = self.other()
otherLoc = getPresetDirs(other, self.tool)[0]
dest = otherLoc / self[-1]
destP4 = None
addToP4 = False
##in this case, we want to make sure the file is open for edit, or added to p4...
#if other == GLOBAL:
#destP4 = P4File(dest)
#if destP4.managed():
#destP4.edit()
#print 'opening %s for edit' % dest
#else:
#addToP4 = True
Path.copy(self, dest)
#if addToP4:
##now if we're adding to p4 - we need to know if the preset is a pickled preset - if it is, we need
##to make sure we add it as a binary file, otherwise p4 assumes text, which screws up the file
#try:
#self.unpickle()
#destP4.add(type=P4File.BINARY)
#except Exception, e:
##so it seems its not a binary file, so just do a normal add
#print 'exception when trying to unpickle - assuming a text preset', e
#destP4.add()
#print 'opening %s for add' % dest
return Preset(self.other(), self.tool, self.name(), self.extension)
def move( self ):
'''
moves the preset from the current locale to the "other" locale. all instance variables are
updated to point to the new location for the preset
'''
newLocation = self.copy()
#delete the file from disk - and handle p4 reversion if appropriate
self.delete()
#now point instance variables to the new locale
self.locale = self.other()
return self.FromFile( newLocation )
def rename( self, newName ):
'''
newName needs only be the new name for the preset - extension is optional. All perforce
transactions are taken care of. all instance attributes are modified in place
ie: a = Preset(GLOBAL, 'someTool', 'presetName')
a.rename('the_new_name)
'''
if not newName.endswith(self.extension):
newName = '%s.%s' % (newName, self.extension)
return Path.rename(self, newName, True)
def getName( self ):
return Path(self).setExtension()[-1]
#end
| Python |
import inspect
def removeDupes( iterable ):
'''
'''
unique = set()
newIterable = iterable.__class__()
for item in iterable:
if item not in unique: newIterable.append(item)
unique.add(item)
return newIterable
def iterBy( iterable, count ):
'''
returns an generator which will yield "chunks" of the iterable supplied of size "count". eg:
for chunk in iterBy( range( 7 ), 3 ): print chunk
results in the following output:
[0, 1, 2]
[3, 4, 5]
[6]
'''
cur = 0
i = iter( iterable )
while True:
try:
toYield = []
for n in range( count ): toYield.append( i.next() )
yield toYield
except StopIteration:
if toYield: yield toYield
break
def findMostRecentDefitionOf( variableName ):
'''
'''
try:
fr = inspect.currentframe()
frameInfos = inspect.getouterframes( fr, 0 )
#in this case, walk up the caller tree and find the first occurance of the variable named <variableName>
for frameInfo in frameInfos:
frame = frameInfo[0]
var = None
if var is None:
try:
var = frame.f_locals[ variableName ]
return var
except KeyError: pass
try:
var = frame.f_globals[ variableName ]
return var
except KeyError: pass
#NOTE: this method should never ever throw an exception...
except: pass
def getArgDefault( function, argName ):
'''
returns the default value of the given named arg. if the arg doesn't exist,
or a NameError is raised. if the given arg has no default an IndexError is
raised.
'''
args, va, vkw, defaults = inspect.getargspec( function )
if argName not in args:
raise NameError( "The given arg does not exist in the %s function" % function )
args.reverse()
idx = args.index( argName )
try:
return list( reversed( defaults ) )[ idx ]
except IndexError:
raise IndexError( "The function %s has no default for the %s arg" % (function, argName) )
#end
| Python |
from __future__ import with_statement
from cacheDecorators import *
import os
import re
import sys
import stat
import shutil
import cPickle
import datetime
#the mail server used to send mail
MAIL_SERVER = 'exchange'
DEFAULT_AUTHOR = 'default_username@your_domain.com'
#set the pickle protocol to use
PICKLE_PROTOCOL = 2
#set some variables for separators
NICE_SEPARATOR = '/'
NASTY_SEPARATOR = '\\'
NATIVE_SEPARATOR = (NICE_SEPARATOR, NASTY_SEPARATOR)[ os.name == 'nt' ]
PATH_SEPARATOR = '/' #(NICE_SEPARATOR, NASTY_SEPARATOR)[ os.name == 'nt' ]
OTHER_SEPARATOR = '\\' #(NASTY_SEPARATOR, NICE_SEPARATOR)[ os.name == 'nt' ]
UNC_PREFIX = PATH_SEPARATOR * 2
def cleanPath( pathString ):
'''
will clean out all nasty crap that gets into pathnames from various sources.
maya will often put double, sometimes triple slashes, different slash types etc
'''
pathString = os.path.expanduser( str( pathString ) )
path = pathString.strip().replace( OTHER_SEPARATOR, PATH_SEPARATOR )
isUNC = path.startswith( UNC_PREFIX )
while UNC_PREFIX in path:
path = path.replace( UNC_PREFIX, PATH_SEPARATOR )
if isUNC:
path = PATH_SEPARATOR + path
return path
ENV_REGEX = re.compile( "\%[^%]+\%" )
findall = re.findall
def resolveAndSplit( path, envDict=None, raiseOnMissing=False ):
'''
recursively expands all environment variables and '..' tokens in a pathname
'''
if envDict is None:
envDict = os.environ
path = os.path.expanduser( str( path ) )
#first resolve any env variables
if '%' in path: #performing this check is faster than doing the regex
matches = findall( ENV_REGEX, path )
missingVars = set()
while matches:
for match in matches:
try:
path = path.replace( match, envDict[ match[ 1:-1 ] ] )
except KeyError:
if raiseOnMissing:
raise
missingVars.add( match )
matches = set( findall( ENV_REGEX, path ) )
#remove any variables that have been found to be missing...
for missing in missingVars:
matches.remove( missing )
#now resolve any subpath navigation
if OTHER_SEPARATOR in path: #believe it or not, checking this first is faster
path = path.replace( OTHER_SEPARATOR, PATH_SEPARATOR )
#is the path a UNC path?
isUNC = path[ :2 ] == UNC_PREFIX
if isUNC:
path = path[ 2: ]
#remove duplicate separators
duplicateSeparator = UNC_PREFIX
while duplicateSeparator in path:
path = path.replace( duplicateSeparator, PATH_SEPARATOR )
pathToks = path.split( PATH_SEPARATOR )
pathsToUse = []
pathsToUseAppend = pathsToUse.append
for n, tok in enumerate( pathToks ):
if tok == "..":
try: pathsToUse.pop()
except IndexError:
if raiseOnMissing:
raise
pathsToUse = pathToks[ n: ]
break
else:
pathsToUseAppend( tok )
#finally convert it back into a path and pop out the last token if its empty
path = PATH_SEPARATOR.join( pathsToUse )
if not pathsToUse[-1]:
pathsToUse.pop()
#if its a UNC path, stick the UNC prefix
if isUNC:
return UNC_PREFIX + path, pathsToUse, True
return path, pathsToUse, isUNC
def resolve( path, envDict=None, raiseOnMissing=False ):
return resolveAndSplit( path, envDict, raiseOnMissing )[0]
resolvePath = resolve
sz_BYTES = 0
sz_KILOBYTES = 1
sz_MEGABYTES = 2
sz_GIGABYTES = 3
class Path(str):
__CASE_MATTERS = os.name != 'nt'
@classmethod
def SetCaseMatter( cls, state ):
cls.__CASE_MATTERS = state
@classmethod
def DoesCaseMatter( cls ):
return cls.__CASE_MATTERS
@classmethod
def Join( cls, *toks, **kw ):
return cls( '/'.join( toks ), **kw )
def __new__( cls, path='', caseMatters=None, envDict=None ):
'''
if case doesn't matter for the path instance you're creating, setting caseMatters
to False will do things like caseless equality testing, caseless hash generation
'''
#early out if we've been given a Path instance - paths are immutable so there is no reason not to just return what was passed in
if isinstance( path, cls ):
return path
#set to an empty string if we've been init'd with None
if path is None:
path = ''
resolvedPath, pathTokens, isUnc = resolveAndSplit( path, envDict )
new = str.__new__( cls, resolvedPath )
new.isUNC = isUnc
new.hasTrailing = resolvedPath.endswith( PATH_SEPARATOR )
new._splits = tuple( pathTokens )
new._passed = path
#case sensitivity, if not specified, defaults to system behaviour
if caseMatters is not None:
new.__CASE_MATTERS = caseMatters
return new
@classmethod
def Temp( cls ):
'''
returns a temporary filepath - the file should be unique (i think) but certainly the file is guaranteed
to not exist
'''
import datetime, random
def generateRandomPathName():
now = datetime.datetime.now()
rnd = '%06d' % (abs(random.gauss(0.5, 0.5)*10**6))
return '%TEMP%'+ PATH_SEPARATOR +'TMP_FILE_%s%s%s%s%s%s%s%s' % (now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond, rnd)
randomPathName = cls( generateRandomPathName() )
while randomPathName.exists():
randomPathName = cls( generateRandomPathName() )
return randomPathName
def __nonzero__( self ):
'''
a Path instance is "non-zero" if its not '' or '/' (although I guess '/' is actually a valid path on *nix)
'''
selfStripped = self.strip()
if selfStripped == '':
return False
if selfStripped == PATH_SEPARATOR:
return False
return True
def __add__( self, other ):
return self.__class__( '%s%s%s' % (self, PATH_SEPARATOR, other), self.__CASE_MATTERS )
#the / or + operator both concatenate path tokens
__div__ = __add__
def __radd__( self, other ):
return self.__class__( other, self.__CASE_MATTERS ) + self
__rdiv__ = __radd__
def __getitem__( self, item ):
return self._splits[ item ]
def __getslice__( self, a, b ):
isUNC = self.isUNC
if a:
isUNC = False
return self._toksToPath( self._splits[ a:b ], isUNC, self.hasTrailing )
def __len__( self ):
if not self:
return 0
return len( self._splits )
def __contains__( self, item ):
if not self.__CASE_MATTERS:
return item.lower() in [ s.lower() for s in self._splits ]
return item in list( self._splits )
def __hash__( self ):
'''
the hash for two paths that are identical should match - the most reliable way to do this
is to use a tuple from self.split to generate the hash from
'''
if not self.__CASE_MATTERS:
return hash( tuple( [ s.lower() for s in self._splits ] ) )
return hash( tuple( self._splits ) )
def _toksToPath( self, toks, isUNC=False, hasTrailing=False ):
'''
given a bunch of path tokens, deals with prepending and appending path
separators for unc paths and paths with trailing separators
'''
toks = list( toks )
if isUNC:
toks = ['', ''] + toks
if hasTrailing:
toks.append( '' )
return self.__class__( PATH_SEPARATOR.join( toks ), self.__CASE_MATTERS )
def resolve( self, envDict=None, raiseOnMissing=False ):
'''
will re-resolve the path given a new envDict
'''
if envDict is None:
return self
else:
return Path( self._passed, self.__CASE_MATTERS, envDict )
def unresolved( self ):
'''
returns the un-resolved path - this is the exact string that the path was instantiated with
'''
return self._passed
def isEqual( self, other ):
'''
compares two paths after all variables have been resolved, and case sensitivity has been
taken into account - the idea being that two paths are only equal if they refer to the
same filesystem object. NOTE: this doesn't take into account any sort of linking on *nix
systems...
'''
if not isinstance( other, Path ):
other = Path( other, self.__CASE_MATTERS )
selfStr = str( self.asFile() )
otherStr = str( other.asFile() )
if not self.__CASE_MATTERS:
selfStr = selfStr.lower()
otherStr = otherStr.lower()
return selfStr == otherStr
__eq__ = isEqual
def __ne__( self, other ):
return not self.isEqual( other )
def doesCaseMatter( self ):
return self.__CASE_MATTERS
@classmethod
def getcwd( cls ):
'''
returns the current working directory as a path object
'''
return cls( os.getcwd() )
@classmethod
def setcwd( cls, path ):
'''
simply sets the current working directory - NOTE: this is a class method so it can be called
without first constructing a path object
'''
newPath = cls( path )
try:
os.chdir( newPath )
except WindowsError: return None
return newPath
putcwd = setcwd
def getStat( self ):
try:
return os.stat( self )
except:
#return a null stat_result object
return os.stat_result( [ 0 for n in range( os.stat_result.n_sequence_fields ) ] )
stat = property( getStat )
def isAbs( self ):
try:
return os.path.isabs( str( self ) )
except: return False
def abs( self ):
'''
returns the absolute path as is reported by os.path.abspath
'''
return self.__class__( os.path.abspath( str( self ) ) )
def split( self ):
'''
returns the splits tuple - ie the path tokens
'''
return list( self._splits )
def asDir( self ):
'''
makes sure there is a trailing / on the end of a path
'''
if self.hasTrailing:
return self
return self.__class__( '%s%s' % (self._passed, PATH_SEPARATOR), self.__CASE_MATTERS )
asdir = asDir
def asFile( self ):
'''
makes sure there is no trailing path separators
'''
if not self.hasTrailing:
return self
return self.__class__( str( self )[ :-1 ], self.__CASE_MATTERS )
asfile = asFile
def isDir( self ):
'''
bool indicating whether the path object points to an existing directory or not. NOTE: a
path object can still represent a file that refers to a file not yet in existence and this
method will return False
'''
return os.path.isdir( self )
isdir = isDir
def isFile( self ):
'''
see isdir notes
'''
return os.path.isfile( self )
isfile = isFile
def getReadable( self ):
'''
returns whether the current instance's file is readable or not. if the file
doesn't exist False is returned
'''
try:
s = os.stat( self )
return s.st_mode & stat.S_IREAD
except:
#i think this only happens if the file doesn't exist
return False
def setWritable( self, state=True ):
'''
sets the writeable flag (ie: !readonly)
'''
try:
setTo = stat.S_IREAD
if state:
setTo = stat.S_IWRITE
os.chmod(self, setTo)
except: pass
def getWritable( self ):
'''
returns whether the current instance's file is writeable or not. if the file
doesn't exist True is returned
'''
try:
s = os.stat( self )
return s.st_mode & stat.S_IWRITE
except:
#i think this only happens if the file doesn't exist - so return true
return True
def getExtension( self ):
'''
returns the extension of the path object - an extension is defined as the string after a
period (.) character in the final path token
'''
try:
endTok = self[ -1 ]
except IndexError:
return ''
idx = endTok.rfind( '.' )
if idx == -1:
return ''
return endTok[ idx+1: ] #add one to skip the period
def setExtension( self, xtn=None, renameOnDisk=False ):
'''
sets the extension the path object. deals with making sure there is only
one period etc...
if the renameOnDisk arg is true, the file on disk (if there is one) is
renamed with the new extension
'''
if xtn is None:
xtn = ''
#make sure there is are no start periods
while xtn.startswith( '.' ):
xtn = xtn[ 1: ]
toks = list( self.split() )
try:
endTok = toks.pop()
except IndexError:
endTok = ''
idx = endTok.rfind( '.' )
name = endTok
if idx >= 0:
name = endTok[ :idx ]
if xtn:
newEndTok = '%s.%s' % (name, xtn)
else:
newEndTok = name
if renameOnDisk:
self.rename( newEndTok, True )
else:
toks.append( newEndTok )
return self._toksToPath( toks, self.isUNC, self.hasTrailing )
extension = property(getExtension, setExtension)
def hasExtension( self, extension ):
'''
returns whether the extension is of a certain value or not
'''
ext = self.getExtension()
if not self.__CASE_MATTERS:
ext = ext.lower()
extension = extension.lower()
return ext == extension
isExtension = hasExtension
def name( self, stripExtension=True, stripAllExtensions=False ):
'''
returns the filename by itself - by default it also strips the extension, as the actual filename can
be easily obtained using self[-1], while extension stripping is either a multi line operation or a
lengthy expression
'''
try:
name = self[ -1 ]
except IndexError:
return ''
if stripExtension:
pIdx = -1
if stripAllExtensions:
pIdx = name.find('.')
else:
pIdx = name.rfind('.')
if pIdx != -1:
return name[ :pIdx ]
return name
def up( self, levels=1 ):
'''
returns a new path object with <levels> path tokens removed from the tail.
ie: Path("a/b/c/d").up(2) returns Path("a/b")
'''
if not levels:
return self
toks = list( self._splits )
levels = max( min( levels, len(toks)-1 ), 1 )
toksToJoin = toks[ :-levels ]
if self.hasTrailing:
toksToJoin.append( '' )
return self._toksToPath( toksToJoin, self.isUNC, self.hasTrailing )
def replace( self, search, replace='', caseMatters=None ):
'''
a simple search replace method - works on path tokens. if caseMatters is None, then the system
default case sensitivity is used
'''
idx = self.find( search, caseMatters )
toks = list( self.split() )
toks[ idx ] = replace
return self._toksToPath( toks, self.isUNC, self.hasTrailing )
def find( self, search, caseMatters=None ):
'''
returns the index of the given path token
'''
if caseMatters is None:
#in this case assume system case sensitivity - ie sensitive only on *nix platforms
caseMatters = self.__CASE_MATTERS
if not caseMatters:
toks = [ s.lower() for s in self.split() ]
search = search.lower()
else:
toks = self.split()
idx = toks.index( search )
return idx
index = find
def exists( self ):
'''
returns whether the file exists on disk or not
'''
return os.path.exists( self )
def matchCase( self ):
'''
If running under an env where file case doesn't matter, this method will return a Path instance
whose case matches the file on disk. It assumes the file exists
'''
if self.doesCaseMatter():
return self
for f in self.up().files():
if f == self:
return f
def getSize( self, units=sz_MEGABYTES ):
'''
returns the size of the file in mega-bytes
'''
div = float( 1024 ** units )
return os.path.getsize( self ) / div
def create( self ):
'''
if the directory doesn't exist - create it
'''
if not self.exists():
os.makedirs( str( self ) )
def delete( self ):
'''
WindowsError is raised if the file cannot be deleted
'''
if self.isfile():
selfStr = str( self )
try:
os.remove( selfStr )
except WindowsError, e:
os.chmod( selfStr, stat.S_IWRITE )
os.remove( selfStr )
elif self.isdir():
selfStr = str( self.asDir() )
for f in self.files( recursive=True ):
f.delete()
os.chmod( selfStr, stat.S_IWRITE )
shutil.rmtree( selfStr, True )
remove = delete
def rename( self, newName, nameIsLeaf=False ):
'''
it is assumed newPath is a fullpath to the new dir OR file. if nameIsLeaf is True then
newName is taken to be a filename, not a filepath. the fullpath to the renamed file is
returned
'''
newPath = Path( newName )
if nameIsLeaf:
newPath = self.up() / newName
if self.isfile():
if newPath != self:
if newPath.exists():
newPath.delete()
#now perform the rename
os.rename( self, newPath )
elif self.isdir():
raise NotImplementedError( 'dir renaming not implemented yet...' )
return newPath
move = rename
def copy( self, target, nameIsLeaf=False ):
'''
same as rename - except for copying. returns the new target name
'''
if self.isfile():
target = Path( target )
if nameIsLeaf:
asPath = self.up() / target
target = asPath
if self == target:
return target
shutil.copy2( str( self ), str( target ) )
return target
elif self.isdir():
raise NotImplementedError( 'dir copying not implemented yet...' )
#shutil.copytree( str(self), str(target) )
def read( self, strip=True ):
'''
returns a list of lines contained in the file. NOTE: newlines are stripped from the end but whitespace
at the head of each line is preserved unless strip=False
'''
if self.exists() and self.isfile():
fileId = file( self )
if strip:
lines = [line.rstrip() for line in fileId.readlines()]
else:
lines = fileId.read()
fileId.close()
return lines
def write( self, contentsStr ):
'''
writes a given string to the file defined by self
'''
#make sure the directory to we're writing the file to exists
self.up().create()
with open( self, 'w' ) as f:
f.write( str(contentsStr) )
def pickle( self, toPickle ):
'''
similar to the write method but pickles the file
'''
self.up().create()
with open( self, 'w' ) as f:
cPickle.dump( toPickle, f, PICKLE_PROTOCOL )
def unpickle( self ):
'''
unpickles the file
'''
fileId = file( self, 'rb' )
data = cPickle.load(fileId)
fileId.close()
return data
def relativeTo( self, other ):
'''
returns self as a path relative to another
'''
if not self:
return None
path = self
other = Path( other )
pathToks = path.split()
otherToks = other.split()
caseMatters = self.__CASE_MATTERS
if not caseMatters:
pathToks = [ t.lower() for t in pathToks ]
otherToks = [ t.lower() for t in otherToks ]
#if the first path token is different, early out - one is not a subset of the other in any fashion
if otherToks[0] != pathToks[0]:
return None
lenPath, lenOther = len( path ), len( other )
if lenPath < lenOther:
return None
newPathToks = []
pathsToDiscard = lenOther
for pathN, otherN in zip( pathToks[ 1: ], otherToks[ 1: ] ):
if pathN == otherN:
continue
else:
newPathToks.append( '..' )
pathsToDiscard -= 1
newPathToks.extend( path[ pathsToDiscard: ] )
path = Path( PATH_SEPARATOR.join( newPathToks ), self.__CASE_MATTERS )
return path
__sub__ = relativeTo
def __rsub__( self, other ):
return self.__class__( other, self.__CASE_MATTERS ).relativeTo( self )
def inject( self, other, envDict=None ):
'''
injects an env variable into the path - if the env variable doesn't
resolve to tokens that exist in the path, a path string with the same
value as self is returned...
NOTE: a string is returned, not a Path instance - as Path instances are
always resolved
NOTE: this method is alias'd by __lshift__ and so can be accessed using the << operator:
d:/main/content/mod/models/someModel.ma << '%VCONTENT%' results in %VCONTENT%/mod/models/someModel.ma
'''
toks = toksLower = self._splits
otherToks = Path( other, self.__CASE_MATTERS, envDict=envDict ).split()
newToks = []
n = 0
if not self.__CASE_MATTERS:
toksLower = [ t.lower() for t in toks ]
otherToks = [ t.lower() for t in otherToks ]
while n < len( toks ):
tok, tokLower = toks[ n ], toksLower[ n ]
if tokLower == otherToks[ 0 ]:
allMatch = True
for tok, otherTok in zip( toksLower[ n + 1: ], otherToks[ 1: ] ):
if tok != otherTok:
allMatch = False
break
if allMatch:
newToks.append( other )
n += len( otherToks ) - 1
else:
newToks.append( toks[ n ] )
else:
newToks.append( tok )
n += 1
return PATH_SEPARATOR.join( newToks )
__lshift__ = inject
def findNearest( self ):
'''
returns the longest path that exists on disk
'''
path = self
while not path.exists() and len( path ) > 1:
path = path.up()
if not path.exists():
raise IOError( "Cannot find any path above this one" )
return path
getClosestExisting = findNearest
nearest = findNearest
def asNative( self ):
'''
returns a string with system native path separators
'''
return str( self ).replace( PATH_SEPARATOR, NATIVE_SEPARATOR )
def startswith( self, other ):
'''
returns whether the current instance begins with a given path fragment. ie:
Path('d:/temp/someDir/').startswith('d:/temp') returns True
'''
if not isinstance( other, type( self ) ):
other = Path( other, self.__CASE_MATTERS )
otherToks = other.split()
selfToks = self.split()
if not self.__CASE_MATTERS:
otherToks = [ t.lower() for t in otherToks ]
selfToks = [ t.lower() for t in selfToks ]
if len( otherToks ) > len( selfToks ):
return False
for tokOther, tokSelf in zip(otherToks, selfToks):
if tokOther != tokSelf: return False
return True
isUnder = startswith
def endswith( self, other ):
'''
determines whether self ends with the given path - it can be a string
'''
#copies of these objects NEED to be made, as the results from them are often cached - hence modification to them
#would screw up the cache, causing really hard to track down bugs... not sure what the best answer to this is,
#but this is clearly not it... the caching decorator could always return copies of mutable objects, but that
#sounds wasteful... for now, this is a workaround
otherToks = list( Path( other ).split() )
selfToks = list( self._splits )
otherToks.reverse()
selfToks.reverse()
if not self.__CASE_MATTERS:
otherToks = [ t.lower() for t in otherToks ]
selfToks = [ t.lower() for t in selfToks ]
for tokOther, tokSelf in zip(otherToks, selfToks):
if tokOther != tokSelf:
return False
return True
def _list_filesystem_items( self, itemtest, namesOnly=False, recursive=False ):
'''
does all the listing work - itemtest can generally only be one of os.path.isfile or
os.path.isdir. if anything else is passed in, the arg given is the full path as a
string to the filesystem item
'''
if not self.exists():
return
if recursive:
walker = os.walk( self )
for path, subs, files in walker:
path = Path( path, self.__CASE_MATTERS )
for sub in subs:
p = path / sub
if itemtest( p ):
if namesOnly:
p = p.name()
yield p
else: break #if this doesn't match, none of the other subs will
for item in files:
p = path / item
if itemtest( p ):
if namesOnly:
p = p.name()
yield p
else: break #if this doesn't match, none of the other items will
else:
for item in os.listdir( self ):
p = self / item
if itemtest( p ):
if namesOnly:
p = p.name()
yield p
def dirs( self, namesOnly=False, recursive=False ):
'''
returns a generator that lists all sub-directories. If namesOnly is True, then only directory
names (relative to the current dir) are returned
'''
return self._list_filesystem_items( os.path.isdir, namesOnly, recursive )
def files( self, namesOnly=False, recursive=False ):
'''
returns a generator that lists all files under the path (assuming its a directory). If namesOnly
is True, then only directory names (relative to the current dir) are returned
'''
return self._list_filesystem_items( os.path.isfile, namesOnly, recursive )
def findInPyPath( filename ):
'''
given a filename or path fragment, will return the full path to the first matching file found in
the sys.path variable
'''
for p in map( Path, sys.path ):
loc = p / filename
if loc.exists():
return loc
return None
def findInPath( filename ):
'''
given a filename or path fragment, will return the full path to the first matching file found in
the PATH env variable
'''
for p in map( Path, os.environ[ 'PATH' ].split( ';' ) ):
loc = p / filename
if loc.exists():
return loc
return None
#end
| Python |
from path import *
from misc import *
#from perforce import *
from presets import *
IS_WING_DEBUG = 'WINGDB_ACTIVE' in os.environ
class GoodException(Exception):
'''
good exceptions are just a general purpose way of breaking out of loops and whatnot. basically anytime an exception is
needed to control code flow and not indicate an actual problem using a GoodException makes it a little more obvious what
the code is doing in the absence of comments
'''
pass
BreakException = GoodException
class Callback(object):
'''
stupid little callable object for when you need to "bake" temporary args into a
callback - useful mainly when creating callbacks for dynamicly generated UI items
'''
def __init__( self, func, *args, **kwargs ):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__( self, *args ):
return self.func( *self.args, **self.kwargs )
#end
| Python |
from baseSkeletonBuilder import *
class Head(SkeletonPart):
HAS_PARITY = False
@property
def head( self ): return self[ -1 ]
@classmethod
def _build( cls, parent=None, neckCount=1, **kw ):
idx = kw[ 'idx' ]
partScale = kw[ 'partScale' ]
parent = getParent( parent )
posInc = partScale / 25.0
head = createJoint( 'head' )
if not neckCount:
cmd.parent( head, parent, relative=True )
return [ head ]
allJoints = []
prevJoint = parent
for n in range( neckCount ):
j = createJoint( 'neck%d' % (n+1) )
cmd.parent( j, prevJoint, relative=True )
move( 0, posInc, posInc, j, r=True, ws=True )
allJoints.append( j )
prevJoint = j
#move the first neck joint up a bunch
move( 0, partScale / 10.0, 0, allJoints[ 0 ], r=True, ws=True )
#parent the head appropriately
cmd.parent( head, allJoints[ -1 ], relative=True )
move( 0, posInc, posInc, head, r=True, ws=True )
allJoints.append( head )
jointSize( head, 2 )
return allJoints
def _align( self, _initialAlign=False ):
#aim all neck joints at the next neck joint
for n, item in enumerate( self[ :-1 ] ):
alignAimAtItem( item, self[ n+1 ] )
if _initialAlign:
alignItemToWorld( self.head )
else:
alignPreserve( self.head )
def visualize( self ):
scale = self.getBuildScale() / 10.0
plane = polyCreateFacet( ch=False, tx=True, s=1, p=((0, -scale, 0), (0, scale, 0), (self.getParityMultiplier() * 2 * scale, 0, 0)) )
cmd.parent( plane, self.head, relative=True )
cmd.parent( listRelatives( plane, shapes=True, pa=True ), self.head, add=True, shape=True )
delete( plane )
def buildItemVolume( self, item, size, centre ):
chainLength = rigUtils.chainLength( self.base, self.end )
height = float( size[0] )
width = chainLength / 2.0 #denominator is arbitrary - tune it to whatever...
if rigUtils.apiExtensions.cmpNodes( item, self.end ): #if the item is the head (ie the last joint in the part's chain) handle it differently
w, h, d = width, width*1.2, width*1.3
geo = polySphere( r=0.1, ax=BONE_AIM_VECTOR, sx=8, sy=4, ch=True )[0]
setAttr( '%s.t' % geo, w, 0, d )
else:
geo = polyCylinder( h=height * 0.95, r=0.01, ax=BONE_AIM_VECTOR, sx=self.AUTO_VOLUME_SIDES, sy=round( height/width ), ch=True )[0]
setAttr( '%s.t' % geo, *centre )
#finally remove the top and bottom cylinder caps - they're always the last 2 faces
numFaces = meshUtils.numFaces( geo )
delete( '%s.f[ %d:%d ]' % (geo, numFaces-2, numFaces-1) )
parent( geo, item, r=True )
return [geo]
#end
| Python |
from baseRigPrimitive import *
from spaceSwitching import build, NO_TRANSLATION, NO_ROTATION
class SplineIK(PrimaryRigPart):
__version__ = 2
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'ArbitraryChain' ), )
PRIORITY = 11
@classmethod
def CanRigThisPart( cls, skeletonPart ):
return len( skeletonPart ) >= 3
def _build( self, skeletonPart, allowFixedLength=True, constrainBetween=True, **kw ):
objs = skeletonPart.items
parentControl, rootControl = getParentAndRootControl( objs[0] )
fittedCurve, linearCurve, proxies, fixedLengthProxies, controls, splineIkHandle, halfIdx = buildControls( objs, parentControl, allowFixedLength=allowFixedLength, constrainBetween=constrainBetween, **kw )
buildDefaultSpaceSwitching( objs[0], controls[0] )
buildDefaultSpaceSwitching( objs[0], controls[-1] )
setAttr( '%s.v' % fixedLengthProxies[0], False )
#group all the proxy joints together
miscGrp = asMObject( group( em=True ) )
rename( miscGrp, '%s_%d_miscGrp%s#' % (type( self ).__name__, self.getIdx(), self.getSuffix()) )
parent( proxies, miscGrp )
parent( fixedLengthProxies[0], miscGrp )
parent( fittedCurve, linearCurve, miscGrp )
parent( miscGrp, self.getPartsNode() )
parent( splineIkHandle, miscGrp )
return controls
def buildControls( objs, controlParent=None, name='control', midName='midControl', allowFixedLength=True, constrainBetween=True, constrainBetweenMid=True, **kw ):
numObjs = numControls = len( objs )
if numObjs < 3:
raise RigPartError( "Need to specify more than 3 objects to use spline IK" )
scale = kw.get( 'scale', 15 )
fittedCurve, linearCurve, proxies = buildCurveThroughObjs( objs, False )
fittedCurveShape = listRelatives( fittedCurve, s=True, pa=True )[0]
#hide the curves and lock them down
setAttr( '%s.v' % fittedCurve, False )
setAttr( '%s.v' % linearCurve, False )
attrState( (fittedCurve, linearCurve), ('t', 'r', 's'), *LOCK_HIDE )
#hook up a curve info node
curveMeasure = createNode( 'curveInfo' )
curveMeasure = rename( curveMeasure, 'curve_measure#' )
connectAttr( '%s.worldSpace[0]' % fittedCurveShape, '%s.inputCurve' % curveMeasure, f=True )
knots = getAttr( '%s.knots' % curveMeasure )[ 0 ][ 2:-2 ]
#figure out which control should be the "mid" control
halfWayKnotValue = knots[-1] / 2
halfIdx = numObjs / 2
for idx, knot in enumerate( knots ):
if knot < halfWayKnotValue:
halfIdx = idx
else:
#is this value closer to the mid knot value? if so use it
deltas = [ (abs( knots[ halfIdx ] - halfWayKnotValue ), halfIdx), (abs( knots[ idx ] - halfWayKnotValue ), idx) ]
deltas.sort()
halfIdx = deltas[0][1]
break
#now build the controls
controls = []
name, midName = '%s_%%d' % name, '%s_%%d' % midName
for n, obj in enumerate( objs ):
isHalfCtrl = n == halfIdx
ctrlName = midName % n if isHalfCtrl else name % n
ctrlScale = scale*1.3 if n in (isHalfCtrl, 0, numControls-1) else scale
ctrlColour = ColourDesc( 'darkblue' ) if isHalfCtrl else ColourDesc( 'blue' )
nControl = buildControl( ctrlName, obj, PivotModeDesc.MID, 'sphere2', ctrlColour, constrain=False, parent=controlParent, scale=ctrlScale, asJoint=True ) #need to be joints to use for skinning below
control.setItemRigControl( obj, nControl )
controls.append( nControl )
halfWayControl = controls[ halfIdx ]
#setup the middle controls to be constrained between all controls
if constrainBetween:
constraintMethod = pointConstraint
if numObjs >= 5 and constrainBetweenMid:
lengths = [ betweenVector( controls[0], c ).get_magnitude() for c in controls[ 1:halfIdx+1 ] ]
lengthSum = sum( lengths )
midControlsA = controls[ 1:halfIdx ]
for length, ctrl in zip( lengths, midControlsA ):
ctrlParent = listRelatives( ctrl, p=True, pa=True )[0]
baseWeight = length / lengthSum
constraintMethod( controls[0], ctrlParent, w=1-baseWeight, mo=True )
constraintMethod( halfWayControl, ctrlParent, w=baseWeight, mo=True )
lengths = [ betweenVector( controls[0], c ).get_magnitude() for c in controls[ halfIdx:-1 ] ]
lengthSum = sum( lengths )
midControlsB = controls[ halfIdx + 1:-1 ]
for length, ctrl in zip( lengths, midControlsB ):
ctrlParent = listRelatives( ctrl, p=True, pa=True )[0]
baseWeight = length / lengthSum
constraintMethod( halfWayControl, ctrlParent, w=1-baseWeight, mo=True )
constraintMethod( controls[-1], ctrlParent, w=baseWeight, mo=True )
ctrlParent = listRelatives( halfWayControl, p=True, pa=True )[0]
baseWeight = halfWayKnotValue / float( knots[-1] )
constraintMethod( controls[0], ctrlParent, w=1-baseWeight, mo=True )
constraintMethod( controls[-1], ctrlParent, w=baseWeight, mo=True )
else:
lengths = [ betweenVector( controls[0], c ).get_magnitude() for c in controls[ 1: ] ]
lengthSum = sum( lengths )
midControls = controls[ 1:-1 ]
for length, ctrl in zip( lengths, midControls ):
ctrlParent = listRelatives( ctrl, p=True, pa=True )[0]
baseWeight = length / lengthSum
constraintMethod( controls[0], ctrlParent, w=1-baseWeight, mo=True )
constraintMethod( controls[-1], ctrlParent, w=baseWeight, mo=True )
for knot, j, proxy in zip( knots, objs, proxies ):
pointConstraint( proxy, j, mo=True )
mpath = createNode( 'pointOnCurveInfo' )
#connect axes individually so they can be broken easily if we need to...
connectAttr( '%s.worldSpace' % fittedCurveShape, '%s.inputCurve' % mpath )
for ax in AXES:
connectAttr( '%s.p%s' % (mpath, ax), '%s.t%s' % (proxy, ax) )
#were using (knot / unitComp) but it seems this is buggy - invalid knot values are returned for a straight curve... so it seems assuming knot is valid works in all test cases I've tried...
setAttr( '%s.parameter' % mpath, knot )
#setup aim constraints to control twisting and orientation along the spline
for n in range( numObjs - 1 ):
obj, nextObj = objs[n], proxies[n + 1]
v = betweenVector( obj, nextObj )
#now get all the axis information to build an aim constraint
aimAxis = getObjectAxisInDirection( obj, v )
otherAxes = aimAxis.otherAxes()
upAxis = otherAxes[0]
upVector = getObjectBasisVectors( obj )[ upAxis ]
upObj = controls[n]
upObjAxis = getObjectAxisInDirection( upObj, upVector )
aimConstraint( nextObj, obj, aim=aimAxis.asVector(), upVector=upAxis.asVector(), wuo=upObj, wut='objectrotation', worldUpVector=upObjAxis.asVector(), mo=True )
orientConstraint( controls[-1], objs[-1], mo=True )
#now skin the linear curve to the controls and setup skinning
lineCluster = skinCluster( controls, linearCurve, tsb=True )[0]
for cvIdx, ctrl in enumerate( controls ):
skinPercent( lineCluster, '%s.cv[%d]' % (linearCurve, cvIdx), transformValue=(ctrl, 1) )
#turn off inherit transforms for the proxy objects and curves so the user can parent them to whatever is needed
for node in proxies:
setAttr( '%s.inheritsTransform' % node, False )
setAttr( '%s.inheritsTransform' % linearCurve, False )
setAttr( '%s.inheritsTransform' % fittedCurve, False )
#now that we've setup the stretchy controls, lets add a splineIK version to blend between
fixedLengthProxies = []
splineIkHandle = None
if allowFixedLength:
for j in proxies:
fixedJ = createJoint( '%s_fixedLength' % j )
delete( parentConstraint( j, fixedJ ) )
if fixedLengthProxies:
parent( fixedJ, fixedLengthProxies[-1] )
fixedLengthProxies.append( fixedJ )
splineIkHandle = cmd.ikHandle( startJoint=fixedLengthProxies[0], endEffector=fixedLengthProxies[-1], curve=fittedCurveShape, createCurve=False, solver='ikSplineSolver' )[0]
addAttr( controls[0], ln='fixedLength', at='double', dv=0, min=0, max=1 )
setAttr( '%s.fixedLength' % controls[0], k=True )
rev = createNode( 'reverse' )
connectAttr( '%s.fixedLength' % controls[0], '%s.inputX' % rev, f=True )
for obj, fixedJ in zip( objs, fixedLengthProxies ):
constraint = pointConstraint( fixedJ, obj, w=0 )[0]
attrs = listAttr( constraint, ud=True )
connectAttr( '%s.outputX' % rev, '%s.%s' % (constraint, attrs[0]), f=True )
connectAttr( '%s.fixedLength' % controls[0], '%s.%s' % (constraint, attrs[1]), f=True )
#hide the joints
setAttr( '%s.v' % obj, False )
setAttr( '%s.v' % fixedJ, False )
attrState( fixedLengthProxies, ('t', 'r', 's'), *LOCK_HIDE )
attrState( fixedLengthProxies, 'v', *HIDE )
attrState( proxies, ('t', 'r', 's'), *LOCK_HIDE )
attrState( proxies, 'v', *HIDE )
return fittedCurve, linearCurve, proxies, fixedLengthProxies, controls, splineIkHandle, halfIdx
def buildNumControls( objs, numControls=3, **kw ):
scale = kw.get( 'scale', 15 )
fittedCurve, linearCurve, proxies = buildCurveThroughObjs( objs )
fittedCurveShape = listRelatives( fittedCurve, s=True, pa=True )[0]
#make sure the numControls is properly bounded: 3 <= numControls <= numObjects
numControls = min( numControls, len( objs ) )
numControls = max( numControls, 3 )
partParent = listRelatives( objs, p=True, pa=True )[0]
#build the spline ik node
ikHandle, ikEffector = cmd.ikHandle( sj=proxies[0], ee=proxies[-1], sol='ikSplineSolver', curve=fittedCurve, createCurve=False )
setAttr( '%s.dTwistControlEnable' % ikHandle, True )
setAttr( '%s.dWorldUpType' % ikHandle, 4 )
connectAttr( '%s.worldMatrix' % partParent, '%s.dWorldUpMatrix' % ikHandle, f=True )
#
halfWayPath = createNode( 'pointOnCurveInfo' )
halfWayPos = group( em=True, n="half" )
arcLength = getAttr( '%s.maxValue' % fittedCurveShape ) - getAttr( '%s.minValue' % fittedCurveShape )
connectAttr( '%s.worldSpace' % fittedCurveShape, '%s.inputCurve' % halfWayPath )
connectAttr( '%s.p' % halfWayPath, '%s.t' % halfWayPos )
maxParam = getAttr( '%s.spans' % fittedCurveShape )
paramInc = maxParam / float( numControls-1 )
#now build the controls
controls = []
controlParent = None
for n in range( numControls ):
setAttr( '%s.parameter' % halfWayPath, n * paramInc )
nControl = buildControl( "control_%d" % n, halfWayPos, PivotModeDesc.MID, 'sphere', ColourDesc( 'darkblue' ), constrain=False, parent=controlParent, scale=scale, asJoint=True )
controlParent = nControl
controls.append( nControl )
connectAttr( '%s.worldMatrix' % controls[-1], '%s.dWorldUpMatrixEnd' % ikHandle, f=True )
orientConstraint( controls[-1], objs[-1], mo=True )
#now skin the linear curve to the controls and setup skinning
lineCluster = skinCluster( controls, linearCurve, tsb=True )[0]
cvIdxs = range( len( objs ) ) #there is one cv per input object
cvsPerControl = float( len( objs ) ) / (numControls - 1) #there is one cv per input object
for n in range( numControls-1 ):
cvsForThisControl = int( round( cvsPerControl * n ) )
weightInc = 1.0 / (cvsForThisControl - 1)
c1, c2 = controls[n], controls[n+1]
cvIdxs = range( n * cvsForThisControl, (n + 1) * cvsForThisControl )
for i, cvIdx in enumerate( cvIdxs ):
weight = 1 - (i * weightInc)
skinPercent( lineCluster, '%s.cv[%d]' % (linearCurve, cvIdx), transformValue=((c1, weight), (c2, 1.0-weight)) )
#now delete the nodes for the motion path - we're done with them
delete( halfWayPath, halfWayPos )
def setupSquish( curve, joints ):
#scaling? create a network to dynamically scale the objects based on the length
#of the segment. there are two curve segments - start to mid, mid to end. this
#scaling is done via SDK so we get control over the in/out of the scaling
"""squishNodes = []
if squish:
curveInfo = createNode( 'curveInfo' )
scaleFac = shadingNode( n='squishCalculator', asUtility='multiplyDivide' )
adder = shadingNode( n='now_add_one', asUtility='plusMinusAverage' )
sdkScaler = createNode( 'animCurveUU', n='squish_sdk' )
initialLength = 0
maxScale = 2.0
minScale = 0.25
addAttr -k 1 -ln length -at double -min 0 -max 1 -dv 1 $deformJoints[0];
addAttr -k 1 -ln squishFactor -at double -min 0 -max 1 -dv 0 $deformJoints[0];
setAttr -k 1 ( $deformJoints[0] +".length" );
setAttr -k 1 ( $deformJoints[0] +".squishFactor" );
connectAttr -f ( $curveShape +".worldSpace[0]" ) ( $curveInfo +".inputCurve" );
initialLength = `getAttr ( $curveInfo +".arcLength" )`;
setAttr ( $adder +".input1D[0]" ) 1;
select -cl;
setKeyframe -f $initialLength -v 0 $sdkScaler;
setKeyframe -f( $initialLength/100 ) -v( $maxScale-1 ) $sdkScaler;
setKeyframe -f( $initialLength*2 ) -v( $minScale-1 ) $sdkScaler;
keyTangent -in 0 -itt flat -ott flat $sdkScaler;
keyTangent -in 2 -itt flat -ott flat $sdkScaler;
connectAttr -f ( $curveInfo +".arcLength" ) ( $sdkScaler +".input" );
connectAttr -f ( $scaleFac +".outputX" ) ( $adder +".input1D[1]" );
connectAttr -f ( $sdkScaler +".output" ) ( $scaleFac +".input1X" );
connectAttr -f ( $deformJoints[0] +".squishFactor" ) ( $scaleFac +".input2X" );
for( $n=0; $n<$numObjs; $n++ ) for( $ax in {"x","y","z"} ) connectAttr -f ( $adder +".output1D" ) ( $objs[$n] +".s"+ $ax );
lengthMults = []
for n in range( numObjs, 1 ):
posOnCurve = getAttr( '%s.parameter' % mpaths[ n ] )
lengthMults[$n] = `shadingNode -n( "length_multiplier"+ $n ) -asUtility multiplyDivide`;
setAttr ( $lengthMults[$n] +".input1X" ) $posOnCurve;
connectAttr -f ( $deformJoints[0] +".length" ) ( $lengthMults[$n] +".input2X" );
connectAttr -f ( $lengthMults[$n] +".outputX" ) ( $mpaths[$n] +".parameter" );
$squishNodes = [ curveInfo, scaleFac, adder, sdkScaler} $lengthMults`;"""
def buildCurveThroughObjs( objs, parentProxies=True ):
#first we need to build a curve - we build an ep curve so that it goes exactly through the joint pivots
numObjs = len( objs )
cmdKw = { 'd': 1 }
cmdKw[ 'p' ] = tuple( xform( obj, q=True, ws=True, rp=True ) for obj in objs )
cmdKw[ 'k' ] = range( numObjs )
baseCurve = curve( **cmdKw )
fittedCurve = fitBspline( baseCurve, ch=True, tol=0.005 )[ 0 ]
curveShape = listRelatives( fittedCurve, s=True, pa=True )[ 0 ]
infoNode = createNode( 'curveInfo' )
connectAttr( '%s.worldSpace[ 0 ]' % curveShape, '%s.inputCurve' % infoNode, f=True )
knots = getAttr( '%s.knots' % infoNode )[ 0 ][ 2:-2 ]
#now build the actual motion path nodes that keep the joints attached to the curve
#there is one proxy for each joint. the original joints get constrained to
#the proxies, which in turn get stuck to the motion path and oriented properly
#then three joints get created, which are used to deform the motion path
mpaths = {}
proxies = {}
unitComp = 1.0
if currentUnit( q=True, l=True ) == "m":
unitComp = 100.0
for n, obj in enumerate( objs ):
select( cl=True )
j = joint( n='%s_proxy' % objs[ n ] )
delete( parentConstraint( obj, j ) )
proxies[ obj ] = j
proxiesList = [ proxies[obj] for obj in objs ]
for n, j in enumerate( proxiesList ):
if n == 0:
continue
if parentProxies:
parent( j, proxiesList[n-1] )
makeIdentity( j, a=True, r=True )
#build a motionpath to get positions along the path - mainly useful for finding the half way mark
halfWayPath = createNode( 'pointOnCurveInfo' )
halfWayPos = group( em=True, n="half" )
arcLength = getAttr( '%s.maxValue' % curveShape ) - getAttr( '%s.minValue' % curveShape )
connectAttr( '%s.worldSpace' % curveShape, '%s.inputCurve' % halfWayPath )
connectAttr( '%s.p' % halfWayPath, '%s.t' % halfWayPos )
setAttr( '%s.parameter' % halfWayPath, knots[ -1 ] / 2.0 )
delete( halfWayPos )
delete( infoNode )
baseCurve = rename( baseCurve, "pointCurve#" )
fittedCurve = rename( fittedCurve, "mPath#" )
return fittedCurve, baseCurve, proxiesList
#end
| Python |
from maya.cmds import *
from baseMelUI import *
from filesystem import removeDupes
from rigUtils import MATRIX_ROTATION_ORDER_CONVERSIONS_FROM, MATRIX_ROTATION_ORDER_CONVERSIONS_TO, \
MAYA_ROTATION_ORDERS, ROO_XYZ, ROO_YZX, ROO_ZXY, ROO_XZY, ROO_YXZ, ROO_ZYX, ROT_ORDER_STRS
from mayaDecorators import d_disableViews, d_noAutoKey, d_unifyUndo, d_restoreTime
from animUtils import KeyServer
from common import printWarningStr
XYZ, YZX, ZXY, XZY, YXZ, ZYX = ROT_ORDER_STRS
@d_unifyUndo
@d_disableViews
@d_noAutoKey
@d_restoreTime
def changeRo( objs=None, ro=XYZ ):
if ro not in ROT_ORDER_STRS:
raise TypeError( "need to specify a valid rotation order - one of: %s" % ' '.join( ROT_ORDER_STRS ) )
if objs is None:
objs = ls( sl=True, type='transform' )
roIdx = list( ROT_ORDER_STRS ).index( ro )
#filter out objects that don't have all 3 rotation axes settable and while we're at it store the rotation orders for each object
#in a dict - since accessing a python dict is WAY faster than doing a getAttr for each frame in the loop below
RO_DICT = {}
objsWithAllChannelsSettable = []
for obj in objs:
if not getAttr( '%s.r' % obj, se=True ):
printWarningStr( "Not all rotation axes on the object %s are settable - skipping!" % obj )
continue
objRo = getAttr( '%s.ro' % obj )
#if the rotation order of this object is the same as what we're changing it to - skip the object entirely
if objRo == roIdx:
printWarningStr( "The object %s already has the rotation order %s - skipping!" % (obj, ro) )
continue
RO_DICT[ obj ] = objRo
objsWithAllChannelsSettable.append( obj )
#early out if we have no objects to work on
objs = objsWithAllChannelsSettable
if not objs:
printWarningStr( "No objects to act on - exiting" )
return
#cache the conversion method
convertToMethod = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ roIdx ]
#construct a key server object to march over keys and objects
keyServer = KeyServer( objs, True )
for time in keyServer:
for obj in keyServer.getNodesAtTime():
setKeyframe( obj, at='r' )
#now that we're secured the rotation poses with keys on all axes, fix up each rotation value to use the desired rotation order
for time in keyServer:
for obj in keyServer.getNodesAtTime():
currentRoIdx = RO_DICT[ obj ]
rot = getAttr( '%s.r' % obj )[0]
rotMatrix = MATRIX_ROTATION_ORDER_CONVERSIONS_FROM[ currentRoIdx ]( degrees=True, *rot )
newRot = convertToMethod( rotMatrix, True )
setAttr( '%s.r' % obj, *newRot )
setKeyframe( obj, at='r' )
#now change the rotation order to what it should be
for obj in objs:
setAttr( '%s.ro' % obj, roIdx )
class ChangeRoLayout(MelColumnLayout):
def __init__( self, parent ):
hLayout = MelHLayout( self )
lbl = MelLabel( hLayout, l='New Rotate Order', h=25 )
self.UI_rotateOrders = UI_rotateOrders = MelOptionMenu( hLayout )
for roStr in ROT_ORDER_STRS:
UI_rotateOrders.append( roStr )
hLayout.layout()
hLayout( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) )
self.UI_go = MelButton( self, l='Change Rotate Order', c=self.on_go )
#setup selection change callbacks and trigger it for the initial selection
self.on_selectionChange()
self.setSelectionChangeCB( self.on_selectionChange )
### EVENT HANDLERS ###
def on_selectionChange( self, *a ):
for obj in ls( sl=True, type='transform' ) or []:
if objExists( '%s.ro' % obj ):
ro = getAttr( '%s.ro' % obj )
self.UI_rotateOrders.selectByIdx( ro )
self.UI_go.setEnabled( True )
return
self.UI_go.setEnabled( False )
def on_go( self, *a ):
roStr = self.UI_rotateOrders.getValue()
changeRo( ro=roStr )
class ChangeRoWindow(BaseMelWindow):
WINDOW_NAME = 'ChangeRooTool'
WINDOW_TITLE = 'Change Rotate Order For Animated Nodes'
DEFAULT_SIZE = 375, 90
DEFAULT_MENU = None
def __init__( self ):
self.UI_editor = ChangeRoLayout( self )
self.show()
#end
| Python |
from maya.OpenMaya import *
from vectors import Vector, Matrix
import sys
import maya.cmds as cmd
import time
getAttr = cmd.getAttr
setAttr = cmd.setAttr
MObject.__MPlug__ = None
def asMObject( otherMobject ):
'''
tries to cast the given obj to an mobject - it can be string
'''
if isinstance( otherMobject, basestring ):
sel = MSelectionList()
sel.add( otherMobject )
if '.' in otherMobject:
plug = MPlug()
sel.getPlug( 0, plug )
tmp = plug.asMObject()
tmp.__MPlug__ = plug
else:
tmp = MObject()
sel.getDependNode( 0, tmp )
return tmp
if isinstance( otherMobject, (MObject, MObjectHandle) ):
return otherMobject
def asMPlug( otherMobject ):
if '.' in otherMobject:
sel = MSelectionList()
sel.add( otherMobject )
plug = MPlug()
sel.getPlug( 0, plug )
return plug
def _asDependencyNode( self ):
if not self.hasFn( MFn.kDependencyNode ):
return None
if self.__MDependencyNode__ is None:
self.__MDependencyNode__ = dep = MFnDependencyNode( self )
return dep
else:
return self.__MDependencyNode__
MObject.__MDependencyNode__ = None
MObject.dependencyNode = _asDependencyNode
def _asDag( self ):
if not self.hasFn( MFn.kDagNode ):
return None
if self.__MDagPath__ is None:
self.__MDagPath__ = dag = MDagPath()
MDagPath.getAPathTo( self, dag )
return dag
else:
return self.__MDagPath__
MObject.__MDagPath__ = None
MObject.dagPath = _asDag
def partialPathName( self ):
'''
returns the partial name of the node
'''
if self.isNull():
return unicode()
if isinstance( self, MObjectHandle ):
self = self.object()
dagPath = self.dagPath()
if dagPath is not None:
return dagPath.partialPathName() #already a unicode instance
if self.hasFn( MFn.kDependencyNode ):
return MFnDependencyNode( self ).name()
elif self.hasFn( MFn.kAttribute ):
sel = MSelectionList()
sel.add( self )
node = MObject()
self.getDependNode( 0, node )
return unicode( MPlug( node, self ) )
return u'<instance of %s>' % self.__class__
def __repr( self ):
return repr( self.partialPathName() )
MObject.__str__ = MObjectHandle.__str__ = partialPathName
MObject.__repr__ = MObjectHandle.__repr__ = __repr
MObject.__unicode__ = MObjectHandle.__unicode__ = partialPathName
MObject.partialPathName = MObjectHandle.partialPathName = partialPathName
MObject.this = None #stops __getattr__ from being called
def isNotEqual( self, other ):
return not self == other
#override the default __eq__ operator on MObject. NOTE: because the original __eq__ method is cached above,
#reloading this module can result in funkiness because the __eq__ gets cached on reload. the alternative is
#to have an "originalMethods" script that never gets reloaded and stores original overridable methods
MObject.__ne__ = isNotEqual
def shortName( self ):
return partialPathName( self ).split( '|' )[ -1 ]
MObject.shortName = MObjectHandle.shortName = shortName
def _hash( self ):
return MObjectHandle( self ).hashCode()
MObject.__hash__ = _hash
def _hash( self ):
return self.hashCode()
MObjectHandle.__hash__ = _hash
def cmpNodes( a, b ):
'''
compares two nodes and returns whether they're equivalent or not - the compare is done on MObjects
not strings so passing the fullname and a partial name to the same dag will still return True
'''
if a is b:
return True
#make sure the objects are valid types...
if b is None:
return False
if isinstance( a, basestring ):
a = asMObject( a )
if isinstance( b, basestring ):
b = asMObject( b )
if not isinstance( a, MObject ):
return False
if not isinstance( b, MObject ):
return False
return a == b
def __eq( self, other ):
if isinstance( other, basestring ):
other = asMObject( other )
return MObjectOriginalEquivalenceMethod( self, other )
#check to see if __eq__ has been setup already - if it has, the sys._MObjectOriginalEquivalenceMethod attribute will exist
if not hasattr( sys, '_MObjectOriginalEquivalenceMethod' ):
sys._MObjectOriginalEquivalenceMethod = MObjectOriginalEquivalenceMethod = MObject.__eq__ #store on sys so that it doesn't get garbage collected when flush is called
MObject.__eq__ = __eq
else:
MObjectOriginalEquivalenceMethod = sys._MObjectOriginalEquivalenceMethod
MObject.__eq__ = __eq
print "mobject __eq__ already setup!"
#preGetAttr = MObject.__getattr__
def __getattr__( self, attr ):
return MFnDependencyNode( self ).findPlug( attr )
#MObject.__getattr__ = __getattr__ #woah! this can really really slow maya down...
MObject.getAttr = __getattr__
def iterAttrs( self, attrNamesToSkip=() ):
'''
iterates over all MPlugs belonging to this assumed to be dependency node
'''
depFn = MFnDependencyNode( self )
for n in range( depFn.attributeCount() ):
mattr = depFn.attribute( n )
if mattr.isNull():
continue
mPlug = MPlug( self, mattr )
mPlugName = mPlug.longName()
skipAttr = False
for skipName in attrNamesToSkip:
if mPlugName == skipName:
skipAttr = True
elif mPlugName.startswith( skipName +'[' ) or mPlugName.startswith( skipName +'.' ):
skipAttr = True
if skipAttr:
continue
yield mPlug
MObject.iterAttrs = iterAttrs
def hasAttribute( self, attr ):
return MFnDependencyNode( self ).hasAttribute( attr )
MObject.hasAttribute = hasAttribute
def getParent( self ):
'''
returns the parent of this node as an mobject
'''
if self.hasFn( MFn.kDagNode ):
dagPath = MDagPath()
MDagPath.getAPathTo( self, dagPath )
dagNode = MFnDagNode( dagPath ).parent( 0 )
if dagNode.apiType() == MFn.kWorld:
return None
return dagNode
def setParent( self, newParent, relative=False ):
'''
sets the parent of this node - newParent can be either another mobject or a node name
'''
dagMod = MDagModifier()
dagMod.reparentNode( self, asMObject( newParent ) )
dagMod.doIt()
#cmd.parent( str( self ), str( newParent ), r=relative )
MObject.getParent = getParent
MObject.setParent = setParent
def hasUniqueName( self ):
return MFnDependencyNode( self ).hasUniqueName()
MObject.hasUniqueName = hasUniqueName
def _rename( self, newName ):
'''
renames the node
'''
return cmd.rename( self, newName )
MObject.rename = _rename
def getShortName( self ):
if not isinstance( self, basestring ):
self = str( self )
return self.split( ':' )[ -1 ]
MObject.shortName = getShortName
def getObjectMatrix( self ):
dag = self.dagPath()
if dag is None:
return None
return dag.getObjectMatrix()
MObject.getObjectMatrix = getObjectMatrix
def getWorldMatrix( self ):
dag = self.dagPath()
if dag is None:
return None
return dag.getWorldMatrix()
MObject.getWorldMatrix = getWorldMatrix
def getWorldInverseMatrix( self ):
dag = self.dagPath()
if dag is None:
return None
return dag.getWorldInverseMatrix()
MObject.getWorldInverseMatrix = getWorldInverseMatrix
def getParentMatrix( self ):
dag = self.dagPath()
if dag is None:
return None
return dag.getParentMatrix()
MObject.getParentMatrix = getParentMatrix
def getParentInverseMatrix( self ):
dag = self.dagPath()
if dag is None:
return None
return dag.getParentInverseMatrix()
MObject.getParentInverseMatrix = getParentInverseMatrix
### MDAGPATH CUSTOMIZATIONS ###
MDagPath.__str__ = MDagPath.partialPathName
MDagPath.__repr__ = MDagPath.partialPathName
MDagPath.__unicode__ = MDagPath.partialPathName
MDagPath.this = None
def getObjectMatrix( self ):
return MFnTransform( self ).transformation().asMatrix().asNice()
MDagPath.getObjectMatrix = getObjectMatrix
def getWorldMatrix( self ):
return self.inclusiveMatrix().asNice()
MDagPath.getWorldMatrix = getWorldMatrix
def getWorldInverseMatrix( self ):
return self.inclusiveMatrixInverse().asNice()
MDagPath.getWorldInverseMatrix = getWorldInverseMatrix
def getParentMatrix( self ):
return self.exclusiveMatrix().asNice()
MDagPath.getParentMatrix = getParentMatrix
def getParentInverseMatrix( self ):
return self.exclusiveMatrixInverse().asNice()
MDagPath.getParentInverseMatrix = getParentInverseMatrix
### MPLUG CUSTOMIZATIONS ###
def __unicode__( self ):
return self.name().replace( '[-1]', '[0]' )
MPlug.__str__ = __unicode__
MPlug.__repr__ = __unicode__
MPlug.__unicode__ = __unicode__
#MPlug.this = None #stops __getattr__ from being called
def __getattr__( self, attr ):
'''
for getting child attributes
'''
if self.numChildren():
return [ self.child(idx) for idx in range( self.numChildren() ) ]
def __getitem__( self, idx ):
'''
for getting indexed attributes
'''
if self.isArray():
return self.elementByLogicalIndex( idx )
raise TypeError( "Attribute %s isn't indexable" % self )
#MPlug.__getattr__ = __getattr__
#MPlug.__getitem__ = __getitem__
MPlug.asMObject = MPlug.attribute
def _set( self, value ):
if isinstance( value, (list, tuple) ):
setAttr( str(self), *value )
else:
setAttr( str(self), value )
def _get( self ):
"""#WOW! the api is SUPER dumb if you want to figure out how to get the value of an attribute...
mobject = self.attribute()
apiType = mobject.apiType()
if mobject.hasFn( MFn.kNumericData ):
dFn = MFnNumericData( mobject )
dFnType = dFn.type()
if dFnType == MFnNumericData.kBoolean:
return self.asBool()
elif dFnType in ( MFnNumericData.kInt, MFnNumericData.kShort, MFnNumericData.kLong ):
return self.asInt()
elif dFnType in ( MFnNumericData.kFloat, MFnNumericData.kDouble ):
return self.asFloat()
elif mobject.hasFn( MFn.kStringData ):
if dFnType == MFnStringData.kString:
return self.asString()
"""
val = getAttr( str(self) ) #use mel instead!
if isinstance( val, list ):
return val[ 0 ]
return val
MPlug.GetValue = _get
MPlug.SetValue = _set
def _hash( self ):
'''
get the node hash, and add the hash of the attribute name
ie: the name of the attribute, not the path to the attribute
'''
return hash( self.node() ) + hash( '.'.join( self.name().split( '.' )[ 1: ] ) )
MPlug.__hash__ = _hash
def _longName( self ):
return self.partialName( False, False, False, False, False, True )
MPlug.longName = _longName
MPlug.shortName = MPlug.partialName
def _aliasName( self ):
#definedAliass = cmd.aliasAttr( self.node(), q=True )
#longName = self.longName()
#shortName = self.shortName()
#if longName in definedAliass or shortName in definedAliass:
#return self.partialName( False, False, False, True )
#return longName
return '.'.join( self.name().split( '.' )[ 1: ] )
MPlug.alias = _aliasName
def _isHidden( self ):
if self.isElement():
return bool( cmd.attributeQuery( self.array().longName(), n=self.node(), hidden=True ) )
return bool( cmd.attributeQuery( self.longName(), n=self.node(), hidden=True ) )
MPlug.isHidden = _isHidden
### MVECTOR, MMATRIX CUSTOMIZATIONS ###
def __asNice( self ):
return Vector( [self.x, self.y, self.z] )
MVector.asNice = __asNice
MPoint.asNice = __asNice
def __asNice( self ):
values = []
for i in range( 4 ):
for j in range( 4 ):
values.append( self(i, j) )
return Matrix( values )
MMatrix.asNice = __asNice
def __str( self ):
return str( self.asNice() )
MVector.__str__ = __str
MVector.__repr__ = __str
MVector.__unicode__ = __str
MPoint.__str__ = __str
MPoint.__repr__ = __str
MPoint.__unicode__ = __str
def _asPy( self ):
return Vector( (self.x, self.y, self.z) )
MVector.asPy = _asPy
def __str( self ):
return str( self.asNice() )
MMatrix.__str__ = __str
MMatrix.__repr__ = __str
MMatrix.__unicode__ = __str
def _asPy( self, size=4 ):
values = []
for i in range( size ):
for j in range( size ):
values.append( self( i, j ) )
return Matrix( values, size )
MMatrix.asPy = _asPy
def __asMaya( self ):
return MVector( *self )
Vector.asMaya = __asMaya
### UTILITIES ###
def castToMObjects( items ):
'''
is a reasonably efficient way to map a list of nodes to mobjects
NOTE: this returns a generator - use list( castToMObjects( nodes ) ) to collapse the generator
'''
sel = MSelectionList()
newItems = []
for n, item in enumerate( items ):
sel.add( item )
mobject = MObject()
sel.getDependNode( n, mobject )
newItems.append( mobject )
return newItems
def getSelected():
items = []
sel = MSelectionList()
MGlobal.getActiveSelectionList( sel )
for n in range( sel.length() ):
mobject = MObject()
sel.getDependNode( n, mobject )
items.append( mobject )
return items
def iterAll():
'''
returns a fast generator that visits all nodes of this class's type in the scene
'''
iterNodes = MItDependencyNodes()
getItem = iterNodes.thisNode
next = iterNodes.next #cache next method for faster access inside the generator
while not iterNodes.isDone():
yield getItem()
next()
def lsAll():
return list( iterAll() )
def ls_( *a, **kw ):
'''
wraps the ls mel command so that it returns mobject instances instead of strings
'''
return castToMObjects( cmd.ls( *a, **kw ) or [] )
def filterByType( items, apiTypes ):
'''
returns a generator that will yield all items in the given list that match the given apiType enums
'''
if not isinstance( apiTypes, (list, tuple) ):
apiTypes = [ apiTypes ]
for item in items:
if item.apiType() in apiTypes:
yield item
def getNodesCreatedBy( function, *args, **kwargs ):
'''
returns a 2-tuple containing all the nodes created by the passed function, and
the return value of said function
'''
#construct the node created callback
newNodeHandles = []
def newNodeCB( newNode, data ):
newNodeHandles.append( MObjectHandle( newNode ) )
def remNodeCB( remNode, data ):
remNodeHandle = MObjectHandle( remNode )
if remNodeHandle in newNodeHandles:
newNodeHandles.remove( remNodeHandle )
newNodeCBMsgId = MDGMessage.addNodeAddedCallback( newNodeCB )
remNodeCBMsgId = MDGMessage.addNodeRemovedCallback( remNodeCB )
ret = function( *args, **kwargs )
MMessage.removeCallback( newNodeCBMsgId )
MMessage.removeCallback( remNodeCBMsgId )
newNodes = [ h.object() for h in newNodeHandles ]
return newNodes, ret
def iterTopNodes( nodes ):
kDagNode = MFn.kDagNode
for node in castToMObjects( nodes ):
if node.hasFn( kDagNode ):
if node.getParent() is None:
yield node
def iterParents( obj ):
parent = cmd.listRelatives( obj, p=True, pa=True )
while parent is not None:
yield parent[ 0 ]
parent = cmd.listRelatives( parent[ 0 ], p=True, pa=True )
def sortByHierarchy( objs ):
sortedObjs = []
for o in objs:
pCount = len( list( iterParents( o ) ) )
sortedObjs.append( (pCount, o) )
sortedObjs.sort()
return [ o[ 1 ] for o in sortedObjs ]
def stripTrailingDigits( name ):
trailingDigits = []
if name[ -1 ].isdigit():
for idx, char in enumerate( reversed( name ) ):
if not char.isdigit():
return name[ :-idx ]
return name
def iterNonUniqueNames():
iterNodes = MItDag() #type=MFn.kTransform ) #NOTE: only dag objects can have non-unique names... despite the fact that the hasUniqueName method lives on MFnDependencyNode (wtf?!)
while not iterNodes.isDone():
mobject = iterNodes.currentItem()
if not MFnDependencyNode( mobject ).hasUniqueName(): #thankfully instantiating MFn objects isn't slow - just MObject and MDagPath
yield mobject
iterNodes.next()
def fixNonUniqueNames():
rename = cmd.rename
for dagPath in iterNonUniqueNames():
name = dagPath.partialPathName()
newName = rename( name, stripTrailingDigits( name.split( '|' )[ -1 ] ) +'#' )
print 'RENAMED:', name, newName
def selectNonUniqueNames():
cmd.select( cl=True )
theNodes = map( str, iterNonUniqueNames() )
if theNodes:
cmd.select( theNodes )
#end
| Python |
from devTest import Path, TestCase
from maya import cmds as cmd
TEST_DIRECTORY = Path( __file__ ).up() / '_devTest_testScenes_' #location for maya files written by tests
def d_makeNewScene( sceneName ):
'''
simple decorator macro - will create a new scene and save it so that it exists on disk
before the function is run, and gets saved once the function exits - saves having to
re-write the 4 lines of code it takes to do this on every test method...
'''
def decorate(f):
def newF( self, *a, **kw ):
cmd.file( new=True, f=True )
filename = (TEST_DIRECTORY / 'maya' / sceneName).setExtension( 'ma' )
cmd.file( rename=filename )
cmd.file( save=True )
ret = f( self, *a, **kw )
cmd.file( save=True )
return ret
return newF
return decorate
class _BaseTest(TestCase):
'''
base class for maya tests - doesn't really do anything except provide a cleanup routine that will delete
all files saved to the TEST_DIRECTORY after the testCase has been run
'''
_CLEANUP = True
def setUp( self ):
mayaDir = TEST_DIRECTORY / 'maya'
mayaDir.create()
def new( self ):
cmd.file( new=True, f=True )
def tearDown( self ):
'''
cleans out all files under the TEST_DIRECTORY folder after the tests have run
'''
cmd.file( new=True, f=True )
#if the user doesn't want us to cleanup, don't!
if not self._CLEANUP:
return
print '--- CLEANING UP TEST FILES ---'
for f in TEST_DIRECTORY.files( recursive=True ):
#delete the file
f.delete()
#end
| Python |
import os
import sys
from api import mel
from maya.cmds import *
from filesystem import Path, removeDupes, BreakException, getArgDefault
from vectors import Vector
import maya.cmds as cmd
import filesystem
import rigUtils
import triggered
import colours
import meshUtils
import profileDecorators
from apiExtensions import asMObject, MObject
from common import printErrorStr
SPACE_WORLD = rigUtils.SPACE_WORLD
SPACE_LOCAL = rigUtils.SPACE_LOCAL
SPACE_OBJECT = rigUtils.SPACE_OBJECT
Axis = rigUtils.Axis
CONTROL_DIRECTORY = None
if CONTROL_DIRECTORY is None:
#try to determine the directory that contains the control macros
dirsToSearch = [ Path( __file__ ).up() ] + sys.path + os.environ[ 'MAYA_SCRIPT_PATH' ].split( os.pathsep )
dirsToSearch = map( Path, dirsToSearch )
dirsToSearch = removeDupes( dirsToSearch )
for dirToSearch in dirsToSearch:
if not dirToSearch.isDir():
continue
foundControlDir = False
for f in dirToSearch.files( recursive=True ):
if f.hasExtension( 'shape' ):
if f.name().startswith( 'control' ):
CONTROL_DIRECTORY = f.up()
foundControlDir = True
break
if foundControlDir:
break
if CONTROL_DIRECTORY is None:
printErrorStr( "Cannot determine the directory that contains the *.control files - please open '%s' and set the CONTROL_DIRECTORY variable appropriately" % Path( __file__ ) )
AX_X, AX_Y, AX_Z, AX_X_NEG, AX_Y_NEG, AX_Z_NEG = map( Axis, range( 6 ) )
DEFAULT_AXIS = AX_X
AXIS_ROTATIONS = { AX_X: (0, 0, -90),
AX_Y: (0, 0, 0),
AX_Z: (90, 0, 0),
AX_X_NEG: (0, 0, 90),
AX_Y_NEG: (180, 0, 0),
AX_Z_NEG: (-90, 0, 0) }
class ShapeDesc(object):
'''
store shape preferences about a control
'''
NULL_SHAPE = None
SKIN = 1
DEFAULT_TYPE = 'cube'
def __init__( self, surfaceType=DEFAULT_TYPE, curveType=None, axis=DEFAULT_AXIS, expand=0.04, joints=None ):
'''
surfaceType must be a valid control preset name - defaults to cube if none is specified
curveType must also be a valid control preset name and defaults to the surface name if not specified
'''
self.surfaceType = surfaceType
self.curveType = curveType
if curveType is None:
self.curveType = surfaceType
self.axis = axis
self.expand = expand
if joints is None:
self.joints = []
else:
self.joints = joints if isinstance( joints, (tuple, list) ) else [ joints ]
def __repr__( self ):
return repr( self.surfaceType or self.curveType )
__str__ = __repr__
DEFAULT_SHAPE_DESC = ShapeDesc()
SHAPE_NULL = ShapeDesc( ShapeDesc.NULL_SHAPE, ShapeDesc.NULL_SHAPE )
Shape_Skin = lambda joints=None, **kw: ShapeDesc( ShapeDesc.SKIN, ShapeDesc.NULL_SHAPE, joints=joints, **kw )
DEFAULT_SKIN_EXTRACTION_TOLERANCE = getArgDefault( meshUtils.extractMeshForJoints, 'tolerance' )
class PlaceDesc(object):
WORLD = None
PLACE_OBJ = 0
ALIGN_OBJ = 1
PIVOT_OBJ = 2
Place = 0
Align = 1
Pivot = 2
def __init__( self, placeAtObj=WORLD, alignToObj=PLACE_OBJ, snapPivotToObj=PLACE_OBJ ):
#now convert the inputs to actual objects, if they're not already
self._placeData = placeAtObj, alignToObj, snapPivotToObj
self.place = self.getObj( self.Place )
self.align = self.getObj( self.Align )
self.pivot = self.getObj( self.Pivot )
def getObj( self, item ):
p = self._placeData[ item ]
if isinstance( p, MObject ): return p
if p == self.PLACE_OBJ:
p = self._placeData[ 0 ]
elif p == self.ALIGN_OBJ:
p = self._placeData[ 1 ]
elif p == self.PIVOT_OBJ:
p = self._placeData[ 2 ]
if isinstance( p, basestring ): return p
if isinstance( p, int ): return self.WORLD
if p is None: return self.WORLD
return p
def getLocation( self, obj ):
if obj is None:
return Vector()
return xform( obj, q=True, ws=True, rp=True )
placePos = property( lambda self: self.getLocation( self.place ) )
alignPos = property( lambda self: self.getLocation( self.align ) )
pivotPos = property( lambda self: self.getLocation( self.pivot ) )
DEFAULT_PLACE_DESC = PlaceDesc()
class PivotModeDesc(object):
BASE, MID, TOP = 0, 1, 2
ColourDesc = colours.Colour
DEFAULT_COLOUR = ColourDesc( 'orange' )
def _performOnAttr( obj, attrName, metaName, metaState ):
childAttrs = attributeQuery( attrName, n=obj, listChildren=True ) or []
if childAttrs:
for a in childAttrs:
setAttr( '%s.%s' % (obj, a), **{ metaName: metaState } )
else:
setAttr( '%s.%s' % (obj, attrName), **{ metaName: metaState } )
NORMAL = False, True
HIDE = None, False, False
LOCK_HIDE = True, False, False
NO_KEY = False, False, True
LOCK_SHOW = True, True, True
def attrState( objs, attrNames, lock=None, keyable=None, show=None ):
if not isinstance( objs, (list, tuple) ):
objs = [ objs ]
objs = map( str, objs )
if not isinstance( attrNames, (list, tuple) ):
attrNames = [ attrNames ]
for obj in objs:
for attrName in attrNames:
#showInChannelBox( False ) doesn't work if setKeyable is true - which is kinda dumb...
if show is not None:
if not show:
_performOnAttr( obj, attrName, 'keyable', False )
keyable = None
_performOnAttr( obj, attrName, 'keyable', show )
if lock is not None: _performOnAttr( obj, attrName, 'lock', lock )
if keyable is not None: _performOnAttr( obj, attrName, 'keyable', keyable )
def getJointSizeAndCentre( joints, threshold=0.65, space=SPACE_OBJECT ):
'''
minor modification to the getJointSize function in rigging.utils - uses the
child of the joint[ 0 ] (if any exist) to determine the size of the joint in
the axis aiming toward
'''
centre = Vector.Zero( 3 )
if not isinstance( joints, (list, tuple) ):
joints = [ joints ]
joints = [ str( j ) for j in joints if j is not None ]
if not joints:
return Vector( (1, 1, 1) )
size, centre = rigUtils.getJointSizeAndCentre( joints, threshold, space )
if size.within( Vector.Zero( 3 ), 1e-2 ):
while threshold > 1e-2:
threshold *= 0.9
size, centre = rigUtils.getJointSizeAndCentre( joints, threshold )
if size.within( Vector.Zero( 3 ), 1e-2 ):
size = Vector( (1, 1, 1) )
children = listRelatives( joints[ 0 ], pa=True, type='transform' )
if children:
childPos = Vector( [ 0.0, 0.0, 0.0 ] )
childPosMag = childPos.get_magnitude()
for child in children:
curChildPos = Vector( xform( child, q=True, ws=True, rp=True ) ) - Vector( xform( joints[ 0 ], q=True, ws=True, rp=True ) )
curChildPosMag = curChildPos.get_magnitude()
if curChildPosMag > childPosMag:
childPos = curChildPos
childPosMag = curChildPosMag
axis = rigUtils.getObjectAxisInDirection( joints[ 0 ], childPos, DEFAULT_AXIS )
axisValue = getAttr( '%s.t%s' % (children[ 0 ], axis.asCleanName()) )
if space == SPACE_WORLD:
axis = Axis.FromVector( childPos )
size[ axis % 3 ] = abs( axisValue )
centre[ axis % 3 ] = axisValue / 2.0
return size, centre
getJointSizeAndCenter = getJointSizeAndCentre #for spelling n00bs
def getJointSize( joints, threshold=0.65, space=SPACE_OBJECT ):
return getJointSizeAndCentre( joints, threshold, space )[ 0 ]
def getAutoOffsetAmount( placeObject, joints=None, axis=AX_Z, threshold=0.65 ):
'''
returns a value reflecting the distance from the placeObject to the edge of
the bounding box containing the verts skinned to the joints in the joints list
the axis controls what edge of the bounding box is used
if joints is None, [placeObject] is used
'''
if joints is None:
joints = [ placeObject ]
else:
joints = removeDupes( [ placeObject ] + joints ) #make sure the placeObject is the first item in the joints list, otherwise the bounds won't be transformed to the correct space
#get the bounds of the geo skinned to the hand and use it to determine default placement of the slider control
bounds = rigUtils.getJointBounds( joints )
offsetAmount = abs( bounds[ axis.isNegative() ][ axis % 3 ] )
#print bounds[ 0 ].x, bounds[ 0 ].y, bounds[ 0 ].z, bounds[ 1 ].x, bounds[ 1 ].y, bounds[ 1 ].z
return offsetAmount
AUTO_SIZE = None
DEFAULT_HIDE_ATTRS = ( 'scale', 'visibility' )
def buildControl( name,
placementDesc=DEFAULT_PLACE_DESC,
pivotModeDesc=PivotModeDesc.MID,
shapeDesc=DEFAULT_SHAPE_DESC,
colour=DEFAULT_COLOUR,
constrain=True,
oriented=True,
offset=Vector( (0, 0, 0) ), offsetSpace=SPACE_OBJECT,
size=Vector( (1, 1, 1) ), scale=1.0, autoScale=False,
parent=None, qss=None,
asJoint=False, freeze=True,
lockAttrs=( 'scale', ), hideAttrs=DEFAULT_HIDE_ATTRS,
niceName=None,
displayLayer=None ):
'''
this rather verbosely called function deals with creating control objects in
a variety of ways.
the following args take "struct" like instances of the classes defined above,
so look to them for more detail on defining those options
displayLayer (int) will create layers (if doesn't exist) and add control shape to that layer.
layer None or zero doesn't create.
'''
select( cl=True )
#sanity checks...
if not isinstance( placementDesc, PlaceDesc ):
if isinstance( placementDesc, (list, tuple) ):
placementDesc = PlaceDesc( *placementDesc )
else:
placementDesc = PlaceDesc( placementDesc )
if not isinstance( shapeDesc, ShapeDesc ):
if isinstance( shapeDesc, (list, tuple) ):
shapeDesc = ShapeDesc( *shapeDesc )
else:
shapeDesc = ShapeDesc( shapeDesc )
offset = Vector( offset )
#if we've been given a parent, cast it to be an MObject so that if its name path changes (for example if
#parent='aNode' and we create a control called 'aNode' then the parent's name path will change to '|aNode' - yay!)
if parent:
parent = asMObject( parent )
#unpack placement objects
place, align, pivot = placementDesc.place, placementDesc.align, placementDesc.pivot
if shapeDesc.surfaceType == ShapeDesc.SKIN:
shapeDesc.curveType = ShapeDesc.NULL_SHAPE #never build curve shapes if the surface type is skin
if shapeDesc.joints is None:
shapeDesc.joints = [ str( place ) ]
shapeDesc.expand *= scale
#determine auto scale/size - if nessecary
if autoScale:
_scale = list( getJointSize( [ place ] + (shapeDesc.joints or []) ) )
_scale = sorted( _scale )[ -1 ]
if abs( _scale ) < 1e-2:
print 'AUTO SCALE FAILED', _scale, name, place
_scale = scale
scale = _scale
if size is AUTO_SIZE:
tmpKw = {} if oriented else { 'space': SPACE_WORLD }
size = getJointSize( [ place ] + (shapeDesc.joints or []), **tmpKw )
for n, v in enumerate( size ):
if abs( v ) < 1e-2:
size[ n ] = scale
scale = 1.0
#if we're doing a SKIN shape, ensure there is actually geometry skinned to the joints, otherwise bail on the skin and change to the default type
if shapeDesc.surfaceType == ShapeDesc.SKIN:
try:
#loop over all joints and see if there is geo skinned to it
for j in shapeDesc.joints:
verts = meshUtils.jointVerts( j, tolerance=DEFAULT_SKIN_EXTRACTION_TOLERANCE )
#if so throw a breakException to bail out of the loop
if verts: raise BreakException
#if we get this far that means none of the joints have geo skinned to them - so set the surface and curve types to their default values
shapeDesc.surfaceType = shapeDesc.curveType = ShapeDesc.DEFAULT_TYPE
print 'WARNING - surface type was set to SKIN, but no geometry is skinned to the joints: %s' % shapeDesc.joints
except BreakException: pass
#build the curve shapes first
if shapeDesc.curveType != ShapeDesc.NULL_SHAPE \
and shapeDesc.curveType != ShapeDesc.SKIN:
curveShapeFile = getFileForShapeName( shapeDesc.curveType )
assert curveShapeFile is not None, "cannot find shape %s" % shapeDesc.curveType
createCmd = ''.join( curveShapeFile.read() )
mel.eval( createCmd )
else:
select( group( em=True ) )
sel = ls( sl=True )
obj = asMObject( sel[ 0 ] )
#now to deal with the surface - if its different from the curve, then build it
if shapeDesc.surfaceType != shapeDesc.curveType \
and shapeDesc.surfaceType != ShapeDesc.NULL_SHAPE \
and shapeDesc.surfaceType != ShapeDesc.SKIN:
#if the typesurface is different from the typecurve, then first delete all existing surface shapes under the control
shapesTemp = listRelatives( obj, s=True, pa=True )
for s in shapesTemp:
if nodeType( s ) == "nurbsSurface":
delete( s )
#now build the temporary control
surfaceShapeFile = getFileForShapeName( shapeDesc.surfaceType )
assert surfaceShapeFile is not None, "cannot find shape %s" % shapeDesc.surfaceType
createCmd = ''.join( surfaceShapeFile.read() )
mel.eval( createCmd )
#and parent its surface shape nodes to the actual control, and then delete it
tempSel = ls( sl=True )
shapesTemp = listRelatives( tempSel[0], s=True, pa=True ) or []
for s in shapesTemp:
if nodeType(s) == "nurbsSurface":
cmd.parent( s, obj, add=True, s=True )
delete( tempSel[ 0 ] )
select( sel )
#if the joint flag is true, parent the object shapes under a joint instead of a transform node
if asJoint:
select( cl=True )
j = joint()
for s in listRelatives( obj, s=True, pa=True ) or []:
cmd.parent( s, j, add=True, s=True )
setAttr( '%s.radius' % j, keyable=False )
setAttr( '%s.radius' % j, cb=False )
delete( obj )
obj = asMObject( j )
setAttr( '%s.s' % obj, scale, scale, scale )
#rename the object - if no name has been given, call it "control". if there is a node with the name already, get maya to uniquify it
if not name:
name = 'control'
if objExists( name ):
name = '%s#' % name
rename( obj, name )
#move the pivot - if needed
makeIdentity( obj, a=1, s=1 )
shapeStrs = getShapeStrs( obj )
if pivotModeDesc == PivotModeDesc.TOP:
for s in shapeStrs:
move( 0, -scale/2.0, 0, s, r=True )
elif pivotModeDesc == PivotModeDesc.BASE:
for s in shapeStrs:
move( 0, scale/2.0, 0, s, r=True )
#rotate it accordingly
rot = AXIS_ROTATIONS[ shapeDesc.axis ]
rotate( rot[0], rot[1], rot[2], obj, os=True )
makeIdentity( obj, a=1, r=1 )
#if the user wants the control oriented, create the orientation group and parent the control
grp = obj
if oriented:
grp = group( em=True, n="%s_space#" % obj )
cmd.parent( obj, grp )
attrState( grp, ['s', 'v'], *LOCK_HIDE )
if align is not None:
delete( parentConstraint( align, grp ) )
#place and align
if place:
delete( pointConstraint( place, grp ) )
if align:
delete( orientConstraint( align, grp ) )
else:
rotate( 0, 0, 0, grp, a=True, ws=True )
#do the size scaling...
if shapeDesc.surfaceType != ShapeDesc.SKIN:
for s in getShapeStrs( obj ):
cmd.scale( size[0], size[1], size[2], s )
#if the parent exists - parent the new control to the given parent
if parent is not None:
grp = cmd.parent( grp, parent )[0]
#do offset
for s in getShapeStrs( obj ):
mkw = { 'r': True }
if offsetSpace == SPACE_OBJECT: mkw[ 'os' ] = True
elif offsetSpace == SPACE_LOCAL: mkw[ 'ls' ] = True
elif offsetSpace == SPACE_WORLD: mkw[ 'ws' ] = True
if offset:
move( offset[0], offset[1], offset[2], s, **mkw )
if freeze:
makeIdentity( obj, a=1, r=1 )
makeIdentity( obj, a=1, t=1 ) #always freeze translations
#delete shape data that we don't want
if shapeDesc.curveType is None:
for s in listRelatives( obj, s=True, pa=True ) or []:
if nodeType(s) == "nurbsCurve":
delete(s)
if shapeDesc.surfaceType is None:
for s in listRelatives( obj, s=True, pa=True ) or []:
if nodeType(s) == "nurbsSurface":
delete(s)
#now snap the pivot to alignpivot object if it exists
if pivot is not None and objExists( pivot ):
p = placementDesc.pivotPos
move( p[0], p[1], p[2], '%s.rp' % obj, '%s.sp' % obj, a=True, ws=True, rpr=True )
#constrain the target object to this control?
if constrain:
#check to see if the transform is constrained already - if so, bail. buildControl doesn't do multi constraints
if not listConnections( pivot, d=0, type='constraint' ):
if place:
parentConstraint( obj, pivot, mo=True )
setItemRigControl( pivot, obj )
#if the user has specified skin geometry as the representation type, then build the geo
#NOTE: this really needs to happen after ALL the placement has happened otherwise the extracted
#will be offset from the surface its supposed to be representing
if shapeDesc.surfaceType == ShapeDesc.SKIN:
#extract the surface geometry
geo = meshUtils.extractMeshForJoints( shapeDesc.joints, expand=shapeDesc.expand )
#if the geo is None, use the default control representation instead
writeTrigger = True
if geo is None:
writeTrigger = False
curveShapeFile = getFileForShapeName( ShapeDesc.DEFAULT_TYPE )
createCmd = ''.join( curveShapeFile.read() )
mel.eval( createCmd )
geo = ls( sl=True )[ 0 ]
geo = cmd.parent( geo, obj )[0]
makeIdentity( geo, a=True, s=True, r=True, t=True )
cmd.parent( listRelatives( geo, s=True, pa=True ), obj, add=True, s=True )
delete( geo )
#when selected, turn the mesh display off, and only highlight edges
if writeTrigger:
triggered.Trigger.CreateTrigger( str( obj ), cmdStr="for( $s in `listRelatives -s -pa #` ) setAttr ( $s +\".displayEdges\" ) 2;" )
#build a shader for the control
if colour is not None:
colours.setObjShader( obj, colours.getShader( colour, True ) )
#add to a selection set if desired
if qss is not None:
sets( obj, add=qss )
#hide and lock attributes
attrState( obj, lockAttrs, lock=True )
attrState( obj, hideAttrs, show=False )
if niceName:
setNiceName( obj, niceName )
# display layer
if displayLayer and not int( displayLayer ) <= 0 :
layerName = 'ctrl_%d' % int( displayLayer )
allLayers = ls( type='displayLayer' )
layer = ''
if layerName in allLayers:
layer = layerName
else:
layer = createDisplayLayer( n=layerName, number=1, empty=True )
setAttr( '%s.color' % layer, 24 + int( displayLayer ) )
for s in listRelatives( obj, s=True, pa=True ) or []:
connectAttr( '%s.drawInfo.visibility' % layer, '%s.v' % s )
connectAttr( '%s.drawInfo.displayType' % layer, '%s.overrideDisplayType' % s )
return obj
def buildControlAt( name, *a, **kw ):
kw[ 'constrain' ] = False
return buildControl( name, *a, **kw )
def buildNullControl( name, *a, **kw ):
kw[ 'shapeDesc' ] = SHAPE_NULL
kw[ 'oriented' ] = False
kw[ 'constrain' ] = False
return buildControl( name, *a, **kw )
def buildAlignedNull( alignTo, name=None, *a, **kw ):
if name is None:
name = 'alignedNull'
return buildControl( name, alignTo, shapeDesc=SHAPE_NULL, constrain=False, oriented=False, freeze=False, *a, **kw )
def setItemRigControl( item, control ):
'''
used to associate an item within a skeleton part with a rig control
'''
attrPath = '%s._skeletonPartRigControl' % item
if not objExists( attrPath ):
addAttr( item, ln='_skeletonPartRigControl', at='message' )
connectAttr( '%s.message' % control, attrPath, f=True )
return True
def getItemRigControl( item ):
'''
returns the control associated with the item within a skeleton part, or None
if there is no control driving the item
'''
attrPath = '%s._skeletonPartRigControl' % item
if objExists( attrPath ):
cons = listConnections( attrPath, d=False )
if cons:
return cons[ 0 ]
return None
def getNiceName( obj ):
attrPath = '%s._NICE_NAME' % obj
if objExists( attrPath ):
return getAttr( attrPath )
return None
def setNiceName( obj, niceName ):
attrPath = '%s._NICE_NAME' % obj
if not objExists( attrPath ):
addAttr( obj, ln='_NICE_NAME', dt='string' )
setAttr( attrPath, niceName, type='string' )
SHAPE_TO_COMPONENT_NAME = { 'nurbsSurface': 'cv',
'nurbsCurve': 'cv',
'mesh': 'vtx' }
def getShapeStrs( obj ):
'''
returns a list of names to refer to all components for all shapes
under the given object
'''
global SHAPE_TO_COMPONENT_NAME
geo = []
shapes = listRelatives( obj, s=True, pa=True ) or []
for s in shapes:
nType = str( nodeType( s ) )
cName = SHAPE_TO_COMPONENT_NAME[ nType ]
geo.append( "%s.%s[*]" % (s, cName) )
return geo
def getControlShapeFiles():
dir = CONTROL_DIRECTORY
if isinstance( dir, basestring ):
dir = Path( dir )
if not isinstance( dir, Path ) or not dir.exists():
dir = Path( __file__ ).up()
shapes = []
if dir.exists():
shapes = [ f for f in dir.files() if f.hasExtension( 'shape' ) ]
if not shapes:
searchPaths = map( Path, sys.path )
searchPaths += map( Path, os.environ.get( 'MAYA_SCRIPT_PATH', '' ).split( ';' ) )
searchPaths = removeDupes( searchPaths )
for d in searchPaths:
try: shapes += [ f for f in d.files() if f.hasExtension( 'shape' ) ]
except WindowsError: continue
return shapes
CONTROL_SHAPE_FILES = getControlShapeFiles()
CONTROL_SHAPE_DICT = {}
for f in CONTROL_SHAPE_FILES:
CONTROL_SHAPE_DICT[ f.name().split( '.' )[ -1 ].lower() ] = f
def getFileForShapeName( shapeName ):
theFile = CONTROL_SHAPE_DICT.get( shapeName.lower(), None )
return theFile
@profileDecorators.d_profile
def speedTest():
import time
start = time.clock()
for n in range( 100 ): buildControl( 'apples' )
print 'time taken %0.3f' % (time.clock()-start)
#end
| Python |
import maya.OpenMaya as om
import maya.cmds as cmd
from math import sqrt
class BlendShape():
def __init__( self, nodeName ):
self.name = nodeName
self.__minRowLength = 5
def __repr__( self ):
return self.targets
def __str__( self ):
return str(self.__repr__())
def __add__( self, value ):
'''value should be a string or a list of strings (object names)'''
if isinstance(value,str):
self.append(value)
elif isinstance(value,list) or isinstance(value,tuple):
for val in value:
self.__add__(val)
else:
raise ArithmeticError("only supports adding strings (name of a known target object) or lists/tuples of strings")
return self
def __sub__( self, value ):
'''value should be a string or a list of strings (object names)'''
if isinstance(value,str):
self.pop(value)
elif isinstance(value,list) or isinstance(value,tuple):
for val in value:
self.__add__(val)
else:
raise ArithmeticError("only supports subtracting strings (name of a known target object) or lists/tuples of strings")
return self
def __getattr__( self, attr ):
if attr in self.targets:
return cmd.getAttr(self.name +'.'+ attr)
#else:
# raise AttributeError("the %s target doesn't exist"%(attr,))
def __getitem__( self, idx ):
return cmd.getAttr(self.name +'.w['+ idx +']')
def append( self, shapeNameToAdd=None, name=None ):
'''deals with adding a target of name shape to the blendshape'''
if shapeNameToAdd == None:
#in this case the user wants to append the current shape of the object being driven to the target list
dupe = cmd.duplicate(self.obj)[0]
shapeNameToAdd = dupe
self.zeroTweak()
if cmd.objExists(shapeNameToAdd):
if name != None:
shapeNameToAdd = cmd.rename(shapeNameToAdd,name)
#make sure the name doesn't clash with an existing target name - otherwise maya will bork
while shapeNameToAdd in self.targets:
shapeNameToAdd += 'Dupe'
numTgts = len(self.targets)
cmd.blendShape(self.name,edit=True,target=(self.obj,numTgts,shapeNameToAdd,1.0))
self.collapse(shapeNameToAdd)
self.zeroTweak()
return shapeNameToAdd
def expand( self, targetToExpand ):
'''makes all the target shapes appear as objects in the scene - objects are placed to the right
(assuming +z is facing forward and +y up) of the base object placed a bounding box width apart.
row length is at least 5, but for large numbers of targets it takes the square root of the target
count'''
SEPARATION_X = 1.3
SEPARATION_Y = 1.3
expanded = self.expanded
targets = self.targets
num = len(expanded)
if targetToExpand in targets:
if self.isExpanded(targetToExpand):
return self.getExpandedName(targetToExpand)
obj = self.obj
maxRowLength = max(self.__minRowLength,int(sqrt(len(targets))))
#get the size of the object so we can place them away from the original
bbox = cmd.getAttr(obj +'.bbmn')[0] + cmd.getAttr(obj +'.bbmx')[0]
size = ( (bbox[3]-bbox[0])*SEPARATION_X, (bbox[4]-bbox[1])*SEPARATION_Y )
x = num%maxRowLength + 1
y = int(num/maxRowLength) * -1
index = self.getTargetIdx(targetToExpand)
self.setTargetWeight(targetToExpand,1,crossfade=True)
dupe = cmd.duplicate(obj)[0]
dupe = cmd.rename(dupe,targetToExpand)
cmd.connectAttr(dupe +'.worldMesh[0]', self.name +'.inputTarget[0].inputTargetGroup['+ str(index) +'].inputTargetItem[6000].inputGeomTarget')
#now move the objects away from the base so they're easier to visualize
cmd.move(size[0]*x,size[1]*y,0,dupe,moveX=True,moveY=True,relative=True)
return dupe
else:
raise AttributeError("target doesn't exist")
def expandAll( self ):
'''expands all targets - convenience really. this is horribly inefficient, but unless the target count
grows into the multi thousands this shouldn't become a problem...'''
initSelection = cmd.ls(selection=True)
targets = self.targets
weights = self.weights
dupes = []
for target in targets:
weight = cmd.getAttr(self.name +'.'+ target)
dupes.append(self.expand(target))
self.setTargetWeight(target,weight,False)
if initSelection: cmd.select(initSelection)
return dupes
def __getExpanded( self ):
expanded = cmd.listConnections(self.name +'.it',destination=False)
if expanded: return expanded
else: return []
expanded = property(__getExpanded)
def getExpandedName( self, target ):
index = self.getTargetIdx(target)
expanded = cmd.listConnections(self.name +'.it[0].inputTargetGroup['+ str(index) +'].inputTargetItem[6000].inputGeomTarget',destination=False)
if expanded: return expanded[0]
else: return []
def isExpanded( self, target=None ):
'''returns whether a given target has been expanded or not. if no target is given this will return
whether ANY target has been expanded'''
cons = self.__getExpanded()
if target:
if self.getExpandedName(target) in cons:
return True
else:
if cons: return True
return False
def collapse( self, targetToCollapse ):
'''collapses the given target object so it's no longer visible in the scene'''
if self.isExpanded(targetToCollapse):
expandedName = self.getExpandedName(targetToCollapse)
cmd.delete(expandedName)
def collapseAll( self ):
for target in self.targets:
self.collapse(target)
def pop( self, targetToRemove ):
'''pops the given shape name or shape index out of the blendShape node - creating the object in
the scene, and removing it from the blendShape node'''
targets = self.targets
indicies = self.indicies
if targetToRemove in targets:
blendIdx = self.getTargetIdx(targetToRemove)
shape = self.expand(targetToRemove)
cmd.blendShape(self.name,edit=True,remove=True,target=(self.obj,blendIdx,shape,1.0))
return shape
else:
raise AttributeError("target doesn't exist")
def remove( self, targetToRemove ):
cmd.delete(self.pop(targetToRemove))
def update( self, targetToUpdate ):
'''overwrites the target name given with the current shape of self.name'''
targets = self.targets
if targetToUpdate in targets:
nameIdx = targets.index(targetToUpdate)
baseDupe = cmd.duplicate(self.obj)[0]
self.zeroTweak()
newTarget = self.expand(targetToUpdate)
cmd.select((baseDupe,newTarget))
tmpBlendNode = cmd.blendShape()[0]
cmd.setAttr(tmpBlendNode +'.w[0]',1)
cmd.delete(newTarget,constructionHistory=True)
cmd.delete(baseDupe)
self.collapse(targetToUpdate)
cmd.select(self.obj)
else:
raise AttributeError("target doesn't exist")
def zeroTweak( self ):
'''deals with zeroing out the tweak node values that have accumulated on a base mesh'''
tweakNode = cmd.ls(cmd.listHistory(self.shape),type='tweak')[0]
totalVertCount = cmd.getAttr(self.shape +'.vrts',size=True)
for n in range(totalVertCount):
cmd.setAttr(tweakNode +'.vlist[0].vt['+ str(n) +']',0,0,0)
def __getTargetNameandIndicies( self ):
'''returns a list of the target names on the blendshape. both the index list and
the name list are guaranteed to be in the correct order'''
indicies = []
aliasList = cmd.aliasAttr(self.name,query=True)
if aliasList == None: return []
for n in range(1,len(aliasList),2):
idx = int(aliasList[n][7:][:-1])
indicies.append(idx)
indicies.sort()
names = [None]*len(indicies) #build the name array of the correct size
for n in range(0,len(aliasList),2):
curNameIdx = int(aliasList[n+1][7:][:-1])
for i in range(len(indicies)):
if curNameIdx == indicies[i]:
names[i] = aliasList[n]
return names,indicies
def __getTargetNames( self ):
'''returns a list of the target names on the blendshape'''
names,indicies = self.__getTargetNameandIndicies()
return names
targets = property(__getTargetNames)
def __getTargetWeights( self ):
'''returns a list of the target names on the blendshape'''
return cmd.getAttr(self.name +'.w')[0]
weights = property(__getTargetWeights)
def __getIndicies( self ):
'''returns a list of the target names on the blendshape'''
names,indicies = self.__getTargetNameandIndicies()
return indicies
indicies = property(__getIndicies)
def getTargetIdx( self, target ):
'''given a target name this method will return its index in the weight attribute'''
indicies = []
aliasList = cmd.aliasAttr(self.name,query=True)
if aliasList == None:
raise Exception( "not aliasAttr found on %s"%(self.name,))
for n in range(0,len(aliasList),2):
if aliasList[n] == target:
idx = aliasList[n+1][7:][:-1]
return int(idx)
raise AttributeError("target doesn't exist")
def __getObject( self ):
return cmd.listRelatives(self.__getShape(),parent=True)[0]
obj = property(__getObject)
def __getShape( self ):
return cmd.ls(cmd.listHistory(self.name +'.outputGeometry',future=True),type='mesh')[0]
shape = property(__getShape)
def rename( self, oldName, newName ):
'''will rename a blend shape target - if the target doesn't exist, the method does nothing...'''
names = self.targets
aliasList = cmd.aliasAttr(self.name,query=True)
if oldName in names:
idx = aliasList.index(oldName)
aliasList[idx] = newName
for n in range(1,len(aliasList),2): aliasList[n] = self.name +'.'+ aliasList[n]
#now remove all the alias'
for name in names: cmd.aliasAttr(self.name +'.'+ name,remove=True)
#finally rebuild the alias'
cmdStr = 'aliasAttr ' + ' '.join(aliasList) +';'
maya.mel.eval(cmdStr)
def setTargetWeight( self, target, weight, additive=False, crossfade=False ):
inititalWeight = cmd.getAttr(self.name +'.'+ target)
if target in self.targets:
#print 'data:',target,weight,additive,crossfade
cmd.setAttr(self.name +'.'+ target,weight)
if crossfade:
pct = abs(1-weight) / 1
idx = self.targets.index(target)
others = self.targets[:]
others.pop(idx)
for other in others:
otherWeight = abs(cmd.getAttr(self.name +'.'+ other))
cmd.setAttr(self.name +'.'+ other,min(0,otherWeight*pct))
else:
raise AttributeError("target doesn't exist")
def setAllWeights( self, weight=0 ):
targets = self.targets
for index in self.indicies:
self.setTargetWeight(targets[index],weight,False)
def propagateTweaks( self ):
'''propagates the data currently in the tweak node to all target objects - this is useful when large
changes to a basemesh need to be made across all targets. NOTE: this is only possible if targets
are expanded...'''
tweakNode = cmd.ls(cmd.listHistory(self.shape),type='tweak')[0]
self.collapseAll()
self.expandAll()
self.zeroTweak()
self.collapseAll()
#need to connect the tweak node up to targets...
def deleteHistory( self ):
'''does a collapse history without destroying blendshape data - this essentially allows you do change
topology on a blendshape setup easily'''
self.collapseAll() #make sure everything is collapsed
newTargets = self.expandAll() #do an expand to ensure all the targets have the same topology as the base mesh
#now we just need to delete the history and rebuild the blendshape setup
obj = self.obj
cmd.delete(obj,constructionHistory=True)
newTargets += [obj]
self.name = cmd.blendShape(newTargets)[0]
self.collapseAll()
def setWeightApi( self, target, weight ):
'''this only exists because its not undoable - which strangely enough is useful - see vBlendShapeManager.mel->doSlideCmd() for details'''
sTmp = om.MSelectionList()
sTmp.add(self.name)
idx = self.getTargetIdx(target)
blendShapeObj = om.MObject()
sTmp.getDependNode(0,blendShapeObj)
blendFn = om.MFnDependencyNode(blendShapeObj)
weightPG = om.MPlug(blendFn.findPlug("w"))
targetPG = om.MPlug(weightPG.elementByPhysicalIndex(idx))
targetPG.setFloat(weight)
class BlendShapePV(BlendShape):
def __init__( self, nodeName ):
BlendShape.__init__(self,nodeName)
cmd.loadPlugin('blendTools',quiet=True)
self.falloffWeights = []
def setAllSliders( self, weight ):
for target in self.targets:
BlendShape.setTargetWeight( self, target, weight )
def setTargetWeight( self, target, weight, additive=False, crossfade=False, falloff=0, selection=None ):
'''deals with setting the weight map for a named shape'''
targets = self.targets
indicies = self.indicies
if target in targets:
idx = self.getTargetIdx(target)
#determine the default selection to use
if selection == None:
sel = cmd.ls(selection=True)
if sel: selection = cmd.polyListComponentConversion(sel,toVertex=True)
else: selection = self.obj +'.vtx[*]'
if selection == '*': selection = self.obj +'.vtx[*]'
#print 'data:',target,weight,falloff,additive,crossfade,selection
#cmd.blendPerVert(selection,node=self.name,target=idx,weight=weight,falloff=falloff,additive=additive,crossfade=crossfade)
cmd.applyFalloffArray(n=self.name,t=tgtIdx,w=weight,add=additive,x=crossfade,undo=True,l=self.falloffWeights)
else:
raise AttributeError("target doesn't exist")
def setAllWeights( self, weight=0 ):
targets = self.targets
for target in targets:
self.setTargetWeight(target,weight)
def generateFalloffList( self, falloff ):
maya.mel.eval('$g_vertFallOffWeights = `getFalloffArray -f %f`;'%falloff)
#self.falloffWeights = cmd.getFalloffArray(f=falloff)
def setWeightApi( self, target, weight, additive=False, crossfade=False ):
'''uses the current falloff weight list'''
if not self.falloffWeights: return #if no falloff weight map has been generated, bail
tgtIdx = self.targets.index(target)
#cmd.applyFalloffArray(node=self.name,target=tgtIdx,w=weight,add=additive,x=crossfade,l=self.falloffWeights)
addStr,xStr = '',''
if additive: addStr = '-add'
if crossfade: xStr = '-x'
maya.mel.eval('applyFalloffArray -n %s -t %d -w %f %s %s -l $g_vertFallOffWeights;')%( self.name,tgtIdx,weight,addStr,xStr)
def getBlendFromObject( object ):
blendNodes = cmd.ls(cmd.listHistory(object),type='blendShape')
if blendNodes != None:
return blendNodes[0]
def clamp( value, min=0, max=1):
if value<min: return min
if value>max: return max
return value
#end
| Python |
from rigPrim_ikFkBase import *
from rigPrim_stretchy import StretchRig
class IkFkArm(IkFkBase):
__version__ = 3 + IkFkBase.__version__ #factor in the version of the ikfk sub rig part
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Arm' ), )
CONTROL_NAMES = 'control', 'fkBicep', 'fkElbow', 'fkWrist', 'poleControl', 'clavicle', 'allPurpose'
def getFkControls( self ):
return self.getControl( 'fkBicep' ), self.getControl( 'fkElbow' ), self.getControl( 'fkWrist' )
def getIkHandle( self ):
ikCons = listConnections( '%s.message' % self.getControl( 'fkBicep' ), s=False, type='ikHandle' )
if ikCons:
return ikCons[0]
def _build( self, skeletonPart, translateClavicle=True, stretchy=True, **kw ):
return self.doBuild( skeletonPart.bicep, skeletonPart.elbow, skeletonPart.wrist, skeletonPart.clavicle, translateClavicle, stretchy, **kw )
def doBuild( self, bicep, elbow, wrist, clavicle=None, translateClavicle=True, stretchy=False, **kw ):
getWristToWorldRotation( wrist, True )
colour = self.getParityColour()
wireColor = 14 if self.getParity() == Parity.LEFT else 13
parentControl, rootControl = getParentAndRootControl( clavicle or bicep )
#build the base controls
self.buildBase( ARM_NAMING_SCHEME )
#create variables for each control used
ikHandle = self.ikHandle
ikArmSpace, fkArmSpace = self.ikSpace, self.fkSpace
fkControls = driverBicep, driverElbow, driverWrist = self.driverUpper, self.driverMid, self.driverLower
elbowControl = self.poleControl
#build the clavicle
if clavicle:
clavOffset = AX_Y.asVector() * getAutoOffsetAmount( clavicle, listRelatives( clavicle, pa=True ), AX_Y )
clavControl = buildControl( 'clavicleControl%s' % self.getParity().asName(), PlaceDesc( bicep, clavicle, clavicle ), shapeDesc=ShapeDesc( 'sphere' ), scale=self.scale*1.25, offset=clavOffset, offsetSpace=SPACE_WORLD, colour=colour )
clavControlOrient = getNodeParent( clavControl )
parent( clavControlOrient, parentControl )
parent( fkArmSpace, clavControl )
if not translateClavicle:
attrState( clavControl, 't', *LOCK_HIDE )
else:
clavControl = None
parent( fkArmSpace, parentControl )
#build space switching
allPurposeObj = self.buildAllPurposeLocator( 'arm' )
buildDefaultSpaceSwitching( bicep, elbowControl, **spaceSwitching.NO_ROTATION )
buildDefaultSpaceSwitching( bicep, self.control, [ allPurposeObj ], [ 'All Purpose' ], True )
buildDefaultSpaceSwitching( bicep, driverBicep, **spaceSwitching.NO_TRANSLATION )
#make the limb stretchy?
if stretchy:
StretchRig.Create( self.getSkeletonPart(), self.control, fkControls, '%s.ikBlend' % ikHandle, parity=self.getParity() )
controls = self.control, driverBicep, driverElbow, driverWrist, elbowControl, clavControl, allPurposeObj
namedNodes = self.ikSpace, self.fkSpace, self.ikHandle, self.endOrient, self.lineNode
return controls, namedNodes
class IkFkLeg(IkFkBase):
__version__ = 2 + IkFkBase.__version__ #factor in the version of the ikfk sub rig part
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Leg' ), )
CONTROL_NAMES = 'control', 'fkThigh', 'fkKnee', 'fkAnkle', 'poleControl', 'allPurpose'
def getFkControls( self ):
return self.getControl( 'fkThigh' ), self.getControl( 'fkKnee' ), self.getControl( 'fkAnkle' )
def getIkHandle( self ):
ikCons = listConnections( '%s.message' % self.getControl( 'fkThigh' ), s=False, type='ikHandle' )
if ikCons:
return ikCons[0]
def _build( self, skeletonPart, stretchy=True, **kw ):
return self.doBuild( skeletonPart.thigh, skeletonPart.knee, skeletonPart.ankle, stretchy=stretchy, **kw )
def doBuild( self, thigh, knee, ankle, stretchy=True, **kw ):
partParent, rootControl = getParentAndRootControl( thigh )
#first rotate the foot so its aligned to a world axis
footCtrlRot = Vector( getAnkleToWorldRotation( str( ankle ), 'z', True ) )
footCtrlRot = (0, -footCtrlRot.y, 0)
#build the base controls
self.buildBase( LEG_NAMING_SCHEME )
#if the legs are parented to a root part - which is usually the case but not always - grab the hips and parent the fk control space to the hips
hipsControl = partParent
partParentRigPart = RigPart.InitFromItem( partParent )
if isinstance( partParentRigPart.getSkeletonPart(), Root ):
hipsControl = partParentRigPart.getControl( 'hips' )
#if the part parent in a Root primitive, grab the hips control instead of the root gimbal - for the leg parts this is preferable
parentRigPart = RigPart.InitFromItem( partParent )
if isinstance( parentRigPart, Root ):
partParent = parentRigPart.getControl( 'hips' )
#create variables for each control used
legControl = self.control
legControlSpace = getNodeParent( legControl )
ikLegSpace, fkLegSpace = self.ikSpace, self.fkSpace
driverThigh, driverKnee, driverAnkle = self.driverUpper, self.driverMid, self.driverLower
fkControls = driverThigh, driverKnee, driverAnkle
kneeControl = self.poleControl
kneeControlSpace = getNodeParent( kneeControl )
parent( kneeControlSpace, partParent )
toe = listRelatives( ankle, type='joint', pa=True ) or None
toeTip = None
if toe:
toe = toe[0]
#if the toe doesn't exist, build a temp one
if not toe:
toe = group( em=True )
parent( toe, ankle, r=True )
move( 0, -self.scale, self.scale, toe, r=True, ws=True )
toeTip = self.getSkeletonPart().endPlacer
if not toeTip:
possibleTips = listRelatives( toe, type='joint', pa=True )
if possibleTips:
toeTip = possibleTips[ 0 ]
#build the objects to control the foot
suffix = self.getSuffix()
footControlSpace = buildNullControl( "foot_controlSpace"+ suffix, ankle, parent=legControl )
heelRoll = buildNullControl( "heel_roll_piv"+ suffix, ankle, offset=(0, 0, -self.scale), parent=footControlSpace )
select( heelRoll ) #move command doesn't support object naming when specifying a single axis move, so we must selec the object first
move( 0, 0, 0, rpr=True, y=True )
if toeTip:
toeRoll = buildNullControl( "leg_toe_roll_piv"+ suffix, toeTip, parent=heelRoll )
else:
toeRoll = buildNullControl( "leg_toe_roll_piv"+ suffix, toe, parent=heelRoll, offset=(0, 0, self.scale) )
footBankL = buildNullControl( "bank_in_piv"+ suffix, toe, parent=toeRoll )
footBankR = buildNullControl( "bank_out_piv"+ suffix, toe, parent=footBankL )
footRollControl = buildNullControl( "roll_piv"+ suffix, toe, parent=footBankR )
#move bank pivots to a good spot on the ground
placers = self.getSkeletonPart().getPlacers()
numPlacers = len( placers )
if placers:
toePos = Vector( xform( toe, q=True, ws=True, rp=True ) )
if numPlacers >= 2:
innerPlacer = Vector( xform( placers[1], q=True, ws=True, rp=True ) )
move( innerPlacer[0], innerPlacer[1], innerPlacer[2], footBankL, a=True, ws=True, rpr=True )
if numPlacers >= 3:
outerPlacer = Vector( xform( placers[2], q=True, ws=True, rp=True ) )
move( outerPlacer[0], outerPlacer[1], outerPlacer[2], footBankR, a=True, ws=True, rpr=True )
if numPlacers >= 4:
heelPlacer = Vector( xform( placers[3], q=True, ws=True, rp=True ) )
move( heelPlacer[0], heelPlacer[1], heelPlacer[2], heelRoll, a=True, ws=True, rpr=True )
#move the knee control so its inline with the leg
rotate( footCtrlRot[0], footCtrlRot[1], footCtrlRot[2], kneeControlSpace, p=xform( thigh, q=True, ws=True, rp=True ), a=True, ws=True )
makeIdentity( kneeControl, apply=True, t=True )
#add attributes to the leg control, to control the pivots
addAttr( legControl, ln='rollBall', at='double', min=0, max=10, k=True )
addAttr( legControl, ln='rollToe', at='double', min=-10, max=10, k=True )
addAttr( legControl, ln='twistFoot', at='double', min=-10, max=10, k=True )
addAttr( legControl, ln='bank', at='double', min=-10, max=10, k=True )
#replace the legControl as a target to the parent constraint on the endOrient transform so the ikHandle respects the foot slider controls
footFinalPivot = buildNullControl( "final_piv"+ suffix, ankle, parent=footRollControl )
delete( parentConstraint( footFinalPivot, self.ikHandle, mo=True ) )
parent( self.ikHandle, footFinalPivot )
replaceGivenConstraintTarget( self.endOrientSpaceConstraint, legControl, footFinalPivot )
#build the SDK's to control the pivots
setDrivenKeyframe( '%s.rx' % footRollControl, cd='%s.rollBall' % legControl, dv=0, v=0 )
setDrivenKeyframe( '%s.rx' % footRollControl, cd='%s.rollBall' % legControl, dv=10, v=90 )
setDrivenKeyframe( '%s.rx' % footRollControl, cd='%s.rollBall' % legControl, dv=-10, v=-90 )
setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=0, v=0 )
setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=10, v=90 )
setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=0, v=0 )
setDrivenKeyframe( '%s.rx' % toeRoll, cd='%s.rollToe' % legControl, dv=-10, v=-90 )
setDrivenKeyframe( '%s.ry' % toeRoll, cd='%s.twistFoot' % legControl, dv=-10, v=-90 )
setDrivenKeyframe( '%s.ry' % toeRoll, cd='%s.twistFoot' % legControl, dv=10, v=90 )
min = -90 if self.getParity() == Parity.LEFT else 90
max = 90 if self.getParity() == Parity.LEFT else -90
setDrivenKeyframe( '%s.rz' % footBankL, cd='%s.bank' % legControl, dv=0, v=0 )
setDrivenKeyframe( '%s.rz' % footBankL, cd='%s.bank' % legControl, dv=10, v=max )
setDrivenKeyframe( '%s.rz' % footBankR, cd='%s.bank' % legControl, dv=0, v=0 )
setDrivenKeyframe( '%s.rz' % footBankR, cd='%s.bank' % legControl, dv=-10, v=min )
#setup the toe if we have one
if toe:
toeSDK = buildControl( "toeSDK%s" % suffix, toe, shapeDesc=SHAPE_NULL, parent=footBankR, scale=self.scale, colour=self.getParityColour() )
toeConstraint = parentConstraint( driverAnkle, toe, w=0, mo=True )[0]
toeConstraintAttrs = listAttr( toeConstraint, ud=True )
expression( s='%s.%s = %s.ikBlend;\n%s.%s = 1 - %s.ikBlend;' % (toeConstraint, toeConstraintAttrs[ 0 ], self.control,
toeConstraint, toeConstraintAttrs[ 1 ], self.control), n='toe_parentingConstraintSwitch' )
addAttr( legControl, ln='toe', at='double', min=-10, max=10, k=True )
setDrivenKeyframe( '%s.r%s' % (toeSDK, ROT_AXIS.asCleanName()), cd='%s.toe' % legControl, dv=-10, v=90 )
setDrivenKeyframe( '%s.r%s' % (toeSDK, ROT_AXIS.asCleanName()), cd='%s.toe' % legControl, dv=10, v=-90 )
#build space switching
parent( fkLegSpace, hipsControl )
allPurposeObj = self.buildAllPurposeLocator( 'leg' )
spaceSwitching.build( legControl, (self.getWorldControl(), hipsControl, rootControl, allPurposeObj), ('World', None, 'Root', 'All Purpose'), space=legControlSpace )
spaceSwitching.build( kneeControl, (legControl, partParent, rootControl, self.getWorldControl()), ("Leg", None, "Root", "World"), **spaceSwitching.NO_ROTATION )
spaceSwitching.build( driverThigh, (hipsControl, rootControl, self.getWorldControl()), (None, 'Root', 'World'), **spaceSwitching.NO_TRANSLATION )
spaceSwitching.build( kneeControl, (self.getWorldControl(), hipsControl, rootControl), ('World', None, 'Root'), **spaceSwitching.NO_ROTATION )
#make the limb stretchy
if stretchy:
StretchRig.Create( self.getSkeletonPart(), legControl, fkControls, '%s.ikBlend' % self.ikHandle, parity=self.getParity() )
if objExists( '%s.elbowPos' % legControl ):
renameAttr( '%s.elbowPos' % legControl, 'kneePos' )
controls = legControl, driverThigh, driverKnee, driverAnkle, kneeControl, allPurposeObj
namedNodes = self.ikSpace, self.fkSpace, self.ikHandle, self.endOrient, self.lineNode
return controls, namedNodes
#end
| Python |
from maya.cmds import *
from maya import OpenMaya
from filesystem import Path, Preset, GLOBAL, LOCAL, removeDupes
from names import *
from vectors import *
from melUtils import mel
from picker import resolveCmdStr
from mappingUtils import *
from common import printWarningStr, printErrorStr
from mayaDecorators import d_noAutoKey, d_unifyUndo, d_disableViews, d_restoreTime
import api
import maya
TOOL_NAME = 'xferAnim'
EXTENSION = 'postTraceScheme'
eul = OpenMaya.MEulerRotation
AXES = "x", "y", "z"
kROOS = "xyz", "yzx", "zxy", "xzy", "yxz", "zyx"
kM_ROOS = [eul.kXYZ, eul.kYZX, eul.kZXY, eul.kXZY, eul.kYXZ, eul.kZYX]
POST_TRACE_ATTR_NAME = 'xferPostTraceCmd'
MATRIX_ROTATION_ORDER_CONVERSIONS_TO = Matrix.ToEulerXYZ, Matrix.ToEulerYZX, Matrix.ToEulerZXY, Matrix.ToEulerXZY, Matrix.ToEulerYXZ, Matrix.ToEulerZYX
def bakeRotateDelta( src, ctrl, presetStr ):
'''
Bakes a post trace command into the ctrl object such that when ctrl is aligned to src (with post
trace cmds enabled) src and tgt are perfectly aligned.
This is useful because rig controls are rarely aligned to the actual joints they drive, but it
can be useful when you have motion from a tool such as SFM, or generated from motion capture that
needs to be applied back to a rig.
'''
mat_j = Matrix( getAttr( '%s.worldInverseMatrix' % srcJoint ) )
mat_c = Matrix( getAttr( '%s.worldMatrix' % jointControl ) )
#generate the matrix describing offset between joint and the rig control
mat_o = mat_j * mat_c
#put into space of the control
rel_mat = mat_o * Matrix( getAttr( '%s.parentInverseMatrix' % jointControl ) )
#now figure out the euler rotations for the offset
ro = getAttr( '%s.ro' % jointControl )
offset = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ ro ]( rel_mat, True )
cmd.rotate( asEuler[ 0 ], asEuler[ 1 ], asEuler[ 2 ], jointControl, relative=True, os=True )
mel.zooSetPostTraceCmd( ctrl, presetStr % offset )
mel.zooAlign( "-src %s -tgt %s -postCmds 1" % (src, ctrl) )
return offset
def bakeManualRotateDelta( src, ctrl, presetStr ):
'''
When you need to apply motion from a skeleton that is completely different from a skeleton driven
by the rig you're working with (transferring motion from old assets to newer assets for example)
you can manually align the control to the joint and then use this function to generate offset
rotations and bake a post trace cmd.
'''
srcInvMat = Matrix( getAttr( '%s.worldInverseMatrix' % src ) )
ctrlMat = Matrix( getAttr( '%s.worldMatrix' % ctrl ) )
#generate the offset matrix as
mat_o = ctrlMat * srcInvMat
#now figure out the euler rotations for the offset
ro = getAttr( '%s.ro' % ctrl )
rotDelta = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ ro ]( mat_o, True )
#now get the positional delta
posDelta = Vector( xform( src, q=True, ws=True, rp=True ) ) - Vector( xform( ctrl, q=True, ws=True, rp=True ) )
posDelta *= -1
ctrlParentInvMat = Matrix( getAttr( '%s.parentInverseMatrix' % ctrl ) )
posDelta = posDelta * ctrlParentInvMat
#construct a list to use for the format str
formatArgs = tuple( rotDelta ) + tuple( posDelta )
#build the post trace cmd str
mel.zooSetPostTraceCmd( ctrl, presetStr % formatArgs )
return rotDelta
#this dict contains UI labels and a presets for offset commands... when adding new ones make sure it contains exactly three format strings...
CMD_PRESETS = CMD_DEFAULT, CMD_SRC_TGT, CMD_IK_FOOT, CMD_COPY = ( ('rotate -r -os %0.2f %0.2f %0.2f #; move -r -os %0.4f %0.4f %0.4f #;', bakeManualRotateDelta),
('rotate -r -os %0.2f %0.2f %0.2f #; move -r -os %0.4f %0.4f %0.4f #;', bakeRotateDelta),
('rotate -r -os %0.2f %0.2f %0.2f #; move -r -os %0.4f %0.4f %0.4f #; traceToe # %%opt0%% x z;', bakeRotateDelta),
('float $f[] = `getAttr %%opt0%%.r`; setAttr #.rx $f[0]; setAttr #.ry $f[1]; setAttr #.rz $f[2];', None) )
def savePostTraceScheme( presetName ):
'''
stores all post trace commands found in the current scene out to disk
'''
#grab a list of transforms with post trace commands on them
postTraceNodes = ls( "*.%s" % POST_TRACE_ATTR_NAME, r=True )
postTraceDict = {}
for n in postTraceNodes:
noNS = n.split( ':' )[ -1 ] #strip the namespace
noNS = noNS.split( '.' )[ 0 ] #strip the attribute
postTraceDict[ noNS ] = getAttr( n )
xportDict = api.writeExportDict( TOOL_NAME, 0 )
p = Preset( GLOBAL, TOOL_NAME, presetName, EXTENSION )
p.pickle( (xportDict, postTraceDict) )
return p
def clearPostTraceScheme():
postTraceNodes = ls( "*.%s" % POST_TRACE_ATTR_NAME, r=True )
for n in postTraceNodes:
#ideally delete the attribute
try:
deleteAttr( n )
#this can happen if the node is referenced - so just set it to an empty string...
except RuntimeError:
setAttr( n, '', typ='string' )
def loadPostTraceSchemeFilepath( presetFile ):
'''
re-applies a stored post trace command scheme back to the controls found in the current scene
'''
#first we need to purge all existing post trace commands
clearPostTraceScheme()
if not isinstance( presetFile, Path ):
presetFile = Path( presetFile )
if not presetFile.isfile():
raise IOError, "no such preset"
xportDict, postTraceDict = presetFile.unpickle()
for n, postTraceCmd in postTraceDict.iteritems():
n = n.split( '.' )[ 0 ] #strip off the attribute
possibles = ls( '*%s' % n, r=True )
if possibles:
nInScene = possibles[0]
mel.zooSetPostTraceCmd( nInScene, postTraceCmd )
def loadPostTraceScheme( presetName ):
'''
added so the load save commands are symmetrical - its sometimes more convenient to load from just
a preset name instead of a full filepath... esp when debugging
'''
p = findPreset( presetName, TOOL_NAME, EXTENSION, LOCAL )
return loadPostTraceSchemeFilepath( p )
def autoGeneratePostTraceScheme( mapping, presetName=None ):
cmdStr, cmdFunc = CMD_DEFAULT
for src, tgt in mapping.iteritems():
src, tgt = findItem( src ), findItem( tgt )
if not src:
continue
if not tgt:
continue
t, r = getAttr( '%s.t' % tgt )[0], getAttr( '%s.r' % tgt )[0]
print tgt, cmdFunc( src, tgt, cmdStr )
try: setAttr( '%s.t' % tgt, *t )
except RuntimeError: pass
try: setAttr( '%s.r' % tgt, *r )
except RuntimeError: pass
if presetName is not None:
print 'SAVING TO', presetName
savePostTraceScheme( presetName )
def getMappingFromPreset( presetName ):
'''
parses a mapping file and returns the mapping dict
'''
p = findPreset( presetName, 'zoo', 'mapping', LOCAL )
return p.read()
def getPostTraceCmd( node ):
return getAttr( '%s.%s' % (node, POST_TRACE_ATTR_NAME) )
def executePostTraceCmd( node ):
cmdStr = getPostTraceCmd( node )
resolvedCmdStr = resolveCmdStr( cmdStr, node, [] )
mel.eval( resolvedCmdStr )
"""
def trace( srcs, tgts, keysOnly=True, matchRotationOrder=True, processPostCmds=True, sortByHeirarchy=True, start=None, end=None, skip=1 ):
if start is None:
keys = keyframe( srcs, q=True )
keys.sort()
start = keys[0]
if end is None:
keys = keyframe( srcs, q=True )
keys.sort()
end = keys[-1]
api.mel.zooXferAnimUtils()
api.mel._zooXferTrace( srcs, tgts, 2 if keysOnly else 0, 0, int( matchRotationOrder ), int( processPostCmds ), int( sortByHeirarchy ), int( start ), int( end ), int( skip ) )
"""
def constructDummyParentConstraint( src, tgt ):
grp = group( em=True )
constraintNode = parentConstraint( src, grp )[0]
parent( constraintNode, w=True )
delete( grp )
connectAttr( '%s.ro' % tgt, '%s.constraintRotateOrder' % constraintNode )
connectAttr( '%s.rotatePivotTranslate' % tgt, '%s.constraintRotateTranslate' % constraintNode )
connectAttr( '%s.rotatePivot' % tgt, '%s.constraintRotatePivot' % constraintNode )
connectAttr( '%s.parentInverseMatrix' % tgt, '%s.constraintParentInverseMatrix' % constraintNode )
return constraintNode
def getParentCount( node ):
count = 1
nodeParent = node
while nodeParent:
nodeParent = listRelatives( nodeParent, p=True, pa=True )
if nodeParent is None:
break
count += 1
return count
class TracePair(object):
SHORT_TRANSFORM_ATTRS = ('tx', 'ty', 'tz',
'rx', 'ry', 'rz')
def __init__( self, src, tgt ):
self._src = src
self._tgt = tgt
self._isTransform = objectType( src, isAType='transform' ) and objectType( tgt, isAType='transform' )
self._keyTimeData = {}
self._postTraceCmd = None
self._constraint = None
self._parentCount = getParentCount( tgt )
self._attrsWeightedTangentsDealtWith = []
def __repr__( self ):
return '%s( "%s", "%s" )' % (type( self ).__name__, self._src, self._tgt)
__str__ = __repr__
def isTransform( self ):
return self._isTransform
def getSrcTgt( self ):
return self._src, self._tgt
def getParentCount( self ):
return self._parentCount
def getKeyTimes( self ):
return self._keyTimeData.keys()
def dealWithWeightedTangents( self, tgtAttrpath ):
'''
this is annoying - so maya has two types of curves - weighted and non-weighted tangent curves, and they've not compatible.
so we need to see what the type of the curve we're querying and make sure the keys we trace have the same curve type. this
is easier said than done - the tgt object may already have keys. if it does, we can just convert the curve right now and be
done with it, but if it doesn't, then we need to convert the curve to weighted tangents after the first key is set, or mess
with the users preferences. neither is pretty... god maya sucks
'''
if keyframe( tgtAttrpath, q=True, kc=True ):
attr = tgtAttrpath[ tgtAttrpath.find( '.' ) + 1: ]
srcAttrpath = '%s.%s' % (self._src, attr)
srcWeightedTangentState = keyTangent( srcAttrpath, q=True, weightedTangents=True )[0]
tgtWeightedTangentState = keyTangent( tgtAttrpath, q=True, weightedTangents=True )[0]
if srcWeightedTangentState != tgtWeightedTangentState:
keyTangent( tgtAttrpath, e=True, weightedTangents=srcWeightedTangentState )
self._attrsWeightedTangentsDealtWith.append( tgtAttrpath )
def preTrace( self ):
if self._isTransform:
if self._constraint is None:
self._constraint = constructDummyParentConstraint( self._src, self._tgt )
#now grab any other keyable attributes
keyableAttrs = listAttr( self._src, keyable=True, scalar=True, shortNames=True ) or []
for attr in keyableAttrs:
tgtAttrpath = '%s.%s' % (self._tgt, attr)
if not objExists( tgtAttrpath ):
continue
#check to see if we need to deal with weighted tangents
srcAttrpath = '%s.%s' % (self._src, attr)
if tgtAttrpath not in self._attrsWeightedTangentsDealtWith:
self.dealWithWeightedTangents( tgtAttrpath )
#now get the list of keys for the attribute and store that as well
srcKeysTimes = keyframe( srcAttrpath, q=True )
if srcKeysTimes:
srcKeysInTangents = keyTangent( srcAttrpath, q=True, itt=True )
srcKeysOutTangents = keyTangent( srcAttrpath, q=True, ott=True )
srcKeysInX = keyTangent( srcAttrpath, q=True, ix=True )
srcKeysInY = keyTangent( srcAttrpath, q=True, iy=True )
srcKeysOutX = keyTangent( srcAttrpath, q=True, ox=True )
srcKeysOutY = keyTangent( srcAttrpath, q=True, oy=True )
#if the attr is a transform attr - set the srcAttrpath to the appropriate attribute on the constraint
if attr in self.SHORT_TRANSFORM_ATTRS:
srcAttrpath = '%s.c%s' % (self._constraint, attr)
for keyTime, keyItt, keyOtt, ix, iy, ox, oy in zip( srcKeysTimes, srcKeysInTangents, srcKeysOutTangents, srcKeysInX, srcKeysInY, srcKeysOutX, srcKeysOutY ):
self._keyTimeData.setdefault( keyTime, [] )
self._keyTimeData[ keyTime ].append( (srcAttrpath, tgtAttrpath, keyItt, keyOtt, ix, iy, ox, oy) )
#finally see if the node has a post trace cmd - if it does, track it
postTraceCmdAttrpath = '%s.xferPostTraceCmd' % self._tgt
if objExists( postTraceCmdAttrpath ):
cmdStr = getAttr( postTraceCmdAttrpath )
self._postTraceCmd = resolveCmdStr( cmdStr, self._tgt, [] )
def traceFrame( self, keyTime ):
if keyTime not in self._keyTimeData:
return
attrDataList = self._keyTimeData[ keyTime ]
for attrData in attrDataList:
#unpack the node data
srcAttrpath, tgtAttrpath, keyItt, keyOtt, ix, iy, ox, oy = attrData
#NOTE: setting itt and ott in the keyframe command doesn't work properly - if itt is spline and ott is stepped, maya sets them both to stepped... win.
setKeyframe( tgtAttrpath, v=getAttr( srcAttrpath ) )
#check to see if we need to deal with weighted tangents
#NOTE: we need to do this BEFORE setting any tangent data!
if tgtAttrpath not in self._attrsWeightedTangentsDealtWith:
self.dealWithWeightedTangents( tgtAttrpath )
#need to special case this otherwise maya will screw up the stepped tangents on the out curve... holy shit maya sucks :(
if keyOtt == 'step':
keyTangent( tgtAttrpath, e=True, t=(keyTime,), itt=keyItt, ott=keyOtt )#, ix=ix, iy=iy )
else:
keyTangent( tgtAttrpath, e=True, t=(keyTime,), itt=keyItt, ott=keyOtt )#, ix=ix, iy=iy, ox=ox, oy=oy )
#execute any post trace command for the tgt nodes on this keyframe
if self._postTraceCmd:
postTraceCmdStr = resolveCmdStr( self._postTraceCmd, self._tgt, [] )
if postTraceCmdStr:
maya.mel.eval( postTraceCmdStr )
#once the post trace cmd has been executed, make sure to re-key each attribute with a key on this frame
for attrData in attrDataList:
tgtAttrpath = attrData[1]
setKeyframe( tgtAttrpath )
def postTrace( self ):
if self._constraint:
delete( self._constraint )
self._constraint = None
#run an euler filter on the rotation curves
if self._isTransform:
filterCurve( '%s.rx' % self._tgt, '%s.ry' % self._tgt, '%s.rz' % self._tgt, filter='euler' )
class Tracer(object):
def __init__( self, keysOnly=True, matchRotationOrder=True, processPostCmds=True, sortByHeirarchy=True, start=None, end=None, skip=1 ):
self._tracePairs = []
self._keysOnly = keysOnly
self._matchRotationOrder = matchRotationOrder
self._processPostCmds = processPostCmds
self._start = start
self._end = end
self._skipFrames = skip
def setKeysOnly( self, state ):
self._keysOnly = state
def setMatchRotationOrder( self, state ):
self._matchRotationOrder = state
def setProcessPostCmds( self, state ):
self._processPostCmds = state
def setStart( self, frame ):
self._start = frame
def setEnd( self, frame ):
self._end = frame
def setSkip( self, count ):
self._skipFrames = cound
def _sortTransformNodes( self ):
'''
ensures all nodes in the _keysTransformAttrpathDict are sorted hierarchically
'''
parentCountDecoratedTracePairs = []
for tracePair in self._tracePairs:
parentCountDecoratedTracePairs.append( (tracePair.getParentCount(), tracePair) )
parentCountDecoratedTracePairs.sort()
tracePairs = [ tracePair for pCnt, tracePair in parentCountDecoratedTracePairs ]
self._tracePairs = tracePairs
def appendPair( self, src, tgt ):
if not objExists( src ) or not objExists( tgt ):
printWarningStr( "Either the src or tgt nodes don't exist!" )
return
self._tracePairs.append( TracePair( src, tgt ) )
def setSrcsAndTgts( self, srcList, tgtList ):
for src, tgt in zip( srcList, tgtList ):
self.appendPair( src, tgt )
def getKeyTimes( self ):
'''
returns a list of key times
'''
if self._keysOnly:
keyTimes = []
for tracePair in self._tracePairs:
keyTimes += tracePair.getKeyTimes()
keyTimes = list( set( keyTimes ) ) #this removes duplicates
keyTimes.sort()
return keyTimes
else:
start = self._start
if start is None:
start = playbackOptions( q=True, min=True )
end = self._end
if end is None:
end = playbackOptions( q=True, max=True )
keyTimes = range( start, end, self._skipFrames )
def getTransformNodePairs( self ):
transformNodePairs = []
for tracePair in self._tracePairs:
if tracePair.isTransform():
transformNodePairs.append( tracePair )
return transformNodePairs
@d_unifyUndo
@d_noAutoKey
@d_disableViews
@d_restoreTime
def trace( self ):
if not self._tracePairs:
printWarningStr( "No objects to trace!" )
return
#wrap the following in a try so we can ensure cleanup gets called always
try:
#make sure the objects in the transform list are sorted properly
self._sortTransformNodes()
#run the pre-trace method on all tracePair instances
for tracePair in self._tracePairs:
tracePair.preTrace()
#early out if there are no keyframes
keyTimes = self.getKeyTimes()
if not keyTimes:
printWarningStr( "No keys to trace!" )
return
#match rotation orders if required
transformTracePairs = list( self.getTransformNodePairs() )
if self._matchRotationOrder:
for tracePair in transformTracePairs:
src, tgt = tracePair.getSrcTgt()
if getAttr( '%s.ro' % tgt, se=True ):
setAttr( '%s.ro' % tgt, getAttr( '%s.ro' % src ) )
#clear out existing animation for the duration of the trace on target nodes
for tracePair in self._tracePairs:
src, tgt = tracePair.getSrcTgt()
cutKey( tgt, t=(keyTimes[0], keyTimes[-1]), clear=True )
#execute the traceFrame method for each tracePair instance
for keyTime in keyTimes:
currentTime( keyTime )
for tracePair in self._tracePairs:
tracePair.traceFrame( keyTime )
#make sure the postTrace method gets executed once the trace finishes
finally:
for tracePair in self._tracePairs:
tracePair.postTrace()
def trace( srcs, tgts, keysOnly=True, matchRotationOrder=True, processPostCmds=True, sortByHeirarchy=True, start=None, end=None, skip=1 ):
tracer = Tracer( keysOnly, matchRotationOrder, processPostCmds, sortByHeirarchy, start, end, skip )
tracer.setSrcsAndTgts( srcs, tgts )
tracer.trace()
class AnimCurveCopier(object):
def __init__( self, srcAnimCurve, tgtAnimCurve ):
self._src = srcAnimCurve
self._tgt = tgtAnimCurve
def iterSrcTgtKeyIndices( self ):
src, tgt = self._src, self._tgt
srcIndices = getAttr( '%s.keyTimeValue' % src, multiIndices=True ) or []
tgtIndices = getAttr( '%s.keyTimeValue' % tgt, multiIndices=True ) or []
srcTimeValues = getAttr( '%s.keyTimeValue[*]' % src ) or []
tgtTimeValues = getAttr( '%s.keyTimeValue[*]' % tgt ) or []
zippedTgtData = zip( tgtIndices, tgtTimeValues )
for srcIdx, (srcTime, srcValue) in zip( srcIndices, srcTimeValues ):
for n, (tgtIdx, (tgtTime, tgtValue)) in enumerate( zippedTgtData ):
if srcTime == tgtTime:
yield (srcIdx, srcTime, srcValue), (tgtIdx, tgtTime, tgtValue)
zippedTgtData = zippedTgtData[ n: ] #chop off the values before this one - we don't need to iterate over them again...
break
def copy( self, values=True, tangents=True, other=True ):
src, tgt = self._src, self._tgt
for srcData, tgtData in self.iterSrcTgtKeyIndices():
srcIdx, srcTime, srcValue = srcData
tgtIdx, tgtTime, tgtValue = tgtData
#if values:
#setAttr( '%s.keyTimeValue[%d]' % (tgt, tgtIdx), tgtTime, srcValue )
if tangents:
setAttr( '%s.keyTanLocked[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanLocked[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyWeightLocked[%d]' % (tgt, tgtIdx), getAttr( '%s.keyWeightLocked[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyTanInX[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanInX[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyTanInY[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanInY[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyTanOutX[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanOutX[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyTanOutY[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanOutY[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyTanInType[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanInType[%d]' % (tgt, tgtIdx) ) )
setAttr( '%s.keyTanOutType[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTanOutType[%d]' % (tgt, tgtIdx) ) )
if other:
setAttr( '%s.keyBreakdown[%d]' % (tgt, tgtIdx), getAttr( '%s.keyBreakdown[%d]' % (tgt, tgtIdx) ) )
#setAttr( '%s.keyTickDrawSpecial[%d]' % (tgt, tgtIdx), getAttr( '%s.keyTickDrawSpecial[%d]' % (tgt, tgtIdx) ) )
def test():
tracer = Tracer()
tracer.setSrcsAndTgts( ['pSphere2', 'pCylinder1'], ['pSphere1', 'pCube1'] )
tracer.trace()
#end | Python |
'''
super simple vector class and vector functionality. i wrote this simply because i couldn't find
anything that was easily accessible and quick to write. this may just go away if something more
comprehensive/mature is found
'''
import re
import math
import random
from math import cos, sin, tan, acos, asin, atan2
sqrt = math.sqrt
zeroThreshold = 1e-8
class MatrixException(Exception):
pass
class Angle(object):
def __init__( self, angle, radian=False ):
'''set the radian to true on init if the angle is in radians - otherwise degrees are assumed'''
if radian:
self.radians = angle
self.degrees = math.degrees(angle)
else:
self.degrees = angle
self.radians = math.radians(angle)
class Vector(list):
'''
provides a bunch of common vector functionality. Vectors must be instantiated a list/tuple of values.
If you need to instantiate with items, use the Vector.FromValues like so:
Vector.FromValues(1,2,3)
'''
@classmethod
def FromValues( cls, *a ):
return cls( a )
def __repr__( self ):
return '%s( %s )' % (type( self ).__name__, tuple( self ))
def __str__( self ):
return '<%s>' % ', '.join( '%0.3g' % v for v in self )
def setIndex( self, idx, value ):
self[ idx ] = value
def __nonzero__( self ):
for item in self:
if item:
return True
return False
def __add__( self, other ):
return self.__class__( [x+y for x, y in zip(self, other)] )
__iadd__ = __add__
def __radd__( self, other ):
return self.__class__( [x+y for x, y in zip(other, self)] )
def __sub__( self, other ):
return self.__class__( [x-y for x,y in zip(self, other)] )
def __mul__( self, factor ):
'''
supports either scalar multiplication, or vector multiplication (dot product). for cross product
use the .cross( other ) method which is bound to the rxor operator. ie: a ^ b == a.cross( b )
'''
if isinstance( factor, (int, float) ):
return self.__class__( [x * factor for x in self] )
elif isinstance( factor, Matrix ):
return multVectorMatrix( self, factor )
#assume its another vector then
value = self[0] * factor[0]
for x, y in zip( self[1:], factor[1:] ):
value += x*y
return value
def __div__( self, denominator ):
return self.__class__( [x / denominator for x in self] )
def __neg__( self ):
return self.__class__( [-x for x in self] )
__invert__ = __neg__
def __eq__( self, other, tolerance=1e-5 ):
'''
overrides equality test - can specify a tolerance if called directly.
NOTE: other can be any iterable
'''
for a, b in zip(self, other):
if abs( a - b ) > tolerance:
return False
return True
within = __eq__
def __ne__( self, other, tolerance=1e-5 ):
return not self.__eq__( other, tolerance )
def __mod__( self, other ):
return self.__class__( [x % other for x in self] )
def __int__( self ):
return int( self.get_magnitude() )
def __hash__( self ):
return hash( tuple( self ) )
@classmethod
def Zero( cls, size=3 ):
return cls( ([0] * size) )
@classmethod
def Random( cls, size=3, valueRange=(0,1) ):
return cls( [random.uniform( *valueRange ) for n in range( size )] )
@classmethod
def Axis( cls, axisName, size=3 ):
'''
returns a vector from an axis name - the axis name can be anything from the Vector.INDEX_NAMES
list. you can also use a - sign in front of the axis name
'''
axisName = axisName.lower()
isNegative = axisName.startswith('-') or axisName.startswith('_')
if isNegative:
axisName = axisName[1:]
new = cls.Zero( size )
val = 1
if isNegative:
val = -1
new.__setattr__( axisName, val )
return new
def dot( self, other, preNormalize=False ):
a, b = self, other
if preNormalize:
a = self.normalize()
b = other.normalize()
dot = sum( [x*y for x,y in zip(a, b)] )
return dot
def __rxor__( self, other ):
'''
used for cross product - called using a**b
NOTE: the cross product is only defined for a 3 vector
'''
x = self[1] * other[2] - self[2] * other[1]
y = self[2] * other[0] - self[0] * other[2]
z = self[0] * other[1] - self[1] * other[0]
return self.__class__( [x, y, z] )
cross = __rxor__
def get_squared_magnitude( self ):
'''
returns the square of the magnitude - which is about 20% faster to calculate
'''
m = 0
for val in self:
m += val**2
return m
def get_magnitude( self ):
#NOTE: this implementation is faster than sqrt( sum( [x**2 for x in self] ) ) by about 20%
m = 0
for val in self:
m += val**2
return sqrt( m )
__float__ = get_magnitude
__abs__ = get_magnitude
length = magnitude = get_magnitude
def set_magnitude( self, factor ):
'''
changes the magnitude of this instance
'''
factor /= self.get_magnitude()
for n in range( len( self ) ):
self[n] *= factor
def normalize( self ):
'''
returns a normalized vector
'''
#inline the code for the SPEEDZ - its about 8% faster by inlining the code to calculate the magnitude
mag = 0
for v in self:
mag += v**2
mag = sqrt( mag )
return self.__class__( [v / mag for v in self] )
def change_space( self, basisX, basisY, basisZ=None ):
'''
will re-parameterize this vector to a different space
NOTE: the basisZ is optional - if not given, then it will be computed from X and Y
NOTE: changing space isn't supported for 4-vectors
'''
if basisZ is None:
basisZ = basisX ^ basisY
basisZ = basisZ.normalize()
dot = self.dot
new = dot( basisX ), dot( basisY ), dot( basisZ )
return self.__class__( new )
def rotate( self, quat ):
'''
Return the rotated vector v.
The quaternion must be a unit quaternion.
This operation is equivalent to turning v into a quat, computing
self*v*self.conjugate() and turning the result back into a vec3.
'''
ww = quat.w * quat.w
xx = quat.x * quat.x
yy = quat.y * quat.y
zz = quat.z * quat.z
wx = quat.w * quat.x
wy = quat.w * quat.y
wz = quat.w * quat.z
xy = quat.x * quat.y
xz = quat.x * quat.z
yz = quat.y * quat.z
newX = ww * self.x + xx * self.x - yy * self.x - zz * self.x + 2*((xy-wz) * self.y + (xz+wy) * self.z)
newY = ww * self.y - xx * self.y + yy * self.y - zz * self.y + 2*((xy+wz) * self.x + (yz-wx) * self.z)
newZ = ww * self.z - xx * self.z - yy * self.z + zz * self.z + 2*((xz-wy) * self.x + (yz+wx) * self.y)
return self.__class__( [newX, newY, newZ] )
def complex( self ):
return self.__class__( [ complex(v) for v in tuple(self) ] )
def conjugate( self ):
return self.__class__( [ v.conjugate() for v in tuple(self.complex()) ] )
x = property( lambda self: self[ 0 ], lambda self, value: self.setIndex( 0, value ) )
y = property( lambda self: self[ 1 ], lambda self, value: self.setIndex( 1, value ) )
z = property( lambda self: self[ 2 ], lambda self, value: self.setIndex( 2, value ) )
w = property( lambda self: self[ 3 ], lambda self, value: self.setIndex( 3, value ) )
class Point(Vector):
def __init__( self, vals ):
if isinstance( vals, Point ):
list.__init__( self, vals )
return
selfLen = len( self )
if selfLen == 3:
vals.append( 1 )
else:
assert selfLen == 4
list.__init__( vals )
class Colour(Vector):
NAMED_PRESETS = { "active": (0.26, 1, 0.64),
"black": (0, 0, 0),
"white": (1, 1, 1),
"grey": (.5, .5, .5),
"lightgrey": (.7, .7, .7),
"darkgrey": (.25, .25, .25),
"red": (1, 0, 0),
"lightred": (1, .5, 1),
"peach": (1, .5, .5),
"darkred": (.6, 0, 0),
"orange": (1., .5, 0),
"lightorange": (1, .7, .1),
"darkorange": (.7, .25, 0),
"yellow": (1, 1, 0),
"lightyellow": (1, 1, .5),
"darkyellow": (.8,.8,0.),
"green": (0, 1, 0),
"lightgreen": (.4, 1, .2),
"darkgreen": (0, .5, 0),
"blue": (0, 0, 1),
"lightblue": (.4, .55, 1),
"darkblue": (0, 0, .4),
"purple": (.7, 0, 1),
"lightpurple": (.8, .5, 1),
"darkpurple": (.375, 0, .5),
"brown": (.57, .49, .39),
"lightbrown": (.76, .64, .5),
"darkbrown": (.37, .28, .17) }
NAMED_PRESETS[ 'highlight' ] = NAMED_PRESETS[ 'active' ]
NAMED_PRESETS[ 'pink' ] = NAMED_PRESETS[ 'lightred' ]
DEFAULT_COLOUR = NAMED_PRESETS[ 'black' ]
DEFAULT_ALPHA = 0.7 #alpha=0 is opaque, alpha=1 is transparent
INDEX_NAMES = 'rgba'
_EQ_TOLERANCE = 0.1
_NUM_RE = re.compile( '^[0-9. ]+' )
def __eq__( self, other, tolerance=_EQ_TOLERANCE ):
return Vector.__eq__( self, other, tolerance )
def __ne__( self, other, tolerance=_EQ_TOLERANCE ):
return Vector.__ne__( self, other, tolerance )
def __init__( self, colour ):
'''
colour can be a combination:
name alpha -> darkred 0.5
name
r g b a -> 1 0 0 0.2
if r, g, b or a are missing, they're assumed to be 0
a 4 float, RGBA array is returned
'''
if isinstance( colour, basestring ):
alpha = self.DEFAULT_ALPHA
toks = colour.lower().split( ' ' )[ :4 ]
if len( toks ) > 1:
if toks[ -1 ].isdigit():
alpha = float( toks[ -1 ] )
clr = [0,0,0,alpha]
for n, c in enumerate( self.DEFAULT_COLOUR[ :4 ] ):
clr[ n ] = c
clr[ 3 ] = alpha
if not toks[ 0 ].isdigit():
try:
clr = list( self.NAMED_PRESETS[ toks[ 0 ] ] )[ :3 ]
clr.append( alpha )
except KeyError: pass
else:
for n, t in enumerate( toks ):
try: clr[ n ] = float( t )
except ValueError: continue
else:
clr = colour
Vector.__init__( self, clr )
def darken( self, factor ):
'''
returns a colour vector that has been darkened by the appropriate ratio.
this is basically just a multiply, but the alpha is unaffected
'''
darkened = self * factor
darkened[ 3 ] = self[ 3 ]
return darkened
def lighten( self, factor ):
toWhiteDelta = Colour( (1,1,1,0) ) - self
toWhiteDelta = toWhiteDelta * factor
lightened = self + toWhiteDelta
lightened[ 3 ] = self[ 3 ]
return lightened
def asRGB( self ):
return list( self )[ :3 ]
@classmethod
def ColourToName( cls, theColour ):
'''
given an arbitrary colour, will return the most appropriate name as
defined in the NAMED_PRESETS class dict
'''
if not isinstance( theColour, Colour ):
theColour = Colour( theColour )
theColour = Vector( theColour[ :3 ] ) #make sure its a 3 vector
matches = []
for name, colour in cls.NAMED_PRESETS.iteritems():
colour = Vector( colour )
diff = (colour - theColour).magnitude()
matches.append( (diff, name) )
matches.sort()
return matches[ 0 ][ 1 ]
Color = Colour #for spelling n00bs
class Axis(int):
BASE_AXES = 'x', 'y', 'z'
AXES = ( 'x', 'y', 'z', \
'-x', '-y', '-z' )
def __new__( cls, idx ):
if isinstance( idx, basestring ):
return cls.FromName( idx )
return int.__new__( cls, idx % 6 )
def __neg__( self ):
return Axis( (self + 3) )
def __abs__( self ):
return type( self )( self % 3 )
positive = __abs__
@classmethod
def FromName( cls, name ):
idx = list( cls.AXES ).index( name.lower().replace( '_', '-' ) )
return cls( idx )
@classmethod
def FromVector( cls, vector ):
'''
returns the closest axis to the given vector
'''
assert len( cls.BASE_AXES ) >= len( vector )
listV = list( vector )
idx, value = 0, listV[ 0 ]
for n, v in enumerate( listV ):
if v > value:
value = v
idx = n
return cls( idx )
def asVector( self ):
v = Vector( [0, 0, 0] )
v[ self % 3 ] = 1 if self < 3 else -1
return v
def isNegative( self ):
return self > 2
def asName( self ):
return self.AXES[ self ]
def asCleanName( self ):
'''
returns the axis name without a negative regardless
'''
return self.AXES[ self ].replace( '-', '' )
def asEncodedName( self ):
'''
returns the axis name, replacing the - with an _
'''
return self.asName().replace( '-', '_' )
def otherAxes( self ):
'''
returns the other two axes that aren't this axis
'''
allAxes = [ 0, 1, 2 ]
allAxes.remove( self % 3 )
return list( map( Axis, allAxes ) )
AX_X, AX_Y, AX_Z = map( Axis, range( 3 ) )
"""
class EulerRotation(Vector):
def __init__( self, vals, degrees=True ):
pass
def radians( self ):
return list( self )
def degrees( self ):
return list( map( math.degrees, self ) )
"""
class Quaternion(Vector):
def __init__( self, xyzw=(0,0,0,1) ):
'''
initialises a vector from either x,y,z,w args or a Matrix instance
'''
if isinstance(xyzw, Matrix):
#the matrix is assumed to be a valid rotation matrix
matrix = x
d1, d2, d3 = matrix.getDiag()
t = d1 + d2 + d3 + 1.0
if t > zeroThreshold:
s = 0.5 / sqrt( t )
w = 0.25 / s
x = ( matrix[2][1] - matrix[1][2] )*s
y = ( matrix[0][2] - matrix[2][0] )*s
z = ( matrix[1][0] - matrix[0][1] )*s
else:
if d1 >= d2 and d1 >= d3:
s = sqrt( 1.0 + d1 - d2 - d3 ) * 2.0
x = 0.5 / s
y = ( matrix[0][1] + matrix[1][0] )/s
z = ( matrix[0][2] + matrix[2][0] )/s
w = ( matrix[1][2] + matrix[2][1] )/s
elif d2 >= d1 and d2 >= d3:
s = sqrt( 1.0 + d2 - d1 - d3 ) * 2.0
x = ( matrix[0][1] + matrix[1][0] )/s
y = 0.5 / s
z = ( matrix[1][2] + matrix[2][1] )/s
w = ( matrix[0][2] + matrix[2][0] )/s
else:
s = sqrt( 1.0 + d3 - d1 - d2 ) * 2.0
x = ( matrix[0][2] + matrix[2][0] )/s
y = ( matrix[1][2] + matrix[2][1] )/s
z = 0.5 / s
w = ( matrix[0][1] + matrix[1][0] )/s
xyzw = x, y, z, w
Vector.__init__( self, xyzw )
def __mul__( self, other ):
if isinstance( other, Quaternion ):
x1, y1, z1, w1 = self
x2, y2, z2, w2 = other
newW = w1*w2 - x1*x2 - y1*y2 - z1*z2
newX = w1*x2 + x1*w2 + y1*z2 - z1*y2
newY = w1*y2 - x1*z2 + y1*w2 + z1*x2
newZ = w1*z2 + x1*y2 - y1*x2 + z1*w2
return self.__class__( [newX, newY, newZ, newW] )
elif isinstance( other, (float, int, long) ):
return self.__class__( [i * other for i in self] )
__rmul__ = __mul__
def __div__( self, other ):
assert isinstance( other, (float, int, long) )
return self.__class__( [i / other for i in self] )
def copy( self ):
return self.__class__(self)
@classmethod
def FromEulerXYZ( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerXYZ(x, y, z, degrees))
@classmethod
def FromEulerYZX( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerYZX(x, y, z, degrees))
@classmethod
def FromEulerZXY( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerZXY(x, y, z, degrees))
@classmethod
def FromEulerXZY( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerXZY(x, y, z, degrees))
@classmethod
def FromEulerYXZ( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerYXZ(x, y, z, degrees))
@classmethod
def FromEulerZYX( cls, x, y, z, degrees=False ): return cls(Matrix.FromEulerZYX(x, y, z, degrees))
@classmethod
def AxisAngle( cls, axis, angle, normalize=False ):
'''angle is assumed to be in radians'''
if normalize:
axis = axis.normalize()
angle /= 2.0
newW = cos( angle )
x, y, z = axis
s = sin( angle ) / sqrt( x**2 + y**2 + z**2 )
newX = x * s
newY = y * s
newZ = z * s
new = cls( [newX, newY, newZ, newW] )
new = new.normalize()
return new
def toAngleAxis( self ):
'''Return angle (in radians) and rotation axis.
'''
nself = self.normalize()
# Clamp nself.w (since the quat has to be normalized it should
# be between -1 and 1 anyway, but it might be slightly off due
# to numerical inaccuracies)
w = max( min(nself[3], 1.0), -1.0 )
w = acos( w )
s = sin( w )
if s < 1e-12:
return (0.0, Vector(0, 0, 0))
return ( 2.0 * w, Vector(nself[0] / s, nself[1] / s, nself[2] / s) )
def as_tuple( self ):
return tuple( self )
def log( self ):
global zeroThreshold
x, y, z, w = self
b = sqrt(x**2 + y**2 + z**2)
res = self.__class__()
if abs( b ) <= zeroThreshold:
if self.w <= zeroThreshold:
raise ValueError, "math domain error"
res.w = math.log( w )
else:
t = atan2(b, w)
f = t / b
res.x = f * x
res.y = f * y
res.z = f * z
ct = cos( t )
if abs( ct ) <= zeroThreshold:
raise ValueError, "math domain error"
r = w / ct
if r <= zeroThreshold:
raise ValueError, "math domain error"
res.w = math.log( r )
return res
class Matrix(list):
'''deals with square matricies'''
def __init__( self, values=(), size=4 ):
'''
initialises a matrix from either an iterable container of values
or a quaternion. in the case of a quaternion the matrix is 3x3
'''
if isinstance( values, Matrix ):
size = values.size
values = values.as_list()
elif isinstance( values, Quaternion ):
#NOTE: quaternions result in a 4x4 matrix
size = 4
x, y, z, w = values
xx = 2.0 * x * x
yy = 2.0 * y * y
zz = 2.0 * z * z
xy = 2.0 * x * y
zw = 2.0 * z * w
xz = 2.0 * x * z
yw = 2.0 * y * w
yz = 2.0 * y * z
xw = 2.0 * x * w
row0 = 1.0-yy-zz, xy-zw, xz+yw, 0
row1 = xy+zw, 1.0-xx-zz, yz-xw, 0
row2 = xz-yw, yz+xw, 1.0-xx-yy, 0
values = row0 + row1 + row2 + (0, 0, 0, 1)
if len(values) > size*size:
raise MatrixException('too many args: the size of the matrix is %d and %d values were given'%(size,len(values)))
self.size = size
for n in range(size):
row = [ 0 ] * size
row[ n ] = 1
self.append( row )
for n in range( len(values) ):
self[ n / size ][ n % size ] = values[ n ]
def __repr__( self ):
fmt = '%6.3g'
asStr = []
for row in self:
rowStr = []
for r in row:
rowStr.append( fmt % r )
asStr.append( '[%s ]' % ','.join( rowStr ) )
return '\n'.join( asStr )
def __str__( self ):
return self.__repr__()
def __add__( self, other ):
new = self.__class__.Zero(self.size)
for i in xrange(self.size):
for j in xrange(self.size):
new[i][j] = self[i][j] + other[i][j]
return new
def __sub__( self, other ):
new = self.__class__.Zero(self.size)
new = self + (other*-1)
return new
def __mul__( self, other ):
new = None
if isinstance( other, (float, int) ):
new = self.__class__.Zero(self.size)
for i in xrange(self.size):
for j in xrange(self.size):
new[i][j] = self[i][j] * other
elif isinstance( other, Vector ):
return multMatrixVector( self, other )
else:
#otherwise assume is a Matrix instance
new = self.__class__.Zero( self.size )
cur = self
if self.size != other.size:
#if sizes are differnet - shoehorn the smaller matrix into a bigger matrix
if self.size < other.size:
cur = self.__class__( self, other.size )
else:
other = self.__class__( other, self.size )
for i in range( self.size ):
for j in range( self.size ):
new[i][j] = Vector( cur[i] ) * Vector( other.getCol(j) )
return new
def __div__( self, other ):
return self.__mul__(1.0/other)
def __eq__( self, other ):
return self.isEqual(other)
def __ne__( self, other ):
return not self.isEqual(other)
def isEqual( self, other, tolerance=1e-5 ):
if self.size != other.size:
return False
for i in xrange(self.size):
for j in xrange(self.size):
if abs( self[i][j] - other[i][j] ) > tolerance:
return False
return True
def copy( self ):
return self.__class__(self,self.size)
def crop( self, newSize ):
new = self.__class__( size=newSize )
for n in range( newSize ):
new.setRow( n, self[ n ][ :newSize ] )
return new
def expand( self, newSize ):
new = self.Identity( newSize )
for i in range( self.size ):
for j in range( self.size ):
new[ i ][ j ] = self[ i ][ j ]
return new
#some alternative ways to build matrix instances
@classmethod
def Zero( cls, size=4 ):
new = cls([0]*size*size,size)
return new
@classmethod
def Identity( cls, size=4 ):
rows = [0]*size*size
for n in xrange(size):
rows[n+(n*size)] = 1
return cls(rows,size)
@classmethod
def Random( cls, size=4, range=(0,1) ):
rows = []
import random
for n in xrange(size*size):
rows.append(random.uniform(*range))
return cls(rows,size)
@classmethod
def RotateFromTo( cls, fromVec, toVec, normalize=False ):
'''Returns a rotation matrix that rotates one vector into another
The generated rotation matrix will rotate the vector from into
the vector to. from and to must be unit vectors'''
e = fromVec*toVec
f = e.magnitude()
if f > 1.0-zeroThreshold:
#from and to vector almost parallel
fx = abs(fromVec.x)
fy = abs(fromVec.y)
fz = abs(fromVec.z)
if fx < fy:
if fx < fz: x = Vector(1.0, 0.0, 0.0)
else: x = Vector(0.0, 0.0, 1.0)
else:
if fy < fz: x = Vector(0.0, 1.0, 0.0)
else: x = Vector(0.0, 0.0, 1.0)
u = x-fromVec
v = x-toVec
c1 = 2.0/(u*u)
c2 = 2.0/(v*v)
c3 = c1*c2*u*v
res = cls(size=3)
for i in xrange(3):
for j in xrange(3):
res[i][j] = - c1*u[i]*u[j] - c2*v[i]*v[j] + c3*v[i]*u[j]
res[i][i] += 1.0
return res
else:
#the most common case unless from == to, or from == -to
v = fromVec^toVec
h = 1.0/(1.0 + e)
hvx = h*v.x
hvz = h*v.z
hvxy = hvx*v.y
hvxz = hvx*v.z
hvyz = hvz*v.y
row0 = e + hvx*v.x, hvxy - v.z, hvxz + v.y
row1 = hvxy + v.z, e + h*v.y*v.y,hvyz - v.x
row2 = hvxz - v.y, hvyz + v.x, e + hvz*v.z
return cls( row0+row1+row2 )
@classmethod
def FromEulerXYZ( cls, x, y, z, degrees=False ):
if degrees: x,y,z = map(math.radians,(x,y,z))
cx = cos(x)
sx = sin(x)
cy = cos(y)
sy = sin(y)
cz = cos(z)
sz = sin(z)
row0 = cy*cz, cy*sz, -sy
row1 = sx*sy*cz - cx*sz, sx*sy*sz + cx*cz, sx*cy
row2 = cx*sy*cz + sx*sz, cx*sy*sz - sx*cz, cx*cy
return cls( row0+row1+row2, 3 )
@classmethod
def FromEulerXZY( cls, x, y, z, degrees=False ):
if degrees: x,y,z = map(math.radians,(x,y,z))
cx = cos(x)
sx = sin(x)
cy = cos(y)
sy = sin(y)
cz = cos(z)
sz = sin(z)
row0 = cy*cz, sz, -cz*sy
row1 = sx*sy - cx*cy*sz, cz*cx, cx*sy*sz + cy*sx
row2 = cy*sx*sz + cx*sy, -cz*sx, cx*cy - sx*sy*sz
return cls( row0+row1+row2, 3 )
@classmethod
def FromEulerYXZ( cls, x, y, z, degrees=False ):
if degrees: x,y,z = map(math.radians,(x,y,z))
cx = cos(x)
sx = sin(x)
cy = cos(y)
sy = sin(y)
cz = cos(z)
sz = sin(z)
row0 = cy*cz - sx*sy*sz, cy*sz + cz*sx*sy, -cx*sy
row1 = -cx*sz, cx*cz, sx
row2 = cy*sx*sz + cz*sy, sy*sz - cy*cz*sx, cx*cy
return cls( row0+row1+row2, 3 )
@classmethod
def FromEulerYZX( cls, x, y, z, degrees=False ):
if degrees: x,y,z = map(math.radians,(x,y,z))
cx = cos(x)
sx = sin(x)
cy = cos(y)
sy = sin(y)
cz = cos(z)
sz = sin(z)
row0 = cy*cz, cx*cy*sz + sx*sy, cy*sx*sz - cx*sy
row1 = -sz, cx*cz, cz*sx
row2 = cz*sy, cx*sy*sz - cy*sx, sx*sy*sz + cx*cy
return cls( row0+row1+row2, 3 )
@classmethod
def FromEulerZXY( cls, x, y, z, degrees=False ):
if degrees: x,y,z = map(math.radians,(x,y,z))
cx = cos(x)
sx = sin(x)
cy = cos(y)
sy = sin(y)
cz = cos(z)
sz = sin(z)
row0 = sx*sy*sz + cy*cz, cx*sz, cy*sx*sz - cz*sy
row1 = cz*sx*sy - cy*sz, cx*cz, sy*sz + cy*cz*sx
row2 = cx*sy, -sx, cx*cy
return cls( row0+row1+row2, 3 )
@classmethod
def FromEulerZYX( cls, x, y, z, degrees=False ):
if degrees: x,y,z = map(math.radians,(x,y,z))
cx = cos(x)
sx = sin(x)
cy = cos(y)
sy = sin(y)
cz = cos(z)
sz = sin(z)
row0 = cy*cz, cx*sz + cz*sx*sy, sx*sz - cx*cz*sy
row1 = -cy*sz, cx*cz - sx*sy*sz, cx*sy*sz + cz*sx
row2 = sy, -cy*sx, cx*cy
return cls( row0+row1+row2, 3 )
@classmethod
def FromVectors( cls, *vectors ):
values = []
for v in vectors:
values.extend( list( v ) )
return cls( values, len( vectors ) )
def getRow( self, row ):
return self[row]
def setRow( self, row, newRow ):
if len(newRow) > self.size: newRow = newRow[:self.size]
if len(newRow) < self.size:
newRow.extend( [0] * (self.size-len(newRow)) )
self[ row ] = newRow
return newRow
def getCol( self, col ):
column = [0]*self.size
for n in xrange(self.size):
column[n] = self[n][col]
return column
def setCol( self, col, newCol ):
newColActual = []
for row, newVal in zip( self, newCol ):
row[ col ] = newVal
def getDiag( self ):
diag = []
for i in xrange(self.size):
diag.append( self[i][i] )
return diag
def setDiag( self, diag ):
for i in xrange(self.size):
self[i][i] = diag[i]
return diag
def swapRow( self, nRowA, nRowB ):
rowA = self.getRow(nRowA)
rowB = self.getRow(nRowB)
tmp = rowA
self.setRow(nRowA,rowB)
self.setRow(nRowB,tmp)
def swapCol( self, nColA, nColB ):
colA = self.getCol(nColA)
colB = self.getCol(nColB)
tmp = colA
self.setCol(nColA,colB)
self.setCol(nColB,tmp)
def transpose( self ):
new = self.__class__.Zero(self.size)
for i in xrange(self.size):
for j in xrange(self.size):
new[i][j] = self[j][i]
return new
def transpose3by3( self ):
new = self.copy()
for i in xrange(3):
for j in xrange(3):
new[i][j] = self[j][i]
return new
def det( self ):
'''
calculates the determinant
'''
d = 0
if self.size <= 0:
return 1
if self.size == 2:
#ad - bc
a, b, c, d = self.as_list()
return (a*d) - (b*c)
for i in range( self.size ):
sign = (1,-1)[ i % 2 ]
cofactor = self.cofactor( i, 0 )
d += sign * self[i][0] * cofactor.det()
return d
determinant = det
def cofactor( self, aI, aJ ):
cf = self.__class__( size=self.size-1 )
cfi = 0
for i in range( self.size ):
if i == aI:
continue
cfj = 0
for j in range( self.size ):
if j == aJ:
continue
cf[cfi][cfj] = self[i][j]
cfj += 1
cfi += 1
return cf
minor = cofactor
def isSingular( self ):
det = self.det()
if abs(det) < 1e-6: return True,0
return False,det
def isRotation( self ):
'''rotation matricies have a determinant of 1'''
return ( abs(self.det()) - 1 < 1e-6 )
def inverse( self ):
'''Each element of the inverse is the determinant of its minor
divided by the determinant of the whole'''
isSingular,det = self.isSingular()
if isSingular: return self.copy()
new = self.__class__.Zero(self.size)
for i in xrange(self.size):
for j in xrange(self.size):
sign = (1,-1)[ (i+j) % 2 ]
new[i][j] = sign * self.cofactor(i,j).det()
new /= det
return new.transpose()
def decompose( self ):
'''
return the scale matrix and rotation parts of this matrix
NOTE: both are returned as 3x3 matrices
'''
sx = Vector( self[ 0 ][ :3 ] ).length()
sy = Vector( self[ 1 ][ :3 ] ).length()
sz = Vector( self[ 2 ][ :3 ] ).length()
S = type( self )( [sx,0,0, 0,sy,0, 0,0,sz], 3 ) #deal with the 3x3 until as finding the inverse of a 4x4 is considerably slower than a 3x3
S = self.getScaleMatrix()
R = self.crop( 3 )
R = S.inverse() * R
return R, S
def getScaleMatrix( self ):
'''
return the scale matrix part of this matrix
'''
sx = Vector( self[ 0 ][ :3 ] ).length()
sy = Vector( self[ 1 ][ :3 ] ).length()
sz = Vector( self[ 2 ][ :3 ] ).length()
S = type( self )( [sx,0,0, 0,sy,0, 0,0,sz], 3 )
return S
def getRotationMatrix( self ):
'''
returns just the rotation part of this matrix - ie scale is factored out
'''
R, S = self.decompose()
return R
def adjoint( self ):
new = self.__class__.Zero(self.size)
for i in xrange(self.size):
for j in xrange(self.size):
new[i][j] = (1,-1)[(i+j)%2] * self.cofactor(i,j).det()
return new.transpose()
def ortho( self ):
'''return a matrix with orthogonal base vectors'''
x = Vector(self[0][:3])
y = Vector(self[1][:3])
z = Vector(self[2][:3])
xl = x.magnitude()
xl *= xl
y = y - ((x*y)/xl)*x
z = z - ((x*z)/xl)*x
yl = y.magnitude()
yl *= yl
z = z - ((y*z)/yl)*y
row0 = ( x.x, y.x, z.x )
row1 = ( x.y, y.y, z.y )
row2 = ( x.z, y.z, z.z )
return self.__class__(row0+row1+row2,size=3)
def getEigenValues( self ):
m = self
a, b, c = m[0]
d, e, f = m[1]
g, h, i = m[2]
flA = -1
flB = a + e + i
flC = ( d * b + g * c + f * h - a * e - a * i - e * i )
flD = ( a * e * i - a * f * h - d * b * i + d * c * h + g * b * f - g * c * e )
return cardanoCubicRoots( flA, flB, flC, flD )
def get_position( self ):
return Vector( self[3][:3] )
def set_position( self, pos ):
pos = Vector( pos )
self[3][:3] = pos
#the following methods return euler angles of a rotation matrix
def ToEulerXYZ( self, degrees=False ):
easy = self[0][2]
if easy == 1:
z = math.pi
y = -math.pi / 2.0
x = -z + atan2( -self[1][0], -self[2][0] )
elif easy == -1:
z = math.pi
y = math.pi / 2.0
x = z + atan2( self[1][0], self[2][0] )
else:
y = -asin( easy )
cosY = cos( y )
x = atan2( self[1][2] * cosY, self[2][2] * cosY )
z = atan2( self[0][1] * cosY, self[0][0] * cosY )
angles = x, y, z
if degrees:
return map( math.degrees, angles )
return angles
def ToEulerXZY( self, degrees=False ):
easy = self[0][1]
z = asin( easy )
cosZ = cos( z )
x = atan2( -self[2][1] * cosZ, self[1][1] * cosZ )
y = atan2( -self[0][2] * cosZ, self[0][0] * cosZ )
angles = x, y, z
if degrees:
return map( math.degrees, angles )
return angles
def ToEulerYXZ( self, degrees=False ):
easy = self[1][2]
x = asin( easy )
cosX = cos( x )
y = atan2( -self[0][2] * cosX, self[2][2] * cosX )
z = atan2( -self[1][0] * cosX, self[1][1] * cosX )
angles = x, y, z
if degrees:
return map( math.degrees, angles )
return angles
def ToEulerYZX( self, degrees=False ):
easy = self[1][0]
z = -asin( easy )
cosZ = cos( z )
x = atan2( self[1][2] * cosZ, self[1][1] * cosZ )
y = atan2( self[2][0] * cosZ, self[0][0] * cosZ )
angles = x, y, z
if degrees:
return map( math.degrees, angles )
return angles
def ToEulerZXY( self, degrees=False ):
easy = self[2][1]
x = -asin( easy )
cosX = cos( x )
z = atan2( self[0][1] * cosX, self[1][1] * cosX )
y = atan2( self[2][0] * cosX, self[2][2] * cosX )
angles = x, y, z
if degrees:
return map( math.degrees, angles )
return angles
def ToEulerZYX( self, degrees=False ):
easy = self[2][0]
y = asin( easy )
cosY = cos( y )
x = atan2( -self[2][1] * cosY, self[2][2] * cosY )
z = atan2( -self[1][0] * cosY, self[0][0] * cosY )
angles = x, y, z
if degrees:
return map( math.degrees, angles )
return angles
#some conversion routines
def as_list( self ):
list = []
for i in xrange(self.size):
list.extend(self[i])
return list
def as_tuple( self ):
return tuple( self.as_list() )
def cullSmallValues( self, epsilon=1e-8 ):
'''
culls small values in the matrix
'''
for row in self:
for idx, value in enumerate( row ):
if abs( value ) < epsilon:
row[ idx ] = 0
'''
#the individual rotation matrices where cx = cos( x ), sx = sin( x ) etc...
RX = Matrix( (1,0,0, 0,cx,sx, 0,-sx,cx) )
RY = Matrix( (cy,0,-sy, 0,1,0, sy,0,cy) )
RY = Matrix( (cz,sz,0, -sz,cz,0, 0,0,1) )
'''
def multMatrixVector( theMatrix, theVector ):
'''
multiplies a matrix by a vector - returns a Vector
'''
size = theMatrix.size #square matrices
size = min( size, len( theVector ) )
new = theVector.Zero( size ) #init using the actual vector instance just in case its a subclass
for i in range( size ):
for j in range( size ):
new[i] += theMatrix[i][j] * theVector[j]
return new
def multVectorMatrix( theVector, theMatrix ):
'''
mulitplies a vector by a matrix
'''
size = theMatrix.size #square matrices
size = min( size, len( theVector ) )
new = theVector.Zero( size ) #init using the actual vector instance just in case its a subclass
for i in range( size ):
for j in range( size ):
new[i] += theVector[j] * theMatrix[j][i]
return new
def cardanoCubicRoots( flA, flB, flC, flD ):
'''
Finds the roots of a Cubic polynomial of the for ax^3 + bx^2 + cx + d = 0
Returns: True - 3 real roots exists, r0, r1, r2
False - 1 real root exists, r0, 2 complex roots exist r2, r2
'''
flSqrtThree = 1.7320508075688772 #sqrt( 3.0 )
flF = ( 3.0 * flC / flA - (flB**2) / flA**2 ) / 3.0
flG = ( 2.0 * (flB**3) / (flA**3) - 9.0 * flB * flC / (flA**2) + 27.0 * flD / flA) / 27.0
flH = flG**2 / 4.0 + flF**3 / 27.0
eigenValues = Vector.Zero( 3 )
if flF == 0 and flG == 0 and flH == 0:
#3 equal roots
eigenValues[0] = -( ( flD / flA )**(1/3.0) ) #cube root
eigenValues[1] = flRoot0
eigenValues[2] = flRoot1
return True, eigenValues
elif flH <= 0:
#3 real roots
flI = ( flG**2 / 4.0 - flH )**0.5
flJ = flI**(1/3.0)
flK = acos( -( flG / ( 2.0 * flI ) ) )
flM = cos( flK / 3 )
flN = flSqrtThree * sin( flK / 3.0 )
flP = -( flB / ( 3.0 * flA ) )
eigenValues[0] = 2 * flJ * flM + flP
eigenValues[1] = -flJ * ( flM + flN ) + flP
eigenValues[2] = -flJ * ( flM - flN ) + flP
return True, eigenValues
#1 Real, 2 Complex Roots
flR = -( flG / 2 ) + flH**0.5
flS = flR**(1/3.0)
flT = -( flG / 2.0 ) - flH**0.5
flU = flT**(1/3.0)
flP = -( flB / ( 3.0 * flA ) )
eigenValues[0] = ( flS + flU ) + flP
#Return the real part but if it gets here there are complex roots
eigenValues[1] = -( flS + flU ) / 2.0 + flP
eigenValues[2] = -( flS + flU ) / 2.0 + flP
return False, eigenValues
#end
| Python |
from filesystem import *
from common import printInfoStr, printErrorStr
from mayaDecorators import d_unifyUndo
import maya.cmds as cmd
import names
import api
import apiExtensions
__author__ = 'mel@macaronikazoo.com'
TOOL_NAME = 'animLib'
kEXT = 'clip'
VER = 3 #version
### clip types
kPOSE = 0
kANIM = 1
kDELTA = 2
kDEFAULT_MAPPING_THRESHOLD = 1
kICON_W_H = 60, 60
mel = api.mel
Mapping = names.Mapping
class AnimLibException(Exception):
def __init__( self, *args ):
Exception.__init__(self, *args)
def getMostLikelyModelView():
'''
returns the panel name for the most likely active panel - the currently active panel can be
ambiguous if the user has been using the outliner, or graph editor or something after viewport
usage... this method simply looks at the currently active panel and if its not a modelPanel,
then it returns the first visible model panel. if no panels are found, returns None
'''
cur = cmd.getPanel(wf=True)
curType = cmd.getPanel(to=cur)
if curType == "modelPanel":
return cur
visPanels = cmd.getPanel(vis=True)
for p in visPanels:
if cmd.getPanel(to=p) == "modelPanel":
return p
return None
def generateIcon( preset ):
'''
given a preset object, this method will generate an icon using the currently active viewport. the
path to the icon is returned
'''
sel = cmd.ls(sl=True)
cmd.select(cl=True)
panel = getMostLikelyModelView()
if panel is None:
raise AnimLibException('cannot determine which panel to use for icon generation')
#store some initial settings, change them to what is required, and then restored at the very end
settings = ["-df", "-cv", "-ca", "-nurbsCurves", "-nurbsSurfaces", "-lt", "-ha", "-dim", "-pv", "-ikh", "-j", "-dy"]
imgFormat = cmd.getAttr("defaultRenderGlobals.imageFormat")
states = []
cmd.setAttr("defaultRenderGlobals.imageFormat", 20)
for setting in settings:
states.append( mel.eval("modelEditor -q %s %s;" % (setting, panel)) )
for setting in settings:
mel.eval("modelEditor -e %s 0 %s;" % (setting, panel))
time = cmd.currentTime(q=True)
#make sure the icon is open for edit if its a global clip
if preset.locale == GLOBAL and preset.icon.exists():
preset.edit()
icon = cmd.playblast(st=time, et=time, w=kICON_W_H[0], h=kICON_W_H[1], fo=True, fmt="image", v=0, p=100, orn=0, cf=str(preset.icon.resolve()))
icon = Path(icon)
if icon.exists():
icon = icon.setExtension('bmp', True)
cmd.setAttr("defaultRenderGlobals.imageFormat", imgFormat)
#restore viewport settings
try: cmd.select(sel)
except TypeError: pass
for setting, initialState in zip(settings, states):
mel.eval("modelEditor -e %s %s %s;" % (setting, initialState, panel))
return icon
class BaseBlender(object):
'''
a blender object is simply a callable object that when called with a percentage arg (0-1) will
apply said percentage of the given clips to the given mapping
'''
def __init__( self, clipA, clipB, mapping=None, attributes=None ):
self.clipA = clipA
self.clipB = clipB
self.__mapping = mapping
if attributes:
attributes = set( attributes )
self.attributes = attributes
def setMapping( self, mapping ):
self.__mapping = mapping
def getMapping( self ):
return self.__mapping
def __call__( self, pct, mapping=None ):
if mapping is not None:
self.setMapping( mapping )
assert self.getMapping() is not None
class PoseBlender(BaseBlender):
def __call__( self, pct, mapping=None, attributes=None ):
BaseBlender.__call__(self, pct, mapping)
cmdQueue = api.CmdQueue()
if mapping is None:
mapping = self.getMapping()
if attributes is None:
attributes = self.attributes
mappingDict = mapping.asDict()
for clipAObj, attrDictA in self.clipA.iteritems():
#if the object isn't in the mapping dict, skip it
if clipAObj not in mappingDict:
continue
clipBObjs = mapping[ clipAObj ]
for a, valueA in attrDictA.iteritems():
if attributes:
if a not in attributes:
continue
if not clipAObj:
continue
attrpath = '%s.%s' % (clipAObj, a)
if not cmd.getAttr( attrpath, settable=True ):
continue
for clipBObj in clipBObjs:
try:
attrDictB = self.clipB[ clipBObj ]
except KeyError: continue
try:
valueB = attrDictB[ a ]
blendedValue = (valueA * (1-pct)) + (valueB * pct)
cmdQueue.append( 'setAttr -clamp %s %f' % (attrpath, blendedValue) )
except KeyError:
cmdQueue.append( 'setAttr -clamp %s %f' % (attrpath, valueA) )
except: pass
cmdQueue()
class AnimBlender(BaseBlender):
def __init__( self, clipA, clipB, mapping=None ):
BaseBlender.__init__(self, clipA, clipB, mapping)
#so now we need to generate a dict to represent the curves for both of the clips
animCurveDictA = self.animCurveDictA = {}
animCurveDictB = self.animCurveDictB = {}
#the curvePairs attribute contains a dict - indexed by attrpath - containing a tuple of (curveA, curveB)
self.curvePairs = {}
for clip, curveDict in zip([self.clipA, self.clipB], [animCurveDictA, animCurveDictB]):
for o, attrDict in clip.iteritems():
curveDict[o] = {}
for a, keyData in attrDict.iteritems():
curve = curveDict[o][a] = animCurve.AnimCurve()
#unpack the key data
weightedTangents, keyList = keyData
#generate the curves
for time, value, itt, ott, ix, iy, ox, oy, isLocked, isWeighted in keyList:
curve.m_bWeighted = weightedTangents
curve.AddKey( time, value, ix, iy, ox, oy )
attrPath = '%s.%s' % (o, a)
try: self.curvePairs[attrPath].append( curve )
except KeyError: self.curvePairs[attrPath] = [ curve ]
#now iterate over each curve pair and make sure they both have keys on the same frames...
for attrPath, curves in self.curvePairs.iteritems():
try:
curveA, curveB = curves
except ValueError: continue
curveTimes = set( curveA.m_keys.keys() + curveB.m_keys.keys() )
for t in curveTimes:
curveA.InsertKey( t )
curveB.InsertKey( t )
print 'keys on', attrPath, 'at times', curveTimes
def __call__( self, pct, mapping=None ):
BaseBlender.__call__(self, pct, mapping)
cmdQueue = api.CmdQueue()
if pct == 0:
self.clipA.apply( self.getMapping() )
elif pct == 1:
self.clipB.apply( self.getMapping() )
else:
for attrPath, curves in self.curvePairs.iteritems():
try:
curveA, curveB = curves
except ValueError: continue
#because we know both curves have the same timings (ie if curveA has a key at time x, curveB is guaranteed to also have a key
#at time x) then we just need to iterate over the keys of one curve, and blend them with the values of the other
for time, keyA in curveA.m_keys.iteritems():
keyB = curveB.m_keys[ time ]
blendedValue = (keyA.m_flValue * (1-pct)) + (keyB.m_flValue * pct)
blendedIX = (keyA.m_flInTanX * (1-pct)) + (keyB.m_flInTanX * pct)
blendedIY = (keyA.m_flInTanY * (1-pct)) + (keyB.m_flInTanY * pct)
blendedOX = (keyA.m_flOutTanX * (1-pct)) + (keyB.m_flOutTanX * pct)
blendedOY = (keyA.m_flOutTanY * (1-pct)) + (keyB.m_flOutTanY * pct)
cmdQueue.append( 'setKeyframe -t %s -v %s %s' % (time, blendedValue, attrPath) )
cmdQueue.append( 'keyTangent -e -t %s -ix %s -iy %s -ox %s -oy %s %s' % (time, blendedIX, blendedIY, blendedOX, blendedOY, attrPath) )
class BaseClip(dict):
'''
baseclass for clips
'''
blender = None
OPTIONS =\
kOPT_ADDITIVE, kOPT_ADDITIVE_WORLD, kOPT_OFFSET, kOPT_CLEAR, kMULT, kOPT_ATTRSELECTION =\
'additive', 'additiveWorld', 'offset', 'clear', 'mult', 'attrSelection'
kOPT_DEFAULTS = { kOPT_ADDITIVE: False,
kOPT_ADDITIVE_WORLD: False,
kOPT_OFFSET: 0,
kOPT_CLEAR: True,
kMULT: 1,
kOPT_ATTRSELECTION: False }
def __init__( self, objects=None ):
if objects is not None:
self.generate( objects )
def generate( self, objects ):
pass
def apply( self, mapping, attributes=None, **kwargs ):
'''
valid kwargs are
additive [False] applys the animation additively
'''
pass
def getObjects( self ):
return self.keys()
def generatePreArgs( self ):
return tuple()
def getObjAttrNames( obj, attrNamesToSkip=() ):
#grab attributes
objAttrs = cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or []
#also grab alias' - its possible to pass in an alias name, so we need to test against them as well
aliass = cmd.aliasAttr( obj, q=True ) or []
#because the aliasAttr cmd returns a list with the alias, attr pairs in a flat list, we need to iterate over the list, skipping every second entry
itAliass = iter( aliass )
for attr in itAliass:
objAttrs.append( attr )
itAliass.next()
filteredAttrs = []
for attr in objAttrs:
skipAttr = False
for skipName in attrNamesToSkip:
if attr == skipName:
skipAttr = True
elif attr.startswith( skipName +'[' ) or attr.startswith( skipName +'.' ):
skipAttr = True
if skipAttr:
continue
filteredAttrs.append( attr )
return filteredAttrs
#defines a mapping between node type, and the function used to get a list of attributes from that node to save to the clip. by default getObjAttrNames( obj ) is called
GET_ATTR_BY_NODE_TYPE = { 'blendShape': lambda obj: getObjAttrNames( obj, ['envelope', 'weight', 'inputTarget'] ) }
class PoseClip(BaseClip):
blender = PoseBlender
@classmethod
def FromObjects( cls, objects ):
new = cls()
cls.generate(new, objects)
return new
def __add__( self, other ):
'''
for adding multiple pose clips together - returns a new PoseClip instance
'''
pass
def __mult__( self, other ):
'''
for multiplying a clip by a scalar value
'''
assert isinstance(other, (int, long, float))
new = PoseClip
for obj, attrDict in self.iteritems():
for attr, value in attrDict.iteritems():
attrDict[attr] = value * other
def generate( self, objects, attrs=None ):
'''
generates a pose dictionary - its basically just dict with node names for keys. key values
are dictionaries with attribute name keys and attribute value keys
'''
self.clear()
if attrs:
attrs = set( attrs )
for obj in objects:
objType = cmd.nodeType( obj )
attrGetFunction = GET_ATTR_BY_NODE_TYPE.get( objType, getObjAttrNames )
objAttrs = set( attrGetFunction( obj ) )
if attrs:
objAttrs = objAttrs.intersection( attrs )
if objAttrs is None:
continue
self[ obj ] = objDict = {}
for attr in objAttrs:
objDict[ attr ] = cmd.getAttr( '%s.%s' % (obj, attr) )
return True
@d_unifyUndo
def apply( self, mapping, attributes=None, **kwargs ):
'''
construct a mel string to pass to eval - so it can be contained in a single undo...
'''
cmdQueue = api.CmdQueue()
#gather options...
additive = kwargs.get( self.kOPT_ADDITIVE,
self.kOPT_DEFAULTS[ self.kOPT_ADDITIVE ] )
#convert the attribute list to a set for fast lookup
if attributes:
attributes = set( attributes )
for clipObj, tgtObj in mapping.iteritems():
try:
attrDict = self[ clipObj ]
except KeyError: continue
for attr, value in attrDict.iteritems():
if attributes:
if attr not in attributes:
continue
if not tgtObj:
continue
attrpath = '%s.%s' % (tgtObj, attr)
try:
if not cmd.getAttr( attrpath, settable=True ): continue
except TypeError: continue
if additive: value += cmd.getAttr( attrpath )
cmdQueue.append( 'setAttr -clamp %s %f;' % (attrpath, value) )
cmdQueue()
class AnimClip(BaseClip):
blender = AnimBlender
def __init__( self, objects=None ):
self.offset = 0
BaseClip.__init__(self, objects)
def __add__( self, other ):
pass
def __mult__( self, other ):
assert isinstance(other, (int, long, float))
for obj, attrDict in self.iteritems():
for attr, value in attrDict.iteritems():
value *= other
def generate( self, objects, attrs=None, startFrame=None, endFrame=None ):
'''
generates an anim dictionary - its basically just dict with node names for keys. key values
are lists of tuples with the form: (keyTime, attrDict) where attrDict is a dictionary with
attribute name keys and attribute value keys
'''
defaultWeightedTangentOpt = bool(cmd.keyTangent(q=True, g=True, wt=True))
self.clear()
if attrs:
attrs = set( attrs )
if startFrame is None:
startFrame = cmd.playbackOptions( q=True, min=True )
if endFrame is None:
endFrame = cmd.playbackOptions( q=True, max=True )
startFrame, endFrame = list( sorted( [startFrame, endFrame] ) )
self.offset = startFrame
#list all keys on the objects - so we can determine the start frame, and range. all times are stored relative to this time
allKeys = cmd.keyframe( objects, q=True ) or []
allKeys.sort()
allKeys = [ k for k in allKeys if startFrame <= k <= endFrame ]
if not allKeys:
return False
self.offset = offset = allKeys[ 0 ]
self.__range = allKeys[ -1 ] - offset
for obj in objects:
objAttrs = set( cmd.listAttr( obj, keyable=True, visible=True, scalar=True ) or [] )
if attrs:
objAttrs = objAttrs.intersection( attrs )
if not objAttrs:
continue
objDict = {}
self[ obj ] = objDict
for attr in objAttrs:
timeTuple = startFrame, endFrame
#so the attr value dict contains a big fat list containing tuples of the form:
#(time, value, itt, ott, ita, ota, iw, ow, isLockedTangents, isWeightLock)
attrpath = '%s.%s' % (obj, attr)
times = cmd.keyframe( attrpath, q=True, t=timeTuple )
weightedTangents = defaultWeightedTangentOpt
#if there is an animCurve this will return its "weighted tangent" state - otherwise it will return None and a TypeError will be raised
try: weightedTangents = bool(cmd.keyTangent(attrpath, q=True, weightedTangents=True)[0])
except TypeError: pass
if times is None:
#in this case the attr has no animation, so simply record the pose for this attr
objDict[attr] = (False, [(None, cmd.getAttr(attrpath), None, None, None, None, None, None, None, None)])
continue
else:
times = [ t-offset for t in times ]
values = cmd.keyframe(attrpath, q=True, t=timeTuple, vc=True)
itts = cmd.keyTangent(attrpath, q=True, t=timeTuple, itt=True)
otts = cmd.keyTangent(attrpath, q=True, t=timeTuple, ott=True)
ixs = cmd.keyTangent(attrpath, q=True, t=timeTuple, ix=True)
iys = cmd.keyTangent(attrpath, q=True, t=timeTuple, iy=True)
oxs = cmd.keyTangent(attrpath, q=True, t=timeTuple, ox=True)
oys = cmd.keyTangent(attrpath, q=True, t=timeTuple, oy=True)
isLocked = cmd.keyTangent(attrpath, q=True, t=timeTuple, weightLock=True)
isWeighted = cmd.keyTangent(attrpath, q=True, t=timeTuple, weightLock=True)
objDict[ attr ] = weightedTangents, zip(times, values, itts, otts, ixs, iys, oxs, oys, isLocked, isWeighted)
return True
@d_unifyUndo
def apply( self, mapping, attributes=None, **kwargs ):
'''
valid kwargs are:
mult [1.0] apply a mutiplier when applying curve values
additive [False]
clear [True]
'''
beginningWeightedTanState = cmd.keyTangent( q=True, g=True, wt=True )
### gather options...
additive = kwargs.get( self.kOPT_ADDITIVE,
self.kOPT_DEFAULTS[self.kOPT_ADDITIVE] )
worldAdditive = kwargs.get( self.kOPT_ADDITIVE_WORLD,
self.kOPT_DEFAULTS[self.kOPT_ADDITIVE_WORLD] )
clear = kwargs.get( self.kOPT_CLEAR,
self.kOPT_DEFAULTS[self.kOPT_CLEAR] )
mult = kwargs.get( self.kMULT,
self.kOPT_DEFAULTS[self.kMULT] )
timeOffset = kwargs.get( self.kOPT_OFFSET, self.offset )
#if worldAdditive is turned on, then additive is implied
if worldAdditive:
additive = worldAdditive
#determine the time range to clear
clearStart = timeOffset
clearEnd = clearStart + self.range
#convert the attribute list to a set for fast lookup
if attributes:
attributes = set( attributes )
for obj, tgtObj in mapping.iteritems():
if not tgtObj:
continue
try:
attrDict = self[ obj ]
except KeyError: continue
for attr, (weightedTangents, keyList) in attrDict.iteritems():
if attributes:
if attr not in attributes:
continue
attrpath = '%s.%s' % (tgtObj, attr)
try:
if not cmd.getAttr(attrpath, settable=True):
continue
except TypeError: continue
except RuntimeError:
print obj, tgtObj, attrpath
raise
#do the clear... maya doesn't complain if we try to do a cutKey on an attrpath with no
#animation - and this is good to do before we determine whether the attrpath has a curve or not...
if clear:
cmd.cutKey( attrpath, t=(clearStart, clearEnd), cl=True )
#is there an anim curve on the target attrpath already?
curveExists = cmd.keyframe(attrpath, index=(0,), q=True) is not None
preValue = 0
if additive:
if worldAdditive:
isWorld = True
#if the control has space switching setup, see if its value is set to "world" - if its not, we're don't treat the control's animation as additive
try: isWorld = cmd.getAttr('%s.parent' % obj, asString=True) == 'world'
except TypeError: pass
#only treat translation as additive
if isWorld and attr.startswith('translate'):
preValue = cmd.getAttr(attrpath)
else:
preValue = cmd.getAttr(attrpath)
for time, value, itt, ott, ix, iy, ox, oy, isLocked, isWeighted in keyList:
value *= mult
value += preValue
if time is None:
#in this case the attr value was just a pose...
cmd.setAttr( attrpath, value )
else:
time += timeOffset
cmd.setKeyframe( attrpath, t=(time,), v=value )
if weightedTangents:
#this needs to be done as two separate commands - because setting the tangent types in the same cmd as setting tangent weights can result
#in the tangent types being ignored (for the case of stepped mainly, but subtle weirdness with flat happens too)
cmd.keyTangent( attrpath, t=(time,), ix=ix, iy=iy, ox=ox, oy=oy, l=isLocked, wl=isWeighted )
cmd.keyTangent( attrpath, t=(time,), itt=itt, ott=ott )
else:
cmd.keyTangent( attrpath, t=(time,), ix=ix, iy=iy, ox=ox, oy=oy )
#cmd.keyTangent( e=True, g=True, wt=beginningWeightedTanState )
def getKeyTimes( self ):
'''
returns an ordered list of key times
'''
keyTimesSet = set()
for obj, attrDict in self.iteritems():
for attr, (weightedTangents, keyList) in attrDict.iteritems():
if keyList[0][0] is None:
continue
for tup in keyList:
keyTimesSet.add( tup[0] )
keyTimes = list( keyTimesSet )
keyTimes.sort()
return keyTimes
def getRange( self ):
'''
returns a tuple of (start, end)
'''
times = self.getKeyTimes()
try:
start, end = times[0], times[-1]
self.offset = start
except IndexError:
start, end = 0, 0
self.__range = 0
return start, end
def getRangeValue( self ):
try:
return self.__range
except AttributeError:
self.getRange()
return self.__range
range = property(getRangeValue)
def generatePreArgs( self ):
return tuple()
kEXPORT_DICT_THE_CLIP = 'clip'
kEXPORT_DICT_CLIP_TYPE = 'clip_type'
kEXPORT_DICT_OBJECTS = 'objects'
kEXPORT_DICT_WORLDSPACE = 'worldspace'
class ClipPreset(Preset):
'''
a clip preset is different from a normal preset because it is actually two separate files - a
pickled animation data file, and an icon
'''
TYPE_CLASSES = {kPOSE: PoseClip,
kANIM: AnimClip,
kDELTA: None}
TYPE_LABELS = {kPOSE: 'pose',
kANIM: 'anim',
kDELTA: 'delta'}
### auto generate a label types
LABEL_TYPES = {}
for t, l in TYPE_LABELS.iteritems():
LABEL_TYPES[l] = t
def __new__( cls, locale, library, name, type=kPOSE ):
tool = '%s/%s' % (TOOL_NAME, library)
typeLbl = cls.TYPE_LABELS[type]
ext = '%s.%s' % (typeLbl, kEXT)
self = Preset.__new__( cls, locale, tool, name, ext )
self.icon = Preset( locale, tool, name, '%s.bmp' % typeLbl )
return self
def asClip( self ):
presetDict = self.unpickle()
return presetDict[ kEXPORT_DICT_THE_CLIP ]
def niceName( self ):
return self.name().split('.')[0]
def getLibrary( self ):
return self[-2]
def setLibrary( self, library ):
self[-2] = library
def getTypeName( self ):
return self.name().split('.')[ -1 ]
def getType( self ):
typeLbl = self.getTypeName()
return self.LABEL_TYPES[typeLbl]
def move( self, library=None ):
if library is None:
library = self.getLibrary()
newLoc = ClipPreset(self.other(), library, self.niceName(), self.getType())
#perform the move...
Path.move(self, newLoc)
Path.move(self.icon, newLoc.icon)
return newLoc
def copy( self, library=None ):
if library is None:
library = self.library
newLoc = ClipPreset(self.other(), library, self.niceName(), self.getType())
#perform the copy...
Path.copy(self, newLoc)
Path.copy(self.icon, newLoc.icon)
return newLoc
def rename( self, newName ):
'''
newName should be the base name - sans any clip type id or extension...
'''
newName = '%s.%s' % (scrubName(newName), self.getTypeName())
Preset.rename(self, newName)
self.icon.rename(newName)
def delete( self ):
Path.delete(self)
self.icon.delete()
@api.d_noAutoKey
def apply( self, objects, attributes=None, **kwargs ):
presetDict = self.unpickle()
srcObjs = presetDict[ kEXPORT_DICT_OBJECTS ]
clip = presetDict[ kEXPORT_DICT_THE_CLIP ]
#do a version check - if older version clip is being used - perhaps we can write conversion functionality?
try:
ver = presetDict[ kEXPORT_DICT_TOOL_VER ]
if ver != VER:
api.melWarning("the anim clip version don't match!")
except KeyError:
api.melWarning("this is an old VER 1 pose clip - I don't know how to load them anymore...")
return
#generate the name mapping
slamApply = kwargs.get( 'slam', False )
if slamApply:
objects = cmd.ls( typ='transform' )
tgts = names.matchNames( srcObjs, objects, threshold=kDEFAULT_MAPPING_THRESHOLD )
mapping = Mapping( srcObjs, tgts )
else:
tgts = names.matchNames( srcObjs, objects, threshold=kDEFAULT_MAPPING_THRESHOLD )
mapping = Mapping( srcObjs, tgts )
#run the clip's apply method
clip.apply( mapping, attributes, **kwargs )
def getClipObjects( self ):
'''
returns a list of all the object names contained in the clip
'''
presetDict = self.unpickle()
srcObjs = presetDict[ kEXPORT_DICT_OBJECTS ]
return srcObjs
def write( self, objects, **kwargs ):
type = self.getType()
clipDict = api.writeExportDict( TOOL_NAME, VER )
clipDict[ kEXPORT_DICT_CLIP_TYPE ] = type
clipDict[ kEXPORT_DICT_OBJECTS ] = objects
clipDict[ kEXPORT_DICT_WORLDSPACE ] = False
theClip = self.TYPE_CLASSES[ type ]()
success = theClip.generate( objects, **kwargs )
if not success:
printErrorStr( "Failed to generate clip!" )
return
clipDict[ kEXPORT_DICT_THE_CLIP ] = theClip
#write the preset file to disk
self.pickle( clipDict )
#generate the icon for the clip and add it to perforce if appropriate
icon = generateIcon( self )
#icon.asP4().add()
printInfoStr( "Generated clip!" )
class ClipManager(PresetManager):
'''
an abstraction for listing libraries and library clips for clip presets - there are two
main differences between clip presets and other presets - clips have a library which is
a subdir of the main preset dir, and there are also multiple types of clips both with
the same extension.
'''
def __init__( self ):
PresetManager.__init__(self, TOOL_NAME, kEXT)
def getLibraryNames( self ):
'''
returns the names of all libraries under the current mod
'''
libraries = set()
for locale, paths in self.getLibraryPaths().iteritems():
for p in paths:
libName = p.name()
libraries.add(libName)
libraries = list(libraries)
libraries.sort()
return libraries
def getLibraryPaths( self ):
'''
returns a dictionary of library paths keyed using locale. ie:
{LOCAL: [path1, path2, ...], GLOBAL: etc...}
'''
localeDict = {}
for locale in LOCAL, GLOBAL:
localeDict[locale] = libraries = []
dirs = self.getPresetDirs(locale)
libraryNames = set()
for d in dirs:
dLibs = d.dirs()
for dLib in dLibs:
dLibName = dLib[-1]
if dLibName not in libraryNames:
libraries.append(dLib)
libraryNames.add(dLibName)
return localeDict
def createLibrary( self, name ):
newLibraryPath = Preset(LOCAL, TOOL_NAME, name, '')
newLibraryPath.create()
def getLibraryClips( self, library ):
global kEXT
clips = {LOCAL: [], GLOBAL: []}
for locale in LOCAL, GLOBAL:
localeClips = clips[locale]
for dir in getPresetDirs(locale, TOOL_NAME):
dir += library
if not dir.exists():
continue
for f in dir.files():
if f.hasExtension( kEXT ):
f = f.setExtension()
name, type = f[ -1 ].split('.')
f = f[ :-1 ]
type = ClipPreset.LABEL_TYPES[ type ]
localeClips.append( ClipPreset(locale, library, name, type) )
return clips
def getPathToLibrary( self, library, locale=LOCAL ):
return getPresetDirs(locale, TOOL_NAME)[0] / library
def reload( self ):
pass
#end
| Python |
from names import *
from apiExtensions import *
def findItem( itemName ):
itemName = str( itemName )
if cmd.objExists( itemName ):
return itemName
match = matchNames( itemName, cmd.ls( type='transform' ) )[ 0 ]
if match:
return match
return None
def resolveMappingToScene( mapping, threshold=1.0 ):
'''
takes a mapping and returns a mapping with actual scene objects
'''
assert isinstance( mapping, Mapping )
toSearch = cmd.ls( typ='transform' )
existingSrcs = []
existingTgts = []
for src, tgt in mapping.iteritems():
if not cmd.objExists( src ):
src = matchNames( [ src ], toSearch, **kw )[ 0 ]
if not cmd.objExists( tgt ):
tgt = matchNames( [ tgt ], toSearch, **kw )[ 0 ]
if cmd.objExists( src ) and cmd.objExists( tgt ):
existingSrcs.append( src )
existingTgts.append( tgt )
return Mapping( existingSrcs, existingTgts )
#end
| Python |
from baseSkeletonBuilder import *
class _QuadCommon(object):
AVAILABLE_IN_UI = False
def _buildPlacers( self ):
assert isinstance( self, SkeletonPart )
parity = self.getParity()
parityMultiplier = parity.asMultiplier()
scale = self.getBuildScale() / 30
toeTipPlacer = buildEndPlacer()
heelPlacer = buildEndPlacer()
innerRollPlacer = buildEndPlacer()
outerRollPlacer = buildEndPlacer()
placers = toeTipPlacer, heelPlacer, innerRollPlacer, outerRollPlacer
cmd.parent( placers, self.end, r=True )
fwd = MAYA_SIDE
side = MAYA_UP
setAttr( '%s.t' % toeTipPlacer, *(fwd * 2 * scale) )
setAttr( '%s.t' % heelPlacer, *(-fwd * scale) )
setAttr( '%s.t' % innerRollPlacer, *(side * scale * parityMultiplier) )
setAttr( '%s.t' % outerRollPlacer, *(-side * scale * parityMultiplier) )
return placers
def visualize( self ):
pass
class QuadrupedFrontLeg(_QuadCommon, SkeletonPart.GetNamedSubclass('Arm')):
'''
A quadruped's front leg is more like a biped's arm as it has clavicle/shoulder
blade functionality, but is generally positioned more like a leg. It is a separate
part because it is rigged quite differently from either a bipedal arm or a bipedal
leg.
'''
AVAILABLE_IN_UI = True
PLACER_NAMES = 'toeTip', 'innerRoll', 'outerRoll', 'heelRoll'
@classmethod
def _build( cls, parent=None, **kw ):
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
parent = getParent( parent )
height = xform( parent, q=True, ws=True, rp=True )[ 1 ]
dirMult = idx.asMultiplier()
parityName = idx.asName()
clavicle = createJoint( 'quadClavicle%s' % parityName )
cmd.parent( clavicle, parent, relative=True )
move( dirMult * partScale / 10.0, -partScale / 10.0, partScale / 6.0, clavicle, r=True, ws=True )
bicep = createJoint( 'quadHumerous%s' % parityName )
cmd.parent( bicep, clavicle, relative=True )
move( 0, -height / 3.0, -height / 6.0, bicep, r=True, ws=True )
elbow = createJoint( 'quadElbow%s' % parityName )
cmd.parent( elbow, bicep, relative=True )
move( 0, -height / 3.0, height / 10.0, elbow, r=True, ws=True )
wrist = createJoint( 'quadWrist%s' % parityName )
cmd.parent( wrist, elbow, relative=True )
move( 0, -height / 3.0, 0, wrist, r=True, ws=True )
jointSize( clavicle, 2 )
jointSize( wrist, 2 )
return [ clavicle, bicep, elbow, wrist ]
class QuadrupedBackLeg(_QuadCommon, SkeletonPart.GetNamedSubclass( 'Arm' )):
'''
The creature's back leg is more like a biped's leg in terms of the joints it contains.
However, like the front leg, the creature stands on his "tip toes" at the back as well.
'''
AVAILABLE_IN_UI = False
@classmethod
def _build( cls, parent=None, **kw ):
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
parent = getParent( parent )
height = xform( parent, q=True, ws=True, rp=True )[ 1 ]
dirMult = idx.asMultiplier()
parityName = idx.asName()
kneeFwdMove = height / 10.0
thigh = createJoint( 'quadThigh%s' % parityName )
thigh = cmd.parent( thigh, parent, relative=True )[ 0 ]
move( dirMult * partScale / 10.0, -partScale / 10.0, -partScale / 5.0, thigh, r=True, ws=True )
knee = createJoint( 'quadKnee%s' % parityName )
knee = cmd.parent( knee, thigh, relative=True )[ 0 ]
move( 0, -height / 3.0, kneeFwdMove, knee, r=True, ws=True )
ankle = createJoint( 'quadAnkle%s' % parityName )
ankle = cmd.parent( ankle, knee, relative=True )[ 0 ]
move( 0, -height / 3.0, -kneeFwdMove, ankle, r=True, ws=True )
toe = createJoint( 'quadToe%s' % parityName )
toe = cmd.parent( toe, ankle, relative=True )[ 0 ]
move( 0, -height / 3.0, 0, toe, r=True, ws=True )
jointSize( thigh, 2 )
jointSize( ankle, 2 )
jointSize( toe, 1.5 )
return [ thigh, knee, ankle, toe ]
class SatyrLeg(_QuadCommon, SkeletonPart.GetNamedSubclass('Leg')):
AVAILABLE_IN_UI = True
PLACER_NAMES = QuadrupedFrontLeg.PLACER_NAMES
@property
def thigh( self ): return self[ 0 ]
@property
def knee( self ): return self[ 1 ]
@property
def ankle( self ): return self[ 2 ]
@property
def toe( self ): return self[ 3 ] if len( self ) > 3 else None
@classmethod
def _build( cls, parent=None, **kw ):
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
parent = getParent( parent )
height = xform( parent, q=True, ws=True, rp=True )[ 1 ]
dirMult = idx.asMultiplier()
parityName = idx.asName()
legDrop = partScale / 12.0
sectionDist = (height - legDrop) / 3.0
kneeFwdMove = (height - legDrop) / 3.0
thigh = createJoint( 'thigh%s' % parityName )
thigh = cmd.parent( thigh, parent, relative=True )[ 0 ]
move( dirMult * partScale / 10.0, -legDrop, 0, thigh, r=True, ws=True )
knee = createJoint( 'knee%s' % parityName )
knee = cmd.parent( knee, thigh, relative=True )[ 0 ]
move( 0, -sectionDist, kneeFwdMove, knee, r=True, ws=True )
ankle = createJoint( 'ankle%s' % parityName )
ankle = cmd.parent( ankle, knee, relative=True )[ 0 ]
move( 0, -sectionDist, -kneeFwdMove, ankle, r=True, ws=True )
toe = createJoint( 'toeBall%s' % parityName )
toe = cmd.parent( toe, ankle, relative=True )[ 0 ]
move( 0, -sectionDist, kneeFwdMove / 2.0, toe, r=True, ws=True )
jointSize( thigh, 2 )
jointSize( ankle, 2 )
jointSize( toe, 1.5 )
return [ thigh, knee, ankle, toe ]
def _align( self, _initialAlign=False ):
upperNormal = getPlaneNormalForObjects( self.thigh, self.knee, self.ankle )
upperNormal *= self.getParityMultiplier()
parity = self.getParity()
alignAimAtItem( self.thigh, self.knee, parity, worldUpVector=upperNormal )
alignAimAtItem( self.knee, self.ankle, parity, worldUpVector=upperNormal )
if self.toe:
lowerNormal = getPlaneNormalForObjects( self.knee, self.ankle, self.toe )
lowerNormal *= self.getParityMultiplier()
alignAimAtItem( self.ankle, self.toe, parity, worldUpVector=upperNormal )
for i in self.getOrphanJoints():
alignItemToLocal( i )
#end
| Python |
def range2( count, start=0 ):
n = start
while n < count:
yield n
def buildMPath( objs, squish=True ):
#first we need to build a curve - we build an ep curve so that it goes exactly through the joint pivots
numObjs = len( objs )
cmdKw = { 'd': 1 }
cmdKw[ 'p' ] = tuple( xform( obj, q=True, ws=True, rp=True ) for obj in objs )
cmdKw[ 'k' ] = range( numObjs )
baseCurve = curve( **cmdKw )
curve = fitBspline( baseCurve, ch=True, tol=0.001 )[ 0 ]
curveShape = curve.getShape()
infoNode = createNode( 'curveInfo' )
connectAttr( curveShape.worldSpace[ 0 ], infoNode.inputCurve, f=True )
knots = infoNode.knots.get()[ 2:-2 ]
#now build the actual motion path nodes that keep the joints attached to the curve
#there is one proxy for each joint. the original joints get constrained to
#the proxies, which in turn get stuck to the motion path and oriented properly
#then three joints get created, which are used to deform the motion path
mpaths = []
proxies = []
upVectors = []
aims = [] #holds the aim constraints
unitComp = 1.0
if currentUnit( q=True, l=True ) == "m":
unitComp = 100.0
for n, obj in enumerate( objs ):
n += 1
mpath = createNode( 'pointOnCurveInfo' )
proxy = group( em=True )
#connect axes individually so they can be broken easily if we need to...
connectAttr( curveShape.worldSpace, mpath.inputCurve )
connectAttr( mpath.px, proxy.tx )
connectAttr( mpath.py, proxy.ty )
connectAttr( mpath.pz, proxy.tz )
mpath.parameter.set( knots[ n ] ) #($n/$unitComp);//were using ($knots[$n]/$unitComp) but it seems this is buggy - invalid knot values are returned for a straight curve... so it seems assuming $n is valid works in all test cases I've tried...
delete( orientConstraint( obj, proxy ) )
mpaths.append( mpath )
proxies.append( proxy )
#build a motionpath to get positions along the path - mainly useful for finding the half way mark
halfWayPath = createNode( 'pointOnCurveInfo' )
halfWayPos = group( em=True, n="half" )
arcLength = curveShape.maxValue.get() - curveShape.minValue.get()
connectAttr( curveShape.worldSpace, halfWayPath.inputCurve )
connectAttr( halfWayPath.p, halfWayPos.t )
halfWayPath.parameter.set( knots[ -1 ] / 2.0 )
#now build the control stucture and place then
deformJoints = []
half = numObjs / 2
select( d=True )
deformJoints.append( joint() ); select( d=True )
deformJoints.append( joint() ); select( d=True )
deformJoints.append( joint() ); select( d=True )
delete( parentConstraint( objs[ 0 ], deformJoints[ 0 ] ) )
delete( parentConstraint( halfWayPos, deformJoints[ 1 ] ) )
delete( parentConstraint( objs[ -1 ], deformJoints[ 2 ] ) )
#orient the middle deform object - this is harder than in sounds because the object doesn't actually correspond to
#any of the proxies so what we do is find the closest proxies and average their orientations based on their proximity
#it looks pretty complicated, but thats all thats going on - proximity based orient constraint weighting
midObjs = []
distancesToObjs = []
isOdd = numObjs % 2
def betweenVector( objA, objB ):
posA = Vector( xform( objA, q=True, ws=True, rp=True ) )
posB = Vector( xform( objB, q=True, ws=True, rp=True ) )
return posB - posA
#if there is an odd number of objs in the chain, we want the surrounding three - NOTE one is almost certain to be very close, whcih is why we
#do the proximity based weighting - the closest one should have the greatest effect on orientation
if isOdd:
midObjs[ 0 ] = objs[ half - 1 ]
midObjs[ 1 ] = objs[ half ]
midObjs[ 2 ] = objs[ half + 1 ]
distancesToObjs[ 0 ] = betweenVector( midObjs[ 0 ], deformJoints[ 1 ] ).magnitude()
distancesToObjs[ 1 ] = betweenVector( midObjs[ 1 ], deformJoints[ 1 ] ).magnitude()
distancesToObjs[ 2 ] = betweenVector( midObjs[ 2 ], deformJoints[ 1 ] ).magnitude()
#but if there are an even number of objs in the chain, we only want the mid two
else:
n = (numObjs - 1) / 2
midObjs[ 0 ] = objs[ n ]
midObjs[ 1 ] = objs[ n + 1 ]
distancesToObjs[ 0 ] = betweenVector( midObjs[ 0 ], deformJoints[ 1 ] ).magnitude()
distancesToObjs[ 1 ] = betweenVector( midObjs[ 1 ], deformJoints[ 1 ] ).magnitude()
total = sum( distancesToObjs )
distancesToObjs = [ total / d for d in distancesToObjs ]
tempConstraint = orientConstraint( midObjs + [ deformJoints[1] ] )[ 0 ]
for obj, weight in enuzip( midObjs, distancesToObjs ):
orientConstraint( tempConstraint, obj, e=True, w=weight )
delete( tempConstraint )
makeIdentity( deformJoints, a=True, r=True )
#now weight the curve to the controls - the weighting is just based on a linear
#falloff from the start to mid joint, and then from the mid joint to the end
skinCluster = skinCluster( deformJoints, baseCurve )
#set the weights to 1 for the bottom and mid joint
for n in range2( half ):
skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[ 0 ], 1) )
for n in range2( numObjs, half ):
skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[ 1 ], 1) )
#now figure out the positional mid point
midToStart = betweenVector( deformJoints[ 1 ], deformJoints[ 0 ] )
startPos = Vector( xform( deformJoints[ 0 ], q=True, ws=True, rp=True ) )
halfByPos = 0
for n in range( numObjs ):
pointPos = Vector( pointPosition( baseCurve.cv[ n ] ) )
relToStart = pointPos - startPos
distFromStart = relToStart.magnitude()
if distFromStart > midToStart:
halfByPos = n
break
#set the weights initially fully to the end deform joints - then figure out the of each point from the mid joint, and apply a weight falloff
midPos = Vector( xform( deformJoints[1], q=True, ws=True, rp=True ) )
midToEnd = betweenVector( deformJoints[2], deformJoints[1] ).magnitude()
for n in range2( halfByPos ):
skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[0], 1) )
for n in range2( numObjs, halfByPos ):
skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[2], 1) )
for n in range2( halfByPos, 1 ):
pointPos = Vector( pointPosition( baseCurve.cv[ n ] ) )
pointToMid = pointPos - midPos
weight = 1 - (pointToMid.magnitude() / midToStart)
skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[1], weight) )
for range2( numObjs, halfByPos ):
pointPos = Vector( pointPosition( baseCurve.cv[ n ] ) )
pointToMid = pointPos - midPos
weight = 1 - (pointToMid.magnitude() / midToEnd)
skinPercent( skinCluster, baseCurve.cv[ n ], tv=(deformJoints[1], weight) )
parentConstraint( deformJoints[0], objs[0] )
pointConstraint( proxies[ numObjs-1 ], objs[ numObjs-1 ] )
orientConstraint( deformJoints[2], objs[ numObjs-1 ] )
#build the aim constraints for the proxies
third_1st = round( numObjs / 3.0 )
third_2nd = round( ( numObjs*2.0 ) / 3.0 )
for range2( numObjs-1, 1 ):
#we're using z as the aim axis for the proxies, and y for the up axis
upObj = deformJoints[0]
aim_float = 0, 0, 1.0
up_float = 0, 1.0, 0
if n >= third_1st and n < third_2nd:
upObj = deformJoints[1]
elif n >= third_2nd:
upObj = deformJoints[2]
#now that we have an aim vector, build the aimconstraint, then we'll need to find the up vector - we need the
#proxy to be aimed at its target first however, so we can get an accurate up axis to use on the deform obj
#because all this is just a proxy rig that the real skeleton is constrained to, axes are all arbitrary...
delete `aimConstraint -aim $aim_float[0] $aim_float[1] $aim_float[2] -u $up_float[0] $up_float[1] $up_float[2] -wu $up_float[0] $up_float[1] $up_float[2] -wuo $upObj -wut objectrotation $proxies[( $n+1 )] $proxies[$n]`;
#now we have to figure out which axis on the deform obj to use as the up axis - we do this by using the x axis on
#the proxy (an arbitrary choice - could just as easily have been y) then seeing what axis is closest to that vector on the deform obj
proxyUpVector = pointMatrixMult($up_float,`xform -q -m $proxies[$n]`); #get aim axis relative to the proxy - we need this so we can figure out which axis on the up object points in that direction
upObjUpAxis = `zooAxisInDirection $upObj $proxyUpVector`;
upVectors[ n ] = `zooArrayToStr_float $up_float " "`;
#now edit the constraint to use the up vector we've determined
aims[ n ] = zooGetElement_str(0,`aimConstraint -mo -aim $aim_float[0] $aim_float[1] $aim_float[2] -u $up_float[0] $up_float[1] $up_float[2] -wu $upObjUpAxis[0] $upObjUpAxis[1] $upObjUpAxis[2] -wuo $upObj -wut objectrotation $proxies[( $n+1 )] $proxies[$n]`);
parentConstraint -mo $proxies[$n] $objs[$n];
#scaling? create a network to dynamically scale the objects based on the length
#of the segment. there are two curve segments - start to mid, mid to end. this
#scaling is done via SDK so we get control over the in/out of the scaling
squishNodes = []
if squish:
curveInfo = createNode( 'curveInfo' )
scaleFac = shadingNode( n='squishCalculator', asUtility='multiplyDivide' )
adder = shadingNode( n='now_add_one', asUtility='plusMinusAverage' )
sdkScaler = createNode( 'animCurveUU', n='squish_sdk' )
initialLength = 0
maxScale = 2.0
minScale = 0.25
addAttr -k 1 -ln length -at double -min 0 -max 1 -dv 1 $deformJoints[0];
addAttr -k 1 -ln squishFactor -at double -min 0 -max 1 -dv 0 $deformJoints[0];
setAttr -k 1 ( $deformJoints[0] +".length" );
setAttr -k 1 ( $deformJoints[0] +".squishFactor" );
connectAttr -f ( $curveShape +".worldSpace[0]" ) ( $curveInfo +".inputCurve" );
initialLength = `getAttr ( $curveInfo +".arcLength" )`;
setAttr ( $adder +".input1D[0]" ) 1;
select -cl;
setKeyframe -f $initialLength -v 0 $sdkScaler;
setKeyframe -f( $initialLength/100 ) -v( $maxScale-1 ) $sdkScaler;
setKeyframe -f( $initialLength*2 ) -v( $minScale-1 ) $sdkScaler;
keyTangent -in 0 -itt flat -ott flat $sdkScaler;
keyTangent -in 2 -itt flat -ott flat $sdkScaler;
connectAttr -f ( $curveInfo +".arcLength" ) ( $sdkScaler +".input" );
connectAttr -f ( $scaleFac +".outputX" ) ( $adder +".input1D[1]" );
connectAttr -f ( $sdkScaler +".output" ) ( $scaleFac +".input1X" );
connectAttr -f ( $deformJoints[0] +".squishFactor" ) ( $scaleFac +".input2X" );
for( $n=0; $n<$numObjs; $n++ ) for( $ax in {"x","y","z"} ) connectAttr -f ( $adder +".output1D" ) ( $objs[$n] +".s"+ $ax );
lengthMults = []
for n in range( numObjs, 1 ):
posOnCurve = mpaths[ n ].parameter.get()
lengthMults[$n] = `shadingNode -n( "length_multiplier"+ $n ) -asUtility multiplyDivide`;
setAttr ( $lengthMults[$n] +".input1X" ) $posOnCurve;
connectAttr -f ( $deformJoints[0] +".length" ) ( $lengthMults[$n] +".input2X" );
connectAttr -f ( $lengthMults[$n] +".outputX" ) ( $mpaths[$n] +".parameter" );
$squishNodes = [ curveInfo, scaleFac, adder, sdkScaler} $lengthMults`;
#rename the curves
baseCurve.rename( "pointCurve" )
curve.rename( "mPath" )
#build the controllers array for returning
controllers = deformJoints
controllers += [ baseCurve, curve, skinCluster ]
controllers += proxies
controllers += mpaths
controllers += aims
controllers += squishNodes
delete( halfWayPos )
select( deformJoints )
return controllers
| Python |
import maya.mel
from maya.cmds import cmd
melEval = maya.mel.eval
def pyArgToMelArg( arg ):
#given a python arg, this method will attempt to convert it to a mel arg string
if isinstance( arg, basestring ):
return u'"%s"' % cmd.encodeString( arg )
#if the object is iterable then turn it into a mel array string
elif hasattr( arg, '__iter__' ):
return '{%s}' % ','.join( map( pyArgToMelArg, arg ) )
#either lower case bools or ints for mel please...
elif isinstance( arg, bool ):
return str( arg ).lower()
#otherwise try converting the sucka to a string directly
return unicode( arg )
class Mel( object ):
'''
creates an easy to use interface to mel code as opposed to having string formatting
operations all over the place in scripts that call mel functionality
'''
def __init__( self, echo=False ):
self.echo = echo
def __getattr__( self, attr ):
if attr.startswith( '__' ) and attr.endswith( '__' ):
return self.__dict__[attr]
#construct the mel cmd execution method
echo = self.echo
def melExecutor( *args ):
strArgs = map( pyArgToMelArg, args )
cmdStr = '%s(%s);' % (attr, ','.join( strArgs ))
if echo:
print cmdStr
try:
retVal = melEval( cmdStr )
except RuntimeError:
print 'cmdStr: %s' % cmdStr
return
return retVal
melExecutor.__name__ = attr
return melExecutor
def source( self, script ):
return melEval( 'source "%s";' % script )
def eval( self, cmdStr ):
if self.echo:
print cmdStr
try:
return melEval( cmdStr )
except RuntimeError:
print 'ERROR :: trying to execute the cmd:'
print cmdStr
raise
mel = Mel()
melecho = Mel(echo=True)
#end
| Python |
from triggered import Trigger
from names import camelCaseToNice
from filesystem import removeDupes
from control import getNiceName
from apiExtensions import asMObject, getShortName
from maya.cmds import *
import re
import triggered
import control
import rigUtils
import maya.cmds as cmd
import apiExtensions
attrState = control.attrState
AXES = rigUtils.Axis.BASE_AXES
class ChangeSpaceCmd(unicode):
'''
contains a bunch of higher level tools to querying the space changing command string
'''
_THE_LINES = 'zooFlags;', 'zooUtils;', 'zooChangeSpace \"-attr parent %d\" %%%d;'
@classmethod
def Create( cls, parentIdx, parentConnectIdx ):
return cls( '\n'.join( cls._THE_LINES ) % (parentIdx, parentConnectIdx) )
@classmethod
def IsChangeSpaceCmd( cls, theStr ):
return '\nzooChangeSpace "' in theStr
def getInterestingLine( self ):
for line in self.split( '\n' ):
if line.startswith( 'zooChangeSpace ' ):
return line
def getIndex( self ):
interestingLine = self.getInterestingLine()
indexStr = interestingLine.split( ' ' )[ -2 ].replace( '"', '' )
return int( indexStr )
def setIndex( self, index ):
lines = self.split( '\n' )
for n, line in enumerate( lines ):
if line.startswith( 'zooChangeSpace ' ):
toks = line.split( ' ' )
toks[ -2 ] = '%d"' % index
lines[ n ] = ' '.join( toks )
return ChangeSpaceCmd( '\n'.join( lines ) )
def getConnectToken( self ):
interestingLine = self.getInterestingLine()
lastToken = interestingLine.split( ' ' )[ -1 ].replace( ';', '' )
return lastToken
def build( src, tgts, names=None, space=None, **kw ):
'''
'''
if names is None:
names = [ None for t in tgts ]
conditions = []
for tgt, name in zip( tgts, names ):
cond = add( src, tgt, name, space, **kw )
conditions.append( cond )
return conditions
CONSTRAINT_TYPES = CONSTRAINT_PARENT, CONSTRAINT_POINT, CONSTRAINT_ORIENT = 'parentConstraint', 'pointConstraint', 'orientConstraint'
CONSTRAINT_CHANNELS = { CONSTRAINT_PARENT: (['t', 'r'], ['ct', 'cr']),
CONSTRAINT_POINT: (['t'], ['ct']),
CONSTRAINT_ORIENT: (['r'], ['cr']) }
NO_TRANSLATION = { 'skipTranslationAxes': ('x', 'y', 'z') }
NO_ROTATION = { 'skipRotationAxes': ('x', 'y', 'z') }
def add( src, tgt,
name=None,
space=None,
maintainOffset=True,
nodeWithParentAttr=None,
skipTranslationAxes=(),
skipRotationAxes=(),
constraintType=CONSTRAINT_PARENT ):
global AXES
AXES = list( AXES )
if space is None:
space = listRelatives( src, p=True, pa=True )[ 0 ]
if nodeWithParentAttr is None:
nodeWithParentAttr = src
if not name:
name = getNiceName( tgt )
if name is None:
name = camelCaseToNice( str( tgt ) )
#if there is an existing constraint, check to see if the target already exists in its target list - if it does, return the condition used it uses
attrState( space, ('t', 'r'), lock=False )
existingConstraint = findConstraint( src )
if existingConstraint:
constraintType = nodeType( existingConstraint )
constraintFunc = getattr( cmd, constraintType )
targetsOnConstraint = constraintFunc( existingConstraint, q=True, tl=True )
if tgt in targetsOnConstraint:
idx = targetsOnConstraint.index( tgt )
aliases = constraintFunc( existingConstraint, q=True, weightAliasList=True )
cons = listConnections( '%s.%s' % (existingConstraint, aliases[ idx ]), type='condition', d=False )
return cons[ 0 ]
#when skip axes are specified maya doesn't handle things properly - so make sure
#ALL transform channels are connected, and remove unwanted channels at the end...
preT, preR = getAttr( '%s.t' % space )[0], getAttr( '%s.r' % space )[0]
if existingConstraint:
chans = CONSTRAINT_CHANNELS[ constraintType ]
for channel, constraintAttr in zip( *chans ):
for axis in AXES:
spaceAttr = '%s.%s%s' %( space, channel, axis)
conAttr = '%s.%s%s' % (existingConstraint, constraintAttr, axis)
if not isConnected( conAttr, spaceAttr ):
connectAttr( conAttr, spaceAttr )
#get the names for the parents from the parent enum attribute
cmdOptionKw = { 'mo': True } if maintainOffset else {}
if objExists( '%s.parent' % nodeWithParentAttr ):
srcs, names = getSpaceTargetsNames( src )
addAttr( '%s.parent' % nodeWithParentAttr, e=True, enumName=':'.join( names + [name] ) )
#if we're building a pointConstraint instead of a parent constraint AND we already
#have spaces on the object, we need to turn the -mo flag off regardless of what the
#user set it to, as the pointConstraint maintain offset has different behaviour to
#the parent constraint
if constraintType in ( CONSTRAINT_POINT, CONSTRAINT_ORIENT ):
cmdOptionKw = {}
else:
addAttr( nodeWithParentAttr, ln='parent', at="enum", en=name )
setAttr( '%s.parent' % nodeWithParentAttr, keyable=True )
#now build the constraint
constraintFunction = getattr( cmd, constraintType )
constraint = constraintFunction( tgt, space, **cmdOptionKw )[ 0 ]
weightAliasList = constraintFunction( constraint, q=True, weightAliasList=True )
targetCount = len( weightAliasList )
constraintAttr = weightAliasList[ -1 ]
condition = shadingNode( 'condition', asUtility=True, n='%s_to_space_%s#' % (getShortName( src ), getShortName( tgt )) )
setAttr( '%s.secondTerm' % condition, targetCount-1 )
setAttr( '%s.colorIfTrue' % condition, 1, 1, 1 )
setAttr( '%s.colorIfFalse' % condition, 0, 0, 0 )
connectAttr( '%s.parent' % nodeWithParentAttr, '%s.firstTerm' % condition )
connectAttr( '%s.outColorR' % condition, '%s.%s' % (constraint, constraintAttr) )
#find out what symbol to use to find the parent attribute
parentAttrIdx = 0
if not apiExtensions.cmpNodes( space, src ):
parentAttrIdx = triggered.addConnect( src, nodeWithParentAttr )
#add the zooObjMenu commands to the object for easy space switching
Trigger.CreateMenu( src,
"parent to %s" % name,
ChangeSpaceCmd.Create( targetCount-1, parentAttrIdx ) )
#when skip axes are specified maya doesn't handle things properly - so make sure
#ALL transform channels are connected, and remove unwanted channels at the end...
for axis, value in zip( AXES, preT ):
if axis in skipTranslationAxes:
attr = '%s.t%s' % (space, axis)
delete( attr, icn=True )
setAttr( attr, value )
for axis, value in zip( AXES, preR ):
if axis in skipRotationAxes:
attr = '%s.r%s' % (space, axis)
delete( attr, icn=True )
setAttr( attr, value )
#make the space node non-keyable and lock visibility
attrState( space, [ 't', 'r', 's' ], lock=True )
attrState( space, 'v', *control.HIDE )
return condition
def removeSpace( src, tgt ):
'''
removes a target (or space) from a "space switching" object
'''
tgts, names = getSpaceTargetsNames( src )
tgt_mobject = asMObject( tgt )
name = None
for index, (aTgt, aName) in enumerate( zip( tgts, names ) ):
aTgt = asMObject( aTgt )
if aTgt == tgt_mobject:
name = aName
break
if name is None:
raise AttributeError( "no such target" )
delete = False
if len( tgts ) == 1:
delete = True
constraint = findConstraint( src )
parentAttrOn = findSpaceAttrNode( src )
space = findSpace( src )
srcTrigger = Trigger( src )
cmds = srcTrigger.iterMenus()
if delete:
delete( constraint )
deleteAttr( '%s.parent' % src )
else:
constraintType = nodeType( constraint )
constraintFunc = getattr( cmd, constraintType )
constraintFunc( tgt, constraint, rm=True )
for slot, cmdName, cmdStr in srcTrigger.iterMenus():
if cmdName == ( "parent to %s" % name ):
srcTrigger.removeMenu( slot )
#rebuild the parent attribute
newNames = names[:]
newNames.pop( index )
addAttr( '%s.parent' % parentAttrOn, e=True, enumName=':'.join( newNames ) )
#now we need to update the indicies in the right click command - all targets that were beyond the one we
#just removed need to have their indices decremented
for slot, cmdName, cmdStr in srcTrigger.iterMenus():
if not cmdName.startswith( 'parent to ' ):
continue
cmdStrObj = ChangeSpaceCmd( cmdStr )
cmdIndex = cmdStrObj.getIndex()
if cmdIndex < index:
continue
cmdStrObj = cmdStrObj.setIndex( cmdIndex-1 )
srcTrigger.setMenuCmd( slot, cmdStrObj )
def getSpaceName( src, theTgt ):
'''
will return the user specified name given to a particular target object
'''
tgts, names = getSpaceTargetsNames( src )
for tgt, name in zip( tgts, names ):
if tgt == theTgt:
return name
def getSpaceTargetsNames( src ):
'''
this procedure returns a 2-tuple: a list of all targets, and a list of user
specified names - for the right click menus
'''
constraint = findConstraint( src )
if constraint is None:
return [], []
space = findSpace( src, constraint )
if space is None:
return [], []
constraintType = nodeType( constraint )
constraintFunc = getattr( cmd, constraintType )
targetsOnConstraint = constraintFunc( constraint, q=True, tl=True )
trigger = Trigger( src )
SPECIAL_STRING = 'parent to '
LEN_SPECIAL_STRING = len( SPECIAL_STRING )
tgts, names = [], []
for slotIdx, slotName, slotCmd in trigger.iterMenus():
if slotName.startswith( SPECIAL_STRING ):
names.append( slotName[ LEN_SPECIAL_STRING: ] )
cmdStrObj = ChangeSpaceCmd( slotCmd )
cmdIndex = cmdStrObj.getIndex()
tgts.append( targetsOnConstraint[ cmdIndex ] )
return tgts, names
def findSpace( obj, constraint=None ):
'''
will return the node being used as the "space node" for any given space switching object
'''
if constraint is None:
constraint = findConstraint( obj )
if constraint is None:
return None
cAttr = '%s.constraintParentInverseMatrix' % constraint
spaces = listConnections( cAttr, type='transform', d=False )
if spaces:
future = ls( listHistory( cAttr, f=True ), type='transform' )
if future:
return future[ -1 ]
def findConstraint( obj ):
'''
will return the name of the constraint node thats controlling the "space node" for any given
space switching object
'''
parentAttrOn = findSpaceAttrNode( obj )
if parentAttrOn is None:
return None
pAttr = '%s.parent' % parentAttrOn
if not objExists( pAttr ):
return None
conditions = listConnections( pAttr, type='condition', s=False ) or []
for condition in conditions:
constraints = listConnections( '%s.outColorR' % condition, type='constraint', s=False )
if constraints:
return constraints[ 0 ]
return None
def findSpaceAttrNode( obj ):
'''
returns the node that contains the parent attribute for the space switch
'''
parentAttrOn = "";
trigger = Trigger( obj )
for slotIdx, slotName, slotCmd in trigger.iterMenus():
if slotName.startswith( 'parent to ' ):
cmdStrObj = ChangeSpaceCmd( slotCmd )
connectToken = cmdStrObj.getConnectToken()
return trigger.resolve( connectToken )
#end
| Python |
from baseSkeletonBuilder import *
class ArbitraryChain(SkeletonPart):
HAS_PARITY = False
@classmethod
def _build( cls, parent=None, partName='', jointCount=5, direction='-z', **kw ):
if not partName:
partName = cls.__name__
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
partName = '%s%s' % (partName, idx)
parent = getParent( parent )
dirMult = cls.ParityMultiplier( idx ) if cls.HAS_PARITY else 1
length = partScale
lengthInc = dirMult * length / jointCount
directionAxis = rigUtils.Axis.FromName( direction )
directionVector = directionAxis.asVector() * lengthInc
directionVector = list( directionVector )
otherIdx = directionAxis.otherAxes()[ 1 ]
parityStr = idx.asName() if cls.HAS_PARITY else ''
allJoints = []
prevParent = parent
half = jointCount / 2
for n in range( jointCount ):
j = createJoint( '%s_%d%s' % (partName, n, parityStr) )
cmd.parent( j, prevParent, r=True )
moveVector = directionVector + [ j ]
moveVector[ otherIdx ] = dirMult * n * lengthInc / jointCount / 5.0
move( moveVector[0], moveVector[1], moveVector[2], j, r=True, ws=True )
allJoints.append( j )
prevParent = j
return allJoints
def _align( self, _initialAlign=False ):
parity = Parity( 0 )
if self.hasParity():
parity = self.getParity()
num = len( self )
if num == 1:
autoAlignItem( self[ 0 ], parity )
elif num == 2:
for i in self.selfAndOrphans(): autoAlignItem( i, parity )
else:
#in this case we want to find a plane that roughly fits the chain.
#for the sake of simplicity take the first, last and some joint in
#the middle and fit a plane to them, and use it's normal for the upAxis
midJoint = self[ num / 2 ]
defaultUpVector = rigUtils.getObjectBasisVectors( self[ 0 ] )[ BONE_OTHER_AXIS ]
normal = getPlaneNormalForObjects( self.base, midJoint, self.end, defaultUpVector )
normal *= parity.asMultiplier()
for n, i in enumerate( self[ :-1 ] ):
alignAimAtItem( i, self[ n+1 ], parity, worldUpVector=normal )
autoAlignItem( self[ -1 ], parity, worldUpVector=normal )
#should we align the orphans?
rigKwargs = self.getRigKwargs()
if 'rigOrphans' in rigKwargs:
if rigKwargs[ 'rigOrphans' ]:
for i in self.getOrphanJoints():
autoAlignItem( i, parity, worldUpVector=normal )
# read just the rotations to be inline with the parent joint -- wish we didn't have to do this
endPlacer = self.endPlacer
if endPlacer:
setAttr( '%s.r' % endPlacer, 0, 0, 0 )
def visualize( self ):
scale = self.getBuildScale() / 10.0
midJoint = self[ len( self ) / 2 ]
class ArbitraryParityChain(ArbitraryChain):
HAS_PARITY = True
#end
| Python |
'''
these are the optional args and their default values for the keyed rig primitive
build functions
'''
PRIM_OPTIONS = { 'zooBuildControl': {},
'zooCSTBuildPrimBasicSpine': {},
#'parents': tuple(),
#'hips': '',
#'scale': 1.0,
#'spaceswitching': True,
#'colour': 'lightblue 0.65',
#'buildhips': True },
'zooCSTBuildPrimHead': {},
#'parents': tuple(),
#'headType': 'skingeometry',
#'neckType': 'pin',
#'colour': 'blue 0.92'
#'scale': 1.0,
#'orient': True,
#'spaceswitching': True,
#'pickwalking': True,
#'buildNeck': True,
#'neckCount': True },
'zooCSTBuildPrimArm': {},
#'parents': tuple(),
#'scale': 1.0,
#'buildclav': True,
#'spaceswitching': True,
#'pickwalking': True,
#'allPurpose': True,
#'stretch': False },
'zooCSTBuildPrimLeg': { #'parents': tuple(),
#'ikType': 'skingeometry',
#'allPurpose': True,
#'scale': 1.0,
#'spaceswitching': True,
#'pickwalking': True,
'stretch': False },
'zooCSTBuildPrimHand': { 'names': ("index", "mid", "ring", "pinky", "thumb"),
#'axes': ("#", "#", "#", "#", "#"),
#'colour': 'orange 0.65',
#'maxSlider': 90,
#'minSlider': -90,
#'maxFingerRot': 90,
#'minFingerRot': -90,
#'scale': 1.0,
'taper': 1.0,
#'pickwalking': True,
'num': 0,
#'invert': True,
'sliders': True,
'triggers': True,
'stretch': False } }
#end
| Python |
'''
general utils to push changes to referenced scene data back to its original source
currently just contains a function to take skin weights from the current scene and push them to the model file
'''
from maya.cmds import *
from filesystem import Path
from api import mel
from common import printWarningStr
from referenceUtils import stripNamespaceFromNamePath
import skinWeights
def getRefFilepathDictForNodes( nodes ):
'''
returns a dictionary keyed by the referenced filename. Key values are dictionaries which are
keyed by reference node (any file can be referenced multiple times) the value of which are the
given nodes that are referenced.
example:
we have a scene with three references:
refA comes from c:/someFile.ma
refB comes from c:/someFile.ma
refC comes from c:/anotherFile.ma
we have 3 nodes: nodeA, nodeB and nodeC.
nodeA comes from refA
nodeB comes from refB
nodeA comes from refC
in this example running getRefFilepathDictForNodes( ('nodeA', 'nodeB', 'nodeC') ) would return:
{ 'c:/someFile.ma': { 'refA': [ 'nodeA' ], 'refB': [ 'nodeB' ],
'c:/anotherFile.ma': { 'refC': [ 'nodeC' ] }
'''
refFileDict = {}
#find the referenced files for the given meshes
for node in nodes:
isReferenced = referenceQuery( node, inr=True )
if isReferenced:
refNode = referenceQuery( node, referenceNode=True )
refFile = Path( referenceQuery( node, filename=True, withoutCopyNumber=True ) )
if refFile in refFileDict:
refNodeDict = refFileDict[ refFile ]
else:
refNodeDict = refFileDict[ refFile ] = {}
refNodeDict.setdefault( refNode, [] )
refNodeDict[ refNode ].append( node )
return refFileDict
def ensureCurrentFileIsCheckedOut():
curFile = Path( file( q=True, sn=True ) )
if not curFile.getWritable():
curFile.edit()
def storeWeightsById( mesh, namespaceToStrip=None ):
weightData = []
skinCluster = mel.findRelatedSkinCluster( mesh )
verts = ls( polyListComponentConversion( mesh, toVertex=True ), fl=True )
for vert in verts:
jointList = skinPercent( skinCluster, vert, ib=1e-4, q=True, transform=None )
weightList = skinPercent( skinCluster, vert, ib=1e-4, q=True, value=True )
#if there is a namespace to strip, we need to strip it from the vertex and the joint name...
if namespaceToStrip is not None:
vert = stripNamespaceFromNamePath( vert, namespaceToStrip )
jointList = [ stripNamespaceFromNamePath( j, namespaceToStrip ) for j in jointList ]
weightData.append( (vert, zip( jointList, weightList )) )
return weightData
def propagateWeightChangesToModel( meshes ):
'''
Given a list of meshes to act on, this function will store the skin weights, remove any
edits from the skin clusters that affect them, open the scene file the meshes come from
and apply the weights to the geometry in that scene.
This makes it possible to fix skinning problems while animating with minimal workflow
changes
'''
curFile = Path( file( q=True, sn=True ) )
referencedMeshes = getRefFilepathDictForNodes( meshes )
if not curFile.name():
printWarningStr( "The current scene isn't saved - please save the current scene first before proceeding!" )
return
for refFilepath, refNodeMeshDict in referencedMeshes.iteritems():
referencesToUnload = []
#make sure we don't visit any of the meshes more than once
meshesToUpdateWeightsOn = []
meshesToUpdateWeightsOn_withNS = []
for refNode, refMeshes in refNodeMeshDict.iteritems():
#get the maya filepath for the reference (with the "copy number")
mayaFilepathForRef = referenceQuery( refNode, f=True )
#get the namespace for this reference
refNodeNamespace = file( mayaFilepathForRef, q=True, namespace=True )
#check to see if there are any meshes in this reference that we need to store weights for
for mesh_withNS in refMeshes:
mesh = stripNamespaceFromNamePath( mesh_withNS, refNodeNamespace )
if mesh in meshesToUpdateWeightsOn:
continue
meshesToUpdateWeightsOn.append( mesh )
meshesToUpdateWeightsOn_withNS.append( (mesh_withNS, refNodeNamespace) )
#append the file to the list of reference files that we need to unload
referencesToUnload.append( mayaFilepathForRef )
#get a list of skin cluster nodes - its actually the skin cluster nodes we want to remove edits from...
nodesToCleanRefEditsFrom = []
for m, ns in meshesToUpdateWeightsOn_withNS:
nodesToCleanRefEditsFrom.append( mel.findRelatedSkinCluster( m ) )
#now we want to store out the weighting from the referenced meshes
weights = []
for mesh, meshNamespace in meshesToUpdateWeightsOn_withNS:
weights.append( storeWeightsById( mesh, meshNamespace ) )
#also lets remove any ref edits from the mesh and all of its shape nodes - this isn't strictly nessecary, but I can't think of a reason to make edits to these nodes outside of their native file
nodesToCleanRefEditsFrom.append( mesh )
nodesToCleanRefEditsFrom += listRelatives( mesh, s=True, pa=True ) or []
#remove the skinweights reference edits from the meshes in the current scene
for f in referencesToUnload:
file( f, unloadReference=True )
#remove ref edits from the shape node as well - this isn't strictly nessecary but there probably shouldn't be changes to the shape node anyway
for node in nodesToCleanRefEditsFrom:
referenceEdit( node, removeEdits=True, successfulEdits=True, failedEdits=True )
#re-load references
for f in referencesToUnload:
file( f, loadReference=True )
#save this scene now that we've removed ref edits
ensureCurrentFileIsCheckedOut()
file( save=True, f=True )
#load up the referenced file and apply the weighting to the meshes in that scene
file( refFilepath, open=True, f=True )
for mesh, weightData in zip( meshesToUpdateWeightsOn, weights ):
#if there is no weight data to store - keep loopin...
if not weightData:
continue
skinCluster = mel.findRelatedSkinCluster( mesh )
if not skinCluster:
printWarningStr( "Couldn't find a skin cluster driving %s - skipping this mesh" % mesh )
continue
skinWeights.setSkinWeights( skinCluster, weightData )
#save the referenced scene now that we've applied the weights to it
ensureCurrentFileIsCheckedOut()
file( save=True, f=True )
#reload the original file
file( curFile, o=True, f=True )
def propagateWeightChangesToModel_confirm():
'''
simply wraps the propagateWeightChangesToModel function with a confirmation dialog
'''
allMeshNodes = ls( type='mesh' )
allSkinnedMeshes = [ mesh for mesh in allMeshNodes if mel.findRelatedSkinCluster( mesh ) ]
if not allSkinnedMeshes:
printWarningStr( "No skinned meshes can be found in the scene! Aborting!" )
return
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
ret = confirmDialog( m='Are you sure you want to push skinning changes to the model?', t='Are you sure?', b=BUTTONS, db=CANCEL )
if ret == OK:
propagateWeightChangesToModel( allSkinnedMeshes )
#end
| Python |
import baseMelUI, visManager, api, skinCluster, presets, presetsUI
import maya.cmds as cmd
mel = api.mel
melecho = api.melecho
name = __name__
ui = None
class VisManagerUI(baseMelUI.BaseMelWindow):
WINDOW_NAME = "visManagerUI"
WINDOW_TITLE = 'vis set manager'
DEFAULT_SIZE = 254, 375
SPACER = " "
EXPANDED = "[-] "
COLLAPSED = "[+]"
def __init__( self ):
baseMelUI.BaseMelWindow.__init__( self )
mel.zooVisManUtils()
mel.zooVisInitialSetup()
api.mel.eval(r'''scriptJob -p %s -e "SceneOpened" "python(\"visManagerUI.ui.populate()\");";''' % self.WINDOW_NAME)
self.UI_form = cmd.formLayout(docTag=0)
self.UI_check_state = cmd.checkBox(v=self.state(), al="left", l="turn ON", cc=self.on_state_change)
self.UI_button_marks = cmd.button(l="bookmarks")
self.UI_tsl_sets = cmd.textScrollList(ams=1, dcc=self.on_collapse, nr=18, sc=self.on_select)
self.POP_marks = cmd.popupMenu(p=self.UI_button_marks, b=1, aob=1, pmc=self.popup_marks)
self.POP_marks_sh = cmd.popupMenu(p=self.UI_button_marks, sh=1, b=1, aob=1, pmc=self.popup_marks_add)
self.POP_sets = cmd.popupMenu(p=self.UI_tsl_sets, b=3, pmc=self.popup_sets)
self.reparentUI = None
cmd.formLayout(self.UI_form, e=True,
af=((self.UI_check_state, "top", 3),
(self.UI_check_state, "left", 3),
(self.UI_button_marks, "top", 0),
(self.UI_button_marks, "right", 0),
(self.UI_tsl_sets, "left", 0),
(self.UI_tsl_sets, "bottom", 0)),
ac=((self.UI_button_marks, "left", 5, self.UI_check_state),
(self.UI_tsl_sets, "top", 0, self.UI_button_marks)),
ap=((self.UI_tsl_sets, "right", 0, 100)) )
self.populate()
self.show()
def __del__( self ):
if self.reparentUI is not None:
if cmd.window(self.reparentUI, ex=True):
cmd.deleteUI(self.reparentUI)
def populate( self ):
sets = mel.zooVisManListHeirarchically()
cmd.textScrollList(self.UI_tsl_sets, e=True, ra=True)
while True:
try:
vset = sets.pop(0)
name = self.EXPANDED
childSets = mel.zooSetRelatives(vset, 0, 0, 1)
depth = len(mel.zooSetRelatives(vset, 0, 1, 1)) #count the number of parents to see how deep in the tree the set is
if not childSets: name = self.SPACER
if cmd.objExists("%s.isoCollapse" % vset):
#if this set is collapsed we need to remove all its children from the list and change the name prefix
name = self.COLLAPSED
for toRemove in childSets: sets.remove(toRemove)
name += self.SPACER * depth
name += vset
cmd.textScrollList(self.UI_tsl_sets, e=True, a=name)
except IndexError: break
self.updateSelection()
def updateSelection( self ):
'''
updates the tsl to reflect the sets that are currently active if any
'''
cmd.textScrollList(self.UI_tsl_sets, e=True, da=True)
displayNames = cmd.textScrollList(self.UI_tsl_sets, q=True, ai=True)
activeISOs = mel.zooVisManGetActiveSets()
toSelect = []
for iso in activeISOs:
for name in displayNames:
if name.rfind(iso) != -1:
toSelect.append(name)
break
for item in toSelect:
cmd.textScrollList(self.UI_tsl_sets, e=True, si=item)
def selection( self ):
selection = cmd.textScrollList(self.UI_tsl_sets, q=True, si=True)
if not selection: return []
clean = []
for s in selection:
idxName = s.rfind(' ')
if idxName == -1: clean.append(s)
else: clean.append(s[idxName+1:])
return clean
def state( self ):
return mel.zooVisManGetState()
def on_state_change( self, *args ):
mel.zooVisManSetVisState( cmd.checkBox(self.UI_check_state, q=True, v=True) )
def on_select( self, *args ):
mel.zooVisManSetActiveSets( self.selection() )
def on_collapse( self, *args ):
selSets = self.selection()
state = not mel.zooVisManGetCollapseState(selSets[0])
for s in selSets:
mel.zooVisManSetCollapseState(s, state)
self.populate()
def on_reparent( self, *args ):
self.reparentUI = ParentChooserUI( self.selection() )
def on_new( self, *args ):
parent = ''
try: parent = self.selection()[0]
except IndexError: pass
ret = cmd.promptDialog(t="new isoSet", message="set name", b=("OK", "Cancel"), db="OK")
text = cmd.promptDialog(q=True, tx=True)
if ret != "OK": return
if text == "": return
newSet = mel.zooVisManCreateSet(parent, text, cmd.ls(sl=True))
cmd.select(cl=True)
self.populate()
def on_delete( self, *args ):
for vset in self.selection():
if cmd.objExists(vset):
mel.zooVisManDeleteSet(vset)
self.populate()
def on_add( self, *args ):
mel.zooVisManAddToSet(self.selection(), cmd.ls(sl=True))
def on_remove( self, *args ):
mel.zooVisManRemFromSet(self.selection(), cmd.ls(sl=True))
def on_set_select( self, *args ):
mel.zooVisManSelectFrom(self.selection())
def on_joint_affected_faces( self, recursive=False ):
'''
'''
faces = []
selJoints = cmd.ls(sl=True, type='joint')
for j in selJoints:
faces += skinCluster.jointFacesForMaya(j, 0.1)
if recursive:
for j in cmd.listRelatives(selJoints, ad=True, type='joint'):
faces += skinCluster.jointFacesForMaya(j, 0.1)
mel.zooVisManAddToSet(self.selection(), faces)
def on_create_bookmark( self, *args ):
ans = cmd.promptDialog(m='', t='', b=('OK', 'Cancel'), db='OK')
if ans != 'OK': return
markName = cmd.promptDialog(q=True, tx=True)
mel.zooVisManCreateBookmark(markName, self.selection())
def on_activate_mark( self, markName, add ):
mel.zooVisManActivateBookmark(markName, add)
self.updateSelection()
def on_eazel( self, *args ):
curState = cmd.optionVar(q='zooVisManEazel') if cmd.optionVar(ex='zooVisManEazel') else True
cmd.optionVar(iv=('zooVisManEazel', not curState))
def popup_marks( self, parent, *args, **kwargs ):
cmd.setParent(parent, m=True)
cmd.menu(parent, e=True, dai=True)
add = kwargs.get('add', False )
marks = mel.zooVisManListBookmarks()
for mark in marks:
cmd.menuItem(l=mark, c=api.Callback(self.on_activate_mark, mark, add))
cmd.menuItem(d=1)
cmd.menuItem(l='create bookmark', c=self.on_create_bookmark)
def popup_marks_add( self, parent, *args ):
self.popup_marks(parent, add=True)
def popup_sets( self, parent, *args ):
cmd.setParent(parent, m=True)
cmd.menu(parent, e=True, dai=True)
items = self.selection()
addEazel = cmd.optionVar(q='zooVisManEazel') if cmd.optionVar(ex='zooVisManEazel') else True
enable = bool(items)
cmd.menuItem(en=enable, l="+ selection to vis set", c=self.on_add)
cmd.menuItem(en=enable, l="- selection from vis set", c=self.on_remove)
cmd.menuItem(en=enable, l="select items in vis set", c=self.on_set_select)
cmd.menuItem(en=enable, l="parent to...", c=self.on_reparent)
cmd.menuItem(d=True)
cmd.menuItem(l="new vis set", c=self.on_new)
cmd.menuItem(en=enable, l="remove vis set", c=self.on_delete)
cmd.menuItem(d=True)
cmd.menuItem(l="always show eazel", cb=addEazel, c=self.on_eazel)
cmd.menuItem(d=True)
cmd.menuItem(l="merge all sets (nasty hack)", c="mel.hackyMergeSets()")
cmd.menuItem(l="add faces affected by joint", c=self.on_joint_affected_faces)
cmd.menuItem(l="add faces affected by joint heirarchy", c=self.on_joint_affected_faces)
cmd.menuItem(d=True)
#build the preset list...
visPresets = presets.listAllPresets(visManager.TOOL_NAME, visManager.EXTENSION, True)
cmd.menuItem(l="build sets from preset", sm=True)
for locale, pList in visPresets.iteritems():
for p in pList:
cmd.menuItem(l=p.name(), c=api.Callback(self.import_preset, p.name(), locale, True, True))
cmd.setParent('..', m=True)
cmd.menuItem(l="import preset volumes", sm=True)
for locale, pList in visPresets.iteritems():
for p in pList:
cmd.menuItem(l=p.name(), c=api.Callback(self.import_preset, p.name(), locale, False, False))
cmd.setParent('..', m=True)
selected = cmd.ls(sl=True)
cmd.menuItem(en=len(selected)==1, l="export volume preset", c=self.export_preset)
cmd.menuItem(l="manage presets", c=lambda *x: presetsUI.load(visManager.TOOL_NAME, visManager.DEFAULT_LOCALE, visManager.EXTENSION))
cmd.menuItem(d=True)
cmd.menuItem(l='create sphere volume', c=lambda *x: assets.createExportVolume(assets.ExportManager.kVOLUME_SPHERE))
cmd.menuItem(l='create cube volume', c=lambda *x: assets.createExportVolume(assets.ExportManager.kVOLUME_CUBE))
def import_preset( self, presetName, locale, createSets, deleteVolumes ):
visManager.importPreset(presetName, locale, createSets, deleteVolumes)
self.populate()
def export_preset( self, *args ):
ans, name = api.doPrompt(t="volume preset name", m="enter a name for the volume preset", db=api.OK)
if ans != api.OK:
return
selected = cmd.ls(sl=True)
visManager.exportPreset(name, selected[0])
#now delete the vis volumes
cmd.delete(selected[0])
class ParentChooserUI(baseMelUI.BaseMelWindow):
WINDOW_NAME = "visManagerParentChooser"
WINDOW_TITLE = "vis set manager"
NO_PARENT = '--no parent--'
DEFAULT_SIZE = 180, 200
def __init__( self, setsToReparent ):
baseMelUI.BaseMelWindow.__init__( self )
allSets = set( mel.zooVisManListHeirarchically() )
allSets.difference_update( set(setsToReparent) )
self.UI_form = cmd.formLayout()
self.UI_tsl = cmd.textScrollList(ams=0, nr=18)
self.UI_button_parent = cmd.button(l="parent")
cmd.textScrollList(self.UI_tsl, e=True, dcc='%s.ui.reparentUI.on_done()' % name)
cmd.button(self.UI_button_parent, e=True, c='%s.ui.reparentUI.on_done()' % name)
#
cmd.textScrollList(self.UI_tsl, e=True, a=self.NO_PARENT)
for vset in allSets:
cmd.textScrollList(self.UI_tsl, e=True, a=vset)
cmd.formLayout(self.UI_form, e=True,
af=((self.UI_tsl, "top", 0),
(self.UI_tsl, "left", 0),
(self.UI_tsl, "right", 0),
(self.UI_button_parent, "left", 0),
(self.UI_button_parent, "right", 0),
(self.UI_button_parent, "bottom", 0)),
ac=((self.UI_tsl, "bottom", 0, self.UI_button_parent)) )
#select the no parent option
cmd.textScrollList(self.UI_tsl, e=True, si=self.NO_PARENT)
self.show()
def selection( self ):
sel = cmd.textScrollList(self.UI_tsl, q=True, si=True)
try: return sel[0]
except IndexError: return self.NO_PARENT
def on_done( self ):
sel = self.selection()
if sel == self.NO_PARENT: sel = ''
mel.zooVisManSetParent(ui.selection(), sel)
ui.populate()
cmd.deleteUI(self.WINDOW_NAME)
def load():
global ui
ui = VisManagerUI()
#end
| Python |
from baseRigPrimitive import *
HandSkeletonCls = SkeletonPart.GetNamedSubclass( 'Hand' )
FINGER_IDX_NAMES = HandSkeletonCls.FINGER_IDX_NAMES or ()
class Hand(PrimaryRigPart):
__version__ = 0
SKELETON_PRIM_ASSOC = ( HandSkeletonCls, )
CONTROL_NAMES = 'control', 'poses'
NAMED_NODE_NAMES = ( 'qss', )
ADD_CONTROLS_TO_QSS = False
def _build( self, skeletonPart, taper=0.8, **kw ):
return self.doBuild( skeletonPart.bases, taper=taper, **kw )
def doBuild( self, bases, wrist=None, num=0, names=FINGER_IDX_NAMES, taper=0.8, **kw ):
if wrist is None:
wrist = getNodeParent( bases[ 0 ] )
scale = kw[ 'scale' ]
idx = kw[ 'idx' ]
parity = Parity( idx )
colour = ColourDesc( 'orange' )
suffix = parity.asName()
#parityMult = parity.asMultiplier()
parityMult = 1.0 # no parity flip on controls
partParent, rootControl = getParentAndRootControl( bases[ 0 ] )
minSlider = -90
maxSlider = 90
minFingerRot = -45 #rotation at minimum slider value
maxFingerRot = 90 #rotation at maxiumum slider value
#get the bounds of the geo skinned to the hand and use it to determine default placement of the slider control
bounds = getJointBounds( [ wrist ] + bases )
backwardAxis = getObjectAxisInDirection( wrist, Vector( (0, 0, -1) ) )
dist = bounds[ not backwardAxis.isNegative() ][ backwardAxis % 3 ]
#build the main hand group, and the slider control for the fingers
handSliders = buildControl( "hand_sliders"+ suffix, wrist, shapeDesc=ShapeDesc( None, 'pointer', backwardAxis ), constrain=False, colour=colour, offset=(0, 0, dist*1.25), scale=scale*1.25 )
poseCurve = buildControl( "hand_poses"+ suffix, handSliders, shapeDesc=ShapeDesc( None, 'starCircle', AX_Y ), oriented=False, constrain=False, colour=colour, parent=handSliders, scale=scale )
handQss = sets( empty=True, text="gCharacterSet", n="hand_ctrls"+ suffix )
handGrp = getNodeParent( handSliders )
poseCurveTrigger = Trigger( poseCurve )
setAttr( '%s.v' % poseCurve, False )
#constrain the group to the wrist
parentConstraint( wrist, handGrp )
parent( handGrp, partParent )
attrState( (handSliders, poseCurve), ('t', 'r'), *LOCK_HIDE )
addAttr( poseCurve, ln='controlObject', at='message' ) #build the attribute so posesToSliders knows where to write the pose sliders to when poses are rebuilt
connectAttr( '%s.message' % handSliders, '%s.controlObject' % poseCurve )
#now start building the controls
allCtrls = [ handSliders, poseCurve ]
allSpaces = []
allConstraints = []
baseControls = []
baseSpaces = []
slider_curl = []
slider_bend = []
for n, base in enumerate( bases ):
#discover the list of joints under the current base
name = names[ n ]
if not num: num = 100
joints = [ base ]
for i in range( num ):
children = listRelatives( joints[ -1 ], type='joint' )
if not children: break
joints.append( children[ 0 ] )
num = len( joints )
#build the controls
ctrls = []
startColour = ColourDesc( (1, 0.3, 0, 0.65) )
endColour = ColourDesc( (0.8, 1, 0, 0.65) )
colour = startColour
colourInc = (endColour - startColour)
iColor = 1
if len( joints ) > 1:
colourInc /= len( joints ) - 1
for i, j in enumerate( joints ):
ctrlScale = ( scale / 3.5 ) * (taper ** i)
c = buildControl( "%sControl_%d%s" % (name, i, suffix), j, shapeDesc=ShapeDesc( 'sphere', 'ring', axis=AIM_AXIS ), colour=colour, parent=handGrp, scale=ctrlScale, qss=handQss )
#setAttr( '%s.v' % c, False ) #hidden by default
cParent = getNodeParent( c )
colours.setDrawOverrideColor( c, (23 + iColor) )
cmd.color( c, ud=iColor )
iColor += 1
if iColor > 8:
iColor = 1
colour += colourInc
if i:
parent( cParent, ctrls[ -1 ] )
ctrls.append( c )
poseCurveTrigger.connect( getNodeParent( c ) )
allCtrls += ctrls
###------
###CURL SLIDERS
###------
driverAttr = name +"Curl"
addAttr( handSliders, ln=driverAttr, k=True, at='double', min=minSlider, max=maxSlider, dv=0 )
driverAttr = '%s.%s' % (handSliders, driverAttr)
setAttr( driverAttr, keyable=True )
spaces = [ getNodeParent( c ) for c in ctrls ]
for s in spaces:
setDrivenKeyframe( '%s.r' % s, cd=driverAttr )
setAttr( driverAttr, maxSlider )
for s in spaces:
rotate( 0, maxFingerRot * parityMult, 0, s, r=True, os=True )
setDrivenKeyframe( '%s.r' % s, cd=driverAttr )
setAttr( driverAttr, minSlider )
for s in spaces:
rotate( 0, minFingerRot * parityMult, 0, s, r=True, os=True )
setDrivenKeyframe( '%s.r' % s, cd=driverAttr )
setAttr( driverAttr, 0 )
slider_curl.append( driverAttr )
###------
###BEND SLIDERS
###------
driverAttr = name +"Bend"
addAttr( handSliders, ln=driverAttr, k=True, at='double', min=minSlider, max=maxSlider, dv=0 )
driverAttr = '%s.%s' % (handSliders, driverAttr)
setAttr( driverAttr, keyable=True )
baseCtrlSpace = spaces[ 0 ]
setDrivenKeyframe( '%s.r' % baseCtrlSpace, cd=driverAttr )
setAttr( driverAttr, maxSlider )
rotate( 0, maxFingerRot * parityMult, 0, baseCtrlSpace, r=True, os=True )
setDrivenKeyframe( '%s.r' % baseCtrlSpace, cd=driverAttr )
setAttr( driverAttr, minSlider )
rotate( 0, minFingerRot * parityMult, 0, baseCtrlSpace, r=True, os=True )
setDrivenKeyframe( '%s.r' % baseCtrlSpace, cd=driverAttr )
setAttr( driverAttr, 0 )
slider_bend.append( driverAttr )
##reorder the finger sliders
#attrOrder = [ attrpath.split( '.' )[1] for attrpath in slider_curl + slider_bend ]
#reorderAttrs( handSliders, attrOrder )
#add toggle finger control vis
handSlidersTrigger = Trigger( handSliders )
qssIdx = handSlidersTrigger.connect( handQss )
handSlidersTrigger.createMenu( 'Toggle Finger Controls',
'string $objs[] = `sets -q %%%d`;\nint $vis = !getAttr( $objs[0] +".v" );\nfor( $o in $objs ) setAttr( $o +".v", $vis );' % qssIdx )
return allCtrls, [handQss]
#end
| Python |
try:
import wingdbstub
except ImportError: pass
from baseMelUI import *
from maya.cmds import *
from common import printWarningStr
#this dict stores attribute values for the selection - attributeChange scriptjobs fire when an attribute changes
#but don't pass in pre/post values, or even the name of the attribute that has changed. So when the scriptjobs
#are first setup, their attribute values are stored in this dict and are updated when they change
PRE_ATTR_VALUES = {}
class AttrpathCallback(object):
'''
callable object that gets executed when the value of the attrpath changes
'''
#defines whether the instance should early out when called or not
ENABLED = True
def __init__( self, ui, attrpath ):
self.ui = ui
self.attrpath = attrpath
#setup the initial value of the attrpath in the global attr value dict
time = currentTime( q=True )
PRE_ATTR_VALUES[ attrpath ] = getAttr( attrpath )
def __call__( self ):
if not self.ENABLED:
return
#if autokey is turned on, bail - this + autokey = potentially weird behaviour
#NOTE: the tool will turn autokey off automatically when loaded - so if its on, its because the user has turned it back on. Also
#worth noting - this tool will restore the initial autokey state when closed/turned off...
if autoKeyframe( q=True ):
printWarningStr( "Autokey is enabled - This tool doesn't play nice with autokey! Please turn it off!" )
return
#if there are no entries in here - bail, they've already been handled
if not PRE_ATTR_VALUES:
return
#put the following into a single undo chunk
try:
undoInfo( openChunk=True )
for attrpath, preValue in PRE_ATTR_VALUES.iteritems():
curValue = getAttr( attrpath )
valueDelta = curValue - preValue
#if there was no delta, keep loopin
if not valueDelta:
continue
#if there are no keyframes on this attribute - keep loopin
if not keyframe( attrpath, q=True, kc=True ):
continue
keyframe( attrpath, e=True, t=(), vc=valueDelta, relative=True )
PRE_ATTR_VALUES.clear()
finally:
undoInfo( closeChunk=True )
#setup an idle event to re-populate the PRE_ATTR_VALUES dict when everything has finished processing
scriptJob( runOnce=True, idleEvent=self.ui.on_selectionChange )
class PosePropagatorLayout(MelHLayout):
def __init__( self, parent ):
MelHLayout.__init__( self, parent )
self._initialAutoKeyState = autoKeyframe( q=True, state=True )
self.UI_dummyParent = None #this is some dummy UI to store attribute change scriptjobs - this easily ensures things get teared down if the tool gets closed
self.UI_on = MelButton( self, h=100, c=self.on_toggleEnable )
self.layout()
self.updateState()
#fire the selection change to update the current selection state
self.on_selectionChange()
self.setSceneChangeCB( self.on_selectionChange )
self.setSelectionChangeCB( self.on_selectionChange )
self.setTimeChangeCB( self.on_timeChange )
self.setDeletionCB( self.on_delete )
def setEnableState( self, state=True ):
'''
sets the on/off state of the tool and updates UI accordingly
'''
#we need to disable autokey when running this tool - but we want to restore the initial autokey state when
#the tool is either turned off or closed, so we need to store the initial auto key state on the instance
if state:
self._initialAutoKeyState = autoKeyframe( q=True, state=True )
autoKeyframe( e=True, state=False )
else:
autoKeyframe( e=True, state=self._initialAutoKeyState )
AttrpathCallback.ENABLED = state
self.updateState()
def updateState( self ):
self.UI_on.setLabel( 'currently on: turn OFF' if AttrpathCallback.ENABLED else 'turn ON' )
self.UI_on.setColour( (1, 0, 0) if AttrpathCallback.ENABLED else (0.6, 0.6, 0.6) )
### EVENT HANDLERS ###
def on_toggleEnable( self, *a ):
self.setEnableState( not AttrpathCallback.ENABLED )
def on_enable( self, *a ):
self.setEnableState( True )
def on_disable( self, *a ):
self.setEnableState( False )
def on_sceneChange( self ):
'''
turn the tool off, and update state
'''
self.setEnableState( False )
self.on_selectionChange()
def on_selectionChange( self ):
'''
delete the old attribute change callbacks and add new ones for the current selection
'''
if self.UI_dummyParent is not None:
self.UI_dummyParent.delete()
PRE_ATTR_VALUES.clear()
#create a dummy piece of UI to "hold" on to the scriptjobs
self.UI_dummyParent = UI_dummyParent = MelButton( self, l='', w=1, h=1, vis=False )
for obj in ls( sl=True ):
for attr in listAttr( obj, keyable=True ):
attrpath = '%s.%s' % (obj, attr)
if objExists( attrpath ):
UI_dummyParent.setAttributeChangeCB( attrpath, AttrpathCallback( self, attrpath ), False )
def on_timeChange( self ):
'''
when the time changes we need to refresh the values in the PRE_ATTR_VALUES dict
'''
time = currentTime( q=True )
PRE_ATTR_VALUES.clear()
for attrpath in PRE_ATTR_VALUES.keys():
PRE_ATTR_VALUES[ attrpath ] = getAttr( attrpath )
def on_delete( self ):
autoKeyframe( e=True, state=self._initialAutoKeyState )
class PosePropagatorWindow(BaseMelWindow):
WINDOW_NAME = 'posePropagatorWindow'
WINDOW_TITLE = 'Pose Propagator'
DEFAULT_MENU = None
DEFAULT_SIZE = 275, 140
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.UI_editor = PosePropagatorLayout( self )
self.UI_editor.setEnableState( AttrpathCallback.ENABLED )
self.show()
#end
| Python |
from maya.cmds import *
from baseMelUI import *
from mayaDecorators import d_disableViews, d_noAutoKey, d_unifyUndo
from common import printWarningStr
@d_unifyUndo
@d_disableViews
@d_noAutoKey
def changeParent( parent=0, objs=None ):
if objs is None:
objs = ls( sl=True, type='transform' ) or []
#only bother with objects that have a "parent" attribute and whose parent attribute value is not the same as the one we've been passed
objsToActOn = []
for obj in objs:
if objExists( '%s.parent' % obj ):
objsToActOn.append( obj )
objs = objsToActOn
#if there are no objects, bail
if not objs:
printWarningStr( "There are no objects to work on - aborting!" )
return
#store the initial time so we can restore it at the end
initialTime = currentTime( q=True )
#first we need to make sure that any frame with a rotation key needs to have a key on ALL rotation axes - so make this happen
keyTimes = keyframe( objs, q=True, at=('t', 'r'), tc=True )
if not keyTimes:
printWarningStr( "No keys found on the objects - nothing to do!" )
return
#remove duplicate key times and sort them
keyTimes = removeDupes( keyTimes )
keyTimes.sort()
#store the objects that each have keys at each key time in a dict so we don't have to query maya again. maya queries are slower than accessing python data structures
timeObjs = {}
for time in keyTimes:
currentTime( time, e=True )
timeObjs[ time ] = objsWithKeysAtThisTime = []
for obj in objs:
keyOnCurrentTime = keyframe( obj, q=True, t=(time,), at=('parent', 't', 'r'), kc=True )
if keyOnCurrentTime:
setKeyframe( obj, at=('parent', 't', 'r') )
objsWithKeysAtThisTime.append( obj )
#now that we've secured the translation/rotation poses with keys on all axes, change the parent on each keyframe
for time, objsWithKeysAtThisTime in timeObjs.iteritems():
currentTime( time, e=True )
for obj in objsWithKeysAtThisTime:
pos = xform( obj, q=True, rp=True, ws=True )
rot = xform( obj, q=True, ro=True, ws=True )
#change the parent and move/rotate back to the original world space pose
setAttr( '%s.parent' % obj, parent )
move( pos[0], pos[1], pos[2], obj, ws=True, rpr=True )
rotate( rot[0], rot[1], rot[2], obj, ws=True )
#lock in the pose
setKeyframe( obj, at=('parent', 't', 'r') )
#finally restore the initial time
currentTime( initialTime, e=True )
class ChangeParentLayout(MelColumnLayout):
def __init__( self, parent ):
hLayout = MelHSingleStretchLayout( self )
lbl = MelLabel( hLayout, l='New Parent' )
self.UI_parent = MelOptionMenu( hLayout )
hLayout.setStretchWidget( self.UI_parent )
hLayout.layout()
hLayout( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) )
self.UI_go = MelButton( self, l='Change Parent', c=self.on_go )
self.on_selectionChange()
self.setSelectionChangeCB( self.on_selectionChange )
### EVENT HANDLERS ###
def on_selectionChange( self, *a ):
self.UI_parent.clear()
#populate the parent list - just use the parents from the first object found with a parent attribute
for obj in ls( sl=True, type='transform' ) or []:
if objExists( '%s.parent' % obj ):
curValue = getAttr( '%s.parent' % obj )
enumStr = addAttr( '%s.parent' % obj, q=True, enumName=True )
enums = enumStr.split( ':' )
for enum in enums:
self.UI_parent.append( enum )
if enums:
self.UI_parent.selectByIdx( curValue )
self.UI_go.enable( True )
return
#if we've made it here, there are no objects with a parent attribute, or no objects with parents - either way disable the go button
self.UI_go.enable( False )
def on_go( self, *a ):
changeParent( self.UI_parent.getSelectedIdx() )
class ChangeParentWindow(BaseMelWindow):
WINDOW_NAME = 'changeParent'
WINDOW_TITLE = 'Change Parent Tool'
DEFAULT_MENU = None
DEFAULT_SIZE = 245, 85
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.UI_editor = ChangeParentLayout( self )
self.show()
#end
| Python |
from baseRigPrimitive import *
from skeletonPart_arbitraryChain import ArbitraryChain
class ControlHierarchy(PrimaryRigPart):
__version__ = 0
#part doesn't have a CONTROL_NAMES list because parts are dynamic - use indices to refer to controls
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'ArbitraryChain' ), )
def _build( self, part, controlShape=DEFAULT_SHAPE_DESC, spaceSwitchTranslation=False, parents=(), rigOrphans=False, **kw ):
joints = list( part ) + (part.getOrphanJoints() if rigOrphans else [])
return controlChain( self, joints, controlShape, spaceSwitchTranslation, parents, rigOrphans, **kw ), ()
class WeaponControlHierarchy(PrimaryRigPart):
__version__ = 0
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'WeaponRoot' ), )
def _build( self, part, controlShape=DEFAULT_SHAPE_DESC, spaceSwitchTranslation=True, parents=(), **kw ):
return controlChain( self, part.selfAndOrphans(), controlShape, spaceSwitchTranslation, parents, True, **kw ), ()
def controlChain( rigPart, joints, controlShape=DEFAULT_SHAPE_DESC, spaceSwitchTranslation=False, parents=(), rigOrphans=False, **kw ):
scale = kw[ 'scale' ]
#discover parent nodes
namespace = ''
try:
namespace = getNamespaceFromReferencing( joints[ 0 ] )
except IndexError: pass
parents = tuple( '%s%s' % (namespace, p) for p in parents )
### DETERMINE THE PART'S PARENT CONTROL AND THE ROOT CONTROL ###
parentControl, rootControl = getParentAndRootControl( joints[ 0 ] )
ctrls = []
prevParent = parentControl
for item in joints:
ctrl = buildControl( '%s_ctrl' % item, item, PivotModeDesc.BASE, controlShape, size=AUTO_SIZE )
ctrlSpace = getNodeParent( ctrl )
#do parenting
parent( ctrlSpace, prevParent )
#stuff objects into appropriate variables
prevParent = ctrl
ctrls.append( ctrl )
#lock un-needed axes
if not spaceSwitchTranslation:
attrState( ctrl, 't', *LOCK_HIDE )
#setup space switching
buildKwargs = {} if spaceSwitchTranslation else spaceSwitching.NO_TRANSLATION
for n, (ctrl, j) in enumerate( zip( ctrls, joints ) ):
buildDefaultSpaceSwitching( j, ctrl, parents, reverseHierarchy=False, **buildKwargs )
createLineOfActionMenu( joints, ctrls )
return ctrls
#end
| Python |
from maya.cmds import *
from devTest_base import d_makeNewScene, _BaseTest
import skeletonBuilder
import skeletonBuilderUI
import rigPrimitives
__all__ = [ 'TestSkeletonBuilder' ]
#PERFORM_RELOAD = False
SkeletonPart = skeletonBuilder.SkeletonPart
Root = SkeletonPart.GetNamedSubclass( 'Root' )
Spine = SkeletonPart.GetNamedSubclass( 'Spine' )
Head = SkeletonPart.GetNamedSubclass( 'Head' )
Arm = SkeletonPart.GetNamedSubclass( 'Arm' )
Hand = SkeletonPart.GetNamedSubclass( 'Hand' )
Leg = SkeletonPart.GetNamedSubclass( 'Leg' )
QuadrupedFrontLeg = SkeletonPart.GetNamedSubclass( 'QuadrupedFrontLeg' )
ArbitraryChain = SkeletonPart.GetNamedSubclass( 'ArbitraryChain' )
ArbitraryParityChain = SkeletonPart.GetNamedSubclass( 'ArbitraryParityChain' )
class TestSkeletonBuilder(_BaseTest):
def runTest( self ):
self.testUberSkeleton()
self.testUberSkeletonAndReferencing()
self.testUI()
def _buildTestSkeleton( self ):
allPartClasses = [ part for part in SkeletonPart.GetSubclasses() if part.AVAILABLE_IN_UI ]
#now remove the ones we're going to create manually
for part in (Root, Spine, Head, Arm, Leg):
allPartClasses.remove( part )
scale = 100
root = Root.Create( partScale=scale )
theSpine = Spine.Create( root, 5, partScale=scale )
theHead = Head.Create( theSpine.end, 2, partScale=scale )
armL = Arm.Create( theSpine.end, partScale=scale )
armR = Arm.Create( theSpine.end, partScale=scale )
legL = Leg.Create( root, partScale=scale )
legR = Leg.Create( root, partScale=scale )
armL.driveOtherPart( armR )
legL.driveOtherPart( legR )
handL = Hand.Create( armL.wrist )
handR = Hand.Create( armR.wrist )
quadSpine = ArbitraryChain.Create( root, 'quadSpine', 6, '-z' )
ArbitraryChain.Create( theHead.end, 'hair1', 3, 'x' )
ArbitraryChain.Create( theHead.end, 'hair2', 3, '-x' )
backlegA = QuadrupedFrontLeg.Create( quadSpine[-1] )
backlegB = QuadrupedFrontLeg.Create( quadSpine[-1] )
quadSpine = ArbitraryChain.Create( quadSpine[-1], 'tail', 4, '-z' )
#make sure skeleton builder can now enumerate the parts it just created
partsCreated = list( SkeletonPart.IterAllParts() )
assert len( partsCreated ) == 15, "Iterating over parts just created failed!"
def testUberSkeleton( self ):
'''
Test that a simple scene gets setup and exports properly
'''
self.new()
self._buildTestSkeleton()
skeletonBuilder.finalizeAllParts()
rigPrimitives.buildRigForAllParts() #build the rig within the current scene
@d_makeNewScene( 'testUberSkeleton_mesh' )
def testUberSkeletonAndReferencing( self ):
'''
Test that a simple scene gets setup and exports properly
'''
self._buildTestSkeleton()
rigScene = rigPrimitives.buildRigForModel() #build the model in a referenced scene
assert rigScene.exists(), "Cannot find the rig scene!"
rigScene.delete()
def testUI( self ):
'''
Test that a simple scene gets setup and exports properly
'''
self.new()
self._buildTestSkeleton()
#test the UI - make sure it loads and doesn't error with the built skeleton in the scene
ui = skeletonBuilderUI.SkeletonBuilderUI()
tabs = skeletonBuilderUI.CreateEditRigTabLayout.IterInstances().next()
#walk through the tabs
for n in range( len( tabs ) ):
tabs.setSelectedTabIdx( n )
#end
| Python |
from vectors import *
from filesystem import Path, resolvePath, writeExportDict
import time, datetime, names, filesystem
TOOL_NAME = 'weightSaver'
TOOL_VERSION = 2
DEFAULT_PATH = Path('%TEMP%/temp_skin.weights')
TOL = 0.25
EXTENSION = 'weights'
_MAX_RECURSE = 35
class SkinWeightException(Exception): pass
class NoVertFound(Exception): pass
class VertSkinWeight(Vector):
'''
extends Vector to store a vert's joint list, weightlist and id
'''
#can be used to store a dictionary so mesh names can be substituted at restore time when restoring by id
MESH_NAME_REMAP_DICT = None
#can be used to store a dictionary so joint names can be substituted at restore time
JOINT_NAME_REMAP_DICT = None
def __str__( self ):
return '<%0.3f, %0.3f, %0.3f> %s' % (self[ 0 ], self[ 1 ], self[ 2 ], ', '.join( '%s: %0.2f' % d for d in zip( self.joints, self.weights ) ))
__repr__ = __str__
def populate( self, meshName, vertIdx, jointList, weightList ):
self.idx = vertIdx
self.weights = tuple( weightList ) #convert to tuple to protect it from changing accidentally...
self.__mesh = meshName
self.__joints = tuple( jointList )
@property
def mesh( self ):
'''
If a MESH_NAME_REMAP Mapping object is present, the mesh name is re-mapped accordingly,
otherwise the stored mesh name is returned.
'''
if self.MESH_NAME_REMAP_DICT is None:
return self.__mesh
return self.MESH_NAME_REMAP_DICT.get( self.__mesh, self.__mesh )
@property
def joints( self ):
'''
Returns the list of joints the vert is skinned to. If a JOINT_NAME_REMAP Mapping object is
present, names are re-mapped accordingly.
'''
jointRemap = self.JOINT_NAME_REMAP_DICT
if jointRemap is None:
return self.__joints
joints = [ jointRemap.get( j, j ) for j in self.__joints ]
if len( joints ) != set( joints ):
joints, self.weights = regatherWeights( joints, self.weights )
return joints
def getVertName( self ):
return '%s.%d' % (self.mesh, self.idx)
class MayaVertSkinWeight(VertSkinWeight):
'''
NOTE: this class needs to be defined in this file otherwise weight files saved from maya will be
unavailable to external tools like modelpipeline because the maya scripts are invisible outside
of maya. When unpickling objects - python needs to know what module to find the object's class
in, so if that module is unavailable, a pickleException is raised when loading the file.
'''
def getVertName( self ):
return '%s.vtx[%d]' % (self.mesh, self.idx)
class WeightSaveData(tuple):
def __init__( self, data ):
self.miscData, self.joints, self.jointHierarchies, self.weightData = data
def getUsedJoints( self ):
allJoints = set()
for jData in self.weightData:
allJoints |= set( jData.joints )
return allJoints
def getUsedMeshes( self ):
allMeshes = set()
for d in self.weightData:
allMeshes.add( d.mesh )
return allMeshes
def getUsedJoints( filepath ):
return WeightSaveData( filepath.unpickle() ).getUsedJoints()
def regatherWeights( actualJointNames, weightList ):
'''
re-gathers weights. when joints are re-mapped (when the original joint can't be found) there is
the potential for joints to be present multiple times in the jointList - in this case, weights
need to be summed for the duplicate joints otherwise maya doesn't weight the vert properly (dupes
just get ignored)
'''
new = {}
[ new.setdefault(j, 0) for j in actualJointNames ]
for j, w in zip( actualJointNames, weightList ):
new[ j ] += w
return new.keys(), new.values()
#end
| Python |
parityTestsL = ["l", "left", "lft", "lf", "lik"]
parityTestsR = ["r", "right", "rgt", "rt", "rik"]
DEFAULT_THRESHOLD = 1
class Parity(int):
PARITIES = NONE, LEFT, RIGHT = None, 0, 1
#odd indices are left sided, even are right sided
NAMES = [ '_L', '_R',
'_A_L', '_A_R',
'_B_L', '_B_R',
'_C_L', '_C_R',
'_D_L', '_D_R' ]
def __new__( cls, idx ):
return int.__new__( cls, idx )
def __eq__( self, other ):
if other is None:
return False
return self % 2 == int( other ) % 2
def __nonzero__( self ):
return self % 2
def __ne__( self, other ):
return not self.__eq__( other )
def asMultiplier( self ):
return (-1) ** self
def asName( self ):
return self.NAMES[ self ]
def isOpposite( self, other ):
return (self % 2) != (other % 2)
Parity.LEFT, Parity.RIGHT = Parity( Parity.LEFT ), Parity( Parity.RIGHT )
class Name(object):
'''
Name objects are strings that are used to identify something such as an object or a filepath.
this class creates some useful ways of comparing and manipulating Name objects
'''
PREFIX_DELIMETERS = ':|'
PUNCTUATION = '_. '
def __init__( self, nameItem='' ):
#NOTE: this value should never be set directly... instead use the set method or the string property
self._string = str( nameItem )
self.item = nameItem
self.prefix = None
#determines what characters denote a prefix boundary - so if it were set to ':' then apples:bananas would have the string 'apples:' as its prefix
self.prefixDelimeters = self.PREFIX_DELIMETERS
self.punctuation = self.PUNCTUATION
def __str__( self ):
return self._string
__repr__ = __str__
def __eq__( self, other ):
return int( self.likeness( other ) )
def __ne__( self, other ):
return not self.__eq__( other )
def __getitem__( self, item ):
return self.split()[item]
def __setitem__( self, item, newItem ):
token = self[ item ]
nameStr = str( self )
startIdx = nameStr.find( token )
endIdx = startIdx + len( token )
#splice together a new string and we're done...
self._string = '%s%s%s' % ( nameStr[:startIdx], newItem, nameStr[endIdx:] )
def pop( self, item, stripSurroundingPunctuation=True ):
PUNCTUATION = self.PUNCTUATION
token = self[ item ]
nameStr = str( self )
startIdx = nameStr.find( token )
endIdx = startIdx + len( token )
'''
#now strip surrounding whitespace or punctuation
if stripSurroundingPunctuation:
puncEndOffset = 0
hasEndPunc = False
for char in nameStr[ endIdx: ]:
if char in PUNCTUATION:
puncEndOffset += 1
hasEndPunc = True
else: break
reversedStartChunk = ''.join( reversed( list( nameStr[ :startIdx ] ) ) )
puncStartOffset = 0
hasStartPunc = False
for char in reversedStartChunk:
if char in PUNCTUATION:
puncStartOffset -= 1
hasStartPunc = True
else: break
if hasStartPunc and hasEndPunc:
startIdx -= max( 0, puncStartOffset )
endIdx += puncEndOffset
'''
newNameStr = '%s%s' % ( nameStr[:startIdx], nameStr[endIdx:] )
removeStart = startIdx
#for n, char in enumerate( newNameStr[ startIdx: ] ):
#splice together a new string and we're done...
self._string = '%s%s' % ( nameStr[:startIdx], nameStr[endIdx:] )
def __nonzero__( self ):
try:
self._string[0]
return True
except IndexError: return False
def set( self, newString ):
self._string = newString
string = property(__str__, set)
def get_parity( self ):
'''
doing this comparison is a little faster than using the cache lookup - and parity gets hammered on in likeness determination
'''
try: return self._parity
except AttributeError:
self._parity, self._parityStr = hasParity( self.split() )
return self._parity
parity = property( get_parity )
def strip_parity( self ):
return str( stripParity( self ) )
def swap_parity( self ):
return self.__class__( swapParity(self) )
def cache_prefix( self, delimeters=None ):
'''strips any namespace or path data from the name string - by default the stripping is done
"in place", but if the inPlace variable is set to true, then a new Name object is returned'''
self.prefix = ''
string = self._string.strip()
lastMatch = -1
if delimeters is None:
delimeters = self.prefixDelimeters
for char in delimeters:
matchPos = string.rfind(char)
if matchPos > lastMatch:
lastMatch = matchPos
#store the prefix string
if lastMatch != -1:
self.prefix = string[:lastMatch+1]
self._string = string[lastMatch+1:]
return self.prefix
def uncache_prefix( self ):
if self.prefix != None:
self._string = self.prefix + self._string
return self._string
def get_prefix( self, delimeters=None ):
'''strips any namespace or path data from the name string - by default the stripping is done
"in place", but if the inPlace variable is set to true, then a new Name object is returned'''
if self.prefix is None:
return self.cache_prefix( delimeters )
else: return self.prefix
def likeness( self, other, parityMatters=False, stripFirst=True ):
'''
given two Name objects this method will return a "likeness" factor based on how similar
the two name strings are. it compares name tokens - tokens are defined by either camel case
or any character defined in the self.punctuation variable. so for example:
thisStringHas_a_fewTokens
has the tokens: this, String, Has, a, few, Tokens
given two names, the more tokens that match, the higher the likeness. the tokens don't have
to match exactly - a few tests are done such as case difference, subset test and numeric comparison
'''
#do stripping if required
#if stripFirst: self.cache_prefix()
#if the names match exactly, return the highest likeness
if str(self) == str(other): return 1
srcTokens = self.split()[:]
tgtTokens = other.split()[:]
if parityMatters:
if self.parity != other.parity:
return 0
#if the split result is exact, early out
if srcTokens == tgtTokens: return 1
exactMatchWeight = 1.025
totalWeight = 0
numSrcToks, numTgtToks = len(srcTokens), len(tgtTokens)
for srcTok in srcTokens:
bestMatch,bestMatchIdx = 0,-1
isSrcDigit = srcTok.isdigit()
for n,tgtTok in enumerate(tgtTokens):
tokSize = len(tgtTok)
isTgtDigit = tgtTok.isdigit()
#if one is a number token and the other isn't - there is no point proceeding as they're not going to match
#letter tokens should not match number tokens - i guess it would be possible to test whether the word token
#was a number name, but this would be expensive, and would only help fringe cases
if isSrcDigit != isTgtDigit:
continue
#first, check to see if the names are the same
if srcTok == tgtTok:
bestMatch = tokSize * exactMatchWeight
bestMatchIdx = n
break
#are the tokens numeric tokens? if so, we need to figure out how similar they are numerically - numbers that are closer to one another should result in a better match
elif isSrcDigit and isTgtDigit:
srcInt,tgtInt = int(srcTok),int(tgtTok)
largest = max( abs(srcInt), abs(tgtInt) )
closeness = 1
if srcInt != tgtInt: closeness = ( largest - abs( srcInt-tgtInt ) ) / float(largest)
bestMatch = tokSize * closeness
bestMatchIdx = n
break
#are the names the same bar case differences?
elif srcTok.lower() == tgtTok.lower():
bestMatch = tokSize
bestMatchIdx = n
break
#so now test to see if any of the tokens are "sub-words" of each other - ie if you have something_otherthing an_other
#the second token, "otherthing" and "other", the second is a subset of the first, so this is a rough match
else:
srcTokSize = len(srcTok)
lowSrcTok,lowTgtTok = srcTok.lower(),tgtTok.lower()
smallestWordSize = min( srcTokSize, tokSize )
subWordWeight = 0
#the weight is calculated as a percentage of matched letters
if srcTokSize > tokSize: subWordWeight = tokSize * tokSize / float(srcTokSize)
else: subWordWeight = srcTokSize * srcTokSize / float(tokSize)
if srcTokSize > 2 and tokSize > 2:
#make sure the src and tgt tokens are non-trivial (ie at least 3 letters)
if lowSrcTok.find(lowTgtTok) != -1 or lowTgtTok.find(lowSrcTok) != -1:
bestMatch = subWordWeight
bestMatchIdx = n
#remove the best match from the list - so it doesn't get matched to any other tokens
if bestMatchIdx != -1:
tgtTokens.pop(bestMatchIdx)
numTgtToks -= 1
totalWeight += bestMatch
#get the total number of letters in the "words" of the longest name - we use this for a likeness baseline
lenCleanSrc = len(self._string)-self._string.count('_')
lenCleanTgt = len(other._string)-other._string.count('_')
#lenCleanSrc = len(''.join(self.split()))
#lenCleanTgt = len(''.join(other.split()))
lenClean = max( lenCleanSrc, lenCleanTgt )
return totalWeight / ( lenClean*exactMatchWeight )
def strip( self, inPlace=True ):
'''strips any namespace or path data from the name string - by default the stripping is done
"in place", but if the inPlace variable is set to false, then a new Name object is returned'''
string = self._string.strip()
for char in self.prefixDelimeters:
lastMatch = string.rfind(char)
if lastMatch != -1:
string = string[lastMatch+1:]
#if we're to perform the operation in place, then modify the self._string variable and return
if inPlace:
self._string = string
return self
return self.__class__( string )
def split( self, aString=None ):
'''
retuns a list of name tokens. tokens are delimited by either camel case separation,
digit grouping, or any character present in the self.punctuation variable - the list of
tokens is returned
'''
if aString is None:
aString = self._string
try:
tokens = [aString[0]]
except IndexError: return []
prevCharCaseWasLower = aString[0].islower()
prevCharWasDigit = aString[0].isdigit()
#step through the string and look for token split cases
for char in aString[1:]:
isLower = char.islower()
if char in self.punctuation:
tokens.append('')
prevCharCaseWasLower = True
prevCharWasDigit = False
continue
if char.isdigit():
if prevCharWasDigit: tokens[-1] += char
else: tokens.append(char)
prevCharCaseWasLower = True
prevCharWasDigit = True
continue
if prevCharWasDigit:
tokens.append(char)
prevCharWasDigit = False
prevCharCaseWasLower = isLower
continue
elif prevCharCaseWasLower and not isLower: tokens.append(char)
else: tokens[-1] += char
prevCharWasDigit = False
prevCharCaseWasLower = isLower
#finally get rid of any empty/null array entries - this could be done above but is easier (maybe even faster?) to do as a post step
return [tok for tok in tokens if tok ]
def redo_split( self, aString=None ):
#forces a rebuild of the token cache
return self.split()
def hasParity( nameToks, popParityToken=True ):
'''
returns a parity number for a given name. parity is 0 for none, 1 for left, and 2 for right
'''
lowerToks = [ tok.lower() for tok in nameToks ]
lowerToksSet = set( lowerToks )
existingParityToksL = lowerToksSet.intersection( set( parityTestsL ) )
if len( existingParityToksL ):
parityStr = existingParityToksL.pop()
if popParityToken:
idx = lowerToks.index( parityStr )
nameToks.pop( idx )
return Parity.LEFT, parityStr
existingParityToksR = lowerToksSet.intersection( set( parityTestsR ) )
if len( existingParityToksR ):
parityStr = existingParityToksR.pop()
if popParityToken:
idx = lowerToks.index( parityStr )
nameToks.pop( idx )
return Parity.RIGHT, parityStr
return Parity.NONE, None
def swapParity( name ):
if not isinstance( name, Name ):
name = Name( name )
nameToks = name.split()
lowerToks = [tok.lower() for tok in nameToks]
lowerToksSet = set(lowerToks)
allParityTests = [ parityTestsL, parityTestsR ]
for parityTests, otherTests in zip( allParityTests, reversed( allParityTests ) ):
parityTokensPresent = lowerToksSet.intersection( set(parityTests) )
if parityTokensPresent:
#this is the caseless parity token
parityToken = parityTokensPresent.pop()
idxInName = lowerToks.index( parityToken )
idxInTokens = parityTests.index( parityToken )
#this gets us the parity token with case - so we can make sure the swapped parity token has the same case...
parityToken = nameToks[ idxInName ]
name[ idxInName ] = matchCase( otherTests[ idxInTokens ], parityToken )
return name
return name
def stripParity( name ):
if not isinstance( name, Name ):
name = Name( name )
nameToks = name.split()
lowerToks = [ tok.lower() for tok in nameToks ]
lowerToksSet = set( lowerToks )
for parityTests in (parityTestsL, parityTestsR):
parityTokensPresent = lowerToksSet.intersection( set( parityTests ) )
if parityTokensPresent:
parityToken = parityTokensPresent.pop()
idxInName = lowerToks.index( parityToken )
name[ idxInName ] = ''
return name
return name
def getCommonPrefix( strs ):
'''
returns the longest prefix common to all given strings
'''
class PrefixDifference(Exception): pass
prefix = ''
first = strs[ 0 ]
for n, s in enumerate( first ):
try:
for aStr in strs[ 1: ]:
if s != aStr[ n ]:
raise PrefixDifference
prefix += s
except PrefixDifference:
return prefix
def matchCase( theStr, caseToMatch ):
matchedCase = []
lastCaseWasLower = True
for charA,charB in zip(theStr,caseToMatch):
lastCaseWasLower = charB.islower()
a = (charA.upper(), charA.lower()) [ lastCaseWasLower ]
matchedCase.append(a)
lenA, lenB = len(theStr), len(caseToMatch)
if lenA > lenB:
remainder = theStr[lenB:]
if lastCaseWasLower: remainder = remainder.lower()
matchedCase.extend( remainder )
return ''.join( matchedCase )
def matchNames( srcList, tgtList, strip=True, parity=True, unique=False, opposite=False, threshold=DEFAULT_THRESHOLD, **kwargs ):
'''
given two lists of strings, this method will return a list (the same size as the first - source list)
with the most appropriate matches found in the second (target) list. the args are:
strip: strips off any prefixes before doing the match - see the Name.__init__ method for details on prefixes
parity: parity tokens are substrings which identify what side of a body a control might lie on. see the
global defines at the start of this script for examples of parity tokens
unique: performs unique matches - ie each tgt will only be matched at most to one src
opposite: if parity is True, only items of the same parity will be matched. if opposite is on, then items
with non-zero parity will be matched to items of the other non-zero parity - ie left is mapped to right
threshold: determines the minimum likeness for two names to be matched. the likeness factor is described in Name.likeness
nomatch: teh object used when no match occurs - defaults to Name()
'''
if isinstance(srcList, basestring): srcList = [srcList]
if isinstance(tgtList, basestring): tgtList = [tgtList]
#build the Name objects for the strings
srcNames = [ Name(name) for name in srcList ]
tgtNames = [ Name(name) for name in tgtList ]
numSrc, numTgt = len(srcList), len(tgtList)
nomatch = kwargs.get('nomatch', Name())
#cache prefixes so they don't affect name matching - caching them stores them on the name instance so we can retrieve them later
if strip:
for a in srcNames: a.cache_prefix()
for a in tgtNames: a.cache_prefix()
matches = []
for name in srcNames:
foundExactMatch = False
likenessList = []
for n, tgt in enumerate(tgtNames):
likeness = name.likeness(tgt, parity)
if likeness >= 1:
#the pop is safe here coz we're bailing
matches.append(tgt)
if unique: tgtNames.pop(n)
foundExactMatch = True
break
likenessList.append(likeness)
#early out
if foundExactMatch:
continue
#find the idx of the highest likeness
bestIdx = -1
for n, curLikeness in enumerate(likenessList):
if curLikeness > likenessList[bestIdx]: bestIdx = n
#for th,tn in zip(likenessList,tgtNames): print th,name.split(),tn.split()
#print '%s -> %s'%(name,tgtNames[bestIdx])
#print '--------------\n'
if bestIdx >= 0 and likenessList[bestIdx] > threshold:
#are we performing unique matching? if so, remove the best target match from the target list
if unique: matches.append(tgtNames.pop(bestIdx))
else: matches.append(tgtNames[bestIdx])
else: matches.append(nomatch)
#re-apply any prefixes we stripped
if strip: matches = [ a.item for a in matches ]
return matches
def matchNamesDict( srcList, tgtList, **kwargs ):
matches = matchNames(srcList, tgtList, **kwargs)
matchDict = {}
for src, tgt in zip(srcList, matches):
matchDict[src] = tgt
return matchDict
class Mapping(object):
def __init__( self, srcList, tgtList ):
self.srcs = srcList[:]
self.tgts = tgtList[:]
def __iter__( self ):
return iter( self.srcs )
def __len__( self ):
return len( self.srcs )
def __contains__( self, item ):
return item in self.asDict()
def __getitem__( self, item ):
return self.asDict()[ item ]
def __setitem__( self, item, value ):
if isinstance( value, basestring ):
value = [ value ]
asDict = self.asDict()
asDict[ item ] = value
self.setFromDict( asDict, self.srcs )
def iteritems( self ):
return iter( zip( self.srcs, self.tgts ) )
def iterkeys( self ):
return self.asDict().iterkeys()
def itervalues( self ):
return self.asDict().itervalues()
def keys( self ):
return self.asDict().keys()
def values( self ):
return self.asDict().values()
def swap( self ):
'''
swaps sources and targets - this is done in place
'''
self.srcs, self.tgts = self.tgts, self.srcs
return self
def copy( self ):
'''
returns a copy of the mapping object
'''
return self.__class__.FromMapping( self )
def pop( self, index=-1 ):
src = self.srcs.pop( index )
tgt = self.tgts.pop( index )
return src, tgt
def insert( self, index, src, tgt ):
self.srcs.insert( index, src )
self.tgts.insert( index, tgt )
def append( self, src, tgt ):
self.srcs.append( src )
self.tgts.append( tgt )
def moveItem( self, index, places=1 ):
src, tgt = self.pop( index )
self.insert( index + places, src, tgt )
def moveItemUp( self, index, places=1 ):
places = abs( places )
return self.moveItem( index, -places )
def moveItemDown( self, index, places=1 ):
places = abs( places )
return self.moveItem( index, places )
def setFromDict( self, mappingDict, ordering=() ):
'''
Sets the mapping from a mapping dictionary. If an ordering iterable is given then the ordering
of those sources is preserved.
'''
srcs = []
tgts = []
def appendTgt( src, tgt ):
if isinstance( tgt, basestring ):
srcs.append( src )
tgts.append( tgt )
elif isinstance( tgt, (list, tuple) ):
for t in tgt:
srcs.append( src )
tgts.append( t )
for src in ordering:
tgt = mappingDict.pop( src )
appendTgt( src, tgt )
for src, tgt in mappingDict.iteritems():
appendTgt( src, tgt )
self.srcs = srcs
self.tgts = tgts
def asStr( self ):
return '\n'.join( [ '%s -> %s' % m for m in self.iteritems() ] )
@classmethod
def FromDict( cls, mappingDict, ordering=() ):
new = Mapping( [], [] )
new.setFromDict( mappingDict, ordering )
return new
@classmethod
def FromMapping( cls, mapping ):
return cls( mapping.srcs, mapping.tgts )
def asDict( self ):
matchDict = {}
for src, tgt in zip(self.srcs, self.tgts):
try: matchDict[ src ].append( tgt )
except KeyError: matchDict[ src ] = [ tgt ]
return matchDict
def asFlatDict( self ):
matchDict = {}
for src, tgt in zip(self.srcs, self.tgts):
matchDict[ src ] = tgt
return matchDict
ABBRVS_TO_EXPAND = {'max': 'maximum',
'min': 'minimum'}
def camelCaseToNice( theString, abbreviationsToExpand=None, niceParityNames=True ):
asName = Name( theString )
words = asName.split()
if niceParityNames:
#does the name have parity? if so use the "nice" version of the parity string
parity = asName.get_parity()
if parity is not Parity.NONE:
niceParityStr = (parityTestsL, parityTestsR)[ parity ][ 1 ]
if abbreviationsToExpand is None: abbreviationsToExpand = {}
abbreviationsToExpand[ asName._parityStr ] = niceParityStr
if abbreviationsToExpand is None:
words = [ w.capitalize() for w in words ]
else:
words = [ abbreviationsToExpand.get(w.lower(), w).capitalize() for w in words ]
return ' '.join( words )
INVALID_CHARS = """`~!@#$%^&*()-+=[]\\{}|;':"/?><., """
def stripInvalidChars( theString, cleanDoubles=True, stripTrailing=True ):
'''
strips "invalid" characters from the given string, replacing them with an "_" character. if
cleanDoubles is true, then any double "_" occurances are replaced with a single "_"
'''
for char in INVALID_CHARS:
theString = theString.replace( char, '_' )
if cleanDoubles:
cleaned = theString
while True:
cleaned = theString.replace( '__', '_' )
if cleaned == theString: break
theString = cleaned
theString = cleaned
if stripTrailing:
while theString.endswith( '_' ):
theString = theString[ :-1 ]
return theString
#end | Python |
from maya.cmds import *
from maya import cmds as cmd
from filesystem import Path
from baseMelUI import *
import os
import api
import names
import skeletonBuilderPresets
import rigPrimitives
import baseRigPrimitive
import rigUtils
import control
import meshUtils
import baseMelUI
import presetsUI
import skinWeightsUI
import spaceSwitchingUI
Axis = rigUtils.Axis
class Callback(object):
'''
stupid little callable object for when you need to "bake" temporary args into a
callback - useful mainly when creating callbacks for dynamicly generated UI items
'''
def __init__( self, func, *args, **kwargs ):
self.func = func
self.args = args
self.kwargs = kwargs
def __call__( self, *args ):
return self.func( *self.args, **self.kwargs )
#stores UI build methods keyed by arg name
UI_FOR_NAMED_RIG_ARGS = {}
SkeletonPart = rigPrimitives.SkeletonPart
ShapeDesc = control.ShapeDesc
class ListEditor(BaseMelWindow):
WINDOW_NAME = 'parentsEditor'
WINDOW_TITLE = 'Edit Custom Parents'
DEFAULT_SIZE = 275, 300
DEFAULT_MENU = None
FORCE_DEFAULT_SIZE = True
def __new__( self, theList, changeCB ):
return BaseMelWindow.__new__( self )
def __init__( self, theList, storage ):
BaseMelWindow.__init__( self )
f = MelForm( self )
self.add = MelButton( f, l='add selected item', c=self.on_add )
self.rem = MelButton( f, l='remove highlighted items', c=self.on_rem )
self.scroll = MelTextScrollList( f )
self.scroll.setItems( theList )
self.storage = storage
f( e=True,
af=((self.add, 'top', 0),
(self.add, 'left', 0),
(self.rem, 'top', 0),
(self.rem, 'right', 0),
(self.scroll, 'left', 0),
(self.scroll, 'right', 0),
(self.scroll, 'bottom', 0)),
ap=((self.add, 'right', 0, 45),
(self.rem, 'left', 0, 45)),
ac=((self.scroll, 'top', 0, self.add)) )
### EVENT HANDLERS ###
def on_add( self, *a ):
sel = cmd.ls( sl=True )
if sel:
self.scroll.appendItems( sel )
self.storage.setValue( self.scroll.getItems() )
self.storage.cb()
def on_rem( self, *a ):
self.scroll.removeSelectedItems()
self.storage.setValue( self.scroll.getItems() )
self.storage.cb()
class MelListEditorButton(MelButton):
def __init__( self, parent, *a, **kw ):
MelButton.__init__( self, parent, *a, **kw )
self.setChangeCB( self.openEditor )
self.setLabel( 'define parents' )
def setValue( self, value, executeChangeCB=False ):
self.value = value
def getValue( self ):
return self.value
def setChangeCB( self, cb ):
self.cb = cb
def openEditor( self, *a ):
win = ListEditor( self.value, self )
win.show()
#hook up list/tuple types to a button - we don't want a text scroll list showing up in the part UI, but a button to bring up said editor is fine
UI_FOR_PY_TYPES[ list ] = MelListEditorButton
UI_FOR_PY_TYPES[ tuple ] = MelListEditorButton
class MelFileBrowser(MelHLayout):
def __init__( self, parent, *a, **kw ):
self.UI_filepath = MelTextField( self )
self.UI_browse = MelButton( self, l='browse', c=self.on_browse, w=50 )
self.setWeight( self.UI_browse, 0 )
self.layout()
def enable( self, state ):
self.UI_filepath.enable( state )
self.UI_browse.enable( state )
def setValue( self, value, executeChangeCB=False ):
'''
the value we recieve should be a fullpath - but we want to store is as a scene relative path
'''
value = Path( value )
#make sure it is actually an absolute path...
if value.isAbs():
curSceneDir = Path( cmd.file( q=True, sn=True ) ).up()
value = value - curSceneDir
self.UI_filepath.setValue( value, executeChangeCB )
def getValue( self ):
'''
return as an absolute path
'''
return Path( cmd.file( q=True, sn=True ) ).up() / self.UI_filepath.getValue()
def setChangeCB( self, cb ):
self.UI_filepath.setChangeCB( cb )
### EVENT HANDLERS ###
def on_browse( self, *a ):
curValue = self.getValue()
ext = curValue.getExtension() or 'txt'
if curValue.isFile():
curValue = curValue.up()
elif not curValue.isDir():
curValue = Path( cmd.file( q=True, sn=True ) ).up( 2 )
if not curValue.exists():
curValue = Path( '' )
filepath = cmd.fileDialog( directoryMask=curValue / ("/*.%s" % ext) )
if filepath:
self.setValue( filepath, True )
baseMelUI.UI_FOR_PY_TYPES[ Path ] = MelFileBrowser
class MelOptionMenu_SkeletonPart(MelOptionMenu):
PART_CLASS = SkeletonPart
def __new__( cls, parent, *a, **kw ):
self = MelOptionMenu.__new__( cls, parent, *a, **kw )
self.populate()
return self
def populate( self ):
self.clear()
for part in self.PART_CLASS.IterAllParts():
self.append( part.end )
def setValue( self, value, executeChangeCB=True ):
if type( value ) is type:
return
return MelOptionMenu.setValue( self, value, executeChangeCB )
def getValue( self ):
value = MelOptionMenu.getValue( self )
return self.PART_CLASS.InitFromItem( value )
class MelOptionMenu_Arm(MelOptionMenu_SkeletonPart):
PART_CLASS = rigPrimitives.SkeletonPart.GetNamedSubclass( 'Arm' )
class MelOptionMenu_Shape(MelOptionMenu):
def __new__( cls, parent, *a, **kw ):
self = MelOptionMenu.__new__( cls, parent, *a, **kw )
self.populate()
return self
def populate( self ):
self.clear()
for shapeName in sorted( rigPrimitives.CONTROL_SHAPE_DICT.keys() ):
self.append( shapeName )
def setValue( self, value, executeChangeCB=True ):
if type( value ) is type:
return
if isinstance( value, ShapeDesc ):
value = value.surfaceType
return MelOptionMenu.setValue( self, value, executeChangeCB )
def getValue( self ):
value = MelOptionMenu.getValue( self )
return ShapeDesc( value )
class MelOptionMenu_Axis(MelOptionMenu):
def __new__( cls, parent, *a, **kw ):
self = MelOptionMenu.__new__( cls, parent, *a, **kw )
self.populate()
return self
def populate( self ):
self.clear()
for shapeName in sorted( Axis.AXES ):
self.append( shapeName )
def setValue( self, value, executeChangeCB=True ):
if type( value ) is type:
return
if isinstance( value, Axis ):
value = value.asName()
return MelOptionMenu.setValue( self, value, executeChangeCB )
#define some UI mappings based on arg types/names...
baseMelUI.UI_FOR_PY_TYPES[ rigPrimitives.SkeletonPart ] = MelOptionMenu_SkeletonPart
baseMelUI.UI_FOR_PY_TYPES[ MelOptionMenu_Arm.PART_CLASS ] = MelOptionMenu_Arm
baseMelUI.UI_FOR_PY_TYPES[ ShapeDesc ] = MelOptionMenu_Shape
UI_FOR_NAMED_RIG_ARGS[ 'axis' ] = MelOptionMenu_Axis
UI_FOR_NAMED_RIG_ARGS[ 'direction' ] = MelOptionMenu_Axis
setParent = cmd.setParent
class SeparatorLabelLayout(MelForm):
def __init__( self, parent, label ):
MelForm.__init__( self, parent )
self.UI_label = MelLabel( self, label=label, align='left' )
setParent( self )
self.UI_separator = cmd.separator( horizontal=True )
self( e=True,
af=((self.UI_label, 'left', 0),
(self.UI_separator, 'top', 6),
(self.UI_separator, 'right', 0)),
ac=((self.UI_separator, 'left', 5, self.UI_label)) )
class SkeletonPresetWindow(presetsUI.PresetWindow):
def __init__( self ):
presetsUI.PresetWindow.__init__( self, rigPrimitives.TOOL_NAME, ext=skeletonBuilderPresets.XTN )
def presetsCopied( self, presets ):
for layout in BuildingLayout.IterInstances():
layout.rePopulatePresets()
def presetsDeleted( self, presets ):
for layout in BuildingLayout.IterInstances():
layout.rePopulatePresets()
def presetsMoved( self, presets ):
for layout in BuildingLayout.IterInstances():
layout.rePopulatePresets()
def presetRenamed( self, preset, renamedPreset ):
for layout in BuildingLayout.IterInstances():
layout.rePopulatePresets()
class SkeletonPresetLayout(MelHSingleStretchLayout):
BUTTON_LBL_TEMPLATE = 'Build a %s Preset'
def __new__( cls, parent, preset ):
return MelHSingleStretchLayout.__new__( cls, parent )
def __init__( self, parent, preset ):
MelHSingleStretchLayout.__init__( self, parent )
self.preset = preset
MelButton( self, l=names.camelCaseToNice( preset.name() ), c=self.on_load, w=160 )
spac = MelSpacer( self )
MelButton( self, l='Overwrite', c=self.on_overwrite, w=100 )
if preset.locale == presetsUI.LOCAL:
self.UI_publish = MelButton( self, l='Publish', c=self.on_publish, w=100 )
#MelButton( self, l='Delete', c=self.on_remove, w=100 )
self.setStretchWidget( spac )
self.layout()
def on_load( self, *a ):
skeletonBuilderPresets.loadPresetFile( self.preset )
def on_overwrite( self, *a ):
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
ret = confirmDialog( t='Are You Sure?', m='Are you sure you want to overwrite the preset %s?' % self.preset.name(), b=BUTTONS, db=CANCEL )
if ret == CANCEL:
return
skeletonBuilderPresets.writePresetToFile( self.preset )
def on_publish( self, *a ):
raise NotImplemented( "you need to define this yourself!" )
#movedPreset = self.preset.move()
#self.preset = movedPreset
#self.UI_publish.delete()
#self.layout()
#p4 = P4File()
#change = p4.getChangeNumFromDesc( '%s skeleton builder preset publish submission' % movedPreset.name() )
#p4.setChange( change, movedPreset )
#p4.submit( change )
#print 'submitted %s' % movedPreset
def on_remove( self, *a ):
pass
class SkeletonPartOptionMenu(MelOptionMenu):
DYNAMIC = False
STATIC_CHOICES = [ partCls.__name__ for partCls in SkeletonPart.GetSubclasses() if partCls.AVAILABLE_IN_UI ]
class ManualPartCreationLayout(MelHSingleStretchLayout):
def __init__( self, parent, *a, **kw ):
MelHSingleStretchLayout.__init__( self, parent, *a, **kw )
self.UI_partType = SkeletonPartOptionMenu( self )
self.UI_convert = MelButton( self, l='Convert Selection To Skeleton Part', c=self.on_convert )
self.setSelectionChangeCB( self.on_selectionChange )
self.setStretchWidget( self.UI_convert )
self.layout()
self.on_selectionChange()
### EVENT HANDLERS ###
def on_convert( self, *a ):
partTypeStr = self.UI_partType.getValue()
partType = SkeletonPart.GetNamedSubclass( partTypeStr )
sel = cmd.ls( sl=True )
newPart = partType( rigPrimitives.buildSkeletonPartContainer( partType, {}, sel ) )
newPart.convert( {} )
self.sendEvent( 'manualPartCreated', newPart )
def on_selectionChange( self, *a ):
sel = cmd.ls( sl=True )
if not sel:
self.UI_convert.disable()
else:
self.UI_convert.enable()
class CommonButtonsLayout(MelColumn):
def __init__( self, parent ):
MelColumn.__init__( self, parent, rowSpacing=4, adj=True )
### SETUP PART DRIVING RELATIONSHIPS
SeparatorLabelLayout( self, 'Part Connection Controls' )
buttonForm = MelHLayout( self )
MelButton( buttonForm, l='Drive All Parts', c=self.on_allDrive )
MelButton( buttonForm, l='Drive Parts With First Selected', c=self.on_drive )
MelButton( buttonForm, l='Break Driver For Selected', c=self.on_breakDrive )
MelButton( buttonForm, l='Break All Drivers', c=self.on_breakAllDrive )
buttonForm.layout()
### SETUP VISUALIZATION CONTROLS
SeparatorLabelLayout( self, 'Visualization' )
buttonForm = MelHLayout( self )
MelButton( buttonForm, l='Visualization ON', c=self.on_visOn )
MelButton( buttonForm, l='Visualization OFF', c=self.on_visOff )
buttonForm.layout()
### SETUP ALIGNMENT CONTROL BUTTONS
SeparatorLabelLayout( self, 'Part Alignment' )
buttonForm = MelHLayout( self )
MelButton( buttonForm, l='Re-Align Selected Part', c=self.on_reAlign )
MelButton( buttonForm, l='Re-Align ALL Parts', c=self.on_reAlignAll )
MelButton( buttonForm, l='Finalize Alignment', c=self.on_finalize )
buttonForm.layout()
### SETUP SKINNING CONTROL BUTTONS
skinFrame = MelFrameLayout( self, l='Skinning Tools', cl=True, cll=True, bs='etchedOut' )
skinCol = MelColumnLayout( skinFrame )
buttonForm = MelHLayout( skinCol )
self.UI_skinOff = MelButton( buttonForm, l='Turn Skinning Off', c=self.on_skinOff )
self.UI_skinOn = MelButton( buttonForm, l='Turn Skinning On', c=self.on_skinOn )
MelButton( buttonForm, l='Reset All Skin Clusters', c=self.on_resetSkin )
buttonForm.layout()
self.updateSkinButtons()
### SETUP VOLUME BUILDER CONTROL BUTTONS
SeparatorLabelLayout( skinCol, 'Volume Tools' )
buttonForm = MelHLayout( skinCol )
MelButton( buttonForm, l='Create Volumes', c=self.on_buildVolumes )
MelButton( buttonForm, l='Extract Selected To Volume', c=self.on_extractSelected )
MelButton( buttonForm, l='Fit Selected Volumes', c=self.on_fitVolumes )
MelButton( buttonForm, l='Remove Volumes', c=self.on_removeVolumes )
buttonForm.layout()
buttonForm = MelHLayout( skinCol )
MelButton( buttonForm, l='Open Skin Weights Tool', c=lambda *a: skinWeightsUI.SkinWeightsWindow() )
MelButton( buttonForm, l='Generate Skin Weights', c=self.on_generateWeights )
buttonForm.layout()
self.setSceneChangeCB( self.on_sceneOpen )
def updateSkinButtons( self ):
state = rigUtils.getSkinClusterEnableState()
self.UI_skinOn( e=True, en=not state )
self.UI_skinOff( e=True, en=state )
def on_allDrive( self, e=None ):
rigPrimitives.setupAutoMirror()
def on_drive( self, e=None ):
selParts = rigPrimitives.getPartsFromObjects( cmd.ls( sl=True ) )
if len( selParts ) <= 1:
print 'WARNING :: please select two or more parts - the first part selected will drive consequent parts'
return
firstPart = selParts.pop( 0 )
for p in selParts:
firstPart.driveOtherPart( p )
def on_breakDrive( self, e=None ):
for p in rigPrimitives.getPartsFromObjects( cmd.ls( sl=True ) ):
p.breakDriver()
def on_breakAllDrive( self, e=None ):
for p in rigPrimitives.SkeletonPart.IterAllParts():
p.breakDriver()
def on_reAlign( self, e=None ):
rigPrimitives.realignSelectedParts()
def on_reAlignAll( self, e=None ):
rigPrimitives.realignAllParts()
def on_finalize( self, e=None ):
rigPrimitives.finalizeAllParts()
def on_visOn( self, e=None ):
for p in rigPrimitives.SkeletonPart.IterAllParts():
p.visualize()
def on_visOff( self, e=None ):
for p in rigPrimitives.SkeletonPart.IterAllParts():
p.unvisualize()
def on_skinOff( self, e=None ):
rigUtils.disableSkinClusters()
self.updateSkinButtons()
def on_skinOn( self, e=None ):
rigUtils.enableSkinClusters()
self.updateSkinButtons()
@api.d_showWaitCursor
def on_resetSkin( self, e=None ):
for sc in ls( typ='skinCluster' ):
rigUtils.resetSkinCluster( sc )
def on_buildVolumes( self, e=None ):
rigPrimitives.buildAllVolumes()
def on_fitVolumes( self, e=None ):
rigPrimitives.shrinkWrapSelection()
def on_removeVolumes( self, e=None ):
rigPrimitives.removeAllVolumes()
def on_extractSelected( self, e=None ):
cmd.select( meshUtils.extractFaces( cmd.ls( sl=True, fl=True ) ) )
api.mel.setSelectMode( "objects", "Objects" )
def on_generateWeights( self, e=None ):
rigPrimitives.volumesToSkinning()
def on_sceneOpen( self, *a ):
self.updateSkinButtons()
class BuildPartLayout(MelForm):
'''
ui for single skeleton part creation
'''
ABBRVS_TO_EXPAND = names.ABBRVS_TO_EXPAND.copy()
ABBRVS_TO_EXPAND[ 'idx' ] = 'index'
BUTTON_LBL_TEMPLATE = 'Create %s'
def __new__( cls, parent, partClass ):
return MelForm.__new__( cls, parent )
def __init__( self, parent, partClass ):
MelForm.__init__( self, parent )
self.partClass = partClass
self.UI_create = cmd.button( l=self.BUTTON_LBL_TEMPLATE % names.camelCaseToNice( partClass.GetPartName() ), c=self.on_create, w=160 )
#now populate the ui for the part's args
self.kwarg_UIs = {} #keyed by arg name
kwargList = partClass.GetDefaultBuildKwargList()
self.UI_argsLayout = MelForm( self )
#everything has a parent attribute, so build it first
prevUI = None
for arg, default in kwargList:
#skip UI for parent - assume selection always
if arg == 'parent':
continue
setParent( self.UI_argsLayout )
lbl = cmd.text( l=names.camelCaseToNice( arg, self.ABBRVS_TO_EXPAND ) )
#determine the function to use for building the UI for the arg
buildMethodFromName = UI_FOR_NAMED_RIG_ARGS.get( arg, None )
buildMethodFromType = getBuildUIMethodForObject( default ) or MelTextField
buildMethod = buildMethodFromName or buildMethodFromType
self.kwarg_UIs[ arg ] = argUI = buildMethod( self.UI_argsLayout )
argUI.setValue( default )
#perform layout
if prevUI is None:
self.UI_argsLayout( e=True, af=((lbl, 'left', 15)) )
else:
self.UI_argsLayout( e=True, ac=((lbl, 'left', 15, prevUI)) )
if isinstance( argUI, MelCheckBox ):
self.UI_argsLayout( e=True, af=((argUI, 'top', 3)) )
self.UI_argsLayout( e=True, af=((lbl, 'top', 3)), ac=((argUI, 'left', 5, lbl)) )
prevUI = argUI
setParent( self )
self( e=True, af=((self.UI_create, 'left', 0),
(self.UI_argsLayout, 'right', 0)),
ac=((self.UI_argsLayout, 'left', 0, self.UI_create)) )
def getKwargDict( self ):
kwargs = {}
for arg, ui in self.kwarg_UIs.iteritems():
kwargs[ arg ] = ui.getValue()
if kwargs.has_key( 'parent' ):
if not kwargs[ 'parent' ]:
kwargs[ 'parent' ] = None
kwargs[ 'partScale' ] = rigPrimitives.getScaleFromSkeleton()
return kwargs
def rePopulate( self ):
for argName, ui in self.kwarg_UIs.iteritems():
if isinstance( ui, MelOptionMenu_SkeletonPart ):
ui.populate()
def on_create( self, e ):
kwargs = self.getKwargDict()
self.partClass.Create( **kwargs )
self.sendEvent( 'rePopulate' )
class BuildingLayout(MelScrollLayout):
'''
ui for skeleton part creation
'''
def __init__( self, parent ):
MelScrollLayout.__init__( self, parent, childResizable=True )
self.UI_col = col = MelColumnLayout( self, rowSpacing=4, adj=True )
MelLabel( col, l='Create Skeleton from Preset', align='left' )
MelLabel( col, l='', height=5 )
### BUILD THE PRESET CREATION BUTTONS ###
self.UI_presetsCol = MelColumnLayout( col )
self.rePopulatePresets()
hLayout = MelHLayout( col )
MelButton( hLayout, l='Create Preset', c=self.on_createPreset )
MelButton( hLayout, l='Manage Presets', c=self.on_managePresets )
hLayout.layout()
MelSeparator( col, horizontal=True )
MelLabel( col, l='Build Individual Parts', align='left' )
MelLabel( col, l='', height=5 )
### BUILD THE PART CREATION BUTTONS ###
self.UI_list = []
parts = SkeletonPart.GetSubclasses()
for part in parts:
if part.AVAILABLE_IN_UI:
self.UI_list.append( BuildPartLayout( col, part ) )
#### BUILD UI FOR MANUAL PART CREATION ###
#MelSeparator( self.UI_col )
#MelLabel( self.UI_col, l='Manually Create Part From Existing Joints', align='left' )
#MelLabel( self.UI_col, l='', height=2 )
#ManualPartCreationLayout( self.UI_col )
def rePopulate( self ):
for ui in self.UI_list:
ui.rePopulate()
def rePopulatePresets( self ):
self.UI_presetsCol.clear()
for locale, presets in skeletonBuilderPresets.listPresets().iteritems():
for preset in presets:
SkeletonPresetLayout( self.UI_presetsCol, preset )
def on_createPreset( self, *a ):
BUTTONS = OK, CANCEL = 'Ok', 'Cancel'
ret = promptDialog( t='Preset Name', m='Enter the name for the preset', b=BUTTONS, db=OK )
if ret == OK:
name = promptDialog( q=True, tx=True )
assert name, "Please enter a name!"
preset = skeletonBuilderPresets.writePreset( name )
SkeletonPresetLayout( self.UI_presetsCol, preset )
def on_managePresets( self, *a ):
SkeletonPresetWindow()
class EditPartLayout(MelForm):
ARGS_TO_HIDE = [ 'parent', 'partScale', 'idx' ]
def __new__( cls, parent, part ):
return MelForm.__new__( cls, parent )
def __init__( self, parent, part ):
MelForm.__init__( self, parent )
self.part = part
self.argUIs = {}
self.populate()
def clear( self ):
MelForm.clear( self )
self.argUIs = {}
def populate( self ):
#remove any existing children
self.clear()
part = self.part
assert isinstance( part, SkeletonPart )
#pimp out the UI
lbl = MelButton( self, l=part.getPartName(), w=140, c=self.on_select )
#grab the args the rigging method takes
argsForm = MelForm( self )
argsUIs = []
buildKwargs = part.getBuildKwargs()
for arg in self.ARGS_TO_HIDE:
buildKwargs.pop( arg, None )
for arg, argValue in buildKwargs.iteritems():
argLbl = MelLabel( argsForm, label=names.camelCaseToNice( arg ) )
#determine the function to use for building the UI for the arg
buildMethodFromName = UI_FOR_NAMED_RIG_ARGS.get( arg, None )
buildMethodFromType = getBuildUIMethodForObject( argValue ) or MelTextField
buildMethod = buildMethodFromName or buildMethodFromType #prioritize the method from name over the method from type
argWidget = buildMethod( argsForm )
argWidget.setValue( argValue )
argsUIs.append( argLbl )
argsUIs.append( argWidget )
self.argUIs[ arg ] = argWidget
try:
inc = 1.0 / len( argsUIs )
except ZeroDivisionError: inc = 1.0
for n, ui in enumerate( argsUIs ):
p = n*inc
if n:
argsForm( e=True, ac=((ui, 'left', 5, argsUIs[ n-1 ])) )
else:
argsForm( e=True, af=((ui, 'left', 0)) )
#finally build the "rebuild" button
reButt = MelButton( self, l="rebuild", c=self.on_rebuild, w=100 )
#perform layout...
self.setWidth( 50 )
argsForm.setWidth( 50 )
self( e=True,
af=((lbl, 'left', 0),
(reButt, 'right', 0)),
ac=((argsForm, 'left', 5, lbl),
(argsForm, 'right', 0, reButt)) )
def getBuildKwargs( self ):
kwargs = {}
for argName, widget in self.argUIs.iteritems():
kwargs[ argName ] = widget.getValue()
return kwargs
def on_rebuild( self, e ):
self.part.rebuild( **self.getBuildKwargs() )
self.populate()
def on_select( self, e=None ):
cmd.select( self.part.items )
class EditingLayout(MelScrollLayout):
def __init__( self, parent ):
MelScrollLayout.__init__( self, parent, childResizable=True )
def populate( self ):
self.clear()
col = MelColumn( self, rowSpacing=4, adj=True )
self.UI_partForms = []
for part in SkeletonPart.IterAllPartsInOrder():
partRigForm = EditPartLayout( col, part )
self.UI_partForms.append( partRigForm )
class RigPartLayout(MelForm):
'''
ui for single rig primitive
'''
def __new__( cls, parent, part ):
return MelForm.__new__( cls, parent )
def __init__( self, parent, part ):
MelForm.__init__( self, parent )
self.part = part
self.argUIs = {}
lbl = MelButton( self, l=part.getPartName(), w=140, c=self.on_select )
rigKwargs = part.getRigKwargs()
#build the disable and optionbox for the rig method
disableState = rigKwargs.get( 'disable', False )
disable = self.UI_disable = MelCheckBox( self, l='disable' )
rigTypes = self.rigTypes = [ rigType for rigType in part.RigTypes if rigType.CanRigThisPart( part ) ]
if len( rigTypes ) > 1:
opts = MelOptionMenu( self, cc=self.on_rigMethodCB )
opts.enable( not disableState )
for method in rigTypes:
opts.append( method.__name__ )
rigMethodName = rigKwargs.get( 'rigMethodName', rigTypes[ 0 ].__name__ )
if rigMethodName in opts.getItems():
opts.selectByValue( rigMethodName, False )
else:
opts = MelLabel( self, l='' )
self.UI_options = opts
argsForm = self.UI_argsForm = MelHRowLayout( self )
self.UI_manualRig = manRig = MelButton( self )
self.updateBuildRigButton()
#perform layout...
self( e=True,
af=((lbl, 'left', 0),
(manRig, 'right', 0)),
ac=((disable, 'left', 3, lbl),
(opts, 'left', 0, disable),
(argsForm, 'left', 0, opts),
(argsForm, 'right', 0, manRig)) )
#set initial UI state
disable.setChangeCB( self.on_argCB )
disable.setValue( disableState, False )
self.populate()
def clearArgs( self ):
self.UI_argsForm.clear()
self.argUIs = {}
def populate( self ):
if not bool( self.rigTypes ):
self.setVisibility( False )
return
#remove any existing children
self.clearArgs()
part = self.part
rigKwargs = part.getRigKwargs()
#build the disable and optionbox for the rig method
disableState = rigKwargs.get( 'disable', False )
#grab the args the rigging method takes
argsForm = self.UI_argsForm
argsUIs = []
rigMethodName = rigKwargs.get( 'rigMethodName', self.rigTypes[ 0 ].__name__ )
rigClass = rigPrimitives.RigPart.GetNamedSubclass( rigMethodName )
if rigClass is None:
rigClass = part.RigTypes[ 0 ]
zeroWeightTypes = MelCheckBox, MelOptionMenu
argNamesAndDefaults = rigClass.GetDefaultBuildKwargList()
for arg, default in argNamesAndDefaults:
argValue = rigKwargs.get( arg, default )
argLbl = MelLabel( argsForm, label=names.camelCaseToNice( arg ) )
#determine the function to use for building the UI for the arg
buildMethodFromName = UI_FOR_NAMED_RIG_ARGS.get( arg, None )
buildMethodFromType = getBuildUIMethodForObject( default ) or MelTextField
buildMethod = buildMethodFromName or buildMethodFromType
argWidget = buildMethod( argsForm )
argWidget.setValue( argValue, False )
argWidget.setChangeCB( self.on_argCB )
argLbl.enable( not disableState )
argWidget.enable( not disableState )
argsUIs.append( argLbl )
argsUIs.append( argWidget )
self.argUIs[ arg ] = argWidget
#if there are no args - create an empty text widget otherwise maya will crash. yay!
argsUIs.append( MelLabel( argsForm, label='' ) )
argsForm.layout()
def getRigKwargs( self ):
disableState = self.UI_disable.getValue()
kwargs = { 'disable': disableState, }
if isinstance( self.UI_options, MelOptionMenu ):
rigMethod = self.UI_options.getValue()
if rigMethod:
kwargs[ 'rigMethodName' ] = rigMethod
for argName, widget in self.argUIs.iteritems():
kwargs[ argName ] = widget.getValue()
self.UI_options.enable( not disableState )
for child in self.UI_argsForm.getChildren():
child.enable( not disableState )
return kwargs
def updateBuildRigButton( self ):
if self.part.isRigged():
self.UI_manualRig.setLabel( 'Delete Rig' )
self.UI_manualRig.setChangeCB( self.on_deleteRig )
else:
self.UI_manualRig.setLabel( 'Build This Rig Only' )
self.UI_manualRig.setChangeCB( self.on_manualRig )
self.UI_manualRig.setWidth( 120 )
rigKwargs = self.part.getRigKwargs()
self.UI_manualRig.setEnabled( not rigKwargs.get( 'disable', False ) )
### EVENT HANDLERS ###
def on_rigMethodCB( self, e ):
#set the rig kwargs based on the current UI - it may be wrong however, because the new rig method may have different calling args
self.part.setRigKwargs( self.getRigKwargs() )
#rebuild the UI to reflect the possibly new options for the changed rig method
self.populate()
#now store the rig kwargs again based on the correct UI
self.part.setRigKwargs( self.getRigKwargs() )
def on_argCB( self, e=None ):
self.part.setRigKwargs( self.getRigKwargs() )
self.updateBuildRigButton()
def on_select( self, e=None ):
cmd.select( self.part.items )
def on_manualRig( self, e=None ):
self.part.finalize()
self.part.rig()
self.updateBuildRigButton()
def on_deleteRig( self, e=None ):
self.part.deleteRig()
self.updateBuildRigButton()
class RiggingLayout(MelForm):
'''
ui for rig primitive creation
'''
def __init__( self, parent ):
MelForm.__init__( self, parent )
scroll = MelScrollLayout( self, cr=True )
self.UI_parts = MelColumn( scroll, rowSpacing=4, adj=True )
self.UI_buttons = MelColumn( self, rowSpacing=4, adj=True )
### BUILD STATIC BUTTONS
buttonParent = self.UI_buttons
setParent( buttonParent )
optsLbl = MelLabel( buttonParent, label='Rig Build Options', align='left' )
buildRigLayout = MelHLayout( buttonParent )
self.UI_reference = MelCheckBox( buildRigLayout, label='reference model' )
self.UI_reference.setValue( False )
buildRigLayout.layout()
setParent( buttonParent )
sep = cmd.separator( horizontal=True )
but = MelButton( buttonParent, l='BUILD RIG', c=self.on_buildRig, height=35 )
self( e=True,
af=((scroll, 'top', 0),
(scroll, 'left', 0),
(scroll, 'right', 0),
(self.UI_buttons, 'left', 0),
(self.UI_buttons, 'right', 0),
(self.UI_buttons, 'bottom', 0)),
ac=((scroll, 'bottom', 3, self.UI_buttons)) )
def populate( self ):
self.UI_parts.clear()
col = self.UI_parts
self.UI_partForms = []
for part in SkeletonPart.IterAllPartsInOrder():
partRigForm = RigPartLayout( col, part )
self.UI_partForms.append( partRigForm )
def on_buildRig( self, e=None ):
curScene = Path( cmd.file( q=True, sn=True ) )
referenceModel = self.UI_reference.getValue()
if referenceModel:
if not curScene:
cmd.confirmDialog( t='Scene not saved!', m="Looks like your current scene isn't saved\n\nPlease save it first so I know where to save the rig. thanks!", b=('OK',), db='OK' )
return
rigPrimitives.buildRigForModel( referenceModel=referenceModel, deletePlacers=False )
#if the model is being referenced run populate to update the rig part instances - container names will have changed because they're now referenced
if referenceModel:
self.populate()
#if we're not referencing the model however, its safe to just run the updateBuildRigButton method on all rig part UI instances
else:
for partUI in self.UI_partForms:
partUI.updateBuildRigButton()
class CreateEditRigTabLayout(MelTabLayout):
def __init__( self, parent, *a, **kw ):
MelTabLayout.__init__( self, parent, *a, **kw )
### THE SKELETON CREATION TAB
insetForm = self.SZ_skelForm = MelForm( self )
self.UI_builder = ed = BuildingLayout( insetForm )
self.UI_commonButtons = bts = CommonButtonsLayout( insetForm )
insetForm( e=True,
af=((ed, 'top', 7),
(ed, 'left', 5),
(ed, 'right', 5),
(bts, 'left', 5),
(bts, 'right', 5),
(bts, 'bottom', 5)),
ac=((ed, 'bottom', 5, bts)) )
### THE EDITING FORM
insetForm = self.SZ_editForm = MelForm( self )
self.UI_editor = ed = EditingLayout( insetForm )
self.UI_commonButtons = bts = CommonButtonsLayout( insetForm )
insetForm( e=True,
af=((ed, 'top', 7),
(ed, 'left', 5),
(ed, 'right', 5),
(bts, 'left', 5),
(bts, 'right', 5),
(bts, 'bottom', 5)),
ac=((ed, 'bottom', 5, bts)) )
### THE RIGGING TAB
insetForm = self.SZ_rigForm = MelForm( self )
self.UI_rigger = ed = RiggingLayout( insetForm )
insetForm( e=True,
af=((ed, 'top', 7),
(ed, 'left', 5),
(ed, 'right', 5),
(ed, 'bottom', 5)) )
self.setLabel( 0, 'create skeleton' )
self.setLabel( 1, 'edit skeleton' )
self.setLabel( 2, 'create rig' )
self.setSceneChangeCB( self.on_sceneOpen )
#rigPrimitives.skeletonBuilderConversion.convertOldParts()
self.setChangeCB( self.on_change )
### EVENT HANDLERS ###
def on_change( self ):
if self.getSelectedTab() == self.SZ_editForm:
self.UI_editor.populate()
elif self.getSelectedTab() == self.SZ_rigForm:
self.UI_rigger.populate()
def on_sceneOpen( self, *a ):
self.setSelectedTabIdx( 0 )
#rigPrimitives.skeletonBuilderConversion.convertOldParts()
class SkeletonBuilderWindow(BaseMelWindow):
WINDOW_NAME = 'skeletonBuilder'
WINDOW_TITLE = 'Skeleton Builder'
DEFAULT_SIZE = 700, 700
DEFAULT_MENU = 'Tools'
HELP_MENU = rigPrimitives.TOOL_NAME, rigPrimitives.__author__, None
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.editor = CreateEditRigTabLayout( self )
tMenu = self.getMenu( 'Tools' )
cmd.menu( tMenu, e=True, pmc=self.buildToolsMenu )
dMenu = self.getMenu( 'Dev' )
cmd.menu( dMenu, e=True, pmc=self.buildDevMenu )
#close related windows...
RigBuilderWindow.Close()
ControlBuildingWindow.Close()
UserAlignListerWindow.Close()
PartExplorerWindow.Close()
self.show()
def buildToolsMenu( self, *a ):
menu = self.getMenu( 'Tools' )
menu.clear()
MelMenuItem( menu, l='Bone Count HUD', cb=headsUpDisplay( rigPrimitives.HUD_NAME, ex=True ), c=lambda *a: rigPrimitives.setupSkeletonBuilderJointCountHUD() )
MelMenuItem( menu, l='Pose Mirroring Tool', c=self.on_loadMirrorTool )
MelMenuItemDiv( menu )
enableState = rigUtils.getSkinClusterEnableState()
MelMenuItem( menu, l='Space Switching Tool', c=lambda *a: spaceSwitchingUI.SpaceSwitchingWindow() )
MelMenuItem( menu, l='Stand Alone Rig Builder Tool', c=lambda *a: RigBuilderWindow() )
MelMenuItem( menu, l='Control Creation Tool', c=lambda *a: ControlBuildingWindow() )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='Mark Selected As User Aligned', c=self.on_markUserAligned )
MelMenuItem( menu, l='Clear User Aligned On Selected', c=self.on_clearUserAligned )
MelMenuItem( menu, l='User Aligned Editor', c=lambda *a: UserAlignListerWindow() )
#MelMenuItemDiv( menu )
#MelMenuItem( menu, l='Clean My Huge Rig', c=lambda *a: rigPrimitives.cleanMeshControls() )
def buildDevMenu( self, *a ):
menu = self.getMenu( 'Dev' )
menu.clear()
MelMenuItem( menu, l='Skeleton Part Code Explorer', c=lambda *a: PartExplorerWindow() )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='Reboot Tool', c=self.on_reboot )
### EVENT HANDLERS ###
def on_markUserAligned( self, *a ):
for j in cmd.ls( sl=True, type='joint' ) or []:
rigPrimitives.setAlignSkipState( j, True )
def on_clearUserAligned( self, *a ):
for j in cmd.ls( sl=True, type='joint' ) or []:
rigPrimitives.setAlignSkipState( j, False )
def on_reboot( self, *a ):
self.close()
import mayaDependencies
mayaDependencies.flush()
import skeletonBuilderUI
skeletonBuilderUI.SkeletonBuilderWindow()
def on_loadMirrorTool( self, *a ):
#check the rig to see if its been setup for pose mirroring
#rigPrimitives.setupMirroring()
import poseSymUI
poseSymUI.PoseSymWindow()
SkeletonBuilderUI = SkeletonBuilderWindow
class PartExplorerLayout(MelTabLayout):
def __init__( self, parent ):
MelTabLayout.__init__( self, parent )
#do skeleton parts
skeletonPartScroll = MelScrollLayout( self )
theCol = MelColumnLayout( skeletonPartScroll )
def getFile( cls ):
clsFile = Path( inspect.getfile( cls ) )
if clsFile.setExtension( 'py' ).exists():
return clsFile.setExtension( 'py' )
return clsFile
for cls in SkeletonPart.IterSubclasses():
clsFile = getFile( cls )
col = MelColumnLayout( theCol )
MelSeparator( col, h=5 )
hLayout = MelHSingleStretchLayout( col )
MelLabel( hLayout, l=cls.GetPartName(), align='left' ).bold( True )
MelSpacer( hLayout, w=10 )
lbl = MelLabel( hLayout, l=clsFile, align='left' )
hLayout.setStretchWidget( lbl )
hLayout.layout()
hLayout = MelHLayout( col )
MelButton( hLayout, l='Explore To', c=Callback( api.mel.zooExploreTo, clsFile ), h=20 )
MelButton( hLayout, l='Edit', c=Callback( os.system, 'start %s' % clsFile ), h=20 )
hLayout.layout()
#do rig parts
rigPartScroll = MelScrollLayout( self )
theCol = MelColumnLayout( rigPartScroll )
for cls in rigPrimitives.RigPart.IterSubclasses():
clsFile = getFile( cls )
col = MelColumnLayout( theCol )
MelSeparator( col, h=5 )
hLayout = MelHSingleStretchLayout( col )
MelLabel( hLayout, l=cls.GetPartName(), align='left' ).bold( True )
MelSpacer( hLayout, w=10 )
lbl = MelLabel( hLayout, l=clsFile, align='left' )
hLayout.setStretchWidget( lbl )
hLayout.layout()
hLayout = MelHLayout( col )
MelButton( hLayout, l='Explore To', c=Callback( api.mel.zooExploreTo, clsFile ), h=20 )
MelButton( hLayout, l='Edit', c=Callback( os.system, 'start %s' % clsFile ), h=20 )
hLayout.layout()
#setup labels
self.setLabel( 0, 'Skeleton Parts' )
self.setLabel( 1, 'Rig Parts' )
def on_change( self ):
self.sendEvent( 'layout' )
class PartExplorerWindow(BaseMelWindow):
WINDOW_NAME = 'skeletonBuilderPartExplorer'
WINDOW_TITLE = '%s: Part Code Explorer' % SkeletonBuilderWindow.WINDOW_TITLE
DEFAULT_MENU = None
DEFAULT_SIZE = 450, 250
FORCE_DEFAULT_SIZE = True
def __init__( self ):
PartExplorerLayout( self )
self.show()
self.layout()
class UserAlignListerLayout(MelVSingleStretchLayout):
def __init__( self, parent ):
def itemAsStr( item ):
if rigPrimitives.getAlignSkipState( item ):
return '* %s' % item
return ' %s' % item
UI_itemList = MelObjectScrollList( self )
UI_itemList.itemAsStr = itemAsStr
for part in SkeletonPart.IterAllPartsInOrder():
for item in part:
UI_itemList.append( item )
hLayout = MelHLayout( self )
MelButton( hLayout, l='Mark As User Aligned' )
MelButton( hLayout, l='Clear User Aligned' )
hLayout.layout()
self.setStretchWidget( UI_itemList )
self.layout()
class UserAlignListerWindow(BaseMelWindow):
WINDOW_NAME = 'skeletonBuilderUserAlignedJointsWindow'
WINDOW_TITLE = '%s: User Aligned Joints' % SkeletonBuilderWindow.WINDOW_TITLE
DEFAULT_MENU = None
DEFAULT_SIZE = 350, 200
def __init__( self ):
self.setSceneChangeCB( lambda: self.close() ) #close on scene load...
UserAlignListerLayout( self )
self.show()
def load():
global ui
ui = SkeletonBuilderWindow()
##############################
### STANDALONE RIG BUILDER ###
##############################
class RigBuilderLayout(MelVSingleStretchLayout):
def __init__( self, parent, *a, **kw ):
MelVSingleStretchLayout.__init__( self, parent, *a, **kw )
MelLabel( self, l="""Select the part's joints in hierarchical order, choose the part type, and hit the convert button.""" )
ManualPartCreationLayout( self )
scroll = MelScrollLayout( self )
self.UI_remove = MelButton( self, l='Remove Skeleton Builder Markup From Selection', c=self.on_remove )
self.setStretchWidget( scroll )
self.layout()
self.UI_partLayouts = []
self.SZ_partLayout = col = MelColumnLayout( scroll, rowSpacing=3 )
self.populate()
self.setSelectionChangeCB( self.on_select )
self.setSceneChangeCB( self.on_scene )
def populate( self ):
self.SZ_partLayout.clear()
for part in SkeletonPart.IterAllPartsInOrder():
self.appendNewPart( part )
def appendNewPart( self, newPart ):
partLayout = RigPartLayout( self.SZ_partLayout, newPart )
self.UI_partLayouts.append( partLayout )
def manualPartCreated( self, newPart ):
self.appendNewPart( newPart )
self.sendEvent( 'layout' )
### EVENT HANDLERS ###
def on_remove( self, *a ):
for item in cmd.ls( sl=True ):
for attrName in listAttr( item, ud=True ):
if attrName.startswith( '_skeletonPart' ) or attrName.startswith( '_skeletonFinalize' ):
cmd.deleteAttr( '%s.%s' % (item, attrName) )
self.populate()
def on_select( self, *a ):
sel = cmd.ls( sl=True )
if sel:
self.UI_remove.enable()
else:
self.UI_remove.disable()
def on_scene( self, *a ):
self.populate()
class RigBuilderWindow(BaseMelWindow):
WINDOW_NAME = 'rigBuilderTool'
WINDOW_TITLE = '%s: Manual Rig Builder Tool' % SkeletonBuilderWindow.WINDOW_TITLE
DEFAULT_SIZE = 475, 300
DEFAULT_MENU = None
def __init__( self ):
BaseMelWindow.__init__( self )
padding = MelSingleLayout( self, 5 )
RigBuilderLayout( padding )
padding.layout()
self.show()
###############################
### CONTROL BUILDING WINDOW ###
###############################
class ControlBuildingLayout(MelForm):
def __init__( self, parent, *a, **kw ):
width = 60
self.UI_place = UI_place = MelObjectSelector( self, label='place at->', labelWidth=width )
self.UI_parent = UI_parent = MelObjectSelector( self, label='parent to->', labelWidth=width )
self.UI_align = UI_align = MelObjectSelector( self, label='align to->', labelWidth=width )
self.UI_pivot = UI_pivot = MelObjectSelector( self, label='pivot to->', labelWidth=width )
self.UI_build = UI_build = MelButton( self, l='build control', c=self.on_build )
self( e=True,
af=(
(UI_place, 'left', 0),
(UI_parent, 'right', 0),
(UI_align, 'left', 0),
(UI_pivot, 'right', 0),
(UI_build, 'left', 0),
(UI_build, 'right', 0),
(UI_build, 'bottom', 0),
),
ac=(
(UI_align, 'top', 0, UI_place),
(UI_pivot, 'top', 0, UI_place),
),
ap=(
(UI_place, 'right', 0, 50),
(UI_parent, 'left', 0, 50),
(UI_align, 'right', 0, 50),
(UI_pivot, 'left', 0, 50),
)
)
def on_build( self, *a ):
place = self.UI_place.getValue()
parent = self.UI_parent.getValue()
align = self.UI_align.getValue()
pivot = self.UI_pivot.getValue()
args = []
if place:
args.append( place )
if align:
args.append( align )
if pivot:
args.append( pivot )
control.buildControl( '%sControl' % place, control.PlaceDesc( *args ) )
class ControlBuildingWindow(BaseMelWindow):
WINDOW_NAME = 'controlBuildingWindow'
WINDOW_TITLE = '%s: Control Builder' % SkeletonBuilderWindow.WINDOW_TITLE
DEFAULT_SIZE = 450, 350
DEFAULT_MENU = 'Help'
DEFAULT_MENU_IS_HELP = True
HELP_MENU = rigPrimitives.TOOL_NAME, rigPrimitives.__author__, None
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.editor = ControlBuildingLayout( self )
self.show()
#end
| Python |
from maya import cmds as cmd
def d_showWaitCursor(f):
'''
turns the wait cursor on while the decorated method is executing, and off again once finished
'''
def func( *args, **kwargs ):
cmd.waitCursor( state=True )
try:
return f( *args, **kwargs )
finally:
cmd.waitCursor( state=False )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_disableViews(f):
'''
disables all viewports before, and re-enables them after
'''
def func( *args, **kwargs ):
modelPanels = cmd.getPanel( vis=True )
emptySelConn = cmd.selectionConnection()
for panel in modelPanels:
if cmd.getPanel( to=panel ) == 'modelPanel':
cmd.isolateSelect( panel, state=True )
cmd.modelEditor( panel, e=True, mlc=emptySelConn )
try:
return f( *args, **kwargs )
finally:
for panel in modelPanels:
if cmd.getPanel( to=panel ) == 'modelPanel':
cmd.isolateSelect( panel, state=False )
cmd.deleteUI( emptySelConn )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_autoKey(f):
'''
forces autoKey on
'''
def func( *args, **kwargs ):
initialState = cmd.autoKeyframe( q=True, state=True )
cmd.autoKeyframe( state=True )
try:
return f( *args, **kwargs )
finally:
cmd.autoKeyframe( state=initialState )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_noAutoKey(f):
'''
forces autoKey off
'''
def func( *args, **kwargs ):
initialState = cmd.autoKeyframe( q=True, state=True )
cmd.autoKeyframe( state=False )
try:
return f( *args, **kwargs )
finally:
cmd.autoKeyframe( state=initialState )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_restoreTime(f):
'''
restores the initial time once the wrapped function exits
'''
def func( *args, **kwargs ):
initialTime = cmd.currentTime( q=True )
try:
return f( *args, **kwargs )
finally:
cmd.currentTime( initialTime, e=True )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_noUndo(f):
'''
forces undo off
'''
def func( *args, **kwargs ):
initialState = cmd.undoInfo( q=True, state=True )
cmd.undoInfo( stateWithoutFlush=False )
try:
return f( *args, **kwargs )
finally:
cmd.undoInfo( stateWithoutFlush=initialState )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_unifyUndo(f):
'''
wraps the function into a definite undo "chunk" - why this needs to be done for python is beyond me...
'''
def func( *args, **kwargs ):
cmd.undoInfo( openChunk=True )
try:
return f( *args, **kwargs )
finally:
cmd.undoInfo( closeChunk=True )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_progress( **dec_kwargs ):
'''
deals with progress window... any kwargs given to the decorator on init are passed to the progressWindow init method
'''
def ffunc(f):
def func( *args, **kwargs ):
try:
cmd.progressWindow( **dec_kwargs )
except: print 'error init-ing the progressWindow'
try:
return f( *args, **kwargs )
finally:
cmd.progressWindow( ep=True )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
return ffunc
_ANIM_LAYER_ATTRS = [ 'mute',
'solo',
'lock',
'override',
#'passthrough',
'weight',
#'parentMute',
#'childsoloed',
#'siblingSolo',
#'outMute',
'preferred',
'selected',
'collapse',
'backgroundWeight' ]
if mayaVer >= 2011:
_ANIM_LAYER_ATTRS += [ 'rotationAccumulationMode',
'scaleAccumulationMode' ]
else:
_ANIM_LAYER_ATTRS += [ 'rotationInterpolateMode',
'scaleInterpolateMode' ]
def d_restoreAnimLayers( f ):
'''
restores animation layer state -
'''
#if this excepts, just return the function as is - anim layers aren't supported by this version
try:
cmd.ls( typ='animLayer' )
except RuntimeError: return f
def func( *a, **kw ):
#store pre-function values
preDict = {}
selectedLayers = []
for l in cmd.ls( typ='animLayer' ):
preDict[ l ] = valueDict = {}
if cmd.animLayer( l, q=True, selected=True ):
selectedLayers.append( l )
for attr in _ANIM_LAYER_ATTRS:
valueDict[ attr ] = cmd.getAttr( '%s.%s' % (l, attr) )
#run the function
try:
f( *a, **kw )
finally:
#restore selection and all layer attributes
for l, valueDict in preDict.iteritems():
for attr, value in valueDict.iteritems():
try: cmd.setAttr( '%s.%s' % (l, attr), value )
except RuntimeError: pass
for l in cmd.ls( typ='animLayer' ):
cmd.animLayer( l, e=True, selected=False )
for l in selectedLayers:
cmd.animLayer( l, e=True, selected=True )
cmd.animLayer( forceUIRefresh=True )
func.__name__ = f.__name__
func.__doc__ = f.__doc__
return func
def d_maintainSceneSelection(f):
def wrapped( *a, **kw ):
initSel = cmd.ls( sl=True )
try:
f( *a, **kw )
finally:
if cmd.ls( sl=True ) != initSel:
initSel = [ o for o in initSel if cmd.objExists( o ) ]
if initSel:
cmd.select( initSel )
wrapped.__name__ = f.__name__
wrapped.__doc__ = f.__doc__
return wrapped
#end
| Python |
import maya.cmds as cmd
class KeyServer(object):
'''
This class is basically an iterator over keys set on the given objects.
Key times are iterated over in chronological order. Calling getNodes
on the iterator will provide a list of nodes that have keys on the
current frame
'''
def __init__( self, nodes, changeTime=True ):
self._nodes = nodes
self._changeTime = changeTime
self._curIndex = 0
self._keys = list( set( cmd.keyframe( nodes, q=True ) or [] ) )
self._keys.sort()
self._keyNodeDict = {}
self._keyNodeDictHasBeenPopulated = False
def _populateDict( self ):
keyNodeDict = self._keyNodeDict
for node in self._nodes:
keys = cmd.keyframe( node, q=True )
if keys:
for key in set( keys ):
keyNodeDict.setdefault( key, [] )
keyNodeDict[ key ].append( node )
self._keyNodeDictHasBeenPopulated = True
def getNodesAtTime( self ):
if not self._keyNodeDictHasBeenPopulated:
self._populateDict()
keyNodeDict = self._keyNodeDict
return keyNodeDict[ self._keys[ self._curIndex ] ][:]
def __iter__( self ):
for key in self._keys:
if self._changeTime:
cmds.currentTime( key, e=True )
yield key
#end
| Python |
from baseRigPrimitive import *
class Root(PrimaryRigPart):
__version__ = 0
SKELETON_PRIM_ASSOC = ( skeletonBuilder.Root, )
CONTROL_NAMES = 'control', 'gimbal', 'hips'
def _build( self, skeletonPart, buildHips=True, **kw ):
root = skeletonPart.base
#deal with colours
colour = ColourDesc( 'blue' )
darkColour = colour.darken( 0.5 )
lightColour = colour.lighten( 0.5 )
#hook up the scale from the main control
connectAttr( '%s.scale' % self.getWorldControl(), '%s.scale' % root )
partParent, altRootControl = getParentAndRootControl( root )
#try to determine a sensible size for the root control - basically grab teh autosize of the root joint, and take the x-z plane values
size = control.getJointSize( [root], 0.5, SPACE_WORLD )
ringSize = Vector( (size[0], size[0] + size[2] / 3.0, size[2]) )
#create the controls, and parent them
rootControl = buildControl( 'upperBodyControl', (root, PlaceDesc.WORLD), shapeDesc=ShapeDesc( 'band', axis=AX_Y ), colour=colour, constrain=False, size=size, parent=partParent )
rootGimbal = buildControl( 'gimbalControl', (root, PlaceDesc.WORLD), shapeDesc=ShapeDesc( 'ring', axis=AX_Y ), colour=darkColour, oriented=False, offset=(0, size.y/2, 0), size=ringSize, parent=rootControl, niceName='Upper Body Control' )
hipsControl = buildControl( 'hipsControl', (root, PlaceDesc.WORLD), shapeDesc=ShapeDesc( 'ring', axis=AX_Y ), colour=lightColour, constrain=False, oriented=False, offset=(0, -size.y/2, 0), size=ringSize, parent=rootGimbal )
rootSpace = listRelatives( rootControl, p=True, pa=True )
#delete the connections to rotation so we can put an orient constraint on the root joint to teh hips control
for ax in AXES:
delete( '%s.r%s' % (root, ax), icn=True )
orientConstraint( hipsControl, root, mo=True )
attrState( hipsControl, 't', *LOCK_HIDE )
#turn unwanted transforms off, so that they are locked, and no longer keyable
attrState( (rootGimbal, hipsControl), 't', *LOCK_HIDE )
for s in listRelatives( rootGimbal, s=True, pa=True ):
setAttr( '%s.visibility' % s, False )
xform( rootControl, p=1, roo='xzy' )
xform( rootGimbal, p=1, roo='zxy' )
#add right click menu to turn on the gimbal control
Trigger.CreateMenu( rootControl,
"toggle gimbal control",
"{\nstring $kids[] = `listRelatives -pa -type transform #`;\n$kids = `listRelatives -s $kids[0]`;\nint $vis = `getAttr ( $kids[0] +\".v\" )`;\nfor( $k in $kids ) setAttr ( $k +\".v\" ) (!$vis);\n}" )
Trigger.CreateMenu( rootGimbal,
"toggle gimbal control",
"{\nstring $kids[] = `listRelatives -pa -s #`;\nint $vis = `getAttr ( $kids[0] +\".v\" )`;\nfor( $k in $kids ) setAttr ( $k +\".v\" ) (!$vis);\nselect `listRelatives -p`;\n}" )
controls = rootControl, rootGimbal, hipsControl
return controls, ()
def setupMirroring( self ):
for control in self:
pair = poseSym.ControlPair.Create( control )
pair.setFlips( 0 )
#end
| Python |
from meshUtils import *
#end | Python |
import apiExtensions
from maya.cmds import *
from filesystem import removeDupes
def resetAttrs( obj, skipVisibility=True ):
'''
simply resets all keyable attributes on a given object to its default value
great for running on a large selection such as all character controls...
'''
#obj = apiExtensions.asMObject( obj )
attrs = listAttr( obj, k=True, s=True, m=True ) or []
if skipVisibility:
if 'visibility' in attrs:
attrs.remove( 'visibility' )
if not attrs:
return
selAttrs = channelBox( 'mainChannelBox', q=True, sma=True ) or channelBox( 'mainChannelBox', q=True, sha=True )
for attr in attrs:
#if there are selected attributes AND the current attribute isn't in the list of selected attributes, skip it...
if selAttrs:
attrShortName = attributeQuery( attr, n=obj, shortName=True )
if attrShortName not in selAttrs:
continue
default = 0
try:
default = attributeQuery( attr, n=obj, listDefault=True )[ 0 ]
except RuntimeError: pass
attrpath = '%s.%s' % (obj, attr)
if not getAttr( attrpath, settable=True ):
continue
#need to catch because maya will let the default value lie outside an attribute's
#valid range (ie maya will let you creat an attrib with a default of 0, min 5, max 10)
try:
setAttr( attrpath, default )
except RuntimeError: pass
#end
| Python |
from filesystem import *
from baseMelUI import *
from mappingUtils import *
import names
import api
import presetsUI
TOOL_NAME = 'zoo'
TOOL_VER = 1
EXT = 'mapping'
ui = None
class MappingForm(MelHLayout):
'''
Acts as a generic UI for editing "mappings". A mapping is basically just a dictionaries in maya,
but they're used for things like animation transfer and weight transfer between one or more
differing name sets.
Mappings can be stored out to presets.
'''
#args for controlling the name mapping algorithm - see the names.matchNames method for documentation on what these variables actually control
STRIP_NAMESPACES = True
PARITY_MATCH = True
UNIQUE_MATCHING = False
MATCH_OPPOSITE_PARITY = False
THRESHOLD = names.DEFAULT_THRESHOLD
#defines whether namespaces are hidden from the list view of the data - defaults to True. the namespaces are still stored, they just aren't displayed
HIDE_NAMESPACES = True
#if this is set to True, then sources can be mapped to multiple targets
ALLOW_MULTI_SELECTION = True
def __new__( cls, parent, *a, **kw ):
return MelHLayout.__new__( cls, parent )
def __init__( self, parent, srcItems=None, tgtItems=None ):
MelHLayout.__init__( self, parent )
self.expand = True
self._srcToTgtDict = {}
self._previousMappingFile = None
szLeft = MelVLayout( self )
szRight = MelVLayout( self )
szLeft.expand = True
szRight.expand = True
self.UI_srcButton = srcBut = MelButton( szLeft, l='Source Items (click for menu)' )
self.UI_tgtButton = tgtBut = MelButton( szRight, l='Target Items (click for menu)' )
szLeft.setWeight( srcBut, 0 )
szRight.setWeight( tgtBut, 0 )
szHLeft = MelHLayout( szLeft )
szHLeft.expand = True
szHRight = MelHLayout( szRight )
szHRight.expand = True
vLayout = MelVLayout( szHLeft )
self.UI_but_srcUp = MelButton( vLayout, label='up', vis=True, width=22, c=self.on_src_up )
self.UI_but_srcDn = MelButton( vLayout, label='dn', vis=True, width=22, c=self.on_src_dn )
vLayout.layout()
szHLeft.setWeight( vLayout, 0 )
self.UI_srcs = srcs = MelObjectScrollList( szHLeft, deleteKeyCommand=self.on_delete, doubleClickCommand=self.on_selectSrc )
self.UI_srcs.setChangeCB( self.on_selectItemSrc )
self.UI_tgts = MelObjectScrollList( szHRight, deleteKeyCommand=self.on_delete, doubleClickCommand=self.on_selectTgt, ams=True )
self.UI_tgts.setChangeCB( self.on_selectItemTgt )
#vLayout = MelVLayout( szHRight )
#self.UI_but_tgtUp = MelButton( vLayout, label='up', vis=False, width=1, c=self.on_tgt_up )
#self.UI_but_tgtDn = MelButton( vLayout, label='dn', vis=False, width=1, c=self.on_tgt_dn )
#vLayout.layout()
szLeft.layout()
szRight.layout()
szHLeft.layout()
szHRight.layout()
self.layout()
MelPopupMenu( self.UI_srcs, pmc=self.build_srcMenu )
MelPopupMenu( self.UI_tgts, pmc=self.build_tgtMenu )
MelPopupMenu( self.UI_srcButton, pmc=self.build_srcMenu )
MelPopupMenu( self.UI_tgtButton, pmc=self.build_tgtMenu )
MelPopupMenu( self.UI_srcButton, b=1, pmc=self.build_srcMenu )
MelPopupMenu( self.UI_tgtButton, b=1, pmc=self.build_tgtMenu )
if srcItems is not None:
self.addSrcItems( srcItems )
if tgtItems is not None:
self.addTgtItems( tgtItems )
@property
def srcs( self ):
return self.UI_srcs.getItems()
@property
def tgts( self ):
return self.UI_tgts.getItems()
def showUpDownButtons( self ):
self.UI_but_srcUp.show()
self.UI_but_srcDn.show()
def hideUpDownButtons( self ):
self.UI_but_srcUp.hide()
self.UI_but_srcDn.hide()
def setSrcsLabel( self, newLabel ):
self.UI_srcButton.setLabel( newLabel )
def setTgtsLabel( self, newLabel ):
self.UI_tgtButton.setLabel( newLabel )
def getUnmappedSrcs( self ):
return list( set( self.srcs ).difference( self.getMapping().srcs ) )
def getUnmappedTgts( self ):
return list( set( self.tgts ).difference( self.getMapping().tgts ) )
def getMapping( self ):
mapping = names.Mapping.FromDict( self._srcToTgtDict )
return mapping
def setMapping( self, mapping ):
if isinstance( mapping, dict ):
self._srcToTgtDict = mapping
elif isinstance( mapping, names.Mapping ):
self._srcToTgtDict = mapping.asDict()
else:
raise TypeError, "unsupported mapping type %s" % type( mapping )
self.refresh()
def getSelectedSrc( self ):
'''
returns the name of the src item selected. None if nothing is selected
'''
try:
return self.UI_srcs.getSelectedItems()[ 0 ]
except IndexError: return None
def getSelectedTgts( self ):
return self.UI_tgts.getSelectedItems()
def mapSrcItem( self, src ):
self._srcToTgtDict[ src ] = names.matchNames( [ src ], self.tgts, self.STRIP_NAMESPACES, self.PARITY_MATCH, self.UNIQUE_MATCHING, self.MATCH_OPPOSITE_PARITY, self.THRESHOLD )
def mapAllSrcItems( self ):
for src in self.srcs:
self.mapSrcItem( src )
def addSrcItems( self, items ):
if items:
self.UI_srcs.appendItems( list( sorted( items ) ) )
for i in items:
self.mapSrcItem( i )
def replaceSrcItems( self, items ):
self.UI_tgts.clear()
self.addSrcItems( items )
def addTgtItems( self, items ):
if items:
self.UI_tgts.appendItems( items )
performMapping = bool( self.UI_tgts.getItems() )
if performMapping:
self.mapAllSrcItems()
def clear( self ):
self._srcToTgtDict = {}
self.UI_srcs.clear()
self.UI_tgts.clear()
def clearSrcs( self ):
self._srcToTgtDict = {}
self.UI_srcs.clear()
def clearTgts( self ):
self._srcToTgtDict = {}
self.UI_tgts.clear()
def refresh( self ):
theSrcs = []
theTgts = []
for src in sorted( self._srcToTgtDict.keys() ):
theSrcs.append( src )
theTgts += self._srcToTgtDict[ src ]
theSrcs = removeDupes( theSrcs )
theTgts = removeDupes( theTgts )
self.UI_srcs.setItems( theSrcs )
self.UI_tgts.setItems( theTgts )
def saveMappingToFile( self, filepath ):
filepath = Path( filepath ).setExtension( EXT )
filedata = api.writeExportDict( TOOL_NAME, TOOL_VER ), self.getMapping()
filepath.pickle( filedata )
def saveMappingPreset( self, presetName ):
filepath = Preset( LOCAL, TOOL_NAME, presetName, EXT )
self.saveMappingToFile( filepath )
def loadMappingFile( self, filepath ):
d, mapping = Path( filepath ).unpickle()
mapping = names.Mapping.FromDict( mapping )
if self.ALLOW_MULTI_SELECTION:
self._srcToTgtDict = mapping.asDict()
else:
self._srcToTgtDict = mapping.asFlatDict()
self.refresh()
def loadMappingPreset( self, presetName ):
filepath = findPreset( presetName, TOOL_NAME, EXT )
self.loadMappingFile( filepath )
### MENU BUILDERS ###
def build_srcMenu( self, *a ):
cmd.setParent( a[ 0 ], menu=True )
cmd.menu( a[ 0 ], e=True, dai=True )
cmd.menuItem( l='Add Selected Objects', c=self.on_addSrc )
cmd.menuItem( l='Replace With Selected Objects', c=self.on_replaceSrc )
cmd.menuItem( d=True )
cmd.menuItem( l='Remove Highlighted Item', c=self.on_removeSrcItem )
cmd.menuItem( d=True )
cmd.menuItem( l='Select All Objects', c=self.on_selectAllSrc )
cmd.menuItem( d=True )
cmd.menuItem( l='Save Mapping...', c=self.on_saveMapping )
cmd.menuItem( l='Load Mapping...', sm=True )
pm = PresetManager( TOOL_NAME, EXT )
presets = pm.listAllPresets( True )
for loc in LOCAL, GLOBAL:
for f in presets[ loc ]:
f = Path( f )
cmd.menuItem( l=f.name(), c=Callback( self.loadMappingFile, f ) )
cmd.menuItem( d=True )
cmd.menuItem( l='Manage Mappings...', c=lambda *x: presetsUI.load( TOOL_NAME, LOCAL, EXT ) )
cmd.setParent( '..', menu=True )
cmd.menuItem( d=True )
cmd.menuItem( l='Swap Mapping', c=self.on_swap )
def build_tgtMenu( self, *a ):
cmd.setParent( a[ 0 ], menu=True )
cmd.menu( a[ 0 ], e=True, dai=True )
cmd.menuItem( l='Add Selected Objects', c=self.on_addTgt )
cmd.menuItem( l='Replace With Selected Objects', c=self.on_replaceTgt )
cmd.menuItem( d=True )
cmd.menuItem( l='Select All Objects', c=self.on_selectAllTgt )
cmd.menuItem( l='Select Highlighted Objects', c=self.on_selectTgt )
cmd.menuItem( d=True )
cmd.menuItem( l='Remove Highlighted Items', c=self.on_removeTgtItem )
cmd.menuItem( d=True)
cmd.menuItem( l='Swap Mapping', c=self.on_swap )
### EVENT CALLBACKS ###
def on_selectAllSrc( self, *a ):
cmd.select( cl=True )
for s in self.UI_srcs.getItems():
s = str( s )
if cmd.objExists( s ):
cmd.select( s, add=True )
def on_selectAllTgt( self, *a ):
cmd.select( cl=True )
for t in self.UI_tgts.getItems():
t = str( t )
if cmd.objExists( t ):
cmd.select( t, add=True )
def on_selectItemSrc( self, *a ):
self.UI_tgts.clearSelection()
src = self.getSelectedSrc()
if src:
try: tgts = self._srcToTgtDict[ src ]
except KeyError:
return
for t in tgts:
if t: self.UI_tgts.selectByValue( t )
def on_addSrc( self, *a ):
self.addSrcItems( cmd.ls( sl=True ) )
def on_replaceSrc( self, *a ):
self._srcToTgtDict = {}
self.UI_srcs.clear()
self.on_addSrc()
def on_removeSrcItem( self, *a ):
sel = self.getSelectedSrc()
try:
self._srcToTgtDict.pop( sel )
except KeyError: pass
try:
self.UI_srcs.removeByValue( sel )
except IndexError: pass
def on_selectSrc( self, *a ):
src = self.getSelectedSrc()
if src:
#if the object doesnt' exist in teh scene - try to find it
src = findItem( src )
if src is not None:
cmd.select( src )
def on_src_up( self, *a ):
self.UI_srcs.moveSelectedItemsUp()
def on_src_dn( self, *a ):
self.UI_srcs.moveSelectedItemsDown()
def on_selectItemTgt( self, *a ):
src = self.getSelectedSrc()
if src:
self._srcToTgtDict[ src ] = self.UI_tgts.getSelectedItems()
else:
self.UI_tgts.clearSelection()
def on_delete( self, *a ):
src = self.getSelectedSrc()
if src:
del( self._srcToTgtDict[ src ] )
self.on_selectItemSrc()
def on_addTgt( self, *a ):
self.addTgtItems( cmd.ls( sl=True ) )
def on_replaceTgt( self, *a ):
self._srcToTgtDict = {}
self.UI_tgts.clear()
self.on_addTgt()
self.mapAllSrcItems()
def on_removeTgtItem( self, *a ):
selTgts = self.getSelectedTgts()
for aSrc, tgts in self._srcToTgtDict.iteritems():
newTgts = [ tgt for tgt in tgts if tgt not in selTgts ]
self._srcToTgtDict[ aSrc ] = newTgts
idxs = self.UI_tgts.getSelectedIdxs()
for idx in reversed( sorted( idxs ) ):
self.UI_tgts.removeByIdx( idx )
def on_selectTgt( self, *a ):
tgts = self.getSelectedTgts()
if tgts:
existingTgts = []
for t in tgts:
t = findItem( t )
if t is not None:
existingTgts.append( t )
if existingTgts:
cmd.select( existingTgts )
def on_tgt_up( self, *a ):
self.UI_tgts.moveSelectedItemsUp()
def on_tgt_dn( self, *a ):
self.UI_tgts.moveSelectedItemsDown()
def on_swap( self, *a ):
curMapping = names.Mapping.FromDict( self._srcToTgtDict )
curMapping.swap()
if self.ALLOW_MULTI_SELECTION:
self._srcToTgtDict = curMapping.asDict()
else:
self._srcToTgtDict = curMapping.asFlatDict()
self.refresh()
def on_saveMapping( self, *a ):
ret = cmd.promptDialog( m='Enter a name for the mapping', t='Enter Name', b=('Ok', 'Cancel'), db='Ok' )
if ret == 'Ok':
self.saveMappingPreset( cmd.promptDialog( q=True, tx=True ) )
def on_loadMapping( self, *a ):
previous = getPresetDirs( LOCAL, TOOL_NAME )[ 0 ]
if self._previousMappingFile is not None:
previous = self._previousDir
filename = cmd.fileDialog( directoryMask=( "%s/*.%s" % (previous, EXT) ) )
filepath = Path( filename )
self._previousMappingFile = filepath.up()
self.loadMappingFile( filepath )
class MappingEditor(BaseMelWindow):
'''
'''
WINDOW_NAME = 'mappingEditorUI'
WINDOW_TITLE = 'Mapping Editor'
DEFAULT_SIZE = 400, 600
def __new__( cls, *a, **kw ):
return BaseMelWindow.__new__( cls )
def __init__( self, srcItems=None, tgtItems=None ):
BaseMelWindow.__init__( self )
self.editor = MappingForm( self, srcItems, tgtItems )
self.show()
def getMapping( self ):
return self.editor.getMapping()
def load():
global ui
ui = MappingEditor()
#end | Python |
import filesystem
import typeFactories
from maya.cmds import *
from maya import cmds as cmd
from rigUtils import *
from control import *
from names import Parity, Name, camelCaseToNice, stripParity
from skeletonBuilder import *
from vectors import Vector, Matrix
from mayaDecorators import d_unifyUndo
from common import printInfoStr, printWarningStr, printErrorStr
import apiExtensions
import skeletonBuilder
import spaceSwitching
import triggered
import poseSym
import vectors
import control
import api
__author__ = 'hamish@macaronikazoo.com'
Trigger = triggered.Trigger
AXES = Axis.BASE_AXES
Vector = vectors.Vector
AIM_AXIS = AX_X
ROT_AXIS = AX_Y
#make sure all setDrivenKeys have linear tangents
setDrivenKeyframe = lambda *a, **kw: cmd.setDrivenKeyframe( inTangentType='linear', outTangentType='linear', *a, **kw )
def connectAttrReverse( srcAttr, destAttr, **kw ):
'''
puts a reverse node in between the two given attributes
'''
revNode = shadingNode( 'reverse', asUtility=True )
connectAttr( srcAttr, '%s.inputX' % revNode, **kw )
connectAttr( '%s.outputX' % revNode, destAttr, **kw )
return revNode
class RigPartError(Exception): pass
def isRigPartContainer( node ):
if objectType( node, isType='objectSet' ):
return sets( node, q=True, text=True ) == 'rigPrimitive'
return False
def getRigPartContainers( compatabilityMode=False ):
existingContainers = [ node for node in ls( type='objectSet', r=True ) or [] if sets( node, q=True, text=True ) == 'rigPrimitive' ]
if compatabilityMode:
existingContainers += [ node.split( '.' )[0] for node in ls( '*._rigPrimitive', r=True ) ]
return existingContainers
def getNodesCreatedBy( function, *args, **kwargs ):
'''
returns a 2-tuple containing all the nodes created by the passed function, and
the return value of said function
NOTE: if any container nodes were created, their contents are omitted from the
resulting node list - the container itself encapsulates them
'''
newNodes, ret = apiExtensions.getNodesCreatedBy( function, *args, **kwargs )
#now remove nodes from all containers from the newNodes list
newContainers = apiExtensions.filterByType( newNodes, apiExtensions.MFn.kSet )
#NOTE: nodes are MObject instances at this point
newNodes = set( [ node for node in newNodes if node is not None ] )
for c in newContainers:
for n in sets( c, q=True ) or []:
if n in newNodes:
newNodes.remove( n )
#containers contained by other containers don't need to be returned (as they're already contained by a parent)
newTopLevelContainers = []
for c in newContainers:
parentContainer = sets( c, q=True, parentContainer=True )
if parentContainer:
continue
newTopLevelContainers.append( c )
newNodes.add( c )
return newNodes, ret
def buildContainer( typeClass, kwDict, nodes, controls, namedNodes=() ):
'''
builds a container for the given nodes, and tags it with various attributes to record
interesting information such as rig primitive version, and the args used to instantiate
the rig. it also registers control objects with attributes, so the control nodes can
queried at a later date by their name
'''
#if typeClass is an instance, then set its container attribute, otherwise instantiate an instance and return it
if isinstance( typeClass, RigPart ):
theInstance = typeClass
typeClass = type( typeClass )
elif issubclass( typeClass, RigPart ):
theInstance = typeClass( None )
#build the container, and add the special attribute to it to
theContainer = sets( em=True, n='%s_%s' % (typeClass.__name__, kwDict.get( 'idx', 'NOIDX' )), text='rigPrimitive' )
theInstance.setContainer( theContainer )
addAttr( theContainer, ln='_rigPrimitive', attributeType='compound', numberOfChildren=7 )
addAttr( theContainer, ln='typeName', dt='string', parent='_rigPrimitive' )
addAttr( theContainer, ln='script', dt='string', parent='_rigPrimitive' )
addAttr( theContainer, ln='version', at='long', parent='_rigPrimitive' )
addAttr( theContainer, ln='skeletonPart', at='message', parent='_rigPrimitive' )
addAttr( theContainer, ln='buildKwargs', dt='string', parent='_rigPrimitive' )
addAttr( theContainer, ln='controls',
multi=True,
indexMatters=True,
attributeType='message',
parent='_rigPrimitive' )
addAttr( theContainer, ln='namedNodes',
multi=True,
indexMatters=True,
attributeType='message',
parent='_rigPrimitive' )
#now set the attribute values...
setAttr( '%s._rigPrimitive.typeName' % theContainer, typeClass.__name__, type='string' )
setAttr( '%s._rigPrimitive.script' % theContainer, inspect.getfile( typeClass ), type='string' )
setAttr( '%s._rigPrimitive.version' % theContainer, typeClass.__version__ )
setAttr( '%s._rigPrimitive.buildKwargs' % theContainer, str( kwDict ), type='string' )
#now add all the nodes
nodes = [ str( node ) if node is not None else node for node in nodes ]
controls = [ str( node ) if node is not None else node for node in controls ]
for node in set( nodes ) | set( controls ):
if node is None:
continue
if objectType( node, isAType='dagNode' ):
sets( node, e=True, add=theContainer )
#if the node is a rig part container add it to this container otherwise skip it
elif objectType( node, isAType='objectSet' ):
if isRigPartContainer( node ):
sets( node, e=True, add=theContainer )
#and now hook up all the controls
controlNames = typeClass.CONTROL_NAMES or [] #CONTROL_NAMES can validly be None, so in this case just call it an empty list
for idx, control in enumerate( controls ):
if control is None:
continue
connectAttr( '%s.message' % control, '%s._rigPrimitive.controls[%d]' % (theContainer, idx), f=True )
#set the kill state on the control if its a transform node
if objectType( control, isAType='transform' ):
triggered.setKillState( control, True )
#hook up all the named nodes
for idx, node in enumerate( namedNodes ):
if node is None:
continue
connectAttr( '%s.message' % node, '%s._rigPrimitive.namedNodes[%d]' % (theContainer, idx), f=True )
return theInstance
class RigPart(typeFactories.trackableClassFactory()):
'''
base rig part class. deals with rig part creation.
rig parts are instantiated by passing the class a rig part container node
to create a new rig part, simply call the RigPartClass.Create( skeletonPart, *args )
where the skeletonPart is the SkeletonPart instance created via the skeleton builder
'''
__version__ = 0
PRIORITY = 0
CONTROL_NAMES = None
NAMED_NODE_NAMES = None
AVAILABLE_IN_UI = False #determines whether this part should appear in the UI or not...
ADD_CONTROLS_TO_QSS = True
AUTO_PICKER = True
#if you want to customize the name as it appears in the UI, set this to the desired string
DISPLAY_NAME = None
def __new__( cls, partContainer, skeletonPart=None ):
if cls is RigPart:
clsName = getAttr( '%s._rigPrimitive.typeName' % partContainer )
cls = cls.GetNamedSubclass( clsName )
if cls is None:
raise TypeError( "Cannot determine the part class for the given part container!" )
return object.__new__( cls, partContainer, skeletonPart )
def __init__( self, partContainer, skeletonPart=None ):
if partContainer is not None:
assert isRigPartContainer( partContainer ), "Must pass a valid rig part container! (received %s - a %s)" % (partContainer, nodeType( partContainer ))
self._container = partContainer
self._skeletonPart = skeletonPart
self._worldPart = None
self._worldControl = None
self._partsNode = None
self._qss = None
self._idx = None
if partContainer:
if skeletonPart is None:
try:
self.getSkeletonPart()
#this isn't fatal, although its not good
except RigPartError, x:
printWarningStr( str( x ) )
def __unicode__( self ):
return u"%s_%d( %r )" % (self.__class__.__name__, self.getIdx(), self._container)
__str__ = __unicode__
def __repr__( self ):
return repr( unicode( self ) )
def __hash__( self ):
'''
the hash for the container mobject uniquely identifies this rig control
'''
return hash( apiExtensions.asMObject( self._container ) )
def __eq__( self, other ):
return self._container == other.getContainer()
def __neq__( self, other ):
return not self == other
def __getitem__( self, idx ):
'''
returns the control at <idx>
'''
connected = listConnections( '%s._rigPrimitive.controls[%d]' % (self._container, idx), d=False )
if connected:
assert len( connected ) == 1, "More than one control was found!!!"
return connected[ 0 ]
return None
def __len__( self ):
'''
returns the number of controls registered on the rig
'''
return getAttr( '%s._rigPrimitive.controls' % self._container, size=True )
def __iter__( self ):
'''
iterates over all controls in the rig
'''
for n in range( len( self ) ):
yield self[ n ]
def getContainer( self ):
return self._container
def setContainer( self, container ):
self._container = container
def getNodes( self ):
'''
returns ALL the nodes that make up this rig part
'''
return sets( self._container, q=True )
nodes = getNodes
def isReferenced( self ):
return referenceQuery( self._container, inr=True )
@classmethod
def GetPartName( cls ):
'''
can be used to get a "nice" name for the part class
'''
if cls.DISPLAY_NAME is None:
return camelCaseToNice( cls.__name__ )
return cls.DISPLAY_NAME
@classmethod
def InitFromItem( cls, item ):
'''
inits the rigPart from a member item - the RigPart instance returned is
cast to teh most appropriate type
'''
if isRigPartContainer( item ):
typeClassStr = getAttr( '%s._rigPrimitive.typeName' % partContainer )
typeClass = RigPart.GetNamedSubclass( typeClassStr )
return typeClass( item )
cons = listConnections( item, s=False, type='objectSet' )
if not cons:
raise RigPartError( "Cannot find a rig container for %s" % item )
for con in cons:
if isRigPartContainer( con ):
typeClassStr = getAttr( '%s._rigPrimitive.typeName' % con )
typeClass = RigPart.GetNamedSubclass( typeClassStr )
return typeClass( con )
raise RigPartError( "Cannot find a rig container for %s" % item )
@classmethod
def IterAllParts( cls, skipSubParts=True ):
'''
iterates over all RigParts in the current scene
NOTE: if skipSubParts is True will skip over parts that inherit from RigSubPart - these are assumed to be contained by another part
'''
for c in getRigPartContainers():
if objExists( '%s._rigPrimitive' % c ):
thisClsName = getAttr( '%s._rigPrimitive.typeName' % c )
thisCls = RigPart.GetNamedSubclass( thisClsName )
if thisCls is None:
raise SkeletonError( "No RigPart called %s" % thisClsName )
if skipSubParts and issubclass( thisCls, RigSubPart ):
continue
if issubclass( thisCls, cls ):
yield cls( c )
@classmethod
def IterAllPartsInOrder( cls, skipSubParts=False ):
for skeletonPart in SkeletonPart.IterAllPartsInOrder():
rigPart = skeletonPart.getRigPart()
if rigPart is None:
continue
if skipSubParts and isinstance( rigPart, RigSubPart ):
continue
yield rigPart
@classmethod
def GetUniqueIdx( cls ):
'''
returns a unique index (unique against the universe of existing indices
in the scene) for the current part class
'''
existingIdxs = []
for part in cls.IterAllParts():
idx = part.getBuildKwargs()[ 'idx' ]
existingIdxs.append( idx )
existingIdxs.sort()
assert len( existingIdxs ) == len( set( existingIdxs ) ), "There is a duplicate ID! %s, %s" % (cls, existingIdxs)
#return the first, lowest, available index
for orderedIdx, existingIdx in enumerate( existingIdxs ):
if existingIdx != orderedIdx:
return orderedIdx
if existingIdxs:
return existingIdxs[ -1 ] + 1
return 0
def createSharedShape( self, name ):
return asMObject( createNode( 'nurbsCurve', n=name +'#', p=self.sharedShapeParent ) )
@classmethod
def Create( cls, skeletonPart, *a, **kw ):
'''
you can pass in the following kwargs to control the build process
addControlsToQss defaults to cls.ADD_CONTROLS_TO_QSS
'''
#check to see if the given skeleton part can actually be rigged by this method
if not cls.CanRigThisPart( skeletonPart ):
return
addControlsToQss = kw.get( 'addControlsToQss', cls.ADD_CONTROLS_TO_QSS )
buildFunc = getattr( cls, '_build', None )
if buildFunc is None:
raise RigPartError( "The rigPart %s has no _build method!" % cls.__name__ )
assert isinstance( skeletonPart, SkeletonPart ), "Need a SkeletonPart instance, got a %s instead" % skeletonPart.__class__
if not skeletonPart.compareAgainstHash():
raise NotFinalizedError( "ERROR :: %s hasn't been finalized!" % skeletonPart )
#now turn the args passed in are a single kwargs dict
argNames, vArgs, vKwargs, defaults = inspect.getargspec( buildFunc )
if defaults is None:
defaults = []
argNames = argNames[ 2: ] #strip the first two args - which should be the instance arg (usually self) and the skeletonPart
if vArgs is not None:
raise RigPartError( 'cannot have *a in rig build functions' )
for argName, value in zip( argNames, a ):
kw[ argName ] = value
#now explicitly add the defaults
for argName, default in zip( argNames, defaults ):
kw.setdefault( argName, default )
#generate an index for the rig part - each part must have a unique index
idx = cls.GetUniqueIdx()
kw[ 'idx' ] = idx
#construct an empty instance - empty RigPart instances are only valid inside this method...
self = cls( None )
self._skeletonPart = skeletonPart
self._idx = idx
#generate a default scale for the rig part
kw.setdefault( 'scale', getScaleFromSkeleton() / 10.0 )
self.scale = kw[ 'scale' ]
#make sure the world part is created first - if its created by the part, then its nodes will be included in its container...
self.getWorldPart()
#create the shared shape transform - this is the transform under which all shared shapes are temporarily parented to, and all
#shapes under this transform are automatically added to all controls returned after the build function returns
self.sharedShapeParent = asMObject( createNode( 'transform', n='_tmp_sharedShape' ) )
defaultSharedShape = self.createSharedShape( '%s_sharedAttrs' % cls.GetPartName() )
kw[ 'sharedShape' ] = defaultSharedShape
#run the build function
newNodes, (controls, namedNodes) = getNodesCreatedBy( self._build, skeletonPart, **kw )
realControls = [ c for c in controls if c is not None ] #its possible for a build function to return None in the control list because it wants to preserve the length of the control list returned - so construct a list of controls that actually exist
realNamedNodes = [ c for c in namedNodes if c is not None ]
if addControlsToQss:
for c in realControls:
sets( c, add=self._qss )
#check to see if there is a layer for the rig controls and add controls to it
if controls:
if objExists( 'rig_controls' ) and nodeType( 'rig_controls' ) == 'displayLayer':
rigLayer = 'rig_controls'
else:
rigLayer = createDisplayLayer( name='rig_controls', empty=True )
editDisplayLayerMembers( rigLayer, controls, noRecurse=True )
#make sure there are no intermediate shapes
for c in realControls:
for shape in listRelatives( c, s=True, pa=True ) or []:
if getAttr( '%s.intermediateObject' % shape ):
delete( shape )
#build the container and initialize the rigPrimtive
buildContainer( self, kw, newNodes, controls, namedNodes )
#add shared shapes to all controls, and remove shared shapes that are empty
sharedShapeParent = self.sharedShapeParent
sharedShapes = listRelatives( sharedShapeParent, pa=True, s=True ) or []
for c in realControls:
if objectType( c, isAType='transform' ):
for shape in sharedShapes:
parent( shape, c, add=True, s=True )
for shape in sharedShapes:
if not listAttr( shape, ud=True ):
delete( shape )
delete( sharedShapeParent )
del( self.sharedShapeParent )
#stuff the part container into the world container - we want a clean top level in the outliner
theContainer = self._container
sets( theContainer, e=True, add=self._worldPart.getContainer() )
#make sure the container "knows" the skeleton part - its not always obvious trawling through
#the nodes in teh container which items are the skeleton part
connectAttr( '%s.message' % skeletonPart.getContainer(), '%s._rigPrimitive.skeletonPart' % theContainer )
return self
@classmethod
def GetControlName( cls, control ):
'''
returns the name of the control as defined in the CONTROL_NAMES attribute
for the part class
'''
cons = listConnections( control.message, s=False, p=True, type='objectSet' )
for c in cons:
typeClassStr = getAttr( '%s._rigPrimitive.typeName' % c.node() )
typeClass = RigPart.GetNamedSubclass( typeClassStr )
if typeClass.CONTROL_NAMES is None:
return str( control )
idx = c[ c.rfind( '[' )+1:-1 ]
try: name = typeClass.CONTROL_NAMES[ idx ]
except ValueError:
printErrorStr( 'type: %s control: %s' % (typeClass, control) )
raise RigPartError( "Doesn't have a name!" )
return name
raise RigPartError( "The control isn't associated with a rig primitive" )
@classmethod
def CanRigThisPart( cls, skeletonPart ):
return True
@classmethod
def GetDefaultBuildKwargList( cls ):
'''
returns a list of 2 tuples: argName, defaultValue
'''
buildFunc = getattr( cls, '_build', None )
spec = inspect.getargspec( buildFunc )
argNames = spec[ 0 ][ 2: ] #strip the first two items because the _build method is a bound method - so the first item is always the class arg (usually called cls), and the second arg is always the skeletonPart
defaults = spec[ 3 ]
if defaults is None:
defaults = []
assert len( argNames ) == len( defaults ), "%s has no default value set for one of its args - this is not allowed" % cls
kwargList = []
for argName, default in zip( argNames, defaults ):
kwargList.append( (argName, default) )
return kwargList
def isPartContained( self ):
'''
returns whether this rig part is "contained" by another rig part. Ie if a rig part was build from within another
rig part, then it is contained. Examples of this are things like the arm rig which builds upon the ikfk sub
primitive rig - the sub-primitive is contained within the arm rig
'''
cons = listConnections( '%s.message' % self._container, s=False, type='objectSet' )
if cons:
for con in cons:
if isRigPartContainer( con ):
rigPart = RigPart( con )
if isinstance( rigPart, WorldPart ):
continue
return True
return False
def getBuildKwargs( self ):
theDict = eval( getAttr( '%s._rigPrimitive.buildKwargs' % self._container ) )
return theDict
def getIdx( self ):
'''
returns the index of the part - all parts have a unique index associated
with them
'''
if self._idx is None:
if self._container is None:
raise RigPartError( 'No index has been defined yet!' )
else:
buildKwargs = self.getBuildKwargs()
self._idx = buildKwargs[ 'idx' ]
return self._idx
def getParity( self ):
return self.getSkeletonPart().getParity()
def getSuffix( self ):
return self.getParity().asName()
def getParityColour( self ):
return ColourDesc( 'green 0.7' ) if self.getParity() == Parity.LEFT else ColourDesc( 'red 0.7' )
def getBuildScale( self ):
return self.getBuildKwargs().get( 'scale', self.PART_SCALE )
def getWorldPart( self ):
if self._worldPart is None:
self._worldPart = worldPart = WorldPart.Create()
self._worldControl = worldPart.getControl( 'control' )
self._partsNode = worldPart.getNamedNode( 'parts' )
self._qss = worldPart.getNamedNode( 'qss' )
return self._worldPart
def getWorldControl( self ):
if self._worldControl is None:
self.getWorldPart()
return self._worldControl
def getPartsNode( self ):
if self._partsNode is None:
self.getWorldPart()
return self._partsNode
def getQssSet( self ):
if self._qss is None:
self.getWorldPart()
return self._qss
def getSkeletonPart( self ):
'''
returns the skeleton part this rig part is driving
'''
#have we cached the skeleton part already? if so, early out!
if self._skeletonPart:
return self._skeletonPart
if self._container is None:
return None
connected = listConnections( '%s.skeletonPart' % self._container )
if connected is None:
raise RigPartError( "There is no skeleton part associated with this rig part! This can happen for a variety of reasons such as name changes on the skeleton in the model file (if you're using referencing), or a incomplete conversion from the old rig format..." )
if nodeType( connected[0] ) == 'reference':
raise RigPartError( "A reference node is connected to the skeletonPart attribute - this could mean the model reference isn't loaded, or a node name from the referenced file has changed - either way I can't determine the skeleton part used by this rig!" )
#cache the value so we can quickly return it on consequent calls
self._skeletonPart = skeletonPart = SkeletonPart.InitFromItem( connected[0] )
return skeletonPart
def getSkeletonPartParity( self ):
return self.getSkeletonPart().getParity()
def getControl( self, attrName ):
'''
returns the control named <attrName>. control "names" are defined by the CONTROL_NAMES class
variable. This list is asked for the index of <attrName> and the control at that index is returned
'''
if self.CONTROL_NAMES is None:
raise AttributeError( "The %s rig primitive has no named controls" % self.__class__.__name__ )
idx = list( self.CONTROL_NAMES ).index( attrName )
if idx < 0:
raise AttributeError( "No control with the name %s" % attrName )
connected = listConnections( '%s._rigPrimitive.controls[%d]' % (self._container, idx), d=False )
if connected:
assert len( connected ) == 1, "More than one control was found!!!"
return connected[ 0 ]
return None
def getControlIdx( self, control ):
'''
returns the index of the given control - each control is plugged into a given "slot"
'''
cons = cmd.listConnections( '%s.message' % control, s=False, p=True ) or []
for c in cons:
node = c.split( '.' )[0]
if not isRigPartContainer( node ):
continue
if objExists( node ):
if node != self._container:
continue
idx = int( c[ c.rfind( '[' )+1:-1 ] )
return idx
raise RigPartError( "The control %s isn't associated with this rig primitive %s" % (control, self) )
def getControlName( self, control ):
'''
returns the name of the control as defined in the CONTROL_NAMES attribute
for the part class
'''
if self.CONTROL_NAMES is None:
return str( control )
controlIdx = self.getControlIdx( control )
try:
return self.CONTROL_NAMES[ controlIdx ]
except IndexError:
return None
raise RigPartError( "The control %s isn't associated with this rig primitive %s" % (control, self) )
def getNamedNode( self, nodeName ):
'''
returns the "named node" called <nodeName>. Node "names" are defined by the NAMED_NODE_NAMES class
variable. This list is asked for the index of <nodeName> and the node at that index is returned
'''
if self.NAMED_NODE_NAMES is None:
raise AttributeError( "The %s rig primitive has no named nodes" % self.__class__.__name__ )
idx = list( self.NAMED_NODE_NAMES ).index( nodeName )
if idx < 0:
raise AttributeError( "No node with the name %s" % nodeName )
connected = listConnections( '%s._rigPrimitive.namedNodes[%d]' % (self._container, idx), d=False )
if connected:
assert len( connected ) == 1, "More than one node was found!!!"
return connected[ 0 ]
return None
def delete( self ):
nodes = sets( self._container, q=True )
for node in nodes:
cleanDelete( node )
if objExists( self._container ):
delete( self._container )
#if the skeleton part is referenced, clean all reference edits off skeleton part joints
skeletonPart = self.getSkeletonPart()
if skeletonPart.isReferenced():
skeletonPartJoints = skeletonPart.items
#now unload the reference
partReferenceFile = Path( referenceQuery( skeletonPart.getContainer(), filename=True ) )
file( partReferenceFile, unloadReference=True )
#remove edits from each joint in the skeleton part
for j in skeletonPartJoints:
referenceEdit( j, removeEdits=True, successfulEdits=True, failedEdits=True )
#reload the referenced file
file( partReferenceFile, loadReference=True )
### POSE MIRRORING/SWAPPING ###
def getOppositePart( self ):
'''
Finds the skeleton part opposite to the one this rig part controls, and returns its rig part.
If no rig part can be found, or if no
'''
thisSkeletonPart = self.getSkeletonPart()
oppositeSkeletonPart = thisSkeletonPart.getOppositePart()
if oppositeSkeletonPart is None:
return None
return oppositeSkeletonPart.getRigPart()
def getOppositeControl( self, control ):
'''
Finds the control that is most likely to be opposite the one given. It first gets the name of
the given control. It then finds the opposite rig part, and then queries it for the control
with the determined name
'''
controlIdx = self.getControlIdx( control )
oppositePart = self.getOppositePart()
if oppositePart:
return oppositePart[ controlIdx ]
return None
def setupMirroring( self ):
for control in self:
if control is None:
continue
oppositeControl = self.getOppositeControl( control )
pair = poseSym.ControlPair.Create( control, oppositeControl )
printInfoStr( 'setting up mirroring on %s %s' % (control, oppositeControl) )
def getFilePartDict():
'''
returns a dictionary keyed by scene name containing a list of the parts contained in that scene
'''
scenePartDict = {}
#special case! we want to skip parts that are of this exact type - in older rigs this class was a RigSubPart, not a super class for the biped limb classes
IkFkBaseCls = RigPart.GetNamedSubclass( 'IkFkBase' )
for rigPart in RigPart.IterAllParts():
if IkFkBaseCls:
if type( rigPart ) is IkFkBaseCls:
continue
isReferenced = rigPart.isReferenced()
if isReferenced:
rigScene = Path( referenceQuery( rigPart.getContainer(), filename=True ) )
else:
rigScene = Path( file( q=True, sn=True ) )
scenePartDict.setdefault( rigScene, [] )
partList = scenePartDict[ rigScene ]
partList.append( rigPart )
return scenePartDict
def generateNiceControlName( control ):
niceName = getNiceName( control )
if niceName is not None:
return niceName
try:
rigPart = RigPart.InitFromItem( control )
if rigPart is None: raise RigPartError( "null" )
controlName = rigPart.getControlName( control )
except RigPartError:
controlName = str( control )
controlName = Name( controlName )
parity = controlName.get_parity()
if parity == Parity.LEFT:
controlName = 'Left '+ str( stripParity( controlName ) )
if parity == Parity.RIGHT:
controlName = 'Right '+ str( stripParity( controlName ) )
else:
controlName = str( controlName )
return camelCaseToNice( controlName )
def getSpaceSwitchControls( theJoint ):
'''
walks up the joint chain and returns a list of controls that drive parent joints
'''
parentControls = []
for p in api.iterParents( theJoint ):
theControl = getItemRigControl( p )
if theControl is not None:
parentControls.append( theControl )
return parentControls
def buildDefaultSpaceSwitching( theJoint, control=None, additionalParents=(), additionalParentNames=(), reverseHierarchy=False, **buildKwargs ):
if control is None:
control = getItemRigControl( theJoint )
theWorld = WorldPart.Create()
spaces = getSpaceSwitchControls( theJoint )
spaces.append( theWorld.getControl( 'control' ) )
#determine default names for the given controls
names = []
for s in spaces:
names.append( generateNiceControlName( s ) )
additionalParents = list( additionalParents )
additionalParentNames = list( additionalParentNames )
for n in range( len( additionalParentNames ), len( additionalParents ) ):
additionalParentNames.append( generateNiceControlName( additionalParents[ n ] ) )
spaces += additionalParents
names += additionalParentNames
#we don't care about space switching if there aren't any non world spaces...
if not spaces:
return
if reverseHierarchy:
spaces.reverse()
names.reverse()
return spaceSwitching.build( control, spaces, names, **buildKwargs )
def getParentAndRootControl( theJoint ):
'''
returns a 2 tuple containing the nearest control up the hierarchy, and the
most likely control to use as the "root" control for the rig. either of these
may be the world control, but both values are guaranteed to be an existing
control object
'''
parentControl, rootControl = None, None
for p in api.iterParents( theJoint ):
theControl = getItemRigControl( p )
if theControl is None:
continue
if parentControl is None:
parentControl = theControl
skelPart = SkeletonPart.InitFromItem( p )
if isinstance( skelPart, skeletonBuilder.Root ):
rootControl = theControl
if parentControl is None or rootControl is None:
world = WorldPart.Create()
if parentControl is None:
parentControl = world.getControl( 'control' )
if rootControl is None:
rootControl = world.getControl( 'control' )
return parentControl, rootControl
def createLineOfActionMenu( controls, joints ):
'''
deals with adding a "draw line of action" menu to each control in the controls
list. the line is drawn through the list of joints passed
'''
if not joints: return
if not isinstance( controls, (list, tuple) ):
controls = [ controls ]
joints = list( joints )
jParent = getNodeParent( joints[ 0 ] )
if jParent:
joints.insert( 0, jParent )
for c in controls:
cTrigger = Trigger( c )
spineConnects = [ cTrigger.connect( j ) for j in joints ]
Trigger.CreateMenu( c,
"draw line of action",
"zooLineOfAction;\nzooLineOfAction_multi { %s } \"\";" % ', '.join( '"%%%d"'%idx for idx in spineConnects ) )
class RigSubPart(RigPart):
'''
'''
#this attribute describes what skeleton parts the rig primitive is associated with. If the attribute's value is None, then the rig primitive
#is considered a "hidden" primitive that has
SKELETON_PRIM_ASSOC = None
class PrimaryRigPart(RigPart):
'''
all subclasses of this class are exposed as available rigging methods to the user
'''
AVAILABLE_IN_UI = True
class WorldPart(RigPart):
'''
the world part can only be created once per scene. if an existing world part instance is found
when calling WorldPart.Create() it will be returned instead of creating a new instance
'''
__version__ = 0
CONTROL_NAMES = 'control', 'exportRelative'
NAMED_NODE_NAMES = 'parts', 'masterQss', 'qss'
WORLD_OBJ_MENUS = [ ('toggle rig vis', """{\nstring $childs[] = `listRelatives -pa -type transform #`;\nint $vis = !`getAttr ( $childs[0]+\".v\" )`;\nfor($a in $childs) if( `objExists ( $a+\".v\" )`) if( `getAttr -se ( $a+\".v\" )`) setAttr ( $a+\".v\" ) $vis;\n}"""),
('draw all lines of action', """string $menuObjs[] = `zooGetObjsWithMenus`;\nfor( $m in $menuObjs ) {\n\tint $cmds[] = `zooObjMenuListCmds $m`;\n\tfor( $c in $cmds ) {\n\t\tstring $name = `zooGetObjMenuCmdName $m $c`;\n\t\tif( `match \"draw line of action\" $name` != \"\" ) eval(`zooPopulateCmdStr $m (zooGetObjMenuCmdStr($m,$c)) {}`);\n\t\t}\n\t}"""),
('show "export relative" node', """""") ]
@classmethod
@d_unifyUndo
def Create( cls, **kw ):
for existingWorld in cls.IterAllParts():
return existingWorld
#try to determine scale - walk through all existing skeleton parts in the scene
for skeletonPart in SkeletonPart.IterAllPartsInOrder():
kw.setdefault( 'scale', skeletonPart.getBuildScale() )
break
worldNodes, (controls, namedNodes) = getNodesCreatedBy( cls._build, **kw )
worldPart = buildContainer( WorldPart, { 'idx': 0 }, worldNodes, controls, namedNodes )
#check to see if there is a layer for the rig controls and add controls to it
if objExists( 'rig_controls' ) and nodeType( 'rig_controls' ) == 'displayLayer':
rigLayer = 'rig_controls'
else:
rigLayer = createDisplayLayer( name='rig_controls', empty=True )
editDisplayLayerMembers( rigLayer, controls, noRecurse=True )
return worldPart
@classmethod
def _build( cls, **kw ):
scale = kw.get( 'scale', skeletonBuilder.TYPICAL_HEIGHT )
scale /= 1.5
world = buildControl( 'main', shapeDesc=ShapeDesc( None, 'hex', AX_Y ), oriented=False, scale=scale, niceName='The World' )
parts = group( empty=True, name='parts_grp' )
qss = sets( empty=True, text="gCharacterSet", n="body_ctrls" )
masterQss = sets( empty=True, text="gCharacterSet", n="all_ctrls" )
exportRelative = buildControl( 'exportRelative', shapeDesc=ShapeDesc( None, 'cube', AX_Y_NEG ), pivotModeDesc=PivotModeDesc.BASE, oriented=False, size=(1, 0.5, 1), scale=scale )
parentConstraint( world, exportRelative )
attrState( exportRelative, ('t', 'r', 's'), *LOCK_HIDE )
attrState( exportRelative, 'v', *HIDE )
setAttr( '%s.v' % exportRelative, False )
#turn scale segment compensation off for all joints in the scene
for j in ls( type='joint' ):
setAttr( '%s.ssc' % j, False )
sets( qss, add=masterQss )
attrState( world, 's', *NORMAL )
connectAttr( '%s.scale' % world, '%s.scale' % parts )
connectAttr( '%s.scaleX' % world, '%s.scaleY' % world )
connectAttr( '%s.scaleX' % world, '%s.scaleZ' % world )
#add right click items to the world controller menu
worldTrigger = Trigger( str( world ) )
qssIdx = worldTrigger.connect( str( masterQss ) )
#add world control to master qss
sets( world, add=masterQss )
sets( exportRelative, add=masterQss )
#turn unwanted transforms off, so that they are locked, and no longer keyable
attrState( world, 's', *NO_KEY )
attrState( world, ('sy', 'sz'), *LOCK_HIDE )
attrState( parts, [ 't', 'r', 's', 'v' ], *LOCK_HIDE )
controls = world, exportRelative
namedNodes = parts, masterQss, qss
return controls, namedNodes
def getSkeletonPart( self ):
#the world part has no skeleton part...
return None
def setupMirroring( self ):
pair = poseSym.ControlPair.Create( self.getControl( 'control' ) )
pair.setFlips( 0 )
### <CHEEKY!> ###
'''
these functions get added to the SkeletonPart class as a way of implementing functionality that relies on
the RigPart class - which isn't available in the baseSkeletonPart script (otherwise you'd have a circular
import dependency)
'''
def _getRigContainer( self ):
'''
returns the container for the rig part - if this part is rigged. None is returned otherwise
NOTE: the container is returned instead of the rig instance because this script can't import
the RigPart base class without causing circular import statements - there is a getRigPart
method that is implemented in the baseRigPrimitive script that gets added to this class
'''
rigContainerAttrpath = '%s.rigContainer' % self.getContainer()
if objExists( rigContainerAttrpath ):
cons = listConnections( rigContainerAttrpath, d=False )
if cons:
return cons[0]
cons = listConnections( '%s.message' % self.getContainer(), s=False, type='objectSet' )
if cons:
connectedRigParts = []
for con in cons:
if isRigPartContainer( con ):
connectedRigParts.append( RigPart( con ) )
#now we have a list of connected rig parts - lets figure out which ones are "top level" parts - ie don't belong to another part
if connectedRigParts:
for rigPart in connectedRigParts:
if not rigPart.isPartContained():
return rigPart
return None
def _getRigPart( self ):
rigContainer = self.getRigContainer()
if rigContainer:
return RigPart( self.getRigContainer() )
return None
SkeletonPart.getRigContainer = _getRigContainer
SkeletonPart.getRigPart = _getRigPart
def _deleteRig( self ):
rigPart = self.getRigPart()
rigPart.delete()
SkeletonPart.deleteRig = d_unifyUndo( _deleteRig )
### </CHEEKY!> ###
@d_unifyUndo
def setupMirroring():
'''
sets up all controls in the scene for mirroring
'''
for rigPart in RigPart.IterAllParts():
rigPart.setupMirroring()
@d_unifyUndo
@api.d_showWaitCursor
def buildRigForModel( scene=None, referenceModel=True, deletePlacers=False ):
'''
given a model scene whose skeleton is assumed to have been built by the
skeletonBuilder tool, this function will create a rig scene by referencing
in said model, creating the rig as best it knows how, saving the scene in
the appropriate spot etc...
'''
#if no scene was passed, assume we're acting on the current scene
if scene is None:
scene = filesystem.Path( cmd.file( q=True, sn=True ) )
#if the scene WAS passed in, open the desired scene if it isn't already open
else:
scene = filesystem.Path( scene )
curScene = filesystem.Path( cmd.file( q=True, sn=True ) )
if curScene:
if scene != curScene:
mel.saveChanges( 'file -f -open "%s"' % scene )
else: cmd.file( scene, f=True, open=True )
#if the scene is still none bail...
if not scene and referenceModel:
raise SceneNotSavedError( "Uh oh, your scene hasn't been saved - Please save it somewhere on disk so I know where to put the rig. Thanks!" )
#backup the current state of the scene, just in case something goes south...
if scene.exists():
backupFilename = scene.up() / ('%s_backup.%s' % (scene.name(), scene.getExtension()))
if backupFilename.exists():
backupFilename.delete()
cmd.file( rename=backupFilename )
cmd.file( save=True, force=True )
cmd.file( rename=scene )
#finalize
failedParts = finalizeAllParts()
if failedParts:
confirmDialog( t='Finalization Failure', m='The following parts failed to finalize properly:\n\n%s' % '\n'.join( map( str, failedParts ) ), b='OK', db='OK' )
return
#delete placers if desired - NOTE: this should be done after after finalization because placers are often used to define alignment for end joints
if deletePlacers:
for part in SkeletonPart.IterAllParts():
placers = part.getPlacers()
if placers:
delete( placers )
#if desired, create a new scene and reference in the model
if referenceModel:
#remove any unknown nodes in the scene - these cause maya to barf when trying to save
unknownNodes = ls( type='unknown' )
if unknownNodes:
delete( unknownNodes )
#scene.editoradd()
cmd.file( f=True, save=True )
cmd.file( f=True, new=True )
api.referenceFile( scene, 'model' )
#rename the scene to the rig
rigSceneName = '%s_rig.ma' % scene.name()
rigScene = scene.up() / rigSceneName
cmd.file( rename=rigScene )
cmd.file( f=True, save=True, typ='mayaAscii' )
else:
rigScene = scene
buildRigForAllParts()
setupMirroring()
return rigScene
@d_unifyUndo
def buildRigForAllParts():
for part in SkeletonPart.IterAllPartsInOrder():
part.rig()
#create a layer for the skeleton
for rootPart in Root.IterAllParts():
pass
@d_unifyUndo
def cleanMeshControls( doConfirm=True ):
shapesRemoved = 0
for node in getRigPartContainers( True ):
clsName = getAttr( '%s._rigPrimitive.typeName' % node )
cls = RigPart.GetNamedSubclass( clsName )
if cls is None:
continue
rigPart = cls( node )
for c in rigPart:
for shape in listRelatives( c, s=True, pa=True ) or []:
if getAttr( '%s.intermediateObject' % shape ):
delete( shape )
shapesRemoved += 1
printInfoStr( "Clean up %d bogus shapes" % shapesRemoved )
if doConfirm:
cmd.confirmDialog( t='Done!', m="I'm done polishing your rig!\n%d shapes removed." % shapesRemoved, b='OK', db='OK' )
#end
| Python |
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
AUTHOR = '-:macaroniKazoo:-'
VERSION = '1.0'
NODE_NAME = 'twister'
ID = OpenMaya.MTypeId( 0x43899 )
class twister( OpenMayaMPx.MPxNode ):
aInWorldMatrixA = OpenMaya.MObject()
aInWorldMatrixB = OpenMaya.MObject()
aAxisA = OpenMaya.MObject()
aAxisB = OpenMaya.MObject()
aDivider = OpenMaya.MObject()
aOutRotate = OpenMaya.MObject()
aOutRotateX = OpenMaya.MObject()
aOutRotateY = OpenMaya.MObject()
aOutRotateZ = OpenMaya.MObject()
def __init__( self ):
OpenMayaMPx.MPxNode.__init__(self)
def compute( self, plug, data ):
if plug == self.aOutRotate or plug == self.aOutRotateX or plug == self.aOutRotateY or plug == self.aOutRotateZ:
#get handles to the attributes
hInWorldMatrixA = data.inputValue(self.aInWorldMatrixA)
matWorldA = hInWorldMatrixA.asMatrix()
matWorldAinv = matWorldA.inverse()
hInWorldMatrixB = data.inputValue(self.aInWorldMatrixB)
matWorldB = hInWorldMatrixB.asMatrix()
hAxisA = data.inputValue(self.aAxisA)
nAxisA = hAxisA.asShort()
hAxisB = data.inputValue(self.aAxisB)
nAxisB = hAxisB.asShort()
hDivider = data.inputValue(self.aDivider)
dDivider = hDivider.asDouble()
#build the vectors to compare
axes = OpenMaya.MVector(1,0,0),OpenMaya.MVector(0,1,0),OpenMaya.MVector(0,0,1)
#any index above 2 is just one of the first 3 axes negated - so deal with it
vVecA = OpenMaya.MVector( axes[nAxisA%3] ) #make a copy of the vectors
vVecB = OpenMaya.MVector( axes[nAxisB%3] )
if nAxisA > 2: vVecA *= -1
if nAxisB > 2: vVecB *= -1
#put the B vector into the space of inputA so we can meaningfully compare them to get an angle between
vVecB *= matWorldB
vVecB *= matWorldAinv
#finally grab the rotation between them and push it out to outRotate
qRotBetween = OpenMaya.MQuaternion(vVecA,vVecB,(1/dDivider))
asEuler = qRotBetween.asEulerRotation()
#grab the output attribute handles and set their values
hOutRotateX = data.outputValue( self.aOutRotateX )
hOutRotateY = data.outputValue( self.aOutRotateY )
hOutRotateZ = data.outputValue( self.aOutRotateZ )
hOutRotateX.setDouble( asEuler.x )
hOutRotateY.setDouble( asEuler.y )
hOutRotateZ.setDouble( asEuler.z )
#mark all attributes as clean
data.setClean(self.aOutRotate)
data.setClean(self.aOutRotateX)
data.setClean(self.aOutRotateY)
data.setClean(self.aOutRotateZ)
else:
return OpenMaya.MStatus.kUnknownParameter
return OpenMaya.MStatus.kSuccess
def initializePlugin( mObject ):
mPlugin = OpenMayaMPx.MFnPlugin( mObject, AUTHOR, VERSION, "Any" )
mPlugin.registerNode( NODE_NAME, ID, nodeCreator, nodeInitializer )
def uninitializePlugin( mObject ):
plugin = OpenMayaMPx.MFnPlugin( mObject )
plugin.deregisterNode( ID )
def nodeCreator():
return OpenMayaMPx.asMPxPtr( twister() )
def nodeInitializer():
nAttr = OpenMaya.MFnNumericAttribute()
mAttr = OpenMaya.MFnMatrixAttribute()
eAttr = OpenMaya.MFnEnumAttribute()
cAttr = OpenMaya.MFnCompoundAttribute()
twister.aInWorldMatrixA = mAttr.create( "inWorldMatrixA", "iwma" )
twister.aInWorldMatrixB = mAttr.create( "inWorldMatrixB", "iwmb" )
twister.aAxisA = eAttr.create("axisA", "axa", 0 )
eAttr.setChannelBox(True)
eAttr.setKeyable(True)
eAttr.addField( "X", 0 )
eAttr.addField( "Y", 1 )
eAttr.addField( "Z", 2 )
eAttr.addField( "-X", 3 )
eAttr.addField( "-Y", 4 )
eAttr.addField( "-Z", 5 )
twister.aAxisB = eAttr.create("axisB", "axb", 0 )
eAttr.setChannelBox(True)
eAttr.setKeyable(True)
eAttr.addField( "X", 0 )
eAttr.addField( "Y", 1 )
eAttr.addField( "Z", 2 )
eAttr.addField( "-X", 3 )
eAttr.addField( "-Y", 4 )
eAttr.addField( "-Z", 5 )
twister.aDivider = nAttr.create( "divider", "div", OpenMaya.MFnNumericData.kDouble, 1 )
nAttr.setMin(0.001)
nAttr.setChannelBox(True)
nAttr.setKeyable(True)
twister.aOutRotateX = nAttr.create( "outRotateX", "orx", OpenMaya.MFnNumericData.kDouble, 0.0 )
twister.aOutRotateY = nAttr.create( "outRotateY", "ory", OpenMaya.MFnNumericData.kDouble, 0.0 )
twister.aOutRotateZ = nAttr.create( "outRotateZ", "orz", OpenMaya.MFnNumericData.kDouble, 0.0 )
twister.aOutRotate = cAttr.create( "outRotate", "or")
cAttr.addChild( twister.aOutRotateX )
cAttr.addChild( twister.aOutRotateY )
cAttr.addChild( twister.aOutRotateZ )
twister.addAttribute( twister.aInWorldMatrixA )
twister.addAttribute( twister.aInWorldMatrixB )
twister.addAttribute( twister.aAxisA )
twister.addAttribute( twister.aAxisB )
twister.addAttribute( twister.aDivider )
twister.addAttribute( twister.aOutRotate )
#setup dependency relationships
twister.attributeAffects( twister.aInWorldMatrixA, twister.aOutRotate )
twister.attributeAffects( twister.aInWorldMatrixB, twister.aOutRotate )
twister.attributeAffects( twister.aDivider, twister.aOutRotate )
twister.attributeAffects( twister.aAxisB, twister.aOutRotate )
twister.attributeAffects( twister.aAxisB, twister.aOutRotate ) | Python |
from maya.cmds import *
import maya.cmds as cmd
import vectors
import re
Vector = vectors.Vector
Colour = Color = vectors.Colour
def setShaderColour( shader, colour ):
if not isinstance( colour, Colour ):
colour = Colour( colour )
setAttr( '%s.outColor' % shader, *colour )
if colour[ 3 ]:
a = colour[ 3 ]
setAttr( '%s.outTransparency' % shader, a, a, a )
def setObjShader( obj, shader ):
SG = listConnections( '%s.outColor' % shader, s=False, type='shadingEngine' )[ 0 ]
shapes = listRelatives( obj, pa=True, s=True ) or []
for shape in shapes:
if nodeType( shape ) == 'nurbsCurve': continue
sets( shape, e=True, forceElement=SG )
def getObjColour( obj ):
shader = getObjShader( obj )
if shader:
return getAttr( '%s.outColor' % shader )[0]
return None
def getObjShader( obj ):
'''
returns the shader currently assigned to the given object
'''
shapes = listRelatives( obj, s=True, pa=True ) or []
if not shapes:
return None
cons = listConnections( shapes, s=False, type='shadingEngine' ) or []
for c in cons:
shaders = listConnections( '%s.surfaceShader' % c, d=False ) or []
if shaders:
return shaders[ 0 ]
def getShader( colour, forceCreate=True ):
'''
given a colour, this proc will either return an existing shader with that colour
or it will create a new shader (if forceCreate is true) if an existing one isn't
found
NOTE - this proc will look for a shader that has a similar colour to the one
specified - so the colour may not always be totally accurate if a shader exists
with a similar colour - the colour/alpha threshold is 0.05
'''
if not isinstance( colour, Colour ):
colour = Colour( colour )
shaders = ls( type='surfaceShader' ) or []
for shader in shaders:
thisColour = list( getAttr( '%s.outColor' % shader )[ 0 ] )
alpha = getAttr( '%s.outTransparency' % shader )[ 0 ][ 0 ]
thisColour.append( alpha )
thisColour = Colour( thisColour )
if thisColour == colour:
return shader
if forceCreate:
return createShader( colour )
return None
def createShader( colour ):
'''
creates a shader of a given colour - always creates a new shader
'''
name = 'rigShader_%s' % Colour.ColourToName( colour )
shader = shadingNode( 'surfaceShader', name=name, asShader=True )
SG = sets( name='%s_SG' % name, renderable=True, noSurfaceShader=True, empty=True )
connectAttr( '%s.outColor' % shader, '%s.surfaceShader' % SG, f=True )
setAttr( '%s.outColor' % shader, *colour[ :3 ] )
a = colour[ 3 ]
setAttr( '%s.outTransparency' % shader, a, a, a )
shadingConnection( '%s.surfaceShader' % SG, e=True, cs=False )
return shader
def setDrawOverrideColor( obj, color=17 ):
"""
edit the given object's shape node override color
"""
shapes = []
if not cmd.objectType( obj, i='nurbsCurve' ) or not cmd.objectType( obj, i='nurbsSurface' ) or not cmd.objectType( obj, i='mesh' ):
shapes.append( obj )
for s in listRelatives( obj, s=True, pa=True ) or []:
shapes.append( s )
if shapes:
for s in shapes:
conns = cmd.listConnections( '%s.drawOverride' % s, s=True )
if not conns:
if not color == 0:
cmd.setAttr ('%s.overrideEnabled' % s, e=True, l=False )
cmd.setAttr ('%s.overrideEnabled' % s, 1 )
cmd.setAttr ('%s.overrideColor' % s, e=True, l=False )
cmd.setAttr ('%s.overrideColor' % s, color )
else:
cmd.color( s )
cmd.setAttr ('%s.overrideColor' % s, e=True, l=False )
cmd.setAttr ('%s.overrideColor' % s, color )
cmd.setAttr ('%s.overrideEnabled' % s, e=True, l=False )
cmd.setAttr ('%s.overrideEnabled' % s, 0 )
#end | Python |
from baseRigPrimitive import *
class StretchRig(RigSubPart):
'''
creates stretch attribs on the given control, and makes all given joints stretchy
-------
control the character prefix used to identify the character
parity which side is the arm on? l (left) or r (right)
axis the stretch axis used by the joints in the limb. default: x
parity the parts node is simply an object that miscellanous dag nodes are parented under - if not specified, miscellanous objects are simply left in worldspace
'''
__version__ = 0
NAMED_NODE_NAMES = 'autoLengthBlender', 'ikfkBlender', 'lengthMods', 'lengthClamp'
ADD_CONTROLS_TO_QSS = False
def _build( self, skeletonPart, control, joints, ikFkBlendAttrpath=None, axis=BONE_AIM_AXIS, parity=Parity.LEFT, elbowPos=1, connectEndJoint=False, **kw ):
'''
ikFkBlendAttrpath this should be the attribute that turns ik on when its value is 1, and off when its value is 0
'''
#do some sanity checking
if not joints:
raise RigPartError( "No joints supplied - you must supply a list of joints to stretch!" )
if ikFkBlendAttrpath is None:
ikFkBlendAttrpath = '%s.ikBlend' % control
if axis is None:
raise NotImplemented( 'auto axis support not written yet - complain loudly!' )
#setup some current unit variables, and take parity into account
stretchAuto = "autoStretch"
stretchName = "stretch"
parityFactor = parity.asMultiplier()
addAttr( control, ln=stretchAuto, at='double', min=0, max=1, dv=1 )
addAttr( control, ln=stretchName, at='double', min=-10, max=10, dv=0 )
attrState( control, (stretchAuto, stretchName), keyable=True )
#build the network for distributing stretch from the fk controls to the actual joints
plusNodes = []
initialNodes = []
fractionNodes = []
allNodes = []
for c in joints:
md = shadingNode( 'multiplyDivide', asUtility=True, name='%s_fraction_pos' % str( c ) )
fractionNodes.append( md )
startObj = joints[0]
endObj = control
clientLengths = [ 0 ]
totalLength = 0
for n, c in enumerate( joints[ :-1 ] ):
thisPos = Vector( xform( c, q=True, ws=True, rp=True ) )
nextPos = Vector( xform( joints[ n+1 ], q=True, ws=True, rp=True ) )
l = (thisPos - nextPos).length()
clientLengths.append( l )
totalLength += l
#build the network to measure limb length
loc_a = group( empty=True )
loc_b = group( empty=True )
measure = loc_b
parent( loc_b, loc_a )
parent( loc_a, self.getPartsNode() )
constraint_a = pointConstraint( startObj, loc_a )[ 0 ]
aim = aimConstraint( endObj, loc_a, aimVector=(1,0,0) )[ 0 ]
setAttr( '%s.tx' % loc_b, totalLength )
constraint_b = pointConstraint( endObj, loc_b )[ 0 ]
attrState( [ loc_a, loc_b ], ('t', 'r'), *LOCK_HIDE )
#create the stretch network
autoLengthBlender = shadingNode( 'blendColors', asUtility=True, n='auto_length_blender' )
fkikBlender = shadingNode( 'blendColors', asUtility=True, n='fkik_blender' ) #turns auto length off when using fk
lengthMods = shadingNode( 'plusMinusAverage', asUtility=True, n='length_mods' ) #adds all lengths together
lengthClamp = shadingNode( 'clamp', asUtility=True, n='length_clamp' ) #clamps the min/max length for the limb
manualStretchMult = shadingNode( 'multiplyDivide', asUtility=True, n='manualStretch_range_multiplier' ) #multiplys manual stretch to a sensible range
#NOTE: the second term attribute of the length condition node holds the initial length for the limb, and is thus connected to the false attribute of all condition nodes
setAttr( '%s.input2X' % manualStretchMult, totalLength / 10 )
setAttr( '%s.minR' % lengthClamp, totalLength )
setAttr( '%s.color2R' % autoLengthBlender, totalLength )
setAttr( '%s.color2R' % fkikBlender, totalLength )
setAttr( '%s.maxR' % lengthClamp, totalLength * 5 )
connectAttr( '%s.tx' % measure, '%s.inputR' % lengthClamp, f=True )
connectAttr( ikFkBlendAttrpath, '%s.blender' % fkikBlender, f=True )
connectAttr( '%s.outputR' % lengthClamp, '%s.color1R' % fkikBlender, f=True )
connectAttr( '%s.outputR' % fkikBlender, '%s.color1R' % autoLengthBlender, f=True )
connectAttr( '%s.%s' % (control, stretchAuto), '%s.blender' % autoLengthBlender, f=True )
connectAttr( '%s.outputR' % autoLengthBlender, '%s.input1D[ 0 ]' % lengthMods, f=True )
connectAttr( '%s.%s' % (control, stretchName), '%s.input1X' % manualStretchMult, f=True )
connectAttr( '%s.outputX' % manualStretchMult, '%s.input1D[ 1 ]' % lengthMods, f=True )
#connect the stretch distribution network up - NOTE this loop starts at 1 because we don't need to connect the
#start of the limb chain (ie the bicep or the thigh) as it doesn't move
if connectEndJoint:
jIter = enumerate( joints )
else:
jIter = enumerate( joints[ :-1 ] )
for n, c in enumerate( joints ):
if n == 0:
continue
setAttr( '%s.input2X' % fractionNodes[ n ], clientLengths[ n ] / totalLength * parityFactor )
#now connect the inital coords to the plus node - then connect the
connectAttr( '%s.output1D' % lengthMods, '%s.input1X' % fractionNodes[ n ], f=True )
#try to unlock the tx attr
if getAttr( '%s.tx' % joints[ n ], lock=True ):
if referenceQuery( joints[ n ], inr=True ):
raise TypeError( "The tx attribute is locked, and the %s node is referenced - maya doesn't let you unlock attributes on referenced nodes!" % joints[n] )
setAttr( '%s.tx' % joints[ n ], lock=False )
#then connect the result of the plus node to the t(axis) pos of the limb joints
connectAttr( '%s.outputX' % fractionNodes[ n ], '%s.tx' % joints[ n ], f=True )
#now if we have only 3 joints, that means we have a simple limb structure
#in which case, lets build an elbow pos network
if len( joints ) == 3 and elbowPos:
default = clientLengths[ 1 ] / totalLength * parityFactor
isNeg = default < 0
default = abs( default )
addAttr( control, ln='elbowPos', at='double', min=0, max=1, dv=default )
setAttr( '%s.elbowPos' % control, keyable=True )
elbowPos = shadingNode( 'reverse', asUtility=True, n='%s_elbowPos' % joints[ 1 ] )
if isNeg:
mult = shadingNode( 'multiplyDivide', asUtility=True )
setAttr( '%s.input2' % mult, -1, -1, -1 )
connectAttr( '%s.elbowPos' % control, '%s.inputX' % elbowPos, f=True )
connectAttr( '%s.elbowPos' % control, '%s.input1X' % mult, f=True )
connectAttr( '%s.outputX' % elbowPos, '%s.input1Y' % mult, f=True )
connectAttr( '%s.outputY' % mult, '%s.input2X' % fractionNodes[2], f=True )
connectAttr( '%s.outputX' % mult, '%s.input2X' % fractionNodes[1], f=True )
else:
connectAttr( '%s.elbowPos' % control, '%s.inputX' % elbowPos, f=True )
connectAttr( '%s.outputX' % elbowPos, '%s.input2X' % fractionNodes[2], f=True )
connectAttr( '%s.elbowPos' % control, '%s.input2X' % fractionNodes[1], f=True )
controls = ()
namedNodes = autoLengthBlender, fkikBlender, lengthMods, lengthClamp
return controls, namedNodes
#end
| Python |
from maya.cmds import *
from maya import cmds as cmd
from baseMelUI import *
import names
import control
import baseMelUI
import spaceSwitching
class ParentsScrollList(MelObjectScrollList):
def itemAsStr( self, item ):
return '%s :: %s' % tuple( item )
class SpaceSwitchingLayout(MelVSingleStretchLayout):
def __init__( self, parent, *a, **kw ):
MelVSingleStretchLayout.__init__( self, parent, expand=True, *a, **kw )
w = 130
hLayout = MelHSingleStretchLayout( self )
self.UI_controlBtn = UI_controlBtn = MelButton( hLayout, l='obj to space switch ->', w=w, c=self.on_loadControl )
self.UI_control = UI_control = MelNameField( hLayout )
hLayout.setStretchWidget( UI_control )
hLayout.layout()
hLayout = MelHSingleStretchLayout( self )
self.UI_spaceBtn = UI_spaceBtn = MelButton( hLayout, l='obj to constrain ->', w=w, c=self.on_loadSpace )
self.UI_space = UI_space = MelNameField( hLayout )
hLayout.setStretchWidget( UI_space )
hLayout.layout()
hLayout = MelHLayout( self )
self.UI_constrainT = UI_constrainT = MelCheckBox( hLayout, l='constrain translation', v=True, cc=self.on_constrainChange )
self.UI_constrainR = UI_constrainR = MelCheckBox( hLayout, l='constrain rotation', v=True, cc=self.on_constrainChange )
self.UI_constraintType = UI_constraintType = MelOptionMenu( hLayout )
hLayout.layout()
#populate the option menu with the constraint types
for constraintType in spaceSwitching.CONSTRAINT_TYPES:
UI_constraintType.append( constraintType )
### PARENTS LIST ###
self.UI_parentsLbl = UI_parentsLbl = MelLabel( self, l='Parents (double click to rename)', align='center' )
hLayout = MelHSingleStretchLayout( self, expand=True )
self.UI_parents = UI_parents = ParentsScrollList( hLayout, dcc=self.on_renameParent )
upDnLayout = MelVLayout( hLayout )
self.UI_up = UI_up = MelButton( upDnLayout, l='up', c=self.on_up )
self.UI_dn = UI_dn = MelButton( upDnLayout, l='dn', c=self.on_dn )
upDnLayout.layout()
hLayout.setStretchWidget( UI_parents )
hLayout.layout()
self.setStretchWidget( hLayout )
### ADD/REMOVE PARENTS BUTTONS ###
hLayout = MelHLayout( self )
self.UI_addParent = UI_addParent = MelButton( hLayout, l='add parent', c=self.on_addParent )
self.UI_remParent = UI_remParent = MelButton( hLayout, l='remove parent', c=self.on_removeParent )
self.UI_removeAll = UI_removeAll = MelButton( hLayout, l='remove all', c=self.on_removeAll )
hLayout.layout()
self.UI_build = UI_build = MelButton( self, l='build space switch', c=self.on_build )
### DO FINAL LAYOUT ###
self.layout()
self.setSceneChangeCB( self.on_sceneChange )
self.update()
def update( self ):
setEnabled = bool( self.getControl() and self.getSpace() )
self.UI_addParent.enable( setEnabled )
self.UI_remParent.enable( setEnabled )
self.UI_removeAll.enable( setEnabled )
self.UI_build.enable( setEnabled )
if not self.UI_constrainT.getValue() and not self.UI_constrainR.getValue():
self.UI_build.enable( False )
if not self.UI_parents.getItems():
self.UI_build.enable( False )
def setControl( self, control ):
self.UI_space.clear()
self.UI_control.setObj( control )
self.UI_parents.clear()
self.update()
def getControl( self ):
return self.UI_control.getObj()
def setSpace( self, space ):
self.UI_space.setObj( space )
self.update()
def getSpace( self ):
return self.UI_space.getObj()
def addParent( self, parent, name=None ):
#sanity check - make sure the parent isn't either the control, the space, already in the list or a child of either the control or space
if parent == self.getControl():
return
elif parent == self.getSpace():
return
if name is None:
name = spaceSwitching.getSpaceName( self.getControl(), parent )
if name is None:
name = names.camelCaseToNice( str( parent ) )
self.UI_parents.append( [parent, name] )
### EVENT HANDLERS ###
def on_loadControl( self, *a ):
selected = ls( sl=True )
if selected:
theControl = selected[ 0 ]
self.setControl( theControl )
space = spaceSwitching.findSpace( theControl )
#if there is an existing space for the control, use it - otherwise try to guess one
if space:
self.setSpace( space )
else:
space = listRelatives( theControl, p=True, pa=True )
if space:
self.setSpace( space[0] )
parents, names = spaceSwitching.getSpaceTargetsNames( theControl )
for parent, name in zip( parents, names ):
self.addParent( parent, name )
self.update()
def on_loadSpace( self, *a ):
selected = ls( sl=True )
if selected:
theSpace = selected[ 0 ]
self.setSpace( theSpace )
self.update()
def on_constrainChange( self, *a ):
self.update()
def on_addParent( self, *a ):
selected = ls( sl=True )
for item in selected:
self.addParent( item )
self.update()
def on_removeParent( self, *a ):
self.UI_parents.removeSelectedItems()
self.update()
def on_removeAll( self, *a ):
self.UI_parents.clear()
self.update()
def on_renameParent( self, *a ):
selItems = self.UI_parents.getSelectedItems()
if selItems:
theItem = selItems[ 0 ]
ret = cmd.promptDialog( t='Enter a name', m='Enter the name you want the parent to appear as', tx=theItem[1], b=('OK', 'Cancel'), db='OK' )
if ret == 'OK':
theItem[ 1 ] = cmd.promptDialog( q=True, tx=True )
self.UI_parents.update()
def on_up( self, *a ):
self.UI_parents.moveSelectedItemsUp()
def on_dn( self, *a ):
self.UI_parents.moveSelectedItemsDown()
def on_sceneChange( self, *a ):
self.UI_control.clear()
self.UI_space.clear()
self.UI_parents.clear()
self.update()
def on_build( self, *a ):
theControl = self.getControl()
theSpace = self.getSpace()
for parent, name in self.UI_parents.getItems():
spaceSwitching.add( theControl, parent,
name=name, space=theSpace,
skipTranslationAxes=() if self.UI_constrainT.getValue() else ('x', 'y', 'z'),
skipRotationAxes=() if self.UI_constrainR.getValue() else ('x', 'y', 'z'),
constraintType=self.UI_constraintType.getValue() )
#spaceSwitching.build( self.getControl(), parents, names=parentNames, space=self.getSpace() )
class SpaceSwitchingWindow(BaseMelWindow):
WINDOW_NAME = 'spaceSwitchingWindow'
WINDOW_TITLE = 'Space Switching'
DEFAULT_SIZE = 400, 350
DEFAULT_MENU = None
#HELP_MENU = 'spaceSwitching', 'hamish@macaronikazoo.com', None
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.editor = SpaceSwitchingLayout( self )
self.show()
#end
| Python |
from baseSkeletonPreset import *
#end
| Python |
from maya.cmds import *
from baseMelUI import *
from common import printWarningStr
from control import attrState, LOCK_HIDE, Axis
from mayaDecorators import d_unifyUndo
from names import camelCaseToNice
from apiExtensions import getNodesCreatedBy
class DynamicChain(object):
'''
provides a high level interface to interact with existing dynamic chain setups in the current scene
to create a new dynamic chain instance, use DynamicChain.Create
to instantiate a previously created chain use DynamicChain( dynamicChainNode )
the dynamic chain node simply describes what nodes to create the dynamic chain on, and provide a place
to store persistent properties. To build the dynamic chain setup you need to call dynChain.construct()
on a DynamicChain instance. Similarly you can turn a dynamic chain "off" by calling dynChain.mute()
'''
#used to identify the sets used by this tool to describe the dynamic chain setups
SET_NODE_IDENTIFIER = 'zooDynamicChain'
@classmethod
@d_unifyUndo
def Create( cls, objs ):
'''
constructs a new DynamicChain instance
NOTE: this only creates the description of the dynamic chain - if you want the dynamic chain to be
"turned on", you'll need to call construct() on the instance returned
'''
if not objs:
raise ValueError( "Must provide a list of objects to construct the DynamicChain on" )
node = sets( empty=True, text=cls.SET_NODE_IDENTIFIER )
node = rename( node, '%s_dynChain#' % objs[0].split( '|' )[-1].split( ':' )[-1] )
addAttr( node, ln='transforms', at='message', indexMatters=True, multi=True )
for n, obj in enumerate( objs ):
connectAttr( '%s.message' % obj, '%s.transforms[%d]' % (node, n) )
#add attributes to the set node - adding them to the set means user set attributes are preserved across muting and unmuting of the chain
addAttr( node, ln='stiffness', at='double', min=0, max=1, dv=0.15, keyable=True )
addAttr( node, ln='lengthFlex', at='double', min=0, max=1, dv=0, keyable=True )
addAttr( node, ln='damping', at='double', min=0, max=25, dv=0, keyable=True )
addAttr( node, ln='drag', at='double', min=0, max=1, dv=0.1, keyable=True )
addAttr( node, ln='friction', at='double', min=0, max=1, dv=0.5, keyable=True )
addAttr( node, ln='gravity', at='double', min=0, max=10, dv=1, keyable=True )
addAttr( node, ln='turbStrength', at='double', min=0, max=1, dv=0, keyable=True )
addAttr( node, ln='turbFreq', at='double', min=0, max=2, dv=0.2, keyable=True )
addAttr( node, ln='turbSpeed', at='double', min=0, max=2, dv=0.2, keyable=True )
addAttr( node, ln='proxyRoot', at='message' )
self = cls( node )
return self
@classmethod
def Iter( cls ):
'''
iterates over all dynamic chains in the current scene
'''
for node in ls( type='objectSet' ):
if sets( node, q=True, text=True ) == cls.SET_NODE_IDENTIFIER:
yield cls( node )
def __init__( self, container ):
self._node = container
def getNode( self ):
return self._node
def getObjs( self ):
'''
returns the objects involved in the dynamic chain
'''
objs = []
nControls = getAttr( '%s.transforms' % self._node, size=True )
for n in range( nControls ):
cons = listConnections( '%s.transforms[%d]' % (self._node, n), d=False )
if cons:
objs.append( cons[0] )
return objs
def getProxyRoot( self ):
'''
returns the
'''
cons = listConnections( '%s.proxyRoot' % self._node, d=False )
if cons:
return cons[0]
return None
@d_unifyUndo
def construct( self ):
'''
builds the actual dynamic hair network
'''
setNode = self._node
objs = self.getObjs()
#before we do anything, check to see whether the selected objects have any incoming connections
warnAboutDisconnections = False
for obj in objs:
#check the object for incoming connections - if it has any, remove them
for chan in ('t', 'r'):
for ax in Axis.BASE_AXES:
cons = listConnections( '%s.%s%s' % (obj, chan, ax), d=False )
if cons:
warnAboutDisconnections = True
if objectType( cons[0], isAType='animCurve' ):
delete( cons[0] )
else:
raise TypeError( "The object %s has non anim curve incoming connections - aborting! Please remove connections manually before proceeding" % obj )
if warnAboutDisconnections:
printWarningStr( "Some of the objects had incoming connections (probably from animation). These connections have been broken! undo if you want them back" )
#wrap the creation of the nodes in a function - below this we execute this function via a wrapper which returns a list of new nodes created
#this is done so we can easily capture the nodes created and store them in the set that describes this dynamic chain
def doCreate():
positions = []
for obj in objs:
positions.append( xform( obj, q=True, ws=True, rp=True ) )
#the objs may not be in the same hierarchy, so create a proxy chain that IS in a heirarchy
proxyJoints = []
for obj in objs:
select( cl=True )
j = createNode( 'joint' )
j = rename( j, '%s_dynChainProxy#' % obj.split( ':' )[-1].split( '|' )[-1] )
if proxyJoints:
parent( j, proxyJoints[-1] )
delete( parentConstraint( obj, j ) )
proxyJoints.append( j )
#constrain the original to the proxy
parentConstraint( j, obj )
#hook up the proxy root to a special message attribute so we can easily find the proxy chain again for things like baking etc...
connectAttr( '%s.message' % proxyJoints[0], '%s.proxyRoot' % setNode )
#build a linear curve
linearCurve = curve( d=1, p=positions )
linearCurveShape = listRelatives( linearCurve, s=True, pa=True )[0]
select( linearCurve )
maya.mel.eval( 'makeCurvesDynamicHairs 1 0 1;' )
#find the dynamic curve shape
cons = listConnections( '%s.worldSpace' % linearCurveShape, s=False )
if not cons:
printWarningStr( "Cannot find follicle" )
return
follicleShape = cons[0]
cons = listConnections( '%s.outHair' % follicleShape, s=False )
if not cons:
printWarningStr( "Cannot find hair system!" )
return
hairSystemNode = cons[0]
setAttr( '%s.startFrame' % hairSystemNode, playbackOptions( q=True, min=True ) )
cons = listConnections( '%s.outCurve' % follicleShape, s=False )
if not cons:
printWarningStr( "Cannot find out curve!" )
return
dynamicCurve = cons[0]
dynamicCurveParent = listRelatives( dynamicCurve, p=True, pa=True ) #grab the dynamic curve's shape
select( dynamicCurve )
maya.mel.eval( 'displayHairCurves "current" 1;' )
follicle = listRelatives( linearCurve, p=True, pa=True )[0]
objParent = listRelatives( objs[0], p=True, pa=True )
if objParent:
objParent = objParent[0]
parent( follicle, objParent )
parent( proxyJoints[0], objParent )
setAttr( '%s.overrideDynamics' % follicle, 1 )
setAttr( '%s.pointLock' % follicle, 1 )
#hook up all the attributes
connectAttr( '%s.stiffness' % setNode, '%s.stiffness' % follicle )
connectAttr( '%s.lengthFlex' % setNode, '%s.lengthFlex' % follicle )
connectAttr( '%s.damping' % setNode, '%s.damp' % follicle )
connectAttr( '%s.drag' % setNode, '%s.drag' % hairSystemNode )
connectAttr( '%s.friction' % setNode, '%s.friction' % hairSystemNode )
connectAttr( '%s.gravity' % setNode, '%s.gravity' % hairSystemNode )
connectAttr( '%s.turbStrength' % setNode, '%s.turbulenceStrength' % hairSystemNode )
connectAttr( '%s.turbFreq' % setNode, '%s.turbulenceFrequency' % hairSystemNode )
connectAttr( '%s.turbSpeed' % setNode, '%s.turbulenceSpeed' % hairSystemNode )
splineIkHandle = ikHandle( sj=proxyJoints[0], ee=proxyJoints[-1], curve=dynamicCurve, sol='ikSplineSolver', ccv=False )[0]
#for some reason the dynamic curve gets re-parented by the ikHandle command (weird) so set the parent back to what it was originally
parent( dynamicCurve, dynamicCurveParent )
newNodes, returnValue = getNodesCreatedBy( doCreate )
#stuff the nodes created into the set that describes this dynamic chain - just add transform nodes...
for aNode in newNodes:
if objectType( aNode, isAType='transform' ):
sets( aNode, e=True, add=setNode )
@d_unifyUndo
def mute( self ):
'''
deletes the hair nodes but retains the settings and objects involved in the hair
'''
#we need to lock the set node before deleting its contents otherwise maya will delete the set
lockNode( self._node, lock=True )
#now delete the set contents
delete( sets( self._node, q=True ) )
#finally unlock the node again
lockNode( self._node, lock=False )
def getMuted( self ):
'''
returns whether this dynamic chain is muted or not
'''
return not bool( sets( self._node, q=True ) )
def setMuted( self, state ):
if state:
self.mute()
else:
self.construct()
@d_unifyUndo
def bake( self, keyEveryNthFrame=4 ):
'''
if this dynamic chain isn't muted, this will bake the motion to keyframes and mute
the dynamic hair
keyEveryNthFrame describes how often keys are baked - set to 1 to bake every frame
'''
#grab the range
timeRange = playbackOptions( q=True, min=True ), playbackOptions( q=True, max=True )
#bake the simulation - NOTE: we DON'T use the keyEveryNthFrame value for the sampleBy arg here because otherwise maya only samples every nth frame which doesn't perform teh simulation properly. yay maya!
bakeSimulation( self.getObjs(), t=timeRange, sampleBy=1, preserveOutsideKeys=True, simulation=True, disableImplicitControl=True, sparseAnimCurveBake=True )
#because of the sampling problem above, we now need to respect the user value specified for keyEveryNthFrame manually
if keyEveryNthFrame > 1:
pass
#finally turn this chain off...
self.mute()
@d_unifyUndo
def delete( self ):
'''
deletes the dynamic chain
'''
nodesInSet = sets( self._node, q=True ) or []
for node in nodesInSet:
if objExists( node ):
delete( node )
#the node shouldn't actually exist anymore - maya should have deleted it automatically after the last object in it was deleted. but
#in the interests of thoroughness, lets make sure. who knows what sort of crazy corner cases exist
if objExists( self._node ):
#check to see if the set node is referenced - if it is, it will be un-deletable
if not referenceQuery( self._node, inr=True ):
delete( self._node )
class DynamicChainScrollList(MelObjectScrollList):
def itemAsStr( self, item ):
isMuted = item.getMuted()
if isMuted:
return '[ muted ] %s' % item.getNode()
return item.getNode()
class DynamicChainEditor(MelColumnLayout):
def __init__( self, parent ):
self._chain = None
MelColumnLayout.__init__( self, parent )
def setChain( self, dynamicChain ):
self.clear()
self._chain = dynamicChain
if dynamicChain is None:
return
dynChainNode = dynamicChain.getNode()
MelLabel( self, l='Editing Dynamic Chain: %s' % dynChainNode )
MelSeparator( self, h=15 )
attrs = listAttr( dynChainNode, k=True ) or []
for attr in attrs:
attrpath = '%s.%s' % (dynChainNode, attr)
niceAttrName = camelCaseToNice( attr )
#query the attribute type and build UI for the types we care about presenting to the user
attrType = getAttr( attrpath, type=True )
ui = None
if attrType == 'bool':
ui = MelCheckBox( self, l=niceAttrName )
elif attrType == 'double':
min, max = addAttr( attrpath, q=True, min=True ), addAttr( attrpath, q=True, max=True )
ui = LabelledFloatSlider( self, min, max, ll=niceAttrName, llw=65 ).getWidget()
if ui is None:
continue
connectControl( ui, attrpath )
MelSeparator( self, h=15 )
hLayout = MelHSingleStretchLayout( self )
lbl = MelLabel( hLayout, l='Key Every N Frames' )
self.UI_nFrame = MelIntField( hLayout, v=4, min=1, max=10, step=1 )
self.UI_bake = MelButton( hLayout, l='Bake To Keys', c=self.on_bake )
hLayout( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) )
hLayout.padding = 10
hLayout.setStretchWidget( self.UI_bake )
hLayout.layout()
### EVENT HANDLERS ###
def on_bake( self, *a ):
if self._chain:
self._chain.bake( self.UI_nFrame.getValue() )
self.sendEvent( 'on_mute' )
class DynamicChainLayout(MelHSingleStretchLayout):
def __init__( self, parent ):
vLayout = MelVSingleStretchLayout( self )
self.UI_dynamicChains = DynamicChainScrollList( vLayout )
self.UI_dynamicChains.setWidth( 175 )
self.UI_dynamicChains.setChangeCB( self.on_chainListSelectionChange )
self.UI_create = MelButton( vLayout, l='Create Chain From Selection', c=self.on_create )
self.UI_mute = MelButton( vLayout, l='Toggle Mute On Highlighted', c=self.on_mute )
MelSeparator( vLayout, h=15 )
self.UI_delete = MelButton( vLayout, l='Delete Highlighted', c=self.on_delete )
vLayout.padding = 0
vLayout.setStretchWidget( self.UI_dynamicChains )
vLayout.layout()
self.UI_editor = DynamicChainEditor( self )
self.padding = 10
self.expand = True
self.setStretchWidget( self.UI_editor )
self.layout()
self.populate()
#hook up callbacks
self.setSelectionChangeCB( self.on_sceneSelectionChange )
self.setSceneChangeCB( self.on_sceneChange )
#run the selection callback to update the UI
self.on_sceneSelectionChange()
def populate( self ):
initialSelection = self.UI_dynamicChains.getSelectedItems()
self.UI_dynamicChains.clear()
chains = list( DynamicChain.Iter() )
for dynamicChain in chains:
self.UI_dynamicChains.append( dynamicChain )
if initialSelection:
if initialSelection[0] in self.UI_dynamicChains:
self.UI_dynamicChains.selectByValue( initialSelection[0], False )
elif chains:
self.UI_dynamicChains.selectByValue( chains[0], False )
#run the highlight callback to update the UI
self.on_chainListSelectionChange()
### EVENT HANDLERS ###
def on_sceneSelectionChange( self, *a ):
areNodesSelected = bool( ls( sl=True, type='transform' ) )
self.UI_create.setEnabled( areNodesSelected )
def on_sceneChange( self, *a ):
self.populate()
def on_chainListSelectionChange( self, *a ):
sel = self.UI_dynamicChains.getSelectedItems()
areItemsSelected = bool( sel )
if areItemsSelected:
self.UI_editor.setChain( sel[0] )
else:
self.UI_editor.setChain( None )
#set enable state on UI that is sensitive to whether we have highlighted items in the dynamic chain list
self.UI_mute.setEnabled( areItemsSelected )
self.UI_delete.setEnabled( areItemsSelected )
def on_create( self, *a ):
selection = ls( sl=True, type='transform' )
dynamicChain = DynamicChain.Create( selection )
dynamicChain.setMuted( False )
self.populate()
self.UI_dynamicChains.selectByValue( dynamicChain, True )
def on_mute( self, *a ):
sel = self.UI_dynamicChains.getSelectedItems()
if sel:
muteStateToSet = not sel[0].getMuted()
for s in sel:
s.setMuted( muteStateToSet )
self.populate()
def on_delete( self, *a ):
sel = self.UI_dynamicChains.getSelectedItems()
if sel:
for s in sel:
s.delete()
self.populate()
class DynamicChainWindow(BaseMelWindow):
WINDOW_NAME = 'zooDynamicChainMaker'
WINDOW_TITLE = 'Dynamic Chain Maker'
DEFAULT_MENU = None
DEFAULT_SIZE = 500, 325
FORCE_DEFAULT_SIZE = True
def __init__( self ):
DynamicChainLayout( self )
self.show()
#end
| Python |
from triggered import *
import spaceSwitching
def removeDupes( iterable ):
unique = set()
newIterable = iterable.__class__()
for item in iterable:
if item not in unique:
newIterable.append( item )
unique.add( item )
return newIterable
def buildMenuItems( parent, obj ):
'''
build the menuItems in the dagProcMenu - it is possible to set a "kill menu" attribute
on an object now that will stop the dagMenu building after the objMenu items have been
added
'''
defaultCmdName = "<empty cmd>"
menusFromConnects = False
killState = False
objs = [ obj ] + (listRelatives( obj, pa=True, s=True ) or [])
#the showMenusFromConnects attribute determines whether the object in question should show right click menus from any items connected to this one via triggered connects
if objExists( '%s.showMenusFromConnects' % obj ):
menusFromConnects = getAttr( '%s.showMenusFromConnects' % obj )
if menusFromConnects:
connects = Trigger( obj ).connects()
for connectObj, connectIdx in connects:
objs.append( connectObj )
objs = removeDupes( objs )
#now get a list of objs that have menus - if there are more than one, build section labels, otherwise skip labels
objsWithMenus = []
for obj in objs:
obj = Trigger( obj )
if obj.menus():
objsWithMenus.append( obj )
doLabels = len( objsWithMenus ) > 1
setParent( parent, m=True )
for obj in objsWithMenus:
#if ANY of the objs have the kill state set, turn it on
if getKillState( obj ):
killState = True
tgts, names = spaceSwitching.getSpaceTargetsNames( obj )
names = [ 'parent to %s' % name for name in names ]
if objExists( '%s.parent' % obj ):
curIdx = getAttr( '%s.parent' % obj )
else: curIdx = None
if doLabels:
menuItem( l='---%s Menus---' % str( obj ).split( '|' )[-1].split( ':' )[-1], en=False )
for idx, cmdName, cmdStr in obj.menus( True ):
#we need to construct the menu item using mel - because the tool was originally mel and all existing obj menu commands are written in mel
#so you have to construct the menu item in mel otherwise its assumed the command is python...
menuCmdToks = [ 'menuItem -l "%s"' % (cmdName or defaultCmdName) ]
#so if the menu name starts with "parent to " then it assumed to be a menu item built by zooSpaceSwitching
if cmdStr.startswith( "^parent to " ):
if curIdx is not None:
if idx == curIdx:
menuCmdToks( '-cb 1' )
if cmdStr:
menuCmdToks.append( '-c "%s"' % encodeString(cmdStr) )
mel.eval( ' '.join( menuCmdToks ) )
#should we die after menu build?
if not killState:
menuItem( d=True )
menuItem( d=True )
return killState
#end
| Python |
import sys
import skeletonBuilder
import baseRigPrimitive
from filesystem import Path
from skeletonBuilder import *
from baseRigPrimitive import *
__author__ = 'hamish@macaronikazoo.com'
RIG_PART_SCRIPT_PREFIX = 'rigPrim_'
### !!! DO NOT IMPORT RIG SCRIPTS BELOW THIS LINE !!! ###
def _iterRigPartScripts():
for p in sys.path:
p = Path( p )
if 'maya' in p: #
for f in p.files():
if f.hasExtension( 'py' ):
if f.name().startswith( RIG_PART_SCRIPT_PREFIX ):
yield f
for f in _iterRigPartScripts():
__import__( f.name() )
def _setupSkeletonPartRigMethods():
'''
sets up the rig method associations on the skeleton parts. This is a list on each skeleton part containing
the rigging methods that are compatible with that skeleton part
'''
_rigMethodDict = {}
for cls in RigPart.GetSubclasses():
try:
assoc = cls.SKELETON_PRIM_ASSOC
except AttributeError: continue
if assoc is None:
continue
for partCls in assoc:
if partCls is None:
continue
try:
_rigMethodDict[ partCls ].append( (cls.PRIORITY, cls) )
except KeyError:
_rigMethodDict[ partCls ] = [ (cls.PRIORITY, cls) ]
for partCls, rigTypes in _rigMethodDict.iteritems():
rigTypes.sort()
rigTypes = [ rigType for priority, rigType in rigTypes ]
partCls.RigTypes = rigTypes
_setupSkeletonPartRigMethods()
#end
| Python |
from maya.cmds import *
import re
import time
import api
import maya.cmds as cmd
mel = api.mel
melecho = api.melecho
def resolveCmdStr( cmdStr, obj, connects, optionals=[] ):
'''
NOTE: both triggered and xferAnim use this function to resolve command strings as well
'''
INVALID = '<invalid connect>'
cmdStr = str( cmdStr )
#resolve # tokens - these represent self
cmdStr = cmdStr.replace( '#', str( obj ) )
#resolve ranged connect array tokens: @<start>,<end> - these represent what is essentially a list slice - although they're end value inclusive unlike python slices...
compile = re.compile
arrayRE = compile( '(@)([0-9]+),(-*[0-9]+)' )
def arraySubRep( matchobj ):
char,start,end = matchobj.groups()
start = int( start )
end = int( end ) + 1
if end == 0:
end = None
try:
return '{ "%s" }' % '","'.join( connects[ start:end ] )
except IndexError:
return "<invalid range: %s,%s>" % (start, end)
cmdStr = arrayRE.sub( arraySubRep, cmdStr )
#resolve all connect array tokens: @ - these are represent a mel array for the entire connects array excluding self
allConnectsArray = '{ "%s" }' % '","'.join( [con for con in connects[1:] if con != INVALID] )
cmdStr = cmdStr.replace( '@', allConnectsArray )
#resolve all single connect tokens: %<x> - these represent single connects
connectRE = compile('(%)(-*[0-9]+)')
def connectRep( matchobj ):
char, idx = matchobj.groups()
try:
return connects[ int(idx) ]
except IndexError:
return INVALID
cmdStr = connectRE.sub( connectRep, cmdStr )
#finally resolve any optional arg list tokens: %opt<x>%
optionalRE = compile( '(\%opt)(-*[0-9]+)(\%)' )
def optionalRep( matchobj ):
charA, idx, charB = matchobj.groups()
try:
return optionals[ int(idx) ]
except IndexError:
return '<invalid optional>'
cmdStr = optionalRE.sub( optionalRep, cmdStr )
return cmdStr
class Trigger(object):
'''
provides an interface to a trigger item
'''
INVALID = '<invalid connect>'
DEFAULT_MENU_NAME = '<empty>'
DEFAULT_CMD_STR = '//blank'
PRESET_SELECT_CONNECTED = "select -d #;\nselect -add @;"
PRESET_KEY_CONNECTED = "select -d #;\nsetKeyframe @;"
PRESET_TOGGLE_CONNECTED = "string $sel[] = `ls -sl`;\nint $vis = !`getAttr %1.v`;\nfor($obj in @) setAttr ($obj +\".v\") $vis;\nif( `size $sel` ) select $sel;"
PRESET_TOOL_TO_MOVE = "setToolTo $gMove;"
PRESET_TOOL_TO_ROTATE = "setToolTo $gRotate;"
def __init__( self, obj ):
if isinstance( obj, Trigger ):
obj = obj.obj
self.obj = obj
@classmethod
def CreateTrigger( cls, object, cmdStr=DEFAULT_CMD_STR, connects=None ):
'''
creates a trigger and returns a new trigger instance
'''
new = cls(object)
new.setCmd(cmdStr)
if connects:
for c in connects:
new.connect( str( c ) )
return new
@classmethod
def CreateMenu( cls, object, name=DEFAULT_MENU_NAME, cmdStr=DEFAULT_CMD_STR, slot=None ):
'''
creates a new menu (optionally forces it to a given slot) and returns a new trigger instance
'''
new = cls(object)
new.setMenuInfo(slot, name, cmdStr)
return new
def __str__( self ):
return str( self.obj )
def __unicode__( self ):
return unicode( self.obj )
def __repr__( self ):
return repr( self.__unicode__() )
def __getitem__( self, slot ):
'''
returns the connect at index <slot>
'''
if slot == 0: return self.obj
slotPrefix = 'zooTrig'
attrPath = "%s.zooTrig%d" % ( self.obj, slot )
try:
objPath = cmd.connectionInfo( attrPath, sfd=True )
if objPath: return objPath.split('.')[0]
except TypeError:
#in this case there is no attribute - so pass and look to the connect cache
pass
attrPathCached = "%scache" % attrPath
try:
obj = cmd.getAttr( attrPathCached )
if cmd.objExists(obj): return obj
except TypeError: pass
raise IndexError('no such connect exists')
def __len__( self ):
'''
returns the number of connects
'''
return len(self.connects())
def iterConnects( self ):
'''
iterator that returns connectObj, connectIdx
'''
return iter( self.connects()[1:] )
def iterMenus( self, resolve=False ):
'''
iterator that returns slot, name, cmd
'''
return iter( self.menus(resolve) )
def getCmd( self, resolve=False, optionals=[] ):
attrPath = '%s.zooTrigCmd0' % self.obj
if objExists( attrPath ):
cmdStr = cmd.getAttr(attrPath)
if resolve: return self.resolve(cmdStr,optionals)
return cmdStr
return None
def setCmd( self, cmdStr ):
cmdAttr = "zooTrigCmd0"
if not objExists( "%s.%s" % ( self.obj, cmdAttr ) ): cmd.addAttr(self.obj, ln=cmdAttr, dt="string")
if cmdStr is None or cmdStr == '':
cmd.deleteAttr(self.obj, at=cmdAttr)
return
cmd.setAttr('%s.%s' % ( self.obj, cmdAttr ), cmdStr, type='string')
def getMenuCmd( self, slot, resolve=False ):
cmdInfo = cmd.getAttr( "%s.zooCmd%d" % ( self.obj, slot ) )
idx = cmdInfo.find('^')
if resolve: return self.resolve(cmdInfo[idx+1:])
return cmdInfo[idx+1:]
def setMenuCmd( self, slot, cmdStr ):
newCmdInfo = '%s^%s' % ( self.getMenuName(slot), cmdStr )
cmd.setAttr("%s.zooCmd%d" % ( self.obj, slot ), newCmdInfo, type='string')
def setMenuInfo( self, slot=None, name=DEFAULT_MENU_NAME, cmdStr=DEFAULT_CMD_STR ):
'''
sets both the name and the command of a given menu item. if slot is None, then a new slot will be
created and its values set accordingly
'''
if slot is None: slot = self.nextMenuSlot()
if name == '': name = self.DEFAULT_MENU_NAME
#try to add the attr - if this complains then we already have the attribute...
try: cmd.addAttr(self.obj, ln='zooCmd%d' % slot, dt='string')
except RuntimeError: pass
cmd.setAttr("%s.zooCmd%d" % ( self.obj, slot ), '%s^%s' % (name, cmdStr), type='string')
self.setKillState( True )
return slot
def createMenu( self, name=DEFAULT_MENU_NAME, cmdStr=DEFAULT_CMD_STR ):
return self.setMenuInfo( None, name, cmdStr )
def getMenuName( self, slot ):
cmdInfo = cmd.getAttr( "%s.zooCmd%d" % ( self.obj, slot ) )
idx = cmdInfo.find('^')
return cmdInfo[:idx]
def setMenuName( self, slot, name ):
newCmdInfo = '%s^%s' % ( name, self.getMenuCmd(slot) )
cmd.setAttr("%s.zooCmd%d" % ( self.obj, slot ), newCmdInfo, type='string')
def getMenuInfo( self, slot, resolve=False ):
cmdInfo = cmd.getAttr( "%s.zooCmd%d" % ( self.obj, slot ) )
idx = cmdInfo.find('^')
if resolve: return cmdInfo[:idx],self.resolve(cmdInfo[idx+1:])
return cmdInfo[:idx],cmdInfo[idx+1:]
def menus( self, resolve=False ):
'''
returns a list of tuples containing the slot,name,cmdStr for all menus on the trigger. if resolve
is True, then all menu commands are returned with their symbols resolved
'''
attrs = cmd.listAttr(self.obj,ud=True)
slotPrefix = 'zooCmd'
prefixSize = len(slotPrefix)
slots = []
if attrs is None:
return slots
for attr in attrs:
try: slot = attr[prefixSize:]
except IndexError: continue
if attr.startswith(slotPrefix) and slot.isdigit():
menuData = cmd.getAttr('%s.%s' % (self.obj,attr))
idx = menuData.find('^')
menuName = menuData[:idx]
menuCmd = menuData[idx+1:]
if resolve: menuCmd = self.resolve(menuCmd)
slots.append( ( int(slot), menuName, menuCmd ) )
slots.sort()
return slots
def connects( self ):
'''returns a list of tuples with the format: (connectName,connectIdx)'''
connects = [(self.obj,0)]
attrs = cmd.listAttr(self.obj, ud=True)
slotPrefix = 'zooTrig'
prefixSize = len(slotPrefix)
#the try is here simply because maya stupidly returns None if there are no attrs instead of an empty list...
try:
#so go through the attributes and make sure they're triggered attributes
for attr in attrs:
try: slot = attr[prefixSize:]
except IndexError: continue
if attr.startswith(slotPrefix) and slot.isdigit():
slot = int(slot)
#now that we've determined its a triggered attribute, trace the connect if it exists
objPath = cmd.connectionInfo( "%s.%s" % ( self.obj, attr ), sfd=True )
#append the object name to the connects list and early out
if objExists(objPath):
connects.append( (objPath.split('.')[0],slot) )
continue
#if there is no connect, then check to see if there is a name cache, and query it - no need to
#check for its existence as we're already in a try block and catching the appropriate exception
#should the attribute not exist...
cacheAttrName = "%s.%s%dcache" % ( self.obj, slotPrefix, slot )
cacheName = cmd.getAttr( cacheAttrName )
if objExists( cacheName ):
self.connect( cacheName, slot ) #add the object to the connect slot
connects.append( (cacheName, slot) )
except TypeError: pass
return connects
def listAllConnectSlots( self, connects=None, emptyValue=None ):
'''
returns a non-sparse list of connects - unlike the connects method output, this is just a list of
names. slots that have no connect attached to them have <emptyValue> as their value
'''
if connects is None:
connects = self.connects()
#build the non-sparse connects list -first we need to find the largest connect idx, and then build a non-sparse list
biggest = max( [c[1] for c in connects] ) + 1
newConnects = [emptyValue]*biggest
for name, idx in connects:
newConnects[idx] = str( name )
return newConnects
def getConnectSlots( self, object ):
'''return a list of the connect slot indicies <object> is connected to'''
object = str( object )
conPrefix = 'zooTrig'
prefixSize = len( conPrefix )
trigger = cmd.ls( self.obj )[0]
object = cmd.ls( object )[0]
slots = set()
try:
#if there are no connections and maya returns None
connections = cmd.listConnections("%s.msg" % object, s=False, p=True)
for con in connections:
try:
obj, attr = con.split('.')
if obj != trigger: continue
slot = attr[ prefixSize: ]
if attr.startswith(conPrefix) and slot.isdigit():
slots.add( int(slot) )
except IndexError: pass
except TypeError: pass
#we need to check against all teh cache attributes to see if the object exists but has been
#disconnected somehow
allSlots = self.connects()
getAttr = cmd.getAttr
for connect, slot in allSlots:
try:
cacheValue = getAttr('%s.%s%dcache' % (trigger, conPrefix, slot))
if cacheValue == object: slots.add( slot )
except TypeError: pass
slots = list( slots )
slots.sort()
return slots
def isConnected( self, object ):
'''returns whether a given <object> is connected as a connect to this trigger'''
object = str( object )
if not objExists(object):
return []
conPrefix = 'zooTrig'
cons = listConnections( '%s.message' % object, s=False, p=True ) or []
for con in cons:
splits = con.split( '.' )
obj = splits[0]
if obj == self.obj:
if splits[1].startswith( conPrefix ):
return True
return False
def connect( self, object, slot=None ):
'''
performs the actual connection of an object to a connect slot
'''
object = str( object )
if not cmd.objExists(object): return -1
#if the user is trying to connect the trigger to itself, return zero which is the reserved slot for the trigger
if self.obj == object: return 0
if slot is None: slot = self.nextSlot()
if slot <= 0: return 0
#make sure the connect isn't already connected - if it is, return the slot number
existingSlots = self.isConnected(object)
if existingSlots: return existingSlots
conPrefix = 'zooTrig'
prefixSize = len(conPrefix)
slotPath = "%s.%s%d" % (self.obj, conPrefix, slot)
if not objExists( slotPath ):
cmd.addAttr(self.obj,ln= "%s%d" % (conPrefix, slot), at='message')
cmd.connectAttr( "%s.msg" % object, slotPath, f=True )
self.cacheConnect( slot )
return slot
def disconnect( self, objectOrSlot ):
'''removes either the specified object from all slots it is connected to, or deletes the given slot index'''
if isinstance(objectOrSlot,basestring):
slots = self.getConnectSlots(objectOrSlot)
for slot in slots:
try: cmd.deleteAttr( '%s.zooTrig%d' % ( self.obj, slot ))
except TypeError: pass
try: cmd.deleteAttr( '%s.zooTrig%dcache' % ( self.obj, slot ))
except TypeError: pass
elif isinstance(objectOrSlot,(int,float)):
try: cmd.deleteAttr( '%s.zooTrig%d' % ( self.obj, int(objectOrSlot) ))
except TypeError: pass
try: cmd.deleteAttr( '%s.zooTrig%dcache' % ( self.obj, int(objectOrSlot) ))
except TypeError: pass
def resolve( self, cmdStr, optionals=[] ):
return resolveCmdStr( cmdStr, self.obj, self.listAllConnectSlots( emptyValue=self.INVALID ), optionals )
def unresolve( self, cmdStr, optionals=[] ):
'''given a cmdStr this method will go through it looking to resolve any names into connect tokens. it only looks for single cmd tokens
and optionals - it doesn't attempt to unresolve arrays'''
connects = self.connects()
for connect,idx in connects:
connectRE = re.compile( r'([^a-zA-Z_|]+)(%s)([^a-zA-Z0-9_|]+)' % connect.replace('|','\\|') )
def tmp(match):
start,middle,end = match.groups()
return '%s%s%d%s' % (start,'%',idx,end)
cmdStr = connectRE.sub(tmp,cmdStr)
return cmdStr
def replaceConnectToken( self, cmdStr, searchConnect, replaceConnect ):
'''returns a resolved cmd string. the cmd string can be either passed in, or if you specify the slot number
the the cmd string will be taken as the given slot's menu command'''
connects = self.listAllConnectSlots()
#perform some early out tests
if not connects: return cmdStr
if searchConnect == replaceConnect: return cmdStr
#build the search and replace tokens - in the case that the replaceConnect is actually a string object, then just use it directly
searchToken = '#' if searchConnect == 0 else '%'+ str(searchConnect)
replaceToken = '#' if replaceConnect == 0 else '%'+ str(replaceConnect)
if isinstance(replaceConnect,basestring): replaceToken = replaceConnect
#build the regex to find the search data
connectRE = re.compile( '(%s)([^0-9])' % searchToken )
def tokenRep( matchobj ):
connectToken,trailingChar = matchobj.groups()
return '%s%s' % ( replaceToken, trailingChar )
cmdStr = connectRE.sub(tokenRep,cmdStr)
return cmdStr
def replaceConnectInCmd( self, searchConnect, replaceConnect ):
return self.replaceConnectToken( self.getCmd(slot), searchConnect, replaceConnect )
def replaceConnectInMenuCmd( self, slot, searchConnect, replaceConnect ):
return self.replaceConnectToken( self.getMenuCmd(slot), searchConnect, replaceConnect )
def replaceConnectInMenuCmds( self, searchConnect, replaceConnect ):
for connect,slot in self.connects:
self.replaceConnectToken( self.getMenuCmd(slot), searchConnect, replaceConnect )
def scrub( self, cmdStr ):
'''
will scrub any lines that contain invalid connects from the cmdStr
'''
#so build the set of missing connects
allSlots = self.listAllConnectSlots(emptyValue=None)
numAllSlots = len(allSlots)
missingSlots = set( [idx for idx,val in enumerate(allSlots) if val is None] )
#now build the list of connect tokens used in the cmd and compare it with the connects
#that are valid - in the situation where there are connects in the cmdStr that don't
#exist on the trigger, we want to scrub these
singleRE = re.compile('%([0-9]+)')
subArrayRE = re.compile('@([0-9]+),(-*[0-9]+)')
nonexistantSlots = set( map(int, singleRE.findall(cmdStr)) )
for start,end in subArrayRE.findall(cmdStr):
start = int(start)
end = int(end)
if end < 0: end += numAllSlots
else: end += 1
[nonexistantSlots.add(slot) for slot in xrange( start, end )]
[nonexistantSlots.discard( slot ) for slot,connect in enumerate(allSlots)]
missingSlots = missingSlots.union( nonexistantSlots ) #now add the nonexistantSlots to the missingSlots
#early out if we can
if not missingSlots: return cmdStr
#otherwise iterate over the list of slots and remove any line that has that slot token in it
for slot in missingSlots:
missingRE = re.compile(r'''^(.*)(%-*'''+ str(slot) +')([^0-9].*)$\n',re.MULTILINE)
cmdStr = missingRE.sub('',cmdStr)
def replaceSubArray( matchObj ):
junk1,start,end,junk2 = matchObj.groups()
start = int(start)
end = int(end)
if end<0: end = start+end
else: end += 1
subArrayNums = set(range(start,end))
common = subArrayNums.intersection( missingSlots )
if common: return ''
return matchObj.string[matchObj.start():matchObj.end()]
subArrayRE = re.compile('^(.*@)([0-9]+),(-*[0-9]+)([^0-9].*)$\n',re.MULTILINE)
cmdStr = subArrayRE.sub(replaceSubArray,cmdStr)
return cmdStr
def scrubCmd( self ):
'''
convenience method for performing self.scrub on the trigger command
'''
self.setCmd( self.scrub( self.getCmd() ))
def scrubMenuCmd( self, slot ):
'''
convenience method for performing self.scrub on a given menu command
'''
self.setMenuCmd(slot, self.scrub( self.getMenuCmd(slot) ))
def scrubMenuCmds( self ):
'''
convenience method for performing self.scrub on all menu commands
'''
for slot,name,cmdStr in self.menus(): self.scrubMenuCmd(slot)
def collapseMenuCmd( self, slot ):
'''
resolves a menu item's command string and writes it back to the menu item - this is most useful when connects are being re-shuffled
and you don't want to have to re-write command strings. there is the counter function - uncollapseMenuCmd that undoes the results
'''
self.setMenuCmd(slot, self.getMenuCmd(slot,True) )
def uncollapseMenuCmd( self, slot ):
self.setMenuCmd(slot, self.unresolve( self.getMenuCmd(slot) ) )
def eval( self, cmdStr, optionals=[] ):
return mel.eval( self.resolve(cmdStr,optionals) )
def evalCmd( self ):
return self.eval( self.getCmd() )
def evalMenu( self, slot ):
return self.eval( self.getMenuCmd(slot) )
def evalCareful( self, cmdStr, optionals=[] ):
'''
does an eval on a line by line basis, catching errors as they happen - its most useful for
when you have large cmdStrs with only a small number of errors
'''
start = time.clock()
lines = cmdStr.split('\n')
evalMethod = mel.eval
validLines = []
for line in lines:
try:
cmd.select(cl=True) #selection is cleared so any missing connects don't work on selection instead of specified objects
resolvedLine = self.resolve(line,optionals)
evalMethod(resolvedLine)
except RuntimeError: continue
validLines.append( line )
end = time.clock()
print 'time taken', end-start, 'seconds'
return '\n'.join(validLines)
def evalForConnectsOnly( self, cmdStr, connectIdxs, optionals=[] ):
'''
will do an eval only if one of the connects in the given a list of connects is contained
in the command string
'''
return self.eval( self.filterConnects( cmdStr, connectIdxs ), optionals )
def filterConnects( self, cmdStr, connectIdxs ):
'''
will return the lines of a command string that refer to connects contained in the given list
'''
connectIdxs = set(connectIdxs)
allSlots = self.listAllConnectSlots(emptyValue=None)
numAllSlots = len(allSlots)
lines = cmdStr.split('\n')
singleRE = re.compile('%([0-9]+)')
subArrayRE = re.compile('@([0-9]+),(-*[0-9]+)')
validLines = []
for line in lines:
#are there any singles in the line?
singles = set( map(int, singleRE.findall(line)) )
if connectIdxs.intersection(singles):
validLines.append(line)
continue
#check if there are any sub arrays which span the any of the connects?
subArrays = subArrayRE.findall(line)
for sub in subArrays:
start = int(sub[0])
end = int(sub[1])
if end < 0: end += numAllSlots
else: end += 1
subRange = set( range(start,end) )
if connectIdxs.intersection(subRange):
validLines.append(line)
break
#finally check to see if there are any single array tokens - these are always added
#NOTE: this check needs to happen AFTER the subarray check - at least in its current state - simply because its such a simple (ie fast) test
if line.find('@') >= 0:
validLines.append(line)
continue
return '\n'.join(validLines)
def removeCmd( self, removeConnects=False ):
'''removes the triggered cmd from self - can optionally remove all the connects as well'''
try:
#catches the case where there is no trigger cmd... faster than a object existence test
cmd.deleteAttr( '%s.zooTrigCmd0' % self.obj )
if removeConnects:
for connect,slot in self.connects():
self.disconnect(slot)
except TypeError: pass
def removeMenu( self, slot, removeConnects=False ):
'''
removes a given menu slot - if removeConnects is True, all connects will be removed ONLY if there are no other menu cmds
'''
attrpath = '%s.zooCmd%d' % ( self.obj, slot )
try:
cmd.deleteAttr( '%s.zooCmd%d' % ( self.obj, slot ))
if removeConnects and not self.menus():
for connect,slot in self.connects():
self.disconnect(slot)
except TypeError: pass
def removeAll( self, removeConnects=False ):
'''
removes all triggered data from self
'''
self.removeCmd(removeConnects)
for idx,name,cmd in self.menus():
self.removeMenu(idx)
def nextSlot( self ):
'''
returns the first available slot index
'''
slots = self.listAllConnectSlots(emptyValue=None)
unused = [con for con,obj in enumerate(slots) if obj is None]
next = 1
if unused: return unused[0]
elif slots: return len(slots)
return next
def nextMenuSlot( self ):
'''
returns the first available menu slot index
'''
slots = self.menus()
next = 0
if slots: return slots[-1][0] + 1
return next
def cacheConnect( self, slot ):
'''caches the objectname of a slot connection'''
try: connectName = self[ slot ]
except IndexError: return None
slotPrefix = 'zooTrig'
cacheAttrName = '%s%dcache' % ( slotPrefix, slot )
cacheAttrPath = '%s.%s' % ( self.obj, cacheAttrName )
if not cmd.objExists( cacheAttrPath ):
cmd.addAttr( self.obj, ln=cacheAttrName, dt='string' )
cmd.setAttr( cacheAttrPath, connectName, type='string' )
def validateConnects( self ):
'''connects maintain a cache which "remembers" the last object that was plugged into them. this method will
run over all connects and for those unconnected ones, it will look for the object that it USED to be connected to
and connect it, and for those that ARE connected, it will make sure the cache is valid. the cache can become
invalid if a connected object's name changes after it was connected'''
slotPrefix = 'zooTrig'
for connect,slot in self.iterConnects():
attrpath = '%s.%s%d' % ( self.obj, slotPrefix, slot )
objPath = cmd.connectionInfo(attrpath, sfd=True)
if not cmd.objExists( objPath ):
#get the cached connect and attach it
cachedValue = cmd.getAttr('%scache' % attrpath)
if cmd.objExists(cachedValue):
self.connect(cachedValue,slot)
def setKillState( self, state ):
'''so the kill state tells the objMenu build script to stop after its build all menu items listed on the object - this method
provides an interface to enabling/disabling that setting'''
attr = 'zooObjMenuDie'
attrpath = '%s.%s' % ( self.obj, attr )
if state:
if not objExists( attrpath ): cmd.addAttr(self.obj, at="bool", ln=attr)
cmd.setAttr(attrpath, 1)
else:
if objExists( attrpath ):
cmd.deleteAttr(attrpath)
def getKillState( self ):
attrpath = "%s.zooObjMenuDie" % self.obj
if objExists( attrpath ): return bool( cmd.getAttr(attrpath) )
return False
killState = property(getKillState,setKillState)
def getConnectIndiciesForObjects( self, objects=None ):
'''returns a list of connection indicies for the given list of objects. NOTE: these list lengths may not match - it is perfectly
valid for a single object to be connected to multiple connect slots'''
if objects is None: objects = cmd.ls(sl=True)
cons = []
for obj in objects:
cons.extend( self.getConnectSlots(obj) )
return cons
def addConnect( obj, connectObj, slot=None ):
return Trigger( obj ).connect( connectObj, slot )
def setKillState( obj, state ):
return Trigger( obj ).setKillState( state )
def getKillState( obj ):
return Trigger( obj ).getKillState()
def writeSetAttrCmd( trigger, objs ):
cmdLines = []
trigger = Trigger(trigger)
for obj in objs:
attrs = cmd.listAttr(obj, k=True, s=True, v=True, m=True)
objSlot = trigger.getConnectSlots(obj)
slots = trigger.getConnectSlots(obj)
if len(slots): objStr = "%"+ str(slots[0])
for a in attrs:
attrType = cmd.getAttr( "%s.%s"%(obj,a), type=True )
if attrType.lower() == "double":
attrVal = cmd.getAttr( "%s.%s" % (obj,a) )
cmdLines.append( "setAttr %s.%s %0.5f;" % ( objStr, a, attrVal ) )
else: cmdLines.append( "setAttr %s.%s %s;" % ( objStr, a, cmd.getAttr( "%s.%s"%(obj,a) ) ) )
return '\n'.join( cmdLines )
def listTriggers():
'''lists all trigger objects in the current scene'''
allObjects = cmd.ls(type='transform')
triggers = []
attr = 'zooTrigCmd0'
try:
for obj in allObjects:
if objExists( '%s.%s' % ( obj, attr ) ):
triggers.connect( obj )
except TypeError: pass
return triggers
def listObjectsWithMenus():
'''lists all objects with menu items in the scene'''
allObjects = cmd.ls(type='transform')
objMenus = []
attrPrefix = 'zooCmd'
prefixSize = len(attrPrefix)
for obj in allObjects:
attrs = cmd.listAttr(obj, ud=True)
try:
for attr in attrs:
try: slot = attr[prefixSize:]
except IndexError: continue
if attr.startswith(attrPrefix) and slot.isdigit():
objMenus.append( obj )
break
except TypeError: continue
return objMenus
def getTriggeredState():
'''returns the state of triggered'''
return mel.zooTriggeredState()
def setTriggeredState( state=True ):
if state: mel.zooTriggeredLoad()
else: mel.zooTriggeredUnload()
def longname( object ):
try:
longname = cmd.ls(object,long=True)
return longname[0]
except IndexError: raise TypeError
#end
| Python |
from maya.OpenMaya import MGlobal
from exceptionHandlers import generateTraceableStrFactory
generateInfoStr, printInfoStr = generateTraceableStrFactory( '*** INFO ***', MGlobal.displayInfo )
generateWarningStr, printWarningStr = generateTraceableStrFactory( '', MGlobal.displayWarning )
generateErrorStr, printErrorStr = generateTraceableStrFactory( '', MGlobal.displayError )
#end
| Python |
'''
this script contains a bunch of useful poly mesh functionality. at this stage its not really
much more than a bunch of functional scripts - there hasn't been any attempt to objectify any
of this stuff yet. as it grows it may make sense to step back a bit and think about how to
design this a little better
'''
from maya.cmds import *
from maya.OpenMayaAnim import MFnSkinCluster
from vectors import Vector, Matrix
from filesystem import Path, BreakException
import maya.cmds as cmd
import api
import apiExtensions
import maya.OpenMaya as OpenMaya
kMAX_INF_PER_VERT = 3
kMIN_SKIN_WEIGHT_VALUE = 0.05
def getASelection():
'''
returns the first object selected or None if no selection - saves having to write this logic over and over
'''
sel = ls( sl=True )
if not sel:
return None
return sel[0]
def numVerts( mesh ):
return len( cmd.ls("%s.vtx[*]" % mesh, fl=True) )
def numFaces( mesh ):
return len( cmd.ls("%s.f[*]" % mesh, fl=True) )
def selectFlipped():
sel = cmd.ls(selection=True)
cmd.select(clear=True)
flipped = findFlipped(sel)
if len(flipped):
cmd.select(flipped,add=True)
def findFlipped( obj ):
flipped = []
faces = cmd.polyListComponentConversion( obj, toFace=True )
if not faces:
return flipped
faces = cmd.ls( faces, flatten=True )
for face in faces:
uvNormal = getUVFaceNormal(face)
#if the uv face normal is facing into screen then its flipped - add it to the list
if uvNormal * Vector([0, 0, 1]) < 0:
flipped.append(face)
return flipped
def getWindingOrder( facepath, doUvs=True ):
'''will return the uvs or verts of a face in their proper 'winding order'. this can be used to determine
things like uv face normals and... well, pretty much that'''
toReturn = []
vtxFaces = cmd.ls(cmd.polyListComponentConversion(facepath,toVertexFace=True),flatten=True)
for vtxFace in vtxFaces:
if doUvs:
uvs = cmd.polyListComponentConversion(vtxFace,fromVertexFace=True,toUV=True)
toReturn.append( uvs[0] )
else:
vtx = cmd.polyListComponentConversion(vtxFace,fromVertexFace=True,toVertex=True)
toReturn.append( vtx[0] )
return toReturn
def getUVFaceNormal( facepath ):
uvs = getWindingOrder(facepath)
if len(uvs) < 3: return (1,0,0) #if there are less than 3 uvs we have no uv area so bail
#get edge vectors and cross them to get the uv face normal
uvAPos = cmd.polyEditUV(uvs[0], query=True, uValue=True, vValue=True)
uvBPos = cmd.polyEditUV(uvs[1], query=True, uValue=True, vValue=True)
uvCPos = cmd.polyEditUV(uvs[2], query=True, uValue=True, vValue=True)
uvAB = Vector( [uvBPos[0]-uvAPos[0], uvBPos[1]-uvAPos[1], 0] )
uvBC = Vector( [uvCPos[0]-uvBPos[0], uvCPos[1]-uvBPos[1], 0] )
uvNormal = uvAB.cross( uvBC ).normalize()
return uvNormal
def getFaceNormal( facepath ):
verts = getWindingOrder(facepath,False)
if len(verts) < 3: return (1, 0, 0) #if there are less than 3 verts we have no uv area so bail
#get edge vectors and cross them to get the uv face normal
vertAPos = Vector(cmd.xform(verts[0], query=True, worldSpace=True, absolute=True, translation=True))
vertBPos = Vector(cmd.xform(verts[1], query=True, worldSpace=True, absolute=True, translation=True))
vertCPos = Vector(cmd.xform(verts[2], query=True, worldSpace=True, absolute=True, translation=True))
vecAB = vertBPos - vertAPos
vecBC = vertCPos - vertBPos
faceNormal = (vecAB ^ vecBC).normalize()
return faceNormal
def extractFaces( faceList, delete=False ):
'''
extracts the given faces into a separate object - unlike the maya function, this is actually
useful... the given faces are extracted to a separate object, and can be optionally deleted from
the original mesh if desired, or just duplicated out.
'''
newMeshes = []
#get a list of meshes present in the facelist
cDict = componentListToDict( faceList )
for mesh, faces in cDict.iteritems():
#is the mesh a shape or a transform - if its a shape, get its transform
if cmd.nodeType( mesh ) == 'mesh':
mesh = cmd.listRelatives( mesh, pa=True, p=True )[ 0 ]
dupeMesh = cmd.duplicate( mesh, renameChildren=True )[ 0 ]
children = cmd.listRelatives( dupeMesh, pa=True, typ='transform' )
if children:
cmd.delete( children )
#unlock transform channels - if possible anyway
try:
for c in ('t', 'r', 's'):
setAttr( '%s.%s' % (dupeMesh, c), l=False )
for ax in ('x', 'y', 'z'):
setAttr( '%s.%s%s' % (dupeMesh, c, ax), l=False )
except RuntimeError: pass
#now delete all faces except those we want to keep
cmd.select( [ '%s.f[%d]' % (dupeMesh, idx) for idx in range( numFaces( dupeMesh ) ) ] )
cmd.select( [ '%s.f[%d]' % (dupeMesh, idx) for idx in faces ], deselect=True )
cmd.delete()
newMeshes.append( dupeMesh )
if delete:
cmd.delete( faceList )
return newMeshes
def extractMeshForEachJoint( joints, tolerance=1e-4 ):
extractedMeshes = []
for j in joints:
meshes = extractFaces( jointFacesForMaya( j, tolerance ) )
extractedMeshes += meshes
for m in meshes:
#unlock all xform attrs
for at in 't', 'r', 's':
cmd.setAttr( '%s.%s' % (m, at), l=False )
for ax in 'x', 'y', 'z':
cmd.setAttr( '%s.%s%s' % (m, at, ax), l=False )
cmd.parent( m, j )
args = cmd.xform( j, q=True, ws=True, rp=True ) + [ '%s.rotatePivot' % m, '%s.scalePivot' % m ]
cmd.move( *args )
cmd.makeIdentity( m, a=True, t=True, r=True, s=True )
cmd.parent( m, world=True )
return extractedMeshes
def extractMeshForJoints( joints, tolerance=0.25, expand=0 ):
'''
given a list of joints this will extract the mesh influenced by these joints into
a separate object. the default tolerance is high because verts are converted to
faces which generally results in a larger than expected set of faces
'''
faces = []
joints = map( str, joints )
for j in joints:
faces += jointFacesForMaya( j, tolerance, False )
if not faces:
return None
theJoint = joints[ 0 ]
meshes = extractFaces( faces )
grp = cmd.group( em=True, name='%s_mesh#' % theJoint )
cmd.delete( cmd.parentConstraint( theJoint, grp ) )
for m in meshes:
#unlock all xform attrs
for at in 't', 'r', 's':
cmd.setAttr( '%s.%s' % (m, at), l=False )
for ax in 'x', 'y', 'z':
cmd.setAttr( '%s.%s%s' % (m, at, ax), l=False )
if expand > 0:
cmd.polyMoveFacet( "%s.vtx[*]" % m, ch=False, ltz=expand )
#parent to the grp and freeze transforms to ensure the shape's space is the same as its new parent
cmd.parent( m, grp )
cmd.makeIdentity( m, a=True, t=True, r=True, s=True )
#parent all shapes to the grp
cmd.parent( cmd.listRelatives( m, s=True, pa=True ), grp, add=True, s=True )
#delete the mesh transform
cmd.delete( m )
#remove any intermediate objects...
for shape in listRelatives( grp, s=True, pa=True ):
if getAttr( '%s.intermediateObject' % shape ):
delete( shape )
return grp
def autoGenerateRagdollForEachJoint( joints, threshold=0.65 ):
convexifiedMeshes = []
for j in joints:
meshes = extractMeshForEachJoint( [ j ], threshold )
if len( meshes ) > 1:
mesh = cmd.polyUnite( meshes, ch=False )[ 0 ]
cmd.delete( meshes )
meshes = [ mesh ]
else: mesh = meshes[ 0 ]
convexifiedMesh = convexifyObjects( mesh )[ 0 ]
convexifiedMesh = cmd.rename( convexifiedMesh, j +'_ragdoll' )
cmd.skinCluster( [ j ], convexifiedMesh )
cmd.delete( meshes )
convexifiedMeshes.append( convexifiedMesh )
return convexifiedMeshes
def isPointInCube( point, volumePos, volumeScale, volumeBasis ):
'''
'''
x, y, z = volumeScale
#make the point's position relative to the volume, and transform it to the volume's local orientation
pointRel = point - volumePos
pointRel = pointRel.change_space( *volumeBasis )
if -x<= pointRel.x <=x and -y<= pointRel.y <=y and -z<= pointRel.z <=z:
acc = 0
for x, px in zip((x, y, z), (point.x, point.y, point.z)):
try: acc += x/px
except ZeroDivisionError: acc += 1
weight = 1 -(acc/3)
return True, weight
return False
def isPointInSphere( point, volumePos, volumeScale, volumeBasis ):
'''
returns whether a given point is contained within a scaled sphere
'''
x, y, z = volumeScale
#make the point's position relative to the volume, and transform it to the volume's local orientation
pointRel = point - volumePos
pointRel = pointRel.change_space(*volumeBasis)
if -x<= pointRel.x <=x and -y<= pointRel.y <=y and -z<= pointRel.z <=z:
pointN = vectors.Vector(pointRel)
pointN.x /= x
pointN.y /= y
pointN.z /= z
pointN = pointN.normalize()
pointN.x *= x
pointN.y *= y
pointN.z *= z
if pointRel.magnitude() <= pointN.mag:
weight = 1 -(pointRel.magnitude() / pointN.magnitude())
return True, weight
return False
def isPointInUniformSphere( point, volumePos, volumeRadius, UNUSED_BASIS=None ):
pointRel = point - volumePos
radius = volumeRadius[0]
if -radius<= pointRel.x <=radius and -radius<= pointRel.y <=radius and -radius<= pointRel.z <=radius:
if pointRel.magnitude() <= radius:
weight = 1 -(pointRel.magnitude() / radius)
return True, weight
return False
def findFacesInVolumeForMaya( meshes, volume, contained=False ):
'''
does the conversion from useful dict to maya selection string - generally only useful to mel trying
to interface with this functionality
'''
objFacesDict = findFacesInVolume(meshes, volume, contained)
allFaces = []
for mesh, faces in objFacesDict.iteritems():
allFaces.extend( ['%s.%s' % (mesh, f) for f in faces] )
return allFaces
def findVertsInVolumeForMaya( meshes, volume ):
'''
does the conversion from useful dict to maya selection string - generally only useful to mel trying
to interface with this functionality
'''
objVertDict = findVertsInVolume(meshes, volume)
allVerts = []
for mesh, verts in objVertDict.iteritems():
allVerts.extend( ['%s.vtx[%s]' % (mesh, v.id) for v in verts] )
return allVerts
def findFacesInVolume( meshes, volume, contained=False ):
'''
returns a dict containing the of faces within a given volume. if contained is True, then only faces wholly contained
by the volume are returned
'''
meshVertsWithin = findVertsInVolume(meshes, volume)
meshFacesWithin = {}
for mesh,verts in meshVertsWithin.iteritems():
if not verts: continue
meshFacesWithin[mesh] = []
vertNames = ['%s.vtx[%d]' % (mesh, v.id) for v in verts]
if contained:
faces = set(cmd.ls(cmd.polyListComponentConversion(vertNames, toFace=True), fl=True))
[faces.remove(f) for f in cmd.ls(cmd.polyListComponentConversion(vertNames, toFace=True, border=True), fl=True)]
meshFacesWithin[mesh] = [f.split('.')[1] for f in faces]
else:
faces = cmd.ls(cmd.polyListComponentConversion(vertNames, toFace=True), fl=True)
meshFacesWithin[mesh] = [f.split('.')[1] for f in faces]
return meshFacesWithin
def findVertsInVolume( meshes, volume ):
'''
returns a dict containing meshes and the list of vert attributes contained
within the given <volume>
'''
#define a super simple vector class to additionally record vert id with position...
class VertPos(vectors.Vector):
def __init__( self, x, y, z, vertIdx=None ):
vectors.Vector.__init__(self, [x, y, z])
self.id = vertIdx
#this dict provides the functions used to determine whether a point is inside a volume or not
insideDeterminationMethod = {ExportManager.kVOLUME_SPHERE: isPointInSphere,
ExportManager.kVOLUME_CUBE: isPointInCube}
#if there are any uniform overrides for the contained method (called if the volume's scale is
#unity) it can be registered here
insideDeterminationIfUniform = {ExportManager.kVOLUME_SPHERE: isPointInUniformSphere,
ExportManager.kVOLUME_CUBE: isPointInCube}
#grab any data we're interested in for the volume
volumePos = vectors.Vector( cmd.xform(volume, q=True, ws=True, rp=True) )
volumeScale = map(abs, cmd.getAttr('%s.s' % volume)[0])
volumeBasis = rigUtils.getObjectBasisVectors( volume )
#make sure the basis is normalized
volumeBasis = [v.normalize() for v in volumeBasis]
#now lets determine the volume type
type = ExportManager.kVOLUME_SPHERE
try: type = int( cmd.getAttr('%s.exportVolume' % volume) )
except TypeError: pass
isContainedMethod = insideDeterminationMethod[type]
print 'method for interior volume determination', isContainedMethod.__name__
sx = volumeScale[0]
if vectors.Vector(volumeScale).within((sx, sx, sx)):
try: isContainedMethod = insideDeterminationIfUniform[type]
except KeyError: pass
#now lets iterate over the geometry
meshVertsWithin = {}
for mesh in meshes:
#its possible to pass not a mesh but a component in - this is totally valid, as the polyListComponentConversion
#should make sure we're always dealing with verts no matter what, but we still need to make sure the dict key is
#the actual name of the mesh - hence this bit of jiggery pokery
dotIdx = mesh.rfind('.')
meshName = mesh if dotIdx == -1 else mesh[:dotIdx]
meshPositions = []
meshVertsWithin[meshName] = meshPositions
#this gives us a huge list of floats - each sequential triple is the position of a vert
try:
#if this complains its most likely coz the geo is bad - so skip it...
vertPosList = cmd.xform(cmd.ls(cmd.polyListComponentConversion(mesh, toVertex=True), fl=True), q=True, t=True, ws=True)
except TypeError: continue
count = len(vertPosList)/3
for idx in xrange(count):
pos = VertPos(vertPosList.pop(0), vertPosList.pop(0), vertPosList.pop(0), idx)
contained = isContainedMethod(pos, volumePos, volumeScale, volumeBasis)
if contained:
pos.weight = contained[1]
meshPositions.append( pos )
return meshVertsWithin
def isNodeVisible( node ):
'''
its actually a bit tricky to determine whether a node is visible or not. A node is hidden if any parent is hidden
by either having a zero visibility attribute. It could also be in a layer or be parented to a node in a layer that
is turned off...
This function will sort all that crap out and return a bool representing the visibility of the given node
'''
def isVisible( n ):
#obvious check first
if not getAttr( '%s.v' % node ):
return False
#now check the layer
displayLayer = listConnections( '%s.drawOverride' % n, d=False, type='displayLayer' )
if displayLayer:
if not getAttr( '%s.v' % displayLayer[0] ):
return False
return True
#check the given node
if not isVisible( node ):
return False
#now walk up the DAG and check visibility on parents
parent = listRelatives( node, p=True, pa=True )
while parent:
if not isVisible( parent[0] ):
return False
parent = listRelatives( parent, p=True, pa=True )
return True
def jointVerts( joint, tolerance=1e-4, onlyVisibleMeshes=True ):
'''
returns a dict containing data about the verts influences by the given joint - dict keys are mesh names the
joint affects. each dict value is a list of tuples containing (weight, idx) for the verts affected by the joint
'''
newObjs = []
meshVerts = {}
joint = apiExtensions.asMObject( joint )
jointMDag = joint.dagPath()
try:
skins = list( set( listConnections( joint, s=0, type='skinCluster' ) ) )
except TypeError:
return meshVerts
MObject = OpenMaya.MObject
MDagPath = OpenMaya.MDagPath
MDoubleArray = OpenMaya.MDoubleArray
MSelectionList = OpenMaya.MSelectionList
MIntArray = OpenMaya.MIntArray
MFnSingleIndexedComponent = OpenMaya.MFnSingleIndexedComponent
for skin in skins:
skin = apiExtensions.asMObject( skin )
mfnSkin = MFnSkinCluster( skin )
mSel = MSelectionList()
mWeights = MDoubleArray()
mfnSkin.getPointsAffectedByInfluence( jointMDag, mSel, mWeights )
for n in range( mSel.length() ):
mesh = MDagPath()
component = MObject()
mSel.getDagPath( n, mesh, component )
#if we only want visible meshes - check to see that this mesh is visible
if onlyVisibleMeshes:
if not isNodeVisible( mesh ):
continue
c = MFnSingleIndexedComponent( component )
idxs = MIntArray()
c.getElements( idxs )
meshVerts[ mesh.partialPathName() ] = [ (w, idx) for idx, w in zip( idxs, mWeights ) if w > tolerance ]
return meshVerts
def jointVertsForMaya( joint, tolerance=1e-4, onlyVisibleMeshes=True ):
'''
converts the dict returned by jointVerts into maya useable component names
'''
items = []
for mesh, data in jointVerts( joint, tolerance, onlyVisibleMeshes ).iteritems():
items.extend( ['%s.vtx[%d]' % (mesh, n) for w, n in data] )
return items
def jointFacesForMaya( joint, tolerance=1e-4, contained=True ):
'''
returns a list containing the faces influences by the given joint
'''
verts = jointVertsForMaya( joint, tolerance )
if not verts:
return []
if contained:
faceList = cmd.polyListComponentConversion( verts, toFace=True )
if faceList:
faceList = set( cmd.ls( faceList, fl=True ) )
for f in cmd.ls( cmd.polyListComponentConversion( verts, toFace=True, border=True ), fl=True ):
faceList.remove( f )
jointFaces = list( faceList )
else:
jointFaces = cmd.ls( cmd.polyListComponentConversion( verts, toFace=True ), fl=True )
return jointFaces
def jointFaces( joint, tolerance=1e-4, contained=True ):
'''
takes the list of maya component names from jointFacesForMaya and converts them to a dict with teh same format
as jointVerts(). this is backwards for faces simply because its based on grabbing the verts, and transforming
them to faces, and then back to a dict...
'''
return componentListToDict( jointFacesForMaya( joint, tolerance, contained ) )
def componentListToDict( componentList ):
componentDict = {}
if not componentList:
return componentDict
#detect the prefix type
suffix = componentList[ 0 ].split( '.' )[ 1 ]
componentPrefix = suffix[ :suffix.find( '[' ) ]
prefixLen = len( componentPrefix ) + 1 #add one because there is always a "[" after the component str
for face in componentList:
mesh, idStr = face.split( '.' )
idx = int( idStr[ prefixLen:-1 ] )
try: componentDict[ mesh ].append( idx )
except KeyError: componentDict[ mesh ] = [ idx ]
return componentDict
def stampVolumeToJoint( joint, volume, amount=0.1 ):
meshes = cmd.ls(cmd.listHistory(joint, f=True, interestLevel=2), type='mesh')
assert meshes
jointPos = Vector(cmd.xform(joint, q=True, ws=True, rp=True))
vertsDict = findVertsInVolume(meshes, volume)
for mesh, verts in vertsDict.iteritems():
skinCluster = cmd.ls(cmd.listHistory(mesh), type='skinCluster')[0]
for vert in verts:
vertName = '%s.vtx[%s]' % (mesh, vert.id)
weight = vert.weight
#print weight, vertName
#print cmd.skinPercent(skinCluster, vertName, q=True, t=joint, v=True)
currentWeight = cmd.skinPercent(skinCluster, vertName, q=True, t=joint, v=True)
currentWeight += weight * amount
#cmd.skinPercent(skinCluster, vertName, t=joint, v=currentWeight)
print vertName, currentWeight
@api.d_progress(t='clamping influence count', st='clamping vert influences to %d' % kMAX_INF_PER_VERT)
def clampVertInfluenceCount( geos=None ):
'''
'''
global kMAX_INF_PER_VERT, kMIN_SKIN_WEIGHT_VALUE
progressWindow = cmd.progressWindow
skinPercent = cmd.skinPercent
halfMin = kMIN_SKIN_WEIGHT_VALUE / 2.0
if geos is None:
geos = cmd.ls(sl=True)
for geo in geos:
skin = cmd.ls(cmd.listHistory(geo), type='skinCluster')[0]
verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True)
inc = 100.0 / len( verts )
progress = 0
vertsFixed = []
for vert in verts:
progress += inc
progressWindow(e=True, progress=progress)
reapplyWeights = False
weightList = skinPercent(skin, vert, ib=1e-5, q=True, value=True)
if len(weightList) > kMAX_INF_PER_VERT:
jointList = skinPercent(skin, vert, ib=halfMin, q=True, transform=None)
sorted = zip(weightList, jointList)
sorted.sort()
#now clamp to the highest kMAX_INF_PER_VERT number of weights, and re-normalize
sorted = sorted[ -kMAX_INF_PER_VERT: ]
weightSum = sum( [ a for a, b in sorted ] )
t_values = [ (b, a/weightSum) for a, b in sorted ]
reapplyWeights = True
else:
for n, v in enumerate( weightList ):
if v <= kMIN_SKIN_WEIGHT_VALUE:
jointList = skinPercent( skin, vert, ib=halfMin, q=True, transform=None )
t_values = [ (a, b) for a, b in zip( jointList, weightList ) if b > halfMin ]
reapplyWeights = True
break
if reapplyWeights:
js = [ a for a, b in t_values ]
vs = renormalizeWithMinimumValue( [ b for a, b in t_values ] )
t_values = zip( js, vs )
skinPercent( skin, vert, tv=t_values )
vertsFixed.append( vert )
#turn on limiting in the skinCluster
cmd.setAttr('%s.maxInfluences' % skin, kMAX_INF_PER_VERT)
cmd.setAttr('%s.maintainMaxInfluences' % skin, 1)
print 'fixed skin weights on %d verts' % len( vertsFixed )
#print '\n'.join( vertsFixed )
def renormalizeWithMinimumValue( values, minValue=kMIN_SKIN_WEIGHT_VALUE ):
minCount = sum( 1 for v in values if v <= minValue )
toAlter = [ n for n, v in enumerate( values ) if v > minValue ]
modValues = [ max( minValue, v ) for v in values ]
toAlterSum = sum( [ values[ n ] for n in toAlter ] )
for n in toAlter:
modValues[ n ] /= toAlterSum
modifier = 1.0035 + ( float( minCount ) * minValue )
for n in toAlter:
modValues[ n ] /= modifier
return modValues
def getBoundsForJoint( joint ):
'''
returns bounding box data (as a 6-tuple: xmin, xmax, ymin etc...) for the geometry influenced by a given joint
'''
verts = jointVertsForMaya(joint, 0.01)
Xs, Ys, Zs = [], [], []
for v in verts:
x, y, z = cmd.xform(v, q=True, ws=True, t=True)
Xs.append(x)
Ys.append(y)
Zs.append(z)
Xs.sort()
Ys.sort()
Zs.sort()
try:
return Xs[0], Xs[-1], Ys[0], Ys[-1], Zs[0], Zs[-1]
except IndexError:
drawSize = cmd.getAttr('%s.radius' % joint)
drawSize /= 2
return -drawSize, drawSize, -drawSize, drawSize, -drawSize, drawSize
def getAlignedBoundsForJoint( joint, threshold=0.65, onlyVisibleMeshes=True ):
'''
looks at the verts the given joint/s and determines a local space (local to the first joint
in the list if multiple are given) bounding box of the verts, and positions the hitbox
accordingly
if onlyVisibleMeshes is True, then only meshes that are visible in the viewport will
contribute to the bounds
'''
theJoint = joint
verts = []
#so this is just to deal with the input arg being a tuple, list or string. you can pass in a list
#of joint names and the verts affected just get accumulated into a list, and the resulting bound
#should be the inclusive bounding box for the given joints
if isinstance( joint, (tuple,list) ):
theJoint = joint[0]
for joint in joint:
verts += jointVertsForMaya( joint, threshold, onlyVisibleMeshes )
else:
verts += jointVertsForMaya( joint, threshold, onlyVisibleMeshes )
jointDag = api.getMDagPath( theJoint )
jointMatrix = jointDag.inclusiveMatrix()
vJointPos = OpenMaya.MTransformationMatrix( jointMatrix ).rotatePivot( OpenMaya.MSpace.kWorld ) + OpenMaya.MTransformationMatrix( jointMatrix ).getTranslation( OpenMaya.MSpace.kWorld )
vJointPos = Vector( [vJointPos.x, vJointPos.y, vJointPos.z] )
vJointBasisX = OpenMaya.MVector(-1,0,0) * jointMatrix
vJointBasisY = OpenMaya.MVector(0,-1,0) * jointMatrix
vJointBasisZ = OpenMaya.MVector(0,0,-1) * jointMatrix
bbox = OpenMaya.MBoundingBox()
for vert in verts:
#get the position relative to the joint in question
vPos = Vector( xform(vert, query=True, ws=True, t=True) )
vPos = vJointPos - vPos
#now transform the joint relative position into the coordinate space of that joint
#we do this so we can get the width, height and depth of the bounds of the verts
#in the space oriented along the joint
vPosInJointSpace = Vector( (vPos.x, vPos.y, vPos.z) )
vPosInJointSpace = vPosInJointSpace.change_space( vJointBasisX, vJointBasisY, vJointBasisZ )
bbox.expand( OpenMaya.MPoint( *vPosInJointSpace ) )
minB, maxB = bbox.min(), bbox.max()
return minB[0], minB[1], minB[2], maxB[0], maxB[1], maxB[2]
def getJointScale( joint ):
'''
basically just returns the average bounding box side length... is useful to use as an approximation for a
joint's "size"
'''
xmn, xmx, ymn, ymx, zmn, zmx = getBoundsForJoint(joint)
x = xmx - xmn
y = ymx - ymn
z = zmx - zmn
return (x + y + z) / 3
#end | Python |
from baseMelUI import *
from filesystem import Path
import maya.cmds as cmd
import poseSym
import os
LabelledIconButton = labelledUIClassFactory( MelIconButton )
class PoseSymLayout(MelVSingleStretchLayout):
ICONS = ICON_SWAP, ICON_MIRROR, ICON_MATCH = 'poseSym_swap.xpm', 'poseSym_mirror.xpm', 'poseSym_match.xpm'
def __init__( self, parent ):
self.UI_swap = swap = LabelledIconButton( self, llabel='swap pose', llabelWidth=65, llabelAlign='right', c=self.on_swap )
swap.setImage( self.ICON_SWAP )
self.UI_mirror = mirror = LabelledIconButton( self, llabel='mirror pose', llabelWidth=65, llabelAlign='right', c=self.on_mirror )
mirror.setImage( self.ICON_MATCH )
#self.UI_match = match = LabelledIconButton( self, llabel='match pose', llabelWidth=65, llabelAlign='right', c=self.on_match )
#match.setImage( self.ICON_MATCH )
spacer = MelSpacer( self )
hLayout = MelHLayout( self )
MelLabel( hLayout, l='mirror: ' )
self.UI_mirror_t = MelCheckBox( hLayout, l='translate', v=1 )
self.UI_mirror_r = MelCheckBox( hLayout, l='rotate', v=1 )
self.UI_mirror_other = MelCheckBox( hLayout, l='other', v=1 )
hLayout.layout()
self.setStretchWidget( spacer )
self.layout()
### EVENT HANDLERS ###
def on_swap( self, *a ):
for pair, obj in poseSym.iterPairAndObj( cmd.ls( sl=True ) ):
pair.swap( t=self.UI_mirror_t.getValue(), r=self.UI_mirror_r.getValue(), other=self.UI_mirror_other.getValue() )
def on_mirror( self, *a ):
for pair, obj in poseSym.iterPairAndObj( cmd.ls( sl=True ) ):
pair.mirror( obj==pair.controlA, t=self.UI_mirror_t.getValue(), r=self.UI_mirror_r.getValue(), other=self.UI_mirror_other.getValue() )
def on_match( self, *a ):
for pair, obj in poseSym.iterPairAndObj( cmd.ls( sl=True ) ):
pair.match( obj==pair.controlA, t=self.UI_mirror_t.getValue(), r=self.UI_mirror_r.getValue(), other=self.UI_mirror_other.getValue() )
class PoseSymWindow(BaseMelWindow):
WINDOW_NAME = 'PoseSymTool'
WINDOW_TITLE = 'Pose Symmetry Tool'
DEFAULT_SIZE = 280, 200
DEFAULT_MENU = 'Setup'
HELP_MENU = WINDOW_NAME, 'hamish@valvesoftware.com', 'https://intranet.valvesoftware.com/wiki/index.php/Pose_Mirror_Tool'
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.editor = PoseSymLayout( self )
self.setupMenu()
self.show()
def setupMenu( self ):
menu = self.getMenu( 'Setup' )
menu.clear()
MelMenuItem( menu, l='Create Paired Mirror', ann='Will put the two selected objects into a "paired" relationship - they will know how to mirror/exchange poses with one another', c=self.on_setupPair )
MelMenuItem( menu, l='Create Single Mirror For Selected', ann='Will setup each selected control with a mirror node so it knows how to mirror poses on itself', c=self.on_setupSingle )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='Auto Setup Skeleton Builder', ann='Tries to determine mirroring relationships from skeleton builder', c=self.on_setupSingle )
### EVENT HANDLERS ###
def on_setupPair( self, *a ):
sel = cmd.ls( sl=True, type='transform' )
if len( sel ) == 1:
pair = poseSym.ControlPair.Create( sel[0] )
cmd.select( pair.node )
elif len( sel ) >= 2:
pair = poseSym.ControlPair.Create( sel[0], sel[1] )
cmd.select( pair.node )
def on_setupSingle( self, *a ):
sel = cmd.ls( sl=True, type='transform' )
nodes = []
for s in sel:
pair = poseSym.ControlPair.Create( s )
nodes.append( pair.node )
cmd.select( nodes )
def on_setupSkeletonBuilder( self, *a ):
import rigPrimitives
rigPrimitives.setupMirroring()
#end
| Python |
from vectors import Matrix, Vector, Axis
import maya.cmds as cmd
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import vectors
import apiExtensions
from maya.OpenMaya import MObject, MFnMatrixAttribute, MFnCompoundAttribute, MFnMessageAttribute, MGlobal, \
MFnEnumAttribute, MFnNumericAttribute, MFnNumericData, MFnUnitAttribute, MFnDependencyNode, \
MPoint, MVector, MSyntax, MArgDatabase
from maya.OpenMayaMPx import MPxNode
MPxCommand = OpenMayaMPx.MPxCommand
kUnknownParameter = OpenMaya.kUnknownParameter
#this list simply maps the rotation orders as found on the rotateOrder enum attribute, to the matrix methods responsible for converting a rotation matrix to euler values
mayaRotationOrders = Matrix.ToEulerXYZ, Matrix.ToEulerYZX, Matrix.ToEulerZXY, Matrix.ToEulerXZY, Matrix.ToEulerYXZ, Matrix.ToEulerZYX
assert len( mayaRotationOrders ) == len( set( mayaRotationOrders ) ) #sanity check
class MirrorNode(MPxNode):
NODE_ID = OpenMaya.MTypeId( 0x00115940 )
NODE_TYPE_NAME = "rotationMirror"
inWorldMatrix = MObject() #this is the input world matrix; the one we want mirrored
inParentMatrixInv = MObject() #this is the input parent inverse matrix. ie the parent inverse matrix of the transform we want mirrored
mirrorAxis = MObject() #which axis are we mirroring on?
mirrorTranslation = MObject() #boolean to determine whether translation mirroring happens in world space or local space
targetJointOrient = MObject() #this is the joint orient attribute for the target joint - so it can be compensated for
targetJointOrientX = MObject()
targetJointOrientY = MObject()
targetJointOrientZ = MObject()
targetParentMatrixInv = MObject() #this is the parent inverse matrix for the target transform
targetRotationOrder = MObject() #the rotation order on the target
outTranslate = MObject() #the output translation
outTranslateX = MObject()
outTranslateY = MObject()
outTranslateZ = MObject()
outRotate = MObject() #the output rotation
outRotateX = MObject()
outRotateY = MObject()
outRotateZ = MObject()
MIRROR_MODES = M_COPY, M_INVERT, M_MIRROR = range( 3 )
MIRROR_MODE_NAMES = 'copy', 'invert', 'mirror'
MIRROR_DEFAULT = M_MIRROR
@classmethod
def Creator( cls ):
return OpenMayaMPx.asMPxPtr( cls() )
@classmethod
def Init( cls ):
attrInWorldMatrix = MFnMatrixAttribute()
attrInParentMatrixInv = MFnMatrixAttribute()
attrMirrorAxis = MFnEnumAttribute()
attrMirrorTranslation = MFnEnumAttribute()
attrTargetParentMatrixInv = MFnMatrixAttribute()
targetRotationOrder = MFnNumericAttribute()
attrOutTranslate = MFnNumericAttribute()
attrOutTranslateX = MFnUnitAttribute()
attrOutTranslateY = MFnUnitAttribute()
attrOutTranslateZ = MFnUnitAttribute()
attrOutRotate = MFnNumericAttribute()
attrOutRotateX = MFnUnitAttribute()
attrOutRotateY = MFnUnitAttribute()
attrOutRotateZ = MFnUnitAttribute()
attrTargetJointOrient = MFnNumericAttribute()
attrTargetJointOrientX = MFnUnitAttribute()
attrTargetJointOrientY = MFnUnitAttribute()
attrTargetJointOrientZ = MFnUnitAttribute()
#create the world matrix
cls.inWorldMatrix = attrInWorldMatrix.create( "inWorldMatrix", "iwm" )
cls.addAttribute( cls.inWorldMatrix )
#create the local matrix
cls.inParentMatrixInv = attrInWorldMatrix.create( "inParentInverseMatrix", "ipmi" )
cls.addAttribute( cls.inParentMatrixInv )
#create the mirror axis
cls.mirrorAxis = attrMirrorAxis.create( "mirrorAxis", "m" )
attrMirrorAxis.addField( 'x', 0 )
attrMirrorAxis.addField( 'y', 1 )
attrMirrorAxis.addField( 'z', 2 )
attrMirrorAxis.setDefault( 'x' )
attrMirrorAxis.setKeyable( False )
attrMirrorAxis.setChannelBox( True )
cls.addAttribute( cls.mirrorAxis )
#create the mirror axis
cls.mirrorTranslation = attrMirrorTranslation.create( "mirrorTranslation", "mt" )
for modeName, modeIdx in zip( cls.MIRROR_MODE_NAMES, cls.MIRROR_MODES ):
attrMirrorTranslation.addField( modeName, modeIdx )
attrMirrorTranslation.setDefault( cls.MIRROR_DEFAULT )
attrMirrorTranslation.setKeyable( False )
attrMirrorTranslation.setChannelBox( True )
cls.addAttribute( cls.mirrorTranslation )
#create the out world matrix inverse
cls.targetParentMatrixInv = attrTargetParentMatrixInv.create( "targetParentInverseMatrix", "owm" )
cls.addAttribute( cls.targetParentMatrixInv )
#create the target rotation order attribute
cls.targetRotationOrder = targetRotationOrder.create( "targetRotationOrder", "troo", MFnNumericData.kInt )
cls.addAttribute( cls.targetRotationOrder )
#create the joint orient compensation attributes
cls.targetJointOrientX = attrTargetJointOrientX.create( "targetJointOrientX", "tjox", MFnUnitAttribute.kAngle )
cls.targetJointOrientY = attrTargetJointOrientY.create( "targetJointOrientY", "tjoy", MFnUnitAttribute.kAngle )
cls.targetJointOrientZ = attrTargetJointOrientZ.create( "targetJointOrientZ", "tjoz", MFnUnitAttribute.kAngle )
cls.targetJointOrient = attrTargetJointOrient.create( "targetJointOrient", "tjo", cls.targetJointOrientX, cls.targetJointOrientY, cls.targetJointOrientZ )
cls.addAttribute( cls.targetJointOrient )
#create the out translate attributes
cls.outTranslateX = attrOutTranslateX.create( "outTranslateX", "otx", MFnUnitAttribute.kDistance )
cls.outTranslateY = attrOutTranslateY.create( "outTranslateY", "oty", MFnUnitAttribute.kDistance )
cls.outTranslateZ = attrOutTranslateZ.create( "outTranslateZ", "otz", MFnUnitAttribute.kDistance )
cls.outTranslate = attrOutTranslate.create( "outTranslate", "ot", cls.outTranslateX, cls.outTranslateY, cls.outTranslateZ )
cls.addAttribute( cls.outTranslate )
#create the out rotation attributes
cls.outRotateX = attrOutRotateX.create( "outRotateX", "orx", MFnUnitAttribute.kAngle )
cls.outRotateY = attrOutRotateY.create( "outRotateY", "ory", MFnUnitAttribute.kAngle )
cls.outRotateZ = attrOutRotateZ.create( "outRotateZ", "orz", MFnUnitAttribute.kAngle )
cls.outRotate = attrOutRotate.create( "outRotate", "or", cls.outRotateX, cls.outRotateY, cls.outRotateZ )
cls.addAttribute( cls.outRotate )
#setup attribute dependency relationships
cls.attributeAffects( cls.inWorldMatrix, cls.outTranslate )
cls.attributeAffects( cls.inWorldMatrix, cls.outRotate )
cls.attributeAffects( cls.inParentMatrixInv, cls.outTranslate )
cls.attributeAffects( cls.inParentMatrixInv, cls.outRotate )
cls.attributeAffects( cls.mirrorAxis, cls.outTranslate )
cls.attributeAffects( cls.mirrorAxis, cls.outRotate )
cls.attributeAffects( cls.mirrorTranslation, cls.outTranslate )
cls.attributeAffects( cls.mirrorTranslation, cls.outRotate )
cls.attributeAffects( cls.targetParentMatrixInv, cls.outTranslate )
cls.attributeAffects( cls.targetParentMatrixInv, cls.outRotate )
cls.attributeAffects( cls.targetRotationOrder, cls.outTranslate )
cls.attributeAffects( cls.targetRotationOrder, cls.outRotate )
cls.attributeAffects( cls.targetJointOrient, cls.outRotate )
def compute( self, plug, dataBlock ):
dh_mirrorTranslation = dataBlock.inputValue( self.mirrorTranslation )
mirrorTranslation = Axis( dh_mirrorTranslation.asShort() )
inWorldMatrix = dataBlock.inputValue( self.inWorldMatrix ).asMatrix()
inParentInvMatrix = dataBlock.inputValue( self.inParentMatrixInv ).asMatrix()
dh_mirrorAxis = dataBlock.inputValue( self.mirrorAxis )
axis = Axis( dh_mirrorAxis.asShort() )
### DEAL WITH ROTATION AND POSITION SEPARATELY ###
R, S = inWorldMatrix.asPy( 3 ).decompose() #this gets just the 3x3 rotation and scale matrices
x, y, z = R #extract basis vectors
#mirror the rotation axes and construct the mirrored rotation matrix
idxA, idxB = axis.otherAxes()
x[ idxA ] = -x[ idxA ]
x[ idxB ] = -x[ idxB ]
y[ idxA ] = -y[ idxA ]
y[ idxB ] = -y[ idxB ]
z[ idxA ] = -z[ idxA ]
z[ idxB ] = -z[ idxB ]
#factor scale back into the matrix
mirroredMatrix = Matrix( x + y + z, 3 ) * S
mirroredMatrix = mirroredMatrix.expand( 4 )
#now put the rotation matrix in the space of the target object
dh_targetParentMatrixInv = dataBlock.inputValue( self.targetParentMatrixInv )
tgtParentMatrixInv = dh_targetParentMatrixInv.asMatrix()
matInv = tgtParentMatrixInv.asPy()
#put the rotation in the space of the target's parent
mirroredMatrix = mirroredMatrix * matInv
#if there is a joint orient, make sure to compensate for it
tgtJoX = dataBlock.inputValue( self.targetJointOrientX ).asDouble()
tgtJoY = dataBlock.inputValue( self.targetJointOrientY ).asDouble()
tgtJoZ = dataBlock.inputValue( self.targetJointOrientZ ).asDouble()
jo = Matrix.FromEulerXYZ( tgtJoX, tgtJoY, tgtJoZ )
joInv = jo.inverse()
joInv = joInv.expand( 4 )
mirroredMatrix = mirroredMatrix * joInv
#grab the rotation order of the target
rotOrderIdx = dataBlock.inputValue( self.targetRotationOrder ).asInt()
#grab euler values
R, S = mirroredMatrix.decompose() #we need to decompose again to extract euler angles...
eulerXYZ = outX, outY, outZ = mayaRotationOrders[ rotOrderIdx ]( R ) #R.ToEulerYZX()
dh_outRX = dataBlock.outputValue( self.outRotateX )
dh_outRY = dataBlock.outputValue( self.outRotateY )
dh_outRZ = dataBlock.outputValue( self.outRotateZ )
#set the rotation
dh_outRX.setDouble( outX )
dh_outRY.setDouble( outY )
dh_outRZ.setDouble( outZ )
dataBlock.setClean( plug )
### NOW DEAL WITH POSITION ###
#set the position
if mirrorTranslation == self.M_COPY:
inLocalMatrix = inWorldMatrix * inParentInvMatrix
pos = MPoint( inLocalMatrix(3,0), inLocalMatrix(3,1), inLocalMatrix(3,2) )
elif mirrorTranslation == self.M_INVERT:
inLocalMatrix = inWorldMatrix * inParentInvMatrix
pos = MPoint( -inLocalMatrix(3,0), -inLocalMatrix(3,1), -inLocalMatrix(3,2) )
elif mirrorTranslation == self.M_MIRROR:
pos = MPoint( inWorldMatrix(3,0), inWorldMatrix(3,1), inWorldMatrix(3,2) )
pos = [ pos.x, pos.y, pos.z ]
pos[ axis ] = -pos[ axis ]
pos = MPoint( *pos )
pos = pos * tgtParentMatrixInv
else:
return
dh_outTX = dataBlock.outputValue( self.outTranslateX )
dh_outTY = dataBlock.outputValue( self.outTranslateY )
dh_outTZ = dataBlock.outputValue( self.outTranslateZ )
dh_outTX.setDouble( pos[0] )
dh_outTY.setDouble( pos[1] )
dh_outTZ.setDouble( pos[2] )
class ControlPairNode(MPxNode):
'''
is used by the poseSym tool for storing control pair relationships
'''
NODE_ID = OpenMaya.MTypeId( 0x00115941 )
NODE_TYPE_NAME = "controlPair"
controlA = MObject()
controlB = MObject()
axis = MObject() #this is the axis which things get mirrored across
flipAxes = MObject()
neverDoT = MObject() #if this is true then translation won't get mirrored/swapped
neverDoR = MObject() #if this is true then rotation won't get mirrored/swapped
neverDoOther = MObject() #if this is true then other keyable attributes won't get mirrored/swapped
worldSpace = MObject() #if this is true mirroring is done in world space - otherwise local spaces
#these are the values for the flip axes
FLIP_AXES = (), (vectors.AX_X, vectors.AX_Y), (vectors.AX_X, vectors.AX_Z), (vectors.AX_Y, vectors.AX_Z)
@classmethod
def Creator( cls ):
return OpenMayaMPx.asMPxPtr( cls() )
@classmethod
def Init( cls ):
attrMsg = MFnMessageAttribute()
cls.controlA = attrMsg.create( "controlA", "ca" )
cls.controlB = attrMsg.create( "controlB", "cb" )
cls.addAttribute( cls.controlA )
cls.addAttribute( cls.controlB )
attrEnum = MFnEnumAttribute()
cls.axis = attrEnum.create( "axis", "ax" )
attrEnum.addField( 'x', 0 )
attrEnum.addField( 'y', 1 )
attrEnum.addField( 'z', 2 )
attrEnum.setDefault( 'x' )
attrEnum.setKeyable( False )
attrEnum.setChannelBox( True )
cls.addAttribute( cls.axis )
cls.axis = attrEnum.create( "flipAxes", "flax" )
for n, thisAxes in enumerate( cls.FLIP_AXES ):
if thisAxes:
enumStr = ''.join( [ ax.asName() for ax in thisAxes ] )
else:
enumStr = 'none'
attrEnum.addField( enumStr, n )
attrEnum.setKeyable( False )
attrEnum.setChannelBox( True )
cls.addAttribute( cls.axis )
numAttr = MFnNumericAttribute()
cls.neverDoT = numAttr.create( "neverDoT", "nvt", MFnNumericData.kBoolean )
cls.neverDoR = numAttr.create( "neverDoR", "nvr", MFnNumericData.kBoolean )
cls.neverDoOther = numAttr.create( "neverDoOther", "nvo", MFnNumericData.kBoolean )
cls.addAttribute( cls.neverDoT )
cls.addAttribute( cls.neverDoR )
cls.addAttribute( cls.neverDoOther )
cls.worldSpace = numAttr.create( "worldSpace", "ws", MFnNumericData.kBoolean, True )
cls.addAttribute( cls.worldSpace )
class CreateMirrorNode(MPxCommand):
CMD_NAME = 'rotationMirror'
_ARG_SPEC = [ ('-h', '-help', MSyntax.kNoArg, 'prints help'),
('-ax', '-axis', MSyntax.kString, 'the axis to mirror across (defaults to x)'),
('-m', '-translationMode', MSyntax.kString, 'the mode in which translation is mirrored - %s (defaults to %s)' % (' '.join( MirrorNode.MIRROR_MODE_NAMES ), MirrorNode.MIRROR_MODE_NAMES[ MirrorNode.MIRROR_DEFAULT ])),
('-d', '-dummy', MSyntax.kNoArg, "builds the node but doesn't hook it up to the target - this can be useful if you want to query what would be mirrored transform"),
#('-s', '-space', MSyntax.kString, 'which space to mirror in - world or local (defaults to world)') ]
]
kFlagHelp = _ARG_SPEC[ 0 ][ 0 ]
kFlagAxis = _ARG_SPEC[ 1 ][ 0 ]
kFlagMode = _ARG_SPEC[ 2 ][ 0 ]
kFlagDummy = _ARG_SPEC[ 3 ][ 0 ]
@classmethod
def SyntaxCreator( cls ):
syntax = OpenMaya.MSyntax()
for shortFlag, longFlag, syntaxType, h in cls.IterArgSpec():
syntax.addFlag( shortFlag, longFlag, syntaxType )
syntax.useSelectionAsDefault( True )
syntax.setObjectType( MSyntax.kSelectionList, 1, 3 )
syntax.enableQuery( True )
syntax.enableEdit( True )
return syntax
@classmethod
def Creator( cls ):
return OpenMayaMPx.asMPxPtr( cls() )
@classmethod
def IterArgSpec( cls ):
for data in cls._ARG_SPEC:
if len( data ) != 4:
yield data + ('<no help available>',)
else:
yield data
def grabArgDb( self, mArgs ):
try:
argData = MArgDatabase( self.syntax(), mArgs )
except RuntimeError:
return True, None
if argData.isFlagSet( self.kFlagHelp ):
self.printHelp()
return True, None
return False, argData
def printHelp( self ):
longestFlag = 5
for shortFlag, longFlag, syntaxType, h in self.IterArgSpec():
longestFlag = max( longestFlag, len(longFlag) )
self.displayInfo( '%s - USAGE' % self.CMD_NAME )
printStr = '*%5s %'+ str( longestFlag ) +'s: %s'
for shortFlag, longFlag, syntaxType, h in self.IterArgSpec():
self.displayInfo( printStr % (shortFlag, longFlag, h) )
def doIt( self, mArgs ):
ret, argData = self.grabArgDb( mArgs )
if ret:
return
sel = OpenMaya.MSelectionList()
argData.getObjects( sel )
objs = []
for n in range( sel.length() ):
obj = MObject()
sel.getDependNode( n, obj )
objs.append( obj )
#
if argData.isQuery():
rotNode = objs[0]
if argData.isFlagSet( self.kFlagAxis ):
self.setResult( cmd.getAttr( '%s.mirrorAxis' % rotNode ) )
elif argData.isFlagSet( self.kFlagMode ):
self.setResult( cmd.getAttr( '%s.mirrorTranslation' % rotNode ) )
return
#if we're in edit mode, find the node
elif argData.isEdit():
rotNode = objs[0]
#otherwise we're in creation mode - so build the node and connect things up
else:
obj, tgt = objs
#is dummy mode set?
isDummyMode = argData.isFlagSet( self.kFlagDummy ) or argData.isFlagSet( self.kFlagDummy )
#see if there is already a node connected
existing = cmd.listConnections( '%s.t' % tgt, '%s.r' % tgt, type=MirrorNode.NODE_TYPE_NAME )
if existing:
self.displayWarning( "There is a %s node already connected - use edit mode!" % MirrorNode.NODE_TYPE_NAME )
self.setResult( existing[ 0 ] )
return
else:
rotNode = cmd.createNode( 'rotationMirror' )
cmd.connectAttr( '%s.worldMatrix' % obj, '%s.inWorldMatrix' % rotNode )
cmd.connectAttr( '%s.parentInverseMatrix' % obj, '%s.inParentInverseMatrix' % rotNode )
cmd.connectAttr( '%s.parentInverseMatrix' % tgt, '%s.targetParentInverseMatrix' % rotNode )
joAttrpath = '%s.jo' % tgt
if cmd.objExists( joAttrpath ):
cmd.connectAttr( joAttrpath, '%s.targetJointOrient' % rotNode )
cmd.connectAttr( '%s.rotateOrder' % tgt, '%s.targetRotationOrder' % rotNode )
if not isDummyMode:
cmd.connectAttr( '%s.outTranslate' % rotNode, '%s.t' % tgt )
cmd.connectAttr( '%s.outRotate' % rotNode, '%s.r' % tgt )
cmd.select( obj )
#set the result to the node created...
self.setResult( rotNode )
#set any attributes passed in from the command-line
if argData.isFlagSet( self.kFlagAxis ):
axisInt = Axis.FromName( argData.flagArgumentString( self.kFlagAxis, 0 ) )
cmd.setAttr( '%s.mirrorAxis' % rotNode, axisInt )
if argData.isFlagSet( self.kFlagMode ):
modeStr = argData.flagArgumentString( self.kFlagMode, 0 )
modeIdx = list( MirrorNode.MIRROR_MODE_NAMES ).index( modeStr )
cmd.setAttr( '%s.mirrorTranslation' % rotNode, modeIdx )
def undoIt( self ):
pass
def isUndoable( self ):
return True
def initializePlugin( mobject ):
mplugin = OpenMayaMPx.MFnPlugin( mobject, 'macaronikazoo', '1' )
try:
mplugin.registerNode( MirrorNode.NODE_TYPE_NAME, MirrorNode.NODE_ID, MirrorNode.Creator, MirrorNode.Init )
mplugin.registerNode( ControlPairNode.NODE_TYPE_NAME, ControlPairNode.NODE_ID, ControlPairNode.Creator, ControlPairNode.Init )
mplugin.registerCommand( CreateMirrorNode.CMD_NAME, CreateMirrorNode.Creator, CreateMirrorNode.SyntaxCreator )
mplugin.registerCommand( CreateMirrorNode.CMD_NAME.lower(), CreateMirrorNode.Creator, CreateMirrorNode.SyntaxCreator )
except:
MGlobal.displayError( "Failed to load zooMirror plugin:" )
raise
def uninitializePlugin( mobject ):
mplugin = OpenMayaMPx.MFnPlugin( mobject )
try:
mplugin.deregisterNode( MirrorNode.NODE_ID )
mplugin.deregisterNode( ControlPairNode.NODE_ID )
mplugin.deregisterCommand( CreateMirrorNode.CMD_NAME )
mplugin.deregisterCommand( CreateMirrorNode.CMD_NAME.lower() )
except:
MGlobal.displayError( "Failed to unload zooMirror plugin:" )
raise
#end
| Python |
import re
import rigPrimitives
from maya.cmds import *
from baseMelUI import *
from mayaDecorators import d_disableViews, d_noAutoKey, d_unifyUndo, d_restoreTime
from common import printWarningStr
from triggered import Trigger
from rigUtils import findPolePosition, alignFast
_FK_CMD_NAME = 'switch to FK'.lower()
_IK_CMD_NAME = 'switch to IK'.lower()
def cropValues( valueList, minVal=None, maxVal=None ):
'''
assumes the input list is sorted
NOTE: the input list is modified in place and nothing is returned
'''
if minVal is not None:
while valueList:
if valueList[0] < minVal:
valueList.pop( 0 )
else: break
if maxVal is not None:
while valueList:
if valueList[-1] > maxVal:
valueList.pop()
else: break
def getJointsFromIkHandle( handle ):
#get the joints the ik control drives - we need these to get keyframes from so we know which frames to trace the ik control on
joints = ikHandle( handle, q=True, jl=True )
effector = ikHandle( handle, q=True, ee=True )
cons = listConnections( '%s.tx' % effector, d=False )
if not cons:
printWarningStr( "Could not find the end effector control!" )
return
joints.append( cons[0] )
return joints
def getControlsFromObjs( control ):
'''
attempts to retrieve the pole vector control, the ik handle and all fk controls given an ik rig control. The
information is returned in a 3 tuple containing:
ikHandle, poleControl, fkControls
'''
errorValue = None, None, None, None
try:
part = rigPrimitives.RigPart.InitFromItem( control )
return part.getControl( 'control' ), part.getIkHandle(), part.getControl( 'poleControl' ), part.getFkControls()
except rigPrimitives.RigPartError: pass
#so if the control we've been given isn't a rig primitive, lets try to extract whatever information we can from right click commands - if any exist
trigger = Trigger( ikControl )
switchCmdStr = None
for n, cmdName, cmdStr in trigger.iterMenus():
if cmdName.lower() == _IK_CMD_NAME:
switchCmdStr = trigger.resolve( cmdStr )
break
if switchCmdStr is None:
printWarningStr( "Cannot find the %s command - aborting!" % _IK_CMD_NAME )
return errorValue
#extract the control handle from the switch command - it may or may not exist, depending on which
rexStr = re.compile( '-ikHandle \%([a-ZA-Z0-9_:|]+)', re.IGNORECASE | re.MULTILINE )
match = rexStr.search( switchCmdStr )
if not match:
if match.groups()[0]:
control = match.groups()[0]
#extract the ik handle from the switch command
rexStr = re.compile( '-ikHandle \%([a-ZA-Z0-9_:|]+)', re.IGNORECASE | re.MULTILINE )
match = rexStr.search( switchCmdStr )
if not match:
printWarningStr( "Could not determine the ik handle from the given control" )
return errorValue
handle = match.groups()[0]
if handle is None:
printWarningStr( "Could not find the ik handle at the given connect index!" )
return errorValue
#now extract the pole control from the switch command
rexStr = re.compile( '-pole \%([a-ZA-Z0-9_:|]+)', re.IGNORECASE | re.MULTILINE )
match = rexStr.search( switchCmdStr )
if not match:
printWarningStr( "Could not determine the pole vector control from the given control" )
return errorValue
poleControl = match.groups()[0]
if poleControl is None:
printWarningStr( "Could not find the ik handle at the given connect index!" )
return errorValue
return control, poleControl, handle, getJointsFromIkHandle( handle )
@d_unifyUndo
@d_disableViews
@d_noAutoKey
@d_restoreTime
def switchAnimationToFk( control, handle=None, attrName='ikBlend', onValue=1, offValue=0, key=True, startFrame=None, endFrame=None ):
#grab the key times for keys set on the t or r channels on the ik control - these are the frames we want to switch to fk on
keyTimes = keyframe( control, q=True, at=('t', 'r'), tc=True )
if not keyTimes:
switchToFk( control, handle, attrName, offValue, key )
printWarningStr( "No keys found on the ik control - nothing to do!" )
return
#remove duplicate key times and sort them
keyTimes = removeDupes( keyTimes )
keyTimes.sort()
cropValues( keyTimes, startFrame, endFrame )
joints = getJointsFromIkHandle( handle )
for time in keyTimes:
currentTime( time, e=True )
switchToFk( control, handle, attrName, onValue, offValue, key, joints )
select( joints[-1] )
@d_unifyUndo
@d_disableViews
@d_noAutoKey
@d_restoreTime
def switchAnimationToIk( control, poleControl=None, handle=None, attrName='ikBlend', onValue=1, key=True, startFrame=None, endFrame=None ):
#get the joints the ik control drives - we need these to get keyframes from so we know which frames to trace the ik control on
joints = getJointsFromIkHandle( handle )
if not joints:
printWarningStr( "Cannot find the fk controls for the given ik control" )
return
#grab the key times for keys set on the t or r channels on the ik control - these are the frames we want to switch to fk on
keyTimes = keyframe( joints, q=True, at=('t', 'r'), tc=True )
if not keyTimes:
switchToIk( ikControl, poleControl, handle, attrName, onValue, key )
printWarningStr( "No keys found on the fk controls - nothing to do!" )
return
#remove duplicate key times and sort them
keyTimes = removeDupes( keyTimes )
keyTimes.sort()
cropValues( keyTimes, startFrame, endFrame )
#clear out the keys for the ik control
cutKey( control, poleControl, t=(keyTimes[0], keyTimes[-1]), cl=True )
startFrame = keyTimes[0]
currentTime( startFrame, e=True )
setKeyframe( control, poleControl, t=(startFrame,) )
for time in keyTimes:
currentTime( time, e=True )
switchToIk( control, poleControl, handle, attrName, onValue, key, joints, _isBatchMode=True )
setKeyframe( control, t=keyTimes, at=attrName, v=onValue )
select( control )
def switchToFk( control, handle=None, attrName='ikBlend', onValue=1, offValue=0, key=False, joints=None ):
if handle is None:
handle = control
if handle is None or not objExists( handle ):
printWarningStr( "no ikHandle specified" )
return
#if we weren't passed in joints - discover them now
if joints is None:
joints = getJointsFromIkHandle( handle )
#make sure ik is on before querying rotations
setAttr( '%s.%s' % (control, attrName), onValue )
rots = []
for j in joints:
rot = getAttr( "%s.r" % j )[0]
rots.append( rot )
#now turn ik off and set rotations for the joints
setAttr( '%s.%s' % (control, attrName), offValue )
for j, rot in zip( joints, rots ):
for ax, r in zip( ('x', 'y', 'z'), rot ):
if getAttr( '%s.r%s' % (j, ax), se=True ):
setAttr( '%s.r%s' % (j, ax), r )
alignFast( joints[2], handle )
if key:
setKeyframe( joints )
setKeyframe( '%s.%s' % (control, attrName) )
def switchToIk( control, poleControl=None, handle=None, attrName='ikBlend', onValue=1, key=False, joints=None, _isBatchMode=False ):
if handle is None:
handle = control
if handle is None or not objExists( handle ):
printWarningStr( "no ikHandle specified" )
return
#if we weren't passed in joints - discover them now
if joints is None:
joints = getJointsFromIkHandle( handle )
alignFast( control, joints[2] )
if poleControl:
if objExists( poleControl ):
pos = findPolePosition( joints[2], joints[1], joints[0] )
move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True )
setKeyframe( poleControl )
setAttr( '%s.%s' % (control, attrName), onValue )
if key:
setKeyframe( control, at=('t', 'r') )
if not _isBatchMode:
setKeyframe( control, at=attrName )
class ChangeIkFkLayout(MelColumnLayout):
def __init__( self, parent ):
self.UI_control = MelObjectSelector( self, 'control ->', None, 100 )
self.UI_pole = MelObjectSelector( self, 'pole control ->', None, 100 )
self.UI_handle = MelObjectSelector( self, 'IK handle ->', None, 100 )
self.UI_control.setChangeCB( self.on_controlChanged )
hLayout = MelHLayout( self )
self.UI_toFk = MelButton( hLayout, l='Switch to FK', c=self.on_toFk )
self.UI_toIk = MelButton( hLayout, l='Switch to IK', c=self.on_toIk )
hLayout.layout()
self.on_controlChanged()
def setControl( self, control ):
self.UI_control.setValue( control )
### EVENT HANDLERS ###
def on_controlChanged( self ):
control = self.UI_control.getValue()
if control:
self.UI_toFk.setEnabled( True )
self.UI_toIk.setEnabled( True )
control, handle, poleControl, _tmp = getControlsFromObjs( control )
self.UI_control.setValue( control, False )
if handle:
self.UI_handle.setValue( handle, False )
if poleControl:
self.UI_pole.setValue( poleControl, False )
else:
self.UI_toFk.setEnabled( False )
self.UI_toIk.setEnabled( False )
### EVENT HANDLERS ###
def on_sceneChange( self, a ):
self.UI_control.clear()
self.UI_pole.clear()
self.UI_handle.clear()
def on_toFk( self, *a ):
control = self.UI_control.getValue()
if control:
switchAnimationToFk( control, self.UI_handle.getValue() )
def on_toIk( self, *a ):
control = self.UI_control.getValue()
if control:
switchAnimationToIk( control, self.UI_pole.getValue(), self.UI_handle.getValue() )
class ChangeIkFkWindow(BaseMelWindow):
WINDOW_NAME = 'changeIkFkWindow'
WINDOW_TITLE = 'Ik Fk Switcher'
DEFAULT_SIZE = 400, 150
DEFAULT_MENU = None
FORCE_DEFAULT_SIZE = True
def __init__( self ):
self.UI_editor = ChangeIkFkLayout( self )
self.show()
def setControl( self, control ):
self.UI_editor.setControl( control )
def loadSelectedInTool():
sel = ls( sl=True, type='transform' )
if sel:
if not ChangeIkFkWindow.Exists():
ChangeIkFkWindow()
for layout in ChangeIkFkLayout.IterInstances():
layout.setControl( sel[0] )
#end
| Python |
from baseMelUI import *
from filesystem import Path, Callback
from common import printWarningStr
import api, presetsUI
PRESET_ID_STR = 'zoo'
PRESET_EXTENSION = 'filter'
class FileScrollList(MelObjectScrollList):
def __init__( self, parent, *a, **kw ):
self._rootDir = None
self._displayRelativeToRoot = True
MelObjectScrollList.__init__( self, parent, *a, **kw )
def itemAsStr( self, item ):
if self._displayRelativeToRoot and self._rootDir:
return str( Path( item ) - self._rootDir )
return str( item )
def getRootDir( self ):
return self._rootDir
def setRootDir( self, rootDir ):
self._rootDir = Path( rootDir )
self.update()
def getDisplayRelative( self ):
return self._displayRelativeToRoot
def setDisplayRelative( self, state=True ):
self._displayRelativeToRoot = state
self.update()
class FileListLayout(MelVSingleStretchLayout):
ENABLE_IMPORT = True
ENABLE_REFERENCE = True
def __new__( cls, parent, *a, **kw ):
return BaseMelWidget.__new__( cls, parent )
def __init__( self, parent, directory=None, files=None, recursive=True ):
self.expand = True
self.padding = 2
self._files = []
self._recursive = recursive
self._extensionSets = []
self._extensionsToDisplay = []
self._ignoreSubstrings = [ 'incrementalSave' ]
self._enableOpen = True
self._enableImport = True
self._enableReference = True
#this allows clients who subclass this class to set additional filter change callbacks - perhaps
#for things like saving the filter string in user preferences, or doing additional work...
self._filterChangeCB = None
hLayout = MelHSingleStretchLayout( self )
MelLabel( hLayout, l='Directory' )
self.UI_dir = MelTextField( hLayout, tx=directory, cc=self.on_dirChange )
MelButton( hLayout, l='Browse', w=80, c=self.on_browse )
hLayout.setStretchWidget( self.UI_dir )
hLayout.layout()
hLayout = MelHSingleStretchLayout( self )
MelLabel( hLayout, l='Filter' )
self.UI_filter = MelTextField( hLayout, cc=self.on_filterChanged )
if not self._extensionSets:
for exts in self._extensionSets:
self.UI_filter = MelOptionMenu( hLayout, l='', cc=self.on_changeExtensionSet )
self.UI_filter.append( ' '.join( exts ) )
hLayout.setStretchWidget( self.UI_filter )
hLayout.layout()
self.UI_files = FileScrollList( self, ams=True, dcc=self.on_doubleClick, h=75 )
### ADD POPUPS
cmd.popupMenu( parent=self.UI_filter, b=3, pmc=self.popup_filterPresets )
cmd.popupMenu( parent=self.UI_files, b=3, pmc=self.popup_files )
if files is None:
self.populateFiles()
else:
self.setFiles( files )
self.setStretchWidget( self.UI_files )
self.layout()
def __contains__( self, item ):
return item in self.UI_files
def setDir( self, dir, update=True ):
self.UI_dir.setValue( str( dir ), update )
def getDir( self ):
return Path( self.UI_dir.getValue() )
def getRecursive( self ):
return self._recursive
def setRecursive( self, state=True, update=True ):
self._recursive = state
if update:
self.populateFiles()
def getExtensionsToDisplay( self ):
return self._extensionsToDisplay[:]
def setExtensionsToDisplay( self, extensionList, update=True ):
self._extensionsToDisplay = extensionList[:]
if update:
self.populateFiles()
def getIgnoreSubstrings( self ):
return self._ignoreSubstrings[:]
def setIgnoreSubstrings( self, substringList, update=True ):
self._ignoreSubstrings = substringList[:]
if update:
self.populateFiles()
def populateFiles( self ):
self.setFiles( list( self.getDir().files( recursive=self.getRecursive() ) ) )
def getDisplayRelative( self ):
return self.UI_files.getDisplayRelative()
def setDisplayRelative( self, state=True ):
self.UI_files.setDisplayRelative( state )
def getFilter( self ):
return self.UI_filter.getValue()
def setFilter( self, filterStr, update=True ):
self.UI_filter.setValue( filterStr, update )
def setFilterChangeCB( self, cb ):
self._filterChangeCB = cb
def setSelectionChangeCB( self, cb ):
self.UI_files.setChangeCB( cb )
def getSelectedFiles( self ):
return self.UI_files.getSelectedItems()
def setSelectedFiles( self, files, executeChangeCB=False ):
#make sure all files are Path instances
files = map( Path, files )
self.UI_files.selectItems( files, executeChangeCB )
def getFiles( self ):
'''
returns the files being listed
'''
return self.UI_files.getItems()
def setFiles( self, files ):
'''
sets the file list to the given iterable
'''
self.UI_files.clear()
self.addFiles( files )
def addFiles( self, files ):
'''
adds files to the UI without clearing
'''
self._files = []
for f in files:
#if the file doesn't have the right extension - bail
if self._extensionsToDisplay:
if f.getExtension().lower() not in self._extensionsToDisplay:
continue
skip = False
for invalid in self._ignoreSubstrings:
if invalid.lower() in str( f ).lower():
skip = True
break
if skip:
continue
self._files.append( f )
self.UI_files.setItems( self._files )
### MENU BUILDERS ###
def popup_filterPresets( self, parent, *args ):
cmd.setParent( parent, m=True )
cmd.menu( parent, e=True, dai=True )
hasItems = False
allFilterPresets = presetsUI.listAllPresets( PRESET_ID_STR, PRESET_EXTENSION )
for locale, filterPresets in allFilterPresets.iteritems():
for item in filterPresets:
itemName = item.name()
cmd.menuItem( l=itemName, c=Callback( self.setFilter, itemName ) )
hasItems = True
if hasItems:
cmd.menuItem( d=True )
cmd.menuItem( l='clear', c=Callback( self.setFilter, '' ) )
if self.getFilter():
cmd.menuItem( d=True )
cmd.menuItem( l='save filter preset', c=self.on_filterSave )
cmd.menuItem( l='manager filter presets', c=self.on_filterManage )
def popup_files( self, parent, *args ):
cmd.setParent( parent, m=True )
cmd.menu( parent, e=True, dai=True )
files = self.getSelectedFiles()
if len( files ) == 1:
if self._enableOpen:
cmd.menuItem( l='open file', c=lambda *x: self.on_open( files[ 0 ] ) )
if self._enableImport:
cmd.menuItem( l='import file', c=lambda *x: self.on_import( files[ 0 ] ) )
if self._enableReference:
cmd.menuItem( l='reference file', c=lambda *x: self.on_reference( files[ 0 ] ) )
cmd.menuItem( d=True )
api.addExploreToMenuItems( files[ 0 ] )
else:
cmd.menuItem( l="please select a single file" )
cmd.menuItem( d=True )
cmd.menuItem( cb=self.getDisplayRelative(), l="Display Relative Paths", c=lambda *x: self.setDisplayRelative( not self.getDisplayRelative() ) )
cmd.menuItem( cb=self.getRecursive(), l="Recursive Directory Listing", c=lambda *x: self.setRecursive( not self.getRecursive() ) )
### EVENT CALLBACKS ###
def on_open( self, theFile ):
api.openFile( theFile )
def on_import( self, theFile ):
api.importFile( theFile )
def on_reference( self, theFile ):
api.referenceFile( theFile, 'ref' )
def on_dirChange( self, theDir=None ):
if theDir is None:
theDir = self.getDir()
theDir = Path( theDir )
self.UI_files.setRootDir( theDir )
self.populateFiles()
def on_browse( self, *args ):
startDir = cmd.workspace( q=True, rootDirectory=True )
cmd.workspace( dir=startDir )
def tempCB( filename, filetype ):
self.setDir( filename )
self.on_dirChange( filename )
cmd.fileBrowserDialog( mode=4, fileCommand=tempCB, an="Choose_Location" )
def on_filterChanged( self, *args ):
self.UI_files.setFilter( self.UI_filter.getValue() )
if self._filterChangeCB:
try:
self._filterChangeCB()
except:
printWarningStr( "The filter change callback %s failed!" % self._filterChangeCB )
def on_changeExtensionSet( self, *args ):
self._extensionsToDisplay = cmd.optionMenu( self.UI_filter, q=True, v=True ).split()
self.populateFiles()
def on_doubleClick( self, *args ):
api.openFile( self.getSelectedFiles()[ 0 ] )
def on_filterSave( self, *args ):
presetName = self.UI_filter.getValue()
presetsUI.savePreset( presetsUI.LOCAL, PRESET_ID_STR, presetName, PRESET_EXTENSION )
def on_filterManage( self, *args ):
presetsUI.load( PRESET_ID_STR, presetsUI.LOCAL, PRESET_EXTENSION )
class FileUIWindow(BaseMelWindow):
WINDOW_NAME = 'fileUITestWindow'
WINDOW_TITLE = 'File UI Test Window'
DEFAULT_MENU = None
DEFAULT_SIZE = 350, 400
def __init__( self ):
editor = FileListLayout( self )
editor.setDir( cmd.workspace( q=True, rootDirectory=True ) )
self.show()
#end | Python |
'''
This module abstracts and packages up the maya UI that is available to script in a more
object oriented fashion. For the most part the framework tries to make working with maya
UI a bit more like proper UI toolkits where possible.
For more information there is some high level documentation on how to use this code here:
http://www.macaronikazoo.com/?page_id=311
'''
import re
import maya
import names
import common
import inspect
import maya.cmds as cmd
import filesystem
import typeFactories
from maya.OpenMaya import MGlobal
mayaVer = int( maya.mel.eval( 'getApplicationVersionAsFloat' ) )
removeDupes = filesystem.removeDupes
_DEBUG = True
#try to import wing...
try:
import wingdbstub
except:
_DEBUG = False
class MelUIError(Exception): pass
def iterBy( iterable, count ):
'''
returns an generator which will yield "chunks" of the iterable supplied of size "count". eg:
for chunk in iterBy( range( 7 ), 3 ): print chunk
results in the following output:
[0, 1, 2]
[3, 4, 5]
[6]
'''
cur = 0
i = iter( iterable )
while True:
try:
toYield = []
for n in range( count ): toYield.append( i.next() )
yield toYield
except StopIteration:
if toYield: yield toYield
break
class Callback(object):
'''
stupid little callable object for when you need to "bake" temporary args into a
callback - useful mainly when creating callbacks for dynamicly generated UI items
'''
def __init__( self, func, *a, **kw ):
self.f = func
self.a = a
self.kw = kw
def __call__( self, *a, **kw ):
args = self.a + a
kw.update( self.kw )
return self.f( *args, **kw )
#this maps ui type strings to actual command objects - they're not always called the same
TYPE_NAMES_TO_CMDS = { u'staticText': cmd.text,
u'field': cmd.textField,
u'cmdScrollField': cmd.scrollField,
u'commandMenuItem': cmd.menuItem,
u'dividorMenuItem': cmd.menuItem }
#stores a list of widget cmds that don't have docTag support - classes that wrap this command need to skip encoding the classname into the docTag. obviously.
WIDGETS_WITHOUT_DOC_TAG_SUPPORT = [ cmd.popupMenu ]
class BaseMelUI(typeFactories.trackableClassFactory( unicode )):
'''
This is a wrapper class for a mel widget to make it behave a little more like an object. It
inherits from str because thats essentially what a mel widget is - a name coupled with a mel
command. To interact with the widget the mel command is called with the UI name as the first arg.
As a shortcut objects of this type are callable - the args taken depend on the specific command,
and can be found in the mel docs.
example:
class AButtonClass(BaseMelUI):
WIDGET_CMD = cmd.button
aButton = AButtonClass( parentName, label='hello' )
aButton( edit=True, label='new label!' )
'''
#this should be set to the mel widget command used by this widget wrapped - ie cmd.button, or cmd.formLayout
WIDGET_CMD = cmd.control
#if not None, this is used to set the default width of the widget when created
DEFAULT_WIDTH = None
#default heights in 2011 aren't consistent - buttons are 24 pixels high by default (this is a minimum possible value too) while input fields are 20
DEFAULT_HEIGHT = None if mayaVer < 2011 else 24
#this is the name of the kwarg used to set and get the "value" of the widget - most widgets use the "value" or "v" kwarg, but others have special names. three cheers for mel!
KWARG_VALUE_NAME = 'v'
KWARG_VALUE_LONG_NAME = 'value'
#populate this dictionary with variable names you want created on instances. values are default values. having this dict saves having to override __new__ and __init__ methods on subclasses just to create instance variables on creation
#the variables are also popped out of the **kw arg by both __new__ and __init__, so specifying variable names and default values here is the equivalent of making them available on the constructor method
_INSTANCE_VARIABLES = {}
#this is the name of the "main" change command kwarg. some widgets have multiple change callbacks that can be set, and they're not abstracted, but this is the name of the change cb name you want to be referenced by the setChangeCB method
KWARG_CHANGE_CB_NAME = 'cc'
#track instances so we can send them update messages -
_INSTANCE_LIST = []
@classmethod
def Exists( cls, theControl ):
if isinstance( theControl, BaseMelUI ):
return theControl.exists()
return cmd.control( theControl, q=True, exists=True )
@classmethod
def IterWidgetClasses( cls, widgetCmd ):
if widgetCmd is None:
return
for subCls in BaseMelUI.IterSubclasses():
if subCls.WIDGET_CMD is widgetCmd:
yield subCls
def __new__( cls, parent, *a, **kw ):
WIDGET_CMD = cls.WIDGET_CMD
kw.pop( 'p', None ) #pop any parent specified in teh kw dict - set it explicitly to the parent specified
if parent is not None:
kw[ 'parent' ] = parent
#pop out any instance variables defined in the _INSTANCE_VARIABLES dict
instanceVariables = {}
for attrName, attrDefaultValue in cls._INSTANCE_VARIABLES.iteritems():
instanceVariables[ attrName ] = kw.pop( attrName, attrDefaultValue )
#set default sizes if applicable
width = kw.pop( 'w', kw.pop( 'width', cls.DEFAULT_WIDTH ) )
if isinstance( width, int ):
kw[ 'width' ] = width
height = kw.pop( 'h', kw.pop( 'height', cls.DEFAULT_HEIGHT ) )
if isinstance( height, int ):
kw[ 'height' ] = height
#not all mel widgets support docTags... :(
if WIDGET_CMD not in WIDGETS_WITHOUT_DOC_TAG_SUPPORT:
#store the name of this class in the widget's docTag - we can use this to re-instantiate the widget once it's been created
kw.pop( 'dtg', kw.pop( 'docTag', None ) )
kw[ 'docTag' ] = docTag=cls.__name__
#pop out the change callback if its been passed in with the kw dict, and run it through the setChangeCB method so it gets registered appropriately
changeCB = kw.pop( cls.KWARG_CHANGE_CB_NAME, None )
#get the leaf name for the parent
parentNameTok = str( parent ).split( '|' )[-1]
#this has the potential to be slow: it generates a unique name for the widget we're about to create, the benefit of doing this is that we're
#guaranteed the widget LEAF name will be unique. I'm assuming maya also does this, but I'm unsure. if there are weird ui naming conflicts
#it might be nessecary to uncomment this code
formatStr = '%s%d__'#+ parentNameTok
baseName, n = cls.__name__, len( cls._INSTANCE_LIST )
uniqueName = formatStr % (baseName, n)
while WIDGET_CMD( uniqueName, q=True, exists=True ):
n += 1
uniqueName = formatStr % (baseName, n)
WIDGET_CMD( uniqueName, **kw )
new = unicode.__new__( cls, uniqueName )
new.parent = parent
new._cbDict = cbDict = {}
cls._INSTANCE_LIST.append( new )
#add the instance variables to the instance
for attrName, attrValue in instanceVariables.iteritems():
new.__dict__[ attrName ] = attrValue
#if the changeCB is valid, add it to the cd dict
if changeCB:
new.setCB( cls.KWARG_CHANGE_CB_NAME, changeCB )
return new
def __init__( self, parent, *a, **kw ):
pass
def __call__( self, *a, **kw ):
return self.WIDGET_CMD( unicode( self ), *a, **kw )
def setChangeCB( self, cb ):
self.setCB( self.KWARG_CHANGE_CB_NAME, cb )
def getChangeCB( self ):
return self.getCB( self.KWARG_CHANGE_CB_NAME )
def setCB( self, cbFlagName, cb ):
if cb is None:
if cbFlagName in self._cbDict:
self._cbDict.pop( cbFlagName )
else:
self.WIDGET_CMD( self, **{ 'e': True, cbFlagName: cb } )
self._cbDict[ cbFlagName ] = cb
def getCB( self, cbFlagName ):
return self._cbDict.get( cbFlagName, None )
def _executeCB( self, cbFlagName=None ):
if cbFlagName is None:
cbFlagName = self.KWARG_CHANGE_CB_NAME
cb = self.getCB( cbFlagName )
if cb is None:
return
if callable( cb ):
try:
cb()
except Exception, x:
common.printErrorStr( "The %s callback failed" % cbFlagName )
def getFullName( self ):
'''
returns the fullname to the UI widget
'''
parents = list( self.iterParents() )
parents.reverse()
parents.append( self )
parents = [ uiFullName.split( '|' )[ -1 ] for uiFullName in parents ]
return '|'.join( parents )
def sendEvent( self, methodName, *methodArgs, **methodKwargs ):
'''
events are nothing more than a tuple containing a methodName, argument list and
keyword dict that gets propagated up the UI hierarchy.
Each widget in the hierarchy is asked whether it has a method of the given name,
and if it does, the method is called with the argumentList and keywordDict and
propagation ends.
'''
self.parent.processEvent( methodName, methodArgs, methodKwargs )
def processEvent( self, methodName, methodArgs, methodKwargs ):
method = getattr( self, methodName, None )
if callable( method ):
#run the method in the buff if we're in debug mode
if _DEBUG:
method( *methodArgs, **methodKwargs )
else:
try:
method( *methodArgs, **methodKwargs )
except:
common.printErrorStr( 'Event Failed: %s, %s, %s' % (methodName, methodArgs, methodKwargs) )
else:
self.parent.processEvent( methodName, methodArgs, methodKwargs )
def getVisibility( self ):
return self( q=True, vis=True )
def setVisibility( self, visibility=True ):
'''
hides the widget
'''
self( e=True, vis=visibility )
def hide( self ):
self.setVisibility( False )
def show( self ):
self.setVisibility( True )
def setWidth( self, width ):
self( e=True, width=width )
def getWidth( self ):
return self( q=True, width=True )
def setHeight( self, height ):
self( e=True, height=height )
def getHeight( self ):
return self( q=True, height=True )
def setSize( self, widthHeight ):
self( e=True, w=widthHeight[ 0 ], h=widthHeight[ 1 ] )
def getSize( self ):
w = self( q=True, w=True )
h = self( q=True, h=True )
return w, h
def getColour( self ):
return self( q=True, bgc=True )
getColor = getColour
def setColour( self, colour ):
initialVis = self( q=True, vis=True )
self( e=True, bgc=colour, vis=False )
if initialVis:
self( e=True, vis=True )
setColor = setColour
def resetColour( self ):
self( e=True, enableBackground=False )
resetColor = resetColour
def getParent( self ):
'''
returns the widget's parent.
NOTE: its not possible to change a widget's parent once its been created
'''
return self.parent #cmd.control( self, q=True, parent=True )
def iterParents( self ):
'''
returns a generator that walks up the widget hierarchy
'''
try:
parent = self.parent
while True:
yield parent
#if the parent isn't an instance of BaseMelUI (the user has mixed baseMelUI and plain old mel) this should throw an attribute error
try:
parent = parent.parent
#in which case, try to cast the widget as a BaseMelUI instance and yield that instead
except AttributeError:
parent = BaseMelUI.FromStr( cmd.control( parent, q=True, parent=True ) )
except RuntimeError: return
def getTopParent( self ):
'''
returns the top widget at the top of this widget's hierarchy
'''
parent = self.parent
while True:
try:
parent = parent.parent
except AttributeError: return parent
def getParentOfType( self, parentClass, exactMatch=False ):
'''
if exactMatch is True the class of the parent must be the parentClass, otherwise it checks
whether the parent is a subclass of parentClass
'''
for parent in self.iterParents():
if exactMatch:
if parent.__class__ is parentClass:
return parent
else:
if issubclass( parent.__class__, parentClass ):
return parent
def exists( self ):
return cmd.control( self, ex=True )
def delete( self ):
cmd.deleteUI( self )
if self in self._INSTANCE_LIST:
self._INSTANCE_LIST.remove( self )
def setSelectionChangeCB( self, cb, compressUndo=True, **kw ):
'''
creates a scriptJob to monitor selection, and fires the given callback when the selection changes
the scriptJob is parented to this widget so it dies when the UI is closed
NOTE: selection callbacks don't take any args
'''
return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('SelectionChanged', cb), **kw )
def setSceneChangeCB( self, cb, compressUndo=True, **kw ):
'''
creates a scriptJob which will fire when the currently open scene changes
the scriptJob is parented to this widget so it dies when the UI is closed
NOTE: scene change callbacks don't take any args
'''
return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('SceneOpened', cb), **kw )
def setTimeChangeCB( self, cb, compressUndo=True, **kw ):
'''
creates a scriptJob which will fire when the current time changes
the scriptJob is parented to this widget so it dies when the UI is closed
NOTE: time change callbacks don't take any args
'''
return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('timeChanged', cb), **kw )
def setAttributeChangeCB( self, attrpath, cb, compressUndo=True, allChildren=False, disregardIndex=False, **kw ):
'''
creates a scriptjob which will fire when the given attribute gets changed
'''
return cmd.scriptJob( compressUndo=compressUndo, parent=self, attributeChange=(attrpath, cb), allChildren=allChildren, disregardIndex=disregardIndex, **kw )
def setDeletionCB( self, cb, compressUndo=True, **kw ):
'''
define a callback that gets triggered when this piece of UI gets deleted
'''
return cmd.scriptJob( compressUndo=compressUndo, uiDeleted=(self, cb), **kw )
def setUndoCB( self, cb, compressUndo=True, **kw ):
'''
define a callback that gets triggered when an undo event is issued
'''
return cmd.scriptJob( compressUndo=compressUndo, parent=self, event=('Undo', cb), **kw )
@classmethod
def FromStr( cls, theStr ):
'''
given a ui name, this will cast the string as a widget instance
'''
#if the instance is in the instance list, return it
if theStr in cls._INSTANCE_LIST:
idx = cls._INSTANCE_LIST.index( theStr )
return cls._INSTANCE_LIST[ idx ]
else:
theStrLeaf = theStr.split( '|' )[-1]
if theStrLeaf in cls._INSTANCE_LIST:
idx = cls._INSTANCE_LIST.index( theStrLeaf )
return cls._INSTANCE_LIST[ idx ]
try:
uiTypeStr = cmd.objectTypeUI( theStr )
except RuntimeError:
try:
uiTypeStr = cmd.objectTypeUI( theStr.split( '|' )[ -1 ] )
except RuntimeError:
uiTypeStr = ''
uiCmd = TYPE_NAMES_TO_CMDS.get( uiTypeStr, getattr( cmd, uiTypeStr, cmd.control ) )
theCls = None
if uiCmd not in WIDGETS_WITHOUT_DOC_TAG_SUPPORT:
#see if the data stored in the docTag is a valid class name - it might not be if teh user has used the docTag for something (why would they? there is no need, but still check...)
try:
possibleClassName = uiCmd( theStr, q=True, docTag=True )
#menu item dividers have a weird type name when queried - "dividorMenuItem", which is a menuItem technically, but you can't query its docTag, so this catch statement is exclusively for this case as far as I know...
except RuntimeError: pass
else:
theCls = BaseMelUI.GetNamedSubclass( possibleClassName )
#if the data stored in the docTag doesn't map to a subclass, then we'll have to guess at the best class...
if theCls is None:
#common.printInfoStr( cmd.objectTypeUI( theStr ) ) ##NOTE: the typestr isn't ALWAYS the same name as the function used to interact with said control, so this debug line can be useful for spewing object type names...
theCls = BaseMelUI #at this point default to be an instance of the base widget class
candidates = list( BaseMelUI.IterWidgetClasses( uiCmd ) )
if candidates:
theCls = candidates[ 0 ]
new = unicode.__new__( theCls, theStr ) #we don't want to run initialize on the object - just cast it appropriately
new._cbDict = cbDict = {}
cls._INSTANCE_LIST.append( new )
#try to grab the parent...
try:
new.parent = cmd.control( theStr, q=True, parent=True )
except RuntimeError: new.parent = None
return new
@classmethod
def ValidateInstanceList( cls ):
control = cmd.control
_INSTANCE_LIST = cls._INSTANCE_LIST
cls._INSTANCE_LIST = [ ui for ui in _INSTANCE_LIST if control( ui, exists=True ) ]
@classmethod
def IterInstances( cls ):
existingInstList = []
for inst in cls._INSTANCE_LIST:
if not isinstance( inst, cls ):
continue
if cls.WIDGET_CMD( inst, q=True, exists=True ):
existingInstList.append( inst )
yield inst
cls._INSTANCE_LIST = existingInstList
class BaseMelLayout(BaseMelUI):
'''
base class for layout UI
'''
WIDGET_CMD = cmd.layout
DEFAULT_WIDTH = None
DEFAULT_HEIGHT = None
def getChildren( self ):
'''
returns a list of all children UI items
'''
children = self( q=True, ca=True ) or []
children = [ BaseMelUI.FromStr( c ) for c in children ]
return children
def getNumChildren( self ):
return len( self.getChildren() )
def printUIHierarchy( self ):
def printChildren( children, depth ):
for child in children:
common.printInfoStr( '%s%s' % (' ' * depth, child) )
if isinstance( child, BaseMelLayout ):
printChildren( child.getChildren(), depth+1 )
common.printInfoStr( self )
printChildren( self.getChildren(), 1 )
def clear( self ):
'''
deletes all children from the layout
'''
for childUI in self.getChildren():
cmd.deleteUI( childUI )
class MelFormLayout(BaseMelLayout):
WIDGET_CMD = cmd.formLayout
ALL_EDGES = 'top', 'left', 'right', 'bottom'
def getOtherEdges( self, edges ):
otherEdges = list( self.ALL_EDGES )
for edge in edges:
if edge in otherEdges:
otherEdges.remove( edge )
return otherEdges
MelForm = MelFormLayout
class MelSingleLayout(MelForm):
'''
Simple layout that causes the child to stretch to the extents of the layout in all directions.
NOTE: make sure to call layout() after the child has been created to setup the layout data
'''
_INSTANCE_VARIABLES = { 'padding': 0 }
def __init__( self, parent, padding=0, *a, **kw ):
MelForm.__init__( self, parent, *a, **kw )
self._padding = padding
def getPadding( self ):
return self._padding
def setPadding( self, padding ):
self._padding = padding
self.layout()
def layout( self ):
children = self.getChildren()
assert len( children ) == 1, "Can only support one child!"
padding = self._padding
theChild = children[ 0 ]
self( e=True, af=((theChild, 'top', padding), (theChild, 'left', padding), (theChild, 'right', padding), (theChild, 'bottom', padding)) )
class _AlignedFormLayout(MelForm):
_EDGES = 'left', 'right'
def getOtherEdges( self ):
return MelFormLayout.getOtherEdges( self, self._EDGES )
def layoutExpand( self, children ):
edge1, edge2 = self._EDGES
try:
padding = self.padding
except AttributeError:
padding = 0
otherEdges = self.getOtherEdges()
otherEdge1, otherEdge2 = otherEdges
for child in children:
self( e=True, af=((child, otherEdge1, padding), (child, otherEdge2, padding)) )
class MelHLayout(_AlignedFormLayout):
'''
emulates a horizontal layout sizer - the only caveat is that you need to explicitly call
the layout method to setup sizing.
NOTE: you need to call layout() once the children have been created to initialize the
layout relationships
example:
row = MelHLayout( self )
MelButton( row, l='apples' )
MelButton( row, l='bananas' )
MelButton( row, l='oranges' )
row.layout()
'''
_INSTANCE_VARIABLES = { '_weights': {},
'padding': 0,
#if True the layout will expand to fill the layout in the "other" direction. Ie HLayouts will expand vertically and VLayouts will expand horizontally to the extents of the layout
'expand': False }
def setWeight( self, widget, weight=1 ):
self._weights[ widget ] = weight
def getHeight( self ):
return max( [ ui.getHeight() for ui in self.getChildren() ] )
def getWidth( self ):
return sum( [ ui.getWidth() for ui in self.getChildren() ] )
def layout( self, expand=None ):
if expand is not None:
self.expand = expand
padding = self.padding
children = self.getChildren()
weightsDict = self._weights
weightsList = []
for child in children:
weight = weightsDict.get( child, 1 )
weightsList.append( weight )
weightSum = float( sum( weightsList ) )
#if not weightSum:
#return
weightAccum = 0
positions = []
for weight in weightsList:
actualWeight = 100 * weightAccum / weightSum
weightAccum += weight
positions.append( actualWeight )
edge1, edge2 = self._EDGES
positions.append( 100 )
for n, child in enumerate( children ):
self( e=True, ap=((child, edge1, padding, positions[n]), (child, edge2, padding, positions[n+1])) )
#if any children have a weight of zero, set the next item in the list to attach to the widget instead of a position
for n, weight in enumerate( weightsList ):
if weight == 0:
thisW = children[ n ]
try:
nextW = children[ n+1 ]
self( e=True, ac=(nextW, edge1, padding, thisW), an=(thisW, edge2) )
except IndexError:
prevW = children[ n-1 ]
self( e=True, ac=(prevW, edge2, padding, thisW), an=(thisW, edge1) )
if self.expand:
self.layoutExpand( children )
class MelVLayout(MelHLayout):
_EDGES = 'top', 'bottom'
def getHeight( self ):
return sum( [ ui.getHeight() for ui in self.getChildren() ] )
def getWidth( self ):
return max( [ ui.getWidth() for ui in self.getChildren() ] )
class MelHRowLayout(_AlignedFormLayout):
'''
Simple row layout - the rowLayout mel command isn't so hot because you have to know ahead
of time how many columns to build, and dynamic sizing is rubbish. This makes writing a
simple row of widgets super easy.
NOTE: like all subclasses of MelFormLayout, make sure to call .layout() after children
have been built
'''
_INSTANCE_VARIABLES = { 'padding': 5,
#if True the layout will expand to fill the layout in the "other" direction. Ie HLayouts will expand vertically and VLayouts will expand horizontally to the extents of the layout
'expand': False }
def layout( self, expand=None ):
if expand is not None:
self.expand = expand
padding = self.padding
children = self.getChildren()
edge1, edge2 = self._EDGES
for n, child in enumerate( children ):
if n:
self( e=True, ac=(child, edge1, padding, children[ n-1 ]) )
else:
self( e=True, af=(child, edge1, 0) )
if self.expand:
self.layoutExpand( children )
class MelVRowLayout(MelHRowLayout):
_EDGES = 'top', 'bottom'
class MelHSingleStretchLayout(_AlignedFormLayout):
'''
Provides an easy interface to a common layout pattern where a single widget in the
row/column is stretchy and the others are statically sized.
Make sure to call setStretchWidget() before calling layout()
'''
_stretchWidget = None
_INSTANCE_VARIABLES = { 'padding': 5,
#if True the layout will expand to fill the layout in the "other" direction. Ie HLayouts will expand vertically and VLayouts will expand horizontally to the extents of the layout
'expand': False }
def setPadding( self, padding ):
self.padding = padding
def setExpand( self, expand ):
'''
make sure to call layout() after changing the expand value
'''
self.expand = expand
def setStretchWidget( self, widget ):
if not isinstance( widget, BaseMelUI ):
widget = BaseMelUI.FromStr( widget )
self._stretchWidget = widget
self.layout()
def layout( self, expand=None ):
if expand is not None:
self.expand = expand
padding = self.padding
children = self.getChildren()
stretchWidget = self._stretchWidget
if stretchWidget is None:
stretchWidget = children[ 0 ]
idx = children.index( stretchWidget )
leftChildren = children[ :idx ]
rightChildren = children[ idx+1: ]
edge1, edge2 = self._EDGES
for n, child in enumerate( leftChildren ):
if n:
self( e=True, ac=(child, edge1, padding, children[ n-1 ]) )
else:
self( e=True, af=(child, edge1, 0) )
if rightChildren:
self( e=True, af=(rightChildren[-1], edge2, 0) )
for n, child in enumerate( rightChildren[ :-1 ] ):
self( e=True, ac=(child, edge2, padding, rightChildren[ n+1 ]) )
if leftChildren and rightChildren:
self( e=True, ac=((stretchWidget, edge1, padding, leftChildren[-1]), (stretchWidget, edge2, padding, rightChildren[0])) )
elif leftChildren and not rightChildren:
self( e=True, ac=(stretchWidget, edge1, padding, leftChildren[-1]), af=(stretchWidget, edge2, 0) )
elif not leftChildren and rightChildren:
self( e=True, af=(stretchWidget, edge1, 0), ac=(stretchWidget, edge2, padding, rightChildren[0]) )
if self.expand:
self.layoutExpand( children )
class MelVSingleStretchLayout(MelHSingleStretchLayout):
_EDGES = 'top', 'bottom'
_INSTANCE_VARIABLES = { 'padding': 5,
'expand': True }
class MelColumnLayout(BaseMelLayout):
WIDGET_CMD = cmd.columnLayout
STRETCHY = True
def __new__( cls, parent, *a, **kw ):
stretchy = kw.pop( 'adjustableColumn', kw.pop( 'adj', cls.STRETCHY ) )
kw.setdefault( 'adjustableColumn', stretchy )
return BaseMelLayout.__new__( cls, parent, *a, **kw )
MelColumn = MelColumnLayout
class MelRowLayout(BaseMelLayout): WIDGET_CMD = cmd.rowLayout
MelRow = MelRowLayout
class MelGridLayout(BaseMelLayout):
WIDGET_CMD = cmd.gridLayout
AUTO_GROW = True
def __new__( cls, parent, **kw ):
autoGrow = kw.pop( 'autoGrow', self.AUTO_GROW )
kw.setdefault( 'ag', autoGrow )
return BaseMelLayout.__new__( cls, parent, **kw )
MelGrid = MelGridLayout
class MelScrollLayout(BaseMelLayout):
WIDGET_CMD = cmd.scrollLayout
def __new__( cls, parent, *a, **kw ):
kw.setdefault( 'childResizable', kw.pop( 'cr', True ) )
return BaseMelLayout.__new__( cls, parent, *a, **kw )
MelScroll = MelScrollLayout
class MelHScrollLayout(MelScrollLayout):
_ORIENTATION_ATTR = 'verticalScrollBarThickness'
def __new__( cls, parent, *a, **kw ):
kw[ cls._ORIENTATION_ATTR ] = 0
return MelScrollLayout.__new__( cls, parent, *a, **kw )
class MelVScrollLayout(MelHScrollLayout):
_ORIENTATION_ATTR = 'horizontalScrollBarThickness'
class MelTabLayout(BaseMelLayout):
WIDGET_CMD = cmd.tabLayout
def __init__( self, parent, *a, **kw ):
BaseMelLayout.__init__( self, parent, *a, **kw )
ccCB = kw.get( 'changeCommand', kw.get( 'cc', None ) )
self.setChangeCB( ccCB )
pscCB = kw.get( 'preSelectCommand', kw.get( 'psc', None ) )
self.setPreSelectCB( pscCB )
dccCB = kw.get( 'doubleClickCommand', kw.get( 'dcc', None ) )
self.setDoubleClickCB( dccCB )
def numTabs( self ):
return self( q=True, numberOfChildren=True )
__len__ = numTabs
def setLabel( self, idx, label ):
self( e=True, tabLabelIndex=(idx+1, label) )
def getLabel( self, idx ):
self( q=True, tabLabelIndex=idx+1 )
def getSelectedTab( self ):
return self( q=True, selectTab=True )
def setSelectedTab( self, child, executeChangeCB=True ):
self( e=True, selectTab=child )
if executeChangeCB:
self._executeCB( 'selectCommand' )
def getSelectedTabIdx( self ):
return self( q=True, selectTabIndex=True )-1 #indices are 1-based... fuuuuuuu alias!
def setSelectedTabIdx( self, idx, executeChangeCB=True ):
self( e=True, selectTabIndex=idx+1 ) #indices are 1-based... fuuuuuuu alias!
if executeChangeCB:
self._executeCB( 'selectCommand' )
def setChangeCB( self, cb ):
self.setCB( 'selectCommand', cb )
def setPreSelectCB( self, cb ):
self.setCB( 'preSelectCommand', cb )
def setDoubleClickCB( self, cb ):
self.setCB( 'doubleClickCommand', cb )
class MelPaneLayout(BaseMelLayout):
WIDGET_CMD = cmd.paneLayout
PREF_OPTION_VAR = None
POSSIBLE_CONFIGS = \
CFG_SINGLE, CFG_HORIZ2, CFG_VERT2, CFG_HORIZ3, CFG_VERT3, CFG_TOP3, CFG_LEFT3, CFG_BOTTOM3, CFG_RIGHT3, CFG_HORIZ4, CFG_VERT4, CFG_TOP4, CFG_LEFT4, CFG_BOTTOM4, CFG_RIGHT4, CFG_QUAD = \
"single", "horizontal2", "vertical2", "horizontal3", "vertical3", "top3", "left3", "bottom3", "right3", "horizontal4", "vertical4", "top4", "left4", "bottom4", "right4", "quad"
CONFIG = CFG_VERT2
KWARG_CHANGE_CB_NAME = 'separatorMovedCommand'
def __init__( self, parent, configuration=None, *a, **kw ):
kw.setdefault( 'separatorMovedCommand', self.on_resize )
if configuration is None:
assert self.CONFIG in self.POSSIBLE_CONFIGS
configuration = self.CONFIG
kw[ 'configuration' ] = configuration
kw.pop( 'cn', None )
BaseMelLayout.__init__( self, parent, *a, **kw )
self( e=True, **kw )
if self.PREF_OPTION_VAR:
if cmd.optionVar( ex=self.PREF_OPTION_VAR ):
storedSize = cmd.optionVar( q=self.PREF_OPTION_VAR )
for idx, size in enumerate( filesystem.iterBy( storedSize, 2 ) ):
self.setPaneSize( idx, size )
def __getitem__( self, idx ):
idx += 1 #indices are 1-based... fuuuuuuu alias!
kw = { 'q': True, 'pane%d' % idx: True }
return BaseMelUI.FromStr( self( **kw ) )
def __setitem__( self, idx, ui ):
idx += 1 #indices are 1-based... fuuuuuuu alias!
return self( e=True, setPane=(ui, idx) )
def getConfiguration( self ):
return self( q=True, configuration=True )
def setConfiguration( self, ui ):
return self( e=True, configuration=ui )
def getPaneUnderPointer( self ):
return BaseMelUI.FromStr( self( q=True, paneUnderPointer=True ) )
def getPaneActive( self ):
return BaseMelUI.FromStr( self( q=True, activePane=True ) )
def getPaneActiveIdx( self ):
return self( q=True, activePaneIndex=True ) - 1 #indices are 1-based...
def getPaneSize( self, idx ):
idx += 1
return self( q=True, paneSize=idx )
def setPaneSize( self, idx, size ):
idx += 1
size = idx, size[0], size[1]
return self( e=True, paneSize=size )
def setPaneWidth( self, idx, size ):
idx += 1
curSize = self.getPaneSize( idx )
return self( e=True, paneSize=(idx, curSize[0], size) )
def setPaneHeight( self, idx, size ):
idx += 1
curSize = self.getPaneSize( idx )
return self( e=True, paneSize=(idx, size, curSize[1]) )
### EVENT HANDLERS ###
def on_resize( self, *a ):
if self.PREF_OPTION_VAR:
size = self.getPaneSize( 0 )
cmd.optionVar( clearArray=self.PREF_OPTION_VAR )
for i in size:
cmd.optionVar( iva=(self.PREF_OPTION_VAR, i) )
class MelFrameLayout(BaseMelLayout):
WIDGET_CMD = cmd.frameLayout
def setCollapseCB( self, cb ):
BaseMelLayout.setChangeCB( self, cb )
def getCollapseCB( self ):
return BaseMelLayout.getChangeCB( self )
def setExpandCB( self, cb ):
self.setCB( 'expandCommand', cb )
def getExpandCB( self ):
return self.getCB( 'expandCommand' )
def getCollapse( self ):
return self( q=True, collapse=True )
def setCollapse( self, state, executeChangeCB=True ):
self( e=True, collapse=state )
if executeChangeCB:
if state:
collapseCB = self.getCollapseCB()
if callable( collapseCB ):
collapseCB()
else:
expandCB = self.getExpandCB()
if callable( expandCB ):
expandCB()
class BaseMelWidget(BaseMelUI):
def setValue( self, value, executeChangeCB=True ):
try:
kw = { 'e': True, self.KWARG_VALUE_NAME: value }
self.WIDGET_CMD( self, **kw )
except TypeError, x:
common.printErrorStr( 'Running setValue method using %s command' % self.WIDGET_CMD )
raise
if executeChangeCB:
self._executeCB()
def getValue( self ):
kw = { 'q': True, self.KWARG_VALUE_NAME: True }
return self.WIDGET_CMD( self, **kw )
def enable( self, state=True ):
try: self( e=True, enable=bool( state ) ) #explicitly cast here in case we've been passed a non-bool. the maya.cmds binding interprets any non-boolean object as True it seems...
except: pass
def disable( self ):
self.enable( False )
def getAnnotation( self ):
return self( q=True, ann=True )
def setAnnotation( self, annotation ):
self( e=True, ann=annotation )
setEnabled = enable
def getEnabled( self ):
try: return self( q=True, enable=True )
except: return True
def editable( self, state=True ):
try: self( e=True, editable=bool( state ) )
except: pass
def setEditable( self, state ):
self.editable( state )
def getEditable( self ):
return bool( self( q=True, ed=True ) )
def setFocus( self ):
cmd.setFocus( self )
class MelLabel(BaseMelWidget):
WIDGET_CMD = cmd.text
KWARG_VALUE_NAME = 'l'
KWARG_VALUE_LONG_NAME = 'label'
def bold( self, state=True ):
self( e=True, font='boldLabelFont' if state else 'plainLabelFont' )
getLabel = BaseMelWidget.getValue
setLabel = BaseMelWidget.setValue
class MelSpacer(MelLabel):
def __new__( cls, parent, w=1, h=1 ):
w = max( w, 1 )
h = max( h, 1 )
return MelLabel.__new__( cls, parent, w=w, h=h, l='' )
class MelButton(BaseMelWidget):
WIDGET_CMD = cmd.button
KWARG_CHANGE_CB_NAME = 'c'
def bold( self, state=True ):
self( e=True, font='boldLabelFont' if state else 'plainLabelFont' )
def getLabel( self ):
return self( q=True, l=True )
def setLabel( self, label ):
initialWidth = self.getWidth()
self( e=True, l=label )
#seems maya screws with the width of the widget when setting the label - yay!
self.setWidth( initialWidth )
class MelIconButton(MelButton):
WIDGET_CMD = cmd.iconTextButton
def setImage( self, imagePath, findInPaths=True ):
self( e=True, image=str( imagePath ) )
def getImage( self ):
return self( q=True, image=True )
def refresh( self ):
img = self.getImage()
self.setImage( '' )
self.setImage( img )
class MelIconCheckBox(MelIconButton):
WIDGET_CMD = cmd.iconTextCheckBox
KWARG_CHANGE_CB_NAME = 'cc'
class MelCheckBox(BaseMelWidget):
WIDGET_CMD = cmd.checkBox
def __new__( cls, parent, *a, **kw ):
#this craziness is so we can default the label to nothing instead of the widget's name... dumb, dumb, dumb
labelArgs = 'l', 'label'
for f in kw.keys():
if f == 'label':
kw[ 'l' ] = kw.pop( 'label' )
break
kw.setdefault( 'l', '' )
return BaseMelWidget.__new__( cls, parent, *a, **kw )
class MelRadioButton(BaseMelWidget):
WIDGET_CMD = cmd.radioButton
def getLabel( self ):
return self( q=True, label=True )
def setLabel( self, label ):
self( e=True, label=label )
def select( self ):
self( e=True, select=True )
def isSelected( self ):
return self( q=True, select=True )
class MelRadioCollection(unicode):
def __new__( self ):
new = unicode.__new__( cls, cmd.radioCollection() )
new._items = []
return new
def addButton( self, button ):
'''
adds the given button to this collection
'''
self._items.append( button( e=True, collection=self ) )
def createButton( self, parent, **kw ):
'''
creates a new radio button and adds it to the collection
'''
button = MelRadioButton( parent, collection=self, **kw )
self._items.append( button )
return button
def getItems( self ):
'''
returns the radio buttons in the collection
'''
return self._items[:]
def count( self ):
'''
returns the items in the collection
'''
return len( self._items )
def getSelected( self ):
'''
returns the selected MelRadio button instance
'''
selItemStr = self( q=True, sl=True )
for item in self._items:
if str( item ) == selItemStr:
return item
class MelSeparator(BaseMelWidget):
WIDGET_CMD = cmd.separator
class MelIntField(BaseMelWidget):
WIDGET_CMD = cmd.intField
DEFAULT_WIDTH = 30
class MelFloatField(BaseMelWidget): WIDGET_CMD = cmd.floatField
class MelTextField(BaseMelWidget):
WIDGET_CMD = cmd.textField
DEFAULT_WIDTH = 150
KWARG_VALUE_NAME = 'tx'
KWARG_VALUE_LONG_NAME = 'text'
def setValue( self, value, executeChangeCB=True ):
if not isinstance( value, unicode ):
value = unicode( value )
BaseMelWidget.setValue( self, value, executeChangeCB )
def clear( self, executeChangeCB=True ):
self.setValue( '', executeChangeCB )
class MelTextScrollField(MelTextField):
WIDGET_CMD = cmd.scrollField
class MelScrollField(MelTextField):
WIDGET_CMD = cmd.scrollField
class MelNameField(MelTextField):
WIDGET_CMD = cmd.nameField
def getValue( self ):
obj = self( q=True, o=True )
if obj:
return obj
return None
getObj = getValue
def setValue( self, obj, executeChangeCB=True ):
if not isinstance( obj, basestring ):
obj = str( obj )
self( e=True, o=obj )
if executeChangeCB:
self._executeCB()
setObj = setValue
def clear( self ):
self.setValue( None )
class MelObjectSelector(MelForm):
def __new__( cls, parent, label='Node->', obj=None, labelWidth=None ):
return MelForm.__new__( cls, parent )
def __init__( self, parent, label='Node->', obj=None, labelWidth=None ):
MelForm.__init__( self, parent )
self.UI_label = MelButton( self, l=label, c=self.on_setValue )
self.UI_obj = MelNameField( self )
if labelWidth is not None:
self.UI_label.setWidth( labelWidth )
if obj is not None:
self.UI_obj.setValue( obj )
self( e=True,
af=((self.UI_label, 'left', 0),
(self.UI_obj, 'right', 0)),
ac=((self.UI_obj, 'left', 0, self.UI_label)) )
self.UI_menu = MelPopupMenu( self.UI_label, pmc=self.buildMenu )
self.UI_menu = MelPopupMenu( self.UI_obj, pmc=self.buildMenu )
def buildMenu( self, menu, menuParent ):
cmd.menu( menu, e=True, dai=True )
obj = self.getValue()
enabled = cmd.objExists( obj ) if obj else False
MelMenuItem( menu, label='select obj', en=enabled, c=self.on_select )
MelMenuItemDiv( menu )
MelMenuItem( menu, label='clear obj', c=self.on_clear )
def getValue( self ):
return self.UI_obj.getValue()
def setValue( self, value, executeChangeCB=True ):
return self.UI_obj.setValue( value, executeChangeCB )
def setChangeCB( self, cb ):
return self.UI_obj.setChangeCB( cb )
def getChangeCB( self ):
return self.UI_obj.getChangeCB()
def clear( self ):
self.UI_obj.clear()
def getLabel( self ):
return self.UI_label.getValue()
def setLabel( self, label ):
self.UI_label.setValue( label )
### EVENT HANDLERS ###
def on_setValue( self, *a ):
sel = cmd.ls( sl=True )
if sel:
self.setValue( sel[ 0 ] )
def on_select( self, *a ):
cmd.select( self.getValue() )
def on_clear( self, *a ):
self.clear()
class _BaseSlider(BaseMelWidget):
DISABLE_UNDO_ON_DRAG = False
def __new__( cls, parent, minValue=0, maxValue=100, defaultValue=None, *a, **kw ):
changeCB = kw.pop( 'changeCommand', kw.pop( 'cc', None ) )
dragCB = kw.pop( 'dragCommand', kw.pop( 'dc', None ) )
new = BaseMelWidget.__new__( cls, parent, minValue=minValue, maxValue=maxValue, *a, **kw )
new._isDragging = False
new._preChangeCB = None
new._postChangeCB = None
new._changeCB = changeCB
return new
def __init__( self, parent, minValue=0, maxValue=100, defaultValue=None, *a, **kw ):
BaseMelWidget.__init__( self, parent, *a, **kw )
kw = {}
kw[ 'changeCommand' ] = self.on_change
kw[ 'dragCommand' ] = self.on_drag
self( e=True, **kw )
self._defaultValue = defaultValue
self._initialUndoState = cmd.undoInfo( q=True, state=True )
def setPreChangeCB( self, cb ):
'''
the callback executed when the slider is first pressed. the preChangeCB should take no args
'''
self._preChangeCB = cb
def getPreChangeCB( self ):
return self._preChangeCB
def setChangeCB( self, cb ):
'''
the callback that is executed when the value is changed. the changeCB should take a single value arg
'''
self._changeCB = cb
def getChangeCB( self ):
return self._changeCB
def setPostChangeCB( self, cb ):
'''
the callback executed when the slider is released. the postChangeCB should take a single value arg just like the changeCB
'''
self._postChangeCB = cb
def getPostChangeCB( self ):
return self._postChangeCB
def reset( self, executeChangeCB=True ):
value = self._defaultValue
if value is None:
value = self( q=True, min=True )
self.setValue( value, executeChangeCB )
### EVENT HANDLERS ###
def on_change( self, value ):
self._isDragging = False
#restore undo if thats what we need to do
if self.DISABLE_UNDO_ON_DRAG:
if self._initialUndoState:
cmd.undoInfo( stateWithoutFlush=True )
if callable( self._postChangeCB ):
self._postChangeCB( value )
def on_drag( self, value ):
if self._isDragging:
if callable( self._changeCB ):
self._changeCB( value )
else:
self._initialUndoState = cmd.undoInfo( q=True, state=True )
if self.DISABLE_UNDO_ON_DRAG:
cmd.undoInfo( stateWithoutFlush=False )
if callable( self._preChangeCB ):
self._preChangeCB()
self._isDragging = True
class MelFloatSlider(_BaseSlider):
WIDGET_CMD = cmd.floatSlider
class MelIntSlider(_BaseSlider):
WIDGET_CMD = cmd.intSlider
class MelTextScrollList(BaseMelWidget):
'''
NOTE: you probably want to use the MelObjectScrollList instead!
'''
WIDGET_CMD = cmd.textScrollList
KWARG_CHANGE_CB_NAME = 'sc'
ALLOW_MULTI_SELECTION = False
def __new__( cls, parent, *a, **kw ):
if 'ams' not in kw and 'allowMultiSelection' not in kw:
kw[ 'ams' ] = cls.ALLOW_MULTI_SELECTION
return BaseMelWidget.__new__( cls, parent, *a, **kw )
def __init__( self, parent, *a, **kw ):
BaseMelWidget.__init__( self, parent, *a, **kw )
self._appendCB = None
def __getitem__( self, idx ):
return self.getItems()[ idx ]
def __contains__( self, value ):
return value in self.getItems()
def __len__( self ):
return self( q=True, numberOfItems=True )
def setItems( self, items ):
self.clear()
for i in items:
self.append( i )
def getItems( self ):
return self( q=True, ai=True )
def getAllItems( self ):
return self( q=True, ai=True )
def setAppendCB( self, cb ):
self._appendCB = cb
def getSelectedItems( self ):
return self( q=True, si=True ) or []
def getSelectedIdxs( self ):
return [ idx-1 for idx in self( q=True, sii=True ) or [] ]
def selectByIdx( self, idx, executeChangeCB=False ):
self( e=True, selectIndexedItem=idx+1 ) #indices are 1-based in mel land - fuuuuuuu alias!!!
if executeChangeCB:
self._executeCB()
def attemptToSelect( self, idx, executeChangeCB=False ):
'''
attempts to select the item at index idx - if the specific index doesn't exist,
it tries to select the closest item to the given index
'''
if len( self ) == 0:
if executeChangeCB:
self._executeCB()
return
if idx >= len( self ):
idx = len( self ) - 1 #set to the end most item
if idx < 0:
idx = 0
self.selectByIdx( idx, executeChangeCB )
def selectByValue( self, value, executeChangeCB=False ):
self( e=True, selectItem=value )
if executeChangeCB:
self._executeCB()
def append( self, item ):
self( e=True, append=item )
def appendItems( self, items ):
for i in items: self.append( i )
def removeByIdx( self, idx ):
self( e=True, removeIndexedItem=idx+1 )
def removeByValue( self, value ):
self( e=True, removeItem=value )
def removeSelectedItems( self ):
for idx in self.getSelectedIdxs():
self.removeByIdx( idx )
def allowMultiSelect( self, state ):
self( e=True, ams=state )
def clear( self ):
self( e=True, ra=True )
def clearSelection( self, executeChangeCB=False ):
self( e=True, deselectAll=True )
if executeChangeCB:
self._executeCB()
def moveSelectedItemsUp( self, count=1 ):
'''
moves selected items "up" <count> units
'''
#these are the selected items as they appear in the UI - we need to map them to "real" indices
selIdxs = self.getSelectedIdxs()
selItems = self.getSelectedItems()
items = self.getAllItems()
realIdxs = []
for selItem in selItems:
for n, item in enumerate( items ):
if selItem is item:
realIdxs.append( n )
break
count = min( count, realIdxs[ 0 ] ) #we can't move more units up than the smallest selected index
if not count:
return
realIdxs.sort()
for idx in realIdxs:
item = items.pop( idx )
items.insert( idx-count, item )
self.setItems( items )
#re-setup selection
self.clearSelection()
for item in selItems:
self.selectByValue( item, False )
def moveSelectedItemsDown( self, count=1 ):
'''
moves selected items "down" <count> units
'''
#these are the selected items as they appear in the UI - we need to map them to "real" indices
selIdxs = self.getSelectedIdxs()
selItems = self.getSelectedItems()
items = self.getAllItems()
realIdxs = []
for selItem in selItems:
for n, item in enumerate( items ):
if selItem is item:
realIdxs.append( n )
break
realIdxs.sort()
maxIdx = len( items )-1
count = min( count, maxIdx - realIdxs[-1] ) #we can't move more units down than the largest selected index
if not count:
return
realIdxs.reverse()
for idx in realIdxs:
item = items.pop( idx )
items.insert( idx+count, item )
self.setItems( items )
#re-setup selection
self.clearSelection()
for item in selItems:
self.selectByValue( item, False )
class MelObjectScrollList(MelTextScrollList):
'''
Unlike MelTextScrollList, this class will actually store and return python objects and display them using either
their native string representation (ie __str__) which is done by passing the object to itemAsStr which is an
overridable instance method. It also lets you set selection by passing either python objects, the string
representations for those objects or indices.
It also provides the ability to set filters on the data. What the widget stores and what it displays can be
different, making it easy to write UI to access internal data without having to write glue code to convert
to/from UI representation.
NOTE: you almost always want to use this class over the MelTextScrollList class... its just better.
'''
#if true the objects are displayed without their namespaces
DISPLAY_NAMESPACES = False
DISPLAY_NICE_NAMES = False
#should we perform caseless filtering?
FILTER_CASELESS = True
def __init__( self, parent, *a, **kw ):
MelTextScrollList.__init__( self, parent, *a, **kw )
self._items = []
self._visibleItems = []
self._filterStr = None
self._compiledFilter = None
def __contains__( self, item ):
return item in self._visibleItems
def itemAsStr( self, item ):
itemStr = str( item )
if not self.DISPLAY_NAMESPACES:
withoutNamespace = str( item ).split( ':' )[ -1 ]
itemStr = withoutNamespace.split( '|' )[ -1 ]
if self.DISPLAY_NICE_NAMES:
itemStr = names.camelCaseToNice( itemStr )
return itemStr
def getFilter( self ):
return self._filterStr
def setFilter( self, filterStr, updateUI=True ):
if not filterStr:
self._filterStr = None
self._compiledFilter = None
else:
self._filterStr = filterStr
#build the compiled regular expression
reArgs = [ filterStr ]
if self.FILTER_CASELESS:
reArgs.append( re.IGNORECASE )
self._compiledFilter = re.compile( *reArgs )
#update the UI
if updateUI:
self.update()
def clearFilter( self ):
self.setFilter( None )
def doesItemPassFilter( self, item ):
return self.doesItemStrPassFilter( self.itemAsStr( item ) )
def doesItemStrPassFilter( self, itemStr ):
if not self._filterStr:
return True
if self.FILTER_CASELESS:
itemStr = itemStr.lower()
if self._filterStr in itemStr:
return True
if self._compiledFilter is None:
return True
try:
if self._compiledFilter.match( itemStr ):
return True
except: return True
return False
def getItems( self ):
'''
returns the list of visible items
NOTE: if the widget has a filter set, this won't return ALL items, just
the visible ones. To get a list of all items, use getAllItems()
'''
return self._visibleItems[:] #return a copy of the visible items list
def getAllItems( self ):
return self._items[:] #return a copy of the items list
def getSelectedItems( self ):
selectedIdxs = self.getSelectedIdxs()
return [ self._visibleItems[ idx ] for idx in selectedIdxs ]
def selectByValue( self, value, executeChangeCB=False ):
if value in self._visibleItems:
idx = self._visibleItems.index( value ) + 1 #mel indices are 1-based...
self( e=True, sii=idx )
else:
valueStr = self.itemAsStr( value )
for idx, item in enumerate( self._visibleItems ):
if self.itemAsStr( item ) == valueStr:
self( e=True, sii=idx+1 ) #mel indices are 1-based...
if executeChangeCB:
self._executeCB()
def selectItems( self, items, executeChangeCB=False ):
'''
provides an efficient way of selecting many items at once
'''
visibleSet = set( self._visibleItems )
itemsSet = set( items )
#get a list of items that are guaranteed to be in the UI
itemsToSelect = itemsSet.intersection( visibleSet )
for idx, item in enumerate( self._visibleItems ):
if item in itemsToSelect:
self( e=True, sii=idx+1 )
if executeChangeCB:
self._executeCB()
def append( self, item, executeAppendCB=True ):
self._items.append( item )
itemStr = self.itemAsStr( item )
if self.doesItemStrPassFilter( itemStr ):
self._visibleItems.append( item )
self( e=True, append=itemStr )
if executeAppendCB:
if callable( self._appendCB ):
self._appendCB( item )
def removeByIdx( self, idx ):
'''
removes an item by its index in the visible list of items
'''
#first pop the item out of the list of visible items
item = self._visibleItems.pop( idx )
self( e=True, removeIndexedItem=idx+1 )
#now pop the item out of the _items list
idx = self._items.index( item )
self._items.pop( idx )
def removeByValue( self, value ):
if value in self._items:
idx = self._items.index( value )
self._items.pop( idx )
if value in self._visibleItems:
idx = self._visibleItems.index( value )
self._visibleItems.pop( idx )
self( e=True, rii=idx+1 ) #mel indices are 1-based...
else:
valueStr = self.itemAsStr( value )
for itemList in (self._visibleItems, self._items):
for idx, item in enumerate( itemList ):
if self.itemAsStr( item ) == valueStr:
itemList.pop( idx )
self( e=True, rii=idx+1 ) #mel indices are 1-based...
def clear( self ):
self._items = []
self._visibleItems = []
self( e=True, ra=True )
def update( self, maintainSelection=True ):
'''
removes and re-adds the items in the UI
'''
selItems = self.getSelectedItems()
#remove all items from the list
self._visibleItems = []
self( e=True, ra=True )
#now re-generate their string representations
for item in self.getAllItems():
itemStr = self.itemAsStr( item )
if self.doesItemStrPassFilter( itemStr ):
self._visibleItems.append( item )
self( e=True, append=itemStr )
if maintainSelection:
for item in selItems:
for idx, visItem in enumerate( self._visibleItems ):
if item is visItem:
self.selectByIdx( idx, False )
class MelSetMemebershipList(MelObjectScrollList):
ALLOWED_NODE_TYPES = None #if None then ANY node type is allowed in the set - otherwise only types in the iterable are allowed to be added to the set
ALLOW_MULTI_SELECTION = True
def __init__( self, parent, **kw ):
MelObjectScrollList.__init__( self, parent, **kw )
self.objectSets = []
self( e=True, dcc=self.on_doubleClickItem )
self.POP_ops = MelPopupMenu( self, pmc=self.buildMenu )
self._addHandler = None
def getSets( self ):
return self.objectSets[:]
def setSets( self, objectSets ):
if not isinstance( objectSets, list ):
objectSets = [ objectSets ]
self.objectSets = objectSets
self.update()
def getAllItems( self ):
items = cmd.sets( self.objectSets, q=True ) or []
items.sort()
return removeDupes( items )
def _addItems( self, items ):
handler = self._addHandler
isHandlerCallable = callable( self._addHandler )
items = self.filterItems( items )
if items:
for objectSet in self.objectSets:
if isHandlerCallable:
handler( objectSet, items )
else:
cmd.sets( items, add=objectSet )
self.update()
def _setItems( self, items ):
items = self.filterItems( items )
if items:
for objectSet in self.objectSets:
cmd.sets( clear=objectSet )
self._addItems( items )
def _removeItems( self, items ):
if items:
for objectSet in self.objectSets:
cmd.sets( items, remove=objectSet )
self.update()
def _removeAllItems( self ):
for objectSet in self.objectSets:
cmd.sets( clear=objectSet )
self.update()
def buildMenu( self, menu, menuParent ):
cmd.menu( menu, e=True, dai=True )
MelMenuItem( menu, l='ADD selected objects to set', c=self.on_addItem )
MelMenuItem( menu, l='REPLACE set items with selected objects', c=self.on_replaceItem )
MelMenuItem( menu, l='REMOVE selected objects from set', c=self.on_removeItem )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='remove HIGHLIGHTED objects from set', c=self.on_removeHighlighted )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='SELECT highlighted objects', c=self.on_doubleClickItem )
MelMenuItemDiv( menu )
MelMenuItem( menu, l='update UI', c=self.on_update )
MelMenuItem( menu, cb=self.DISPLAY_NAMESPACES, l='Show Namespaces', c=self.on_showNameSpaces )
MelMenuItem( menu, cb=self.DISPLAY_NICE_NAMES, l='Show Nice Names', c=self.on_showNiceNames )
def removeItems( self, items ):
curItems = self.getItems()
if curItems:
newItems = curItems.difference( items )
if len( curItems ) == len( newItems ):
return
self.setItems( newItems )
def filterItems( self, items ):
if not self.ALLOWED_NODE_TYPES:
return items
filteredItems = []
for item in items:
if nodeType in self.ALLOWED_NODE_TYPES:
if cmd.objectType( item, isAType=nodeType ):
filteredItems.append( item )
return filteredItems
### EVENT HANDLERS ###
def on_doubleClickItem( self, *a ):
sel = self.getSelectedItems()
if sel:
cmd.select( sel )
def on_addItem( self, *a ):
self._addItems( cmd.ls( sl=True ) )
def on_replaceItem( self, *a ):
self._setItems( cmd.ls( sl=True ) )
def on_removeItem( self, *a ):
self._removeItems( cmd.ls( sl=True ) )
def on_removeHighlighted( self, *a ):
self._removeItems( self.getSelectedItems() )
def on_update( self, *a ):
self.update()
def on_showNameSpaces( self, *a ):
self.DISPLAY_NAMESPACES = not self.DISPLAY_NAMESPACES
self.update()
def on_showNiceNames( self, *a ):
self.DISPLAY_NICE_NAMES = not self.DISPLAY_NICE_NAMES
self.update()
class MelTreeView(BaseMelWidget):
'''
Thanks to Dave Shaw for the majority of this implementation
'''
WIDGET_CMD = cmd.treeView
#the valid button "types"
BUTTON_TYPES = BT_PUSH_BUTTON, BT_2STATE, BT_3STATE = 'pushButton', '2StateButton', '3StateButton'
#the valid button "states"
BUTTON_STATES = BS_UP, BS_DOWN, BS_BETWEEN = 'buttonUp', 'buttonDown', 'buttonThirdState'
def __init__( self, parent, *a, **kw ):
BaseMelWidget.__init__( self, parent, *a, **kw )
self( e=True, **kw )
self._pressCBs = {}
def addItem( self, itemName, itemParent=None ):
self( edit=True, addItem=(itemName, itemParent) )
def doesItemExist( self, itemName ):
return self( q=True, itemExists=itemName )
def getItemIndex( self, itemName ):
return self( q=True, itemIndex=itemName )
def getItemParent( self, itemName ):
return self( q=True, itemParent=itemName )
def isItemSelected( self, itemName ):
return self( q=True, itemSelected=itemName )
def setButtonLabel( self, itemName, buttonIndex, label ):
self( e=True, buttonTextIcon=(itemName, buttonIndex, label) )
def setButtonState( self, itemName, buttonIndex, state ):
'''
There are only 3 valid states:
buttonUp - button is up
buttonDown - button is down
buttonThirdState - button is in state three (used by the "3StateButton" button style)
'''
if state not in self.BUTTON_STATES:
raise TypeError( "Invalid button state: %s" % state )
self( e=True, buttonState=(a_item, a_button, a_state) )
def setButtonStyle( self, itemName, buttonIndex, style ):
'''
Possible button types:
pushButton - two possible states, button is reset to up upon release
2StateButton - two possible states, button changes state on click
3StateButton - three button states, button changes state on click
'''
if style not in self.BUTTON_TYPES:
raise TypeError( "Invalid button style: %s" % style )
self( e=True, buttonStyle=(itemName, buttonIndex, style) )
def removeAll( self ):
self( e=True, removeAll=True )
def setPressCommand( self, buttonIndex, cb ):
'''
Sets the python callback function to be invoked when the button at <buttonIndex> is pressed. The callback should
take two args - the first is the itemName that the button pressed belongs to, and the second is the button press state
that has just been activated
'''
#generate a likely unique name for a global proc - treeView press commands have to be mel proc names and can't be python
#callbacks. This hack makes it easier to work with tree view callbacks and keep everything in python
melCmdName = '__%s_pressCB%d' % (self, buttonIndex)
#construct the mel proc
melCmd = """global proc %s( string $str, int $index ) {
python( "import baseMelUI; baseMelUI.BaseMelUI.FromStr( '%s' )._executePressCB( %d, '"+ $str +"', "+ $index +" );" );
}""" % (melCmdName, self, buttonIndex)
#execute the proc we just constructed
maya.mel.eval( melCmd )
#store the python function we want to execute - NOTE: the function needs to take 3 args: func( str, int ) - see treeView docs for details
self._pressCBs[ buttonIndex ] = cb
#tell the widget what its press callback is...
self( e=True, pressCommand=(buttonIndex, melCmdName) )
def getPressCommand( self, buttonIndex ):
try:
return self._pressCBs[ buttonIndex ]
except KeyError:
return None
def _executePressCB( self, a_button, *a ):
self._pressCBs[ a_button ]( *a )
def getItemChildren( self, itemName ):
return self( q=True, children=itemName )
def clearSelection( self ):
self( e=True, clearSelection=True )
class _MelBaseMenu(BaseMelWidget):
DYNAMIC = False
KWARG_VALUE_NAME = 'l'
KWARG_VALUE_LONG_NAME = 'label'
KWARG_CHANGE_CB_NAME = 'pmc'
DEFAULT_WIDTH = None
DEFAULT_HEIGHT = None
STATIC_CHOICES = [] #if you populate this variable you'll have the options automatically appear in the list unless its a DYNAMIC menu
def __init__( self, parent, *a, **kw ):
super( _MelBaseMenu, self ).__init__( parent, *a, **kw )
if self.DYNAMIC:
if 'pmc' not in kw and 'postMenuCommand' not in kw: #make sure there isn't a pmc passed in
self( e=True, pmc=self._build )
else:
for item in self.STATIC_CHOICES:
self.append( item )
def __len__( self ):
return self( q=True, numberOfItems=True )
def __contains__( self, item ):
return item in self.getItems()
def _build( self, menu, menuParent ):
'''
converts the menu and menuParent args into proper MelXXX instance
'''
menu = BaseMelWidget.FromStr( menu ) #this should be the same as "self"...
menuParent = BaseMelWidget.FromStr( menuParent )
self.build( menu, menuParent )
def build( self, menu, menuParent ):
pass
def getMenuItems( self ):
itemNames = self( q=True, itemArray=True ) or []
return [ MelMenuItem.FromStr( itemName ) for itemName in itemNames ]
def getItems( self ):
return [ menuItem.getValue() for menuItem in self.getMenuItems() ]
def append( self, strToAppend ):
return MelMenuItem( self, label=strToAppend )
def clear( self ):
for menuItem in self.getMenuItems():
cmd.deleteUI( menuItem )
class MelMenu(_MelBaseMenu):
WIDGET_CMD = cmd.menu
DYNAMIC = True
def __new__( self, *a, **kw ):
return _MelBaseMenu.__new__( self, None, *a, **kw )
def __init__( self, *a, **kw ):
super( _MelBaseMenu, self ).__init__( None, *a, **kw )
if self.DYNAMIC:
if 'pmc' not in kw and 'postMenuCommand' not in kw: #make sure there isn't a pmc passed in
self( e=True, pmc=self._build )
def iterParents( self ):
return iter([])
def getFullName( self ):
return str( self )
def _build( self, *a ):
self.build()
def build( self, *a ):
pass
class MelOptionMenu(_MelBaseMenu):
WIDGET_CMD = cmd.optionMenu
KWARG_VALUE_NAME = 'v'
KWARG_VALUE_LONG_NAME = 'value'
KWARG_CHANGE_CB_NAME = 'cc'
DYNAMIC = False
def __getitem__( self, idx ):
return self.getItems()[ idx ]
def __setitem__( self, idx, value ):
menuItems = self.getMenuItems()
menuItems[ idx ].setValue( value )
def getMenuItems( self ):
itemNames = self( q=True, itemListShort=True ) or []
return [ MelMenuItem.FromStr( itemName ) for itemName in itemNames ]
def selectByIdx( self, idx, executeChangeCB=True ):
self( e=True, select=idx+1 ) #indices are 1-based in mel land - fuuuuuuu alias!!!
if executeChangeCB:
self._executeCB()
def selectByValue( self, value, executeChangeCB=True ):
idx = self.getItems().index( value )
self.selectByIdx( idx, executeChangeCB )
def setValue( self, value, executeChangeCB=True ):
self.selectByValue( value, executeChangeCB )
def getSelectedIdx( self ):
return self( q=True, select=True ) - 1 #indices are 1-based in mel land - fuuuuuuu alias!!!
class MelObjectMenu(MelOptionMenu):
def __new__( cls, parent, *a, **kw ):
new = MelOptionMenu.__new__( cls, parent, *a, **kw )
new._objs = []
return new
def _itemAsStr( self, item ):
return str( item )
def __setitem__( self, idx, value ):
menuItems = self.getMenuItems()
menuItems[ idx ].setValue( self._itemAsStr( value ) )
def append( self, obj ):
MelOptionMenu.append( self, obj )
self._objs.append( obj )
def getItems( self ):
return self._objs
def clear( self ):
MelOptionMenu.clear( self )
self._objs = []
class MelPopupMenu(_MelBaseMenu):
WIDGET_CMD = cmd.popupMenu
DYNAMIC = True
def iterParents( self ):
return iter([])
def getFullName( self ):
return str( self )
def clear( self ):
self( e=True, dai=True ) #clear the menu
class MelMenuItem(BaseMelWidget):
WIDGET_CMD = cmd.menuItem
KWARG_VALUE_NAME = 'l'
KWARG_VALUE_LONG_NAME = 'label'
KWARG_CHANGE_CB_NAME = 'pmc'
DEFAULT_WIDTH = None
DEFAULT_HEIGHT = None
def iterParents( self ):
return iter([])
def getFullName( self ):
return str( self )
class MelMenuItemDiv(MelMenuItem):
def __new__( cls, parent, *a, **kw ):
kw[ 'divider' ] = True
super( MelMenuItemDiv, cls ).__new__( cls, parent, *a, **kw )
class MelIteratorUI(object):
def __init__( self, iterableObject, maxRange=None, **kw ):
self.progress = 0
self.items = iterableObject
if maxRange is None:
maxRange = len( iterableObject )
self._maxRange = maxRange
cmd.progressWindow( progress=0, isInterruptable=True, minValue=0, maxValue=maxRange, **kw )
def __iter__( self ):
progressWindow = cmd.progressWindow
maxRange = self._maxRange
progress = 0
try:
for item in self.items:
yield item
if progressWindow( q=True, ic=True ):
return
progress += 1
progressWindow( e=True, progress=progress )
finally:
self.close()
def __del__( self ):
self.close()
def isCancelled( self ):
return cmd.progressWindow( q=True, ic=True )
def close( self ):
cmd.progressWindow( e=True, ep=True )
def makePathSceneRelative( filepath ):
#make sure it is actually an absolute path...
if filepath.isAbs():
curSceneDir = filesystem.Path( cmd.file( q=True, sn=True ) ).up()
filepath = filepath - curSceneDir
return filepath
def buildLabelledWidget( parent, label, labelWidth, WidgetClass, *a, **kw ):
layout = MelHSingleStretchLayout( parent )
lblKw = { 'align': 'left' }
if label:
lblKw[ 'l' ] = label
if labelWidth:
lblKw[ 'w' ] = labelWidth
lbl = MelLabel( layout, **lblKw )
ui = WidgetClass( layout, *a, **kw )
layout.setStretchWidget( ui )
layout.layout()
return ui, lbl, layout
def labelledUIClassFactory( baseCls ):
'''
this class factory creates "labelled" widget classes. a labelled widget class acts just like the baseCls instance except
that it has a label
NOTE: the following constructor keywords can be used:
llabel, ll sets the text label for the widget
llabelWidth, llw sets the label width
llabelAlign, lla sets the label alignment
the keyword "label" isn't used because the class might be wrapping a widget that validly has a label such as MelButton or MelCheckbox
'''
clsName = 'Labelled%s' % baseCls.__name__.replace( 'Mel', '' )
class _tmp(MelHSingleStretchLayout):
_IS_SETUP = False
def __new__( cls, parent, *a, **kw ):
#extract any specific keywords from the dict before setting up the instance
label = kw.pop( 'llabel', kw.pop( 'll', '<-no label->' ) )
labelWidth = kw.pop( 'llabelWidth', kw.pop( 'llw', None ) )
labelAlign = kw.pop( 'llabelAlign', kw.pop( 'lla', 'left' ) )
self = MelHSingleStretchLayout.__new__( cls, parent )
self.UI_lbl = lbl = MelLabel( self, l=label, align=labelAlign )
if labelWidth:
lbl.setWidth( labelWidth )
self.ui = ui = baseCls( self, *a, **kw )
self.setStretchWidget( ui )
self.layout()
self( e=True, af=((lbl, 'top', 0), (lbl, 'bottom', 0)) )
#these functions are built within the constructor scope for a few reasons
#first we get access to the ui object without having to go via a __getattr__ call
#second we can't put all the functionality into the __getattr__ and __setattr__ methods on the _tmp class because they will interfere with the super class' constructor (where most of the work is done)
#so basically construct these functions here and store them as _get and _set, and have the real __getattr__ and __setattr__ methods look for them once the instance has been properly constructed
def _get( self, attr ):
if attr in self.__dict__:
return self.__dict__[ attr ]
val = getattr( ui, attr, None )
if val is None:
raise AttributeError( "No attribute '%s' was found on the object or its '%s' widget member" % (attr, baseCls) )
return val
def _set( self, attr, value ):
if attr in self.__dict__:
setattr( self, attr, value )
setattr( ui, attr, value )
self._get = _get
self._set = _set
self._IS_SETUP = True
return self
def __getattr__( self, attr ):
if self._IS_SETUP:
return self._get( self, attr )
return super( MelHSingleStretchLayout, self ).__getattr__( attr )
def __setattr__( self, attr, value ):
if self._IS_SETUP:
self._set( self, attr, value )
return
super( MelHSingleStretchLayout, self ).__setattr__( attr, value )
#add some convenience methods for querying and setting the label and label width - they're named deliberately named awkwardly, see the class doc above for more information
def getLlabel( self ):
self.UI_lbl.getValue()
def setLlabel( self, label ):
self.UI_lbl.setValue( label )
def getLlabelWidth( self ):
self.UI_lbl.setWidth()
def setLlabelWidth( self, width ):
self.UI_lbl.setWidth( width )
def getWidget( self ):
return self.ui
_tmp.__name__ = clsName
_tmp.__doc__ = baseCls.__doc__
return _tmp
#now construct some Labelled classes
LabelledTextField = labelledUIClassFactory( MelTextField )
LabelledIntField = labelledUIClassFactory( MelIntField )
LabelledFloatField = labelledUIClassFactory( MelFloatField )
LabelledFloatSlider = labelledUIClassFactory( MelFloatSlider )
LabelledIntSlider = labelledUIClassFactory( MelIntSlider )
LabelledOptionMenu = labelledUIClassFactory( MelOptionMenu )
class MayaNode(object): pass
UI_FOR_PY_TYPES = { bool: MelCheckBox,
int: MelIntField,
float: MelFloatField,
basestring: MelTextField,
list: MelTextScrollList,
tuple: MelTextScrollList,
MayaNode: MelObjectSelector }
def getBuildUIMethodForObject( obj, typeMapping=None ):
if typeMapping is None:
typeMapping = UI_FOR_PY_TYPES
objType = obj if type( obj ) is type else type( obj )
#first see if there is an exact type match in the dict
buildClass = None
try: buildClass = typeMapping[ objType ]
except KeyError:
#if not, see if there is an inheritance match - its possible there may by multiple matches
#however, so we need to check them all and see which is the most appropriate
mro = list( inspect.getmro( objType ) )
bestMatch = None
for aType, aBuildClass in typeMapping.iteritems():
if aType in mro:
bestMatch = mro.index( aType )
if bestMatch:
buildClass = aBuildClass
break
return buildClass
def buildUIForObject( obj, parent, typeMapping=None ):
'''
'''
buildClass = getBuildUIMethodForObject( obj, typeMapping )
if buildClass is None:
raise MelUIError( "there is no build class defined for object's of type %s (%s)" % (type( obj ), obj) )
ui = buildClass( parent )
ui.setValue( obj )
return ui
class BaseMelWindow(BaseMelUI):
'''
This is a wrapper class for a mel window to make it behave a little more like an object. It
inherits from str because thats essentially what a mel widget is.
Objects of this class are callable. Calling an object is basically the same as passing the given
args to the cmd.window maya command:
aWindow = BaseMelWindow()
aWindow( q=True, exists=True )
is the same as doing:
aWindow = cmd.window()
cmd.window( aWindow, q=True, exists=True )
'''
WINDOW_NAME = 'unnamed_window'
WINDOW_TITLE = 'Unnamed Tool'
RETAIN = False
DEFAULT_SIZE = 250, 250
DEFAULT_MENU = 'File'
DEFAULT_MENU_IS_HELP = False
#set this class variable to a 3-tuple containing toolName, authorEmailAddress, helpPage
#if you don't have a help page you can set the third tuple value to None
#example:
#HELP_MENU = 'testTool', 'mel@macaronikazoo.com', 'http://www.macaronikazoo.com/docs/Space_Switching'
HELP_MENU = None
FORCE_DEFAULT_SIZE = True
@classmethod
def Exists( cls ):
'''
returns whether there is an instance of this class already open
'''
return cmd.window( cls.WINDOW_NAME, ex=True )
@classmethod
def Get( cls ):
'''
returns the existing instance
'''
return cls.FromStr( cls.WINDOW_NAME )
@classmethod
def Close( cls ):
'''
closes the window (if it exists)
'''
if cls.Exists():
cmd.deleteUI( cls.WINDOW_NAME )
@classmethod
def FromStr( cls, theStr ):
#see if the data stored in the docTag is a valid class name - it might not be if teh user has used the docTag for something (why would they? there is no need, but still check...)
possibleClassName = cmd.window( theStr, q=True, docTag=True )
theCls = BaseMelWindow.GetNamedSubclass( possibleClassName )
#if the data stored in the docTag doesn't map to a subclass, then we'll have to guess at the best class...
if theCls is None:
theCls = BaseMelWindow #at this point default to be an instance of the base widget class
new = unicode.__new__( theCls, theStr ) #we don't want to run initialize on the object - just cast it appropriately
return new
def __new__( cls, *a, **kw ):
kw.setdefault( 'title', cls.WINDOW_TITLE )
kw.setdefault( 'widthHeight', cls.DEFAULT_SIZE )
kw.setdefault( 'menuBar', True )
kw.setdefault( 'retain', cls.RETAIN )
if cmd.window( cls.WINDOW_NAME, ex=True ):
cmd.deleteUI( cls.WINDOW_NAME )
new = unicode.__new__( cls, cmd.window( cls.WINDOW_NAME, **kw ) )
cmd.window( new, e=True, docTag=cls.__name__ ) #store the classname in the
if cls.DEFAULT_MENU is not None:
MelMenu( l=cls.DEFAULT_MENU, helpMenu=cls.DEFAULT_MENU_IS_HELP )
if cls.HELP_MENU:
toolName, authorEmail, helpPage = cls.HELP_MENU
helpMenu = new.getMenu( 'Help' )
MelMenuItem( helpMenu, l="Help...", en=helpPage is not None, c=lambda x: cmd.showHelp(helpPage, absolute=True) )
#MelMenuItemDiv( helpMenu )
#bugReporterUI.addBugReporterMenuItems( toolName, assignee=authorEmail, parent=helpMenu )
#validate the instance list - this should be done regularly, but not always because its kinda slow...
BaseMelUI.ValidateInstanceList()
#track the instance
cls._INSTANCE_LIST.append( new )
return new
def __init__( self, *a, **kw ): pass
def __call__( self, *a, **kw ):
return cmd.window( self, *a, **kw )
def setTitle( self, newTitle ):
cmd.window( self.WINDOW_NAME, e=True, title=newTitle )
def getMenus( self ):
menus = self( q=True, menuArray=True ) or []
return [ MelMenu.FromStr( m ) for m in menus ]
def getMenu( self, menuName, createIfNotFound=True ):
'''
returns the UI name for the menu with the given name
'''
for m in self.getMenus():
if m.getValue() == menuName:
return m
if createIfNotFound:
return MelMenu( l=menuName, helpMenu='help' in menuName.lower() )
def getLayout( self ):
'''
returns the layout parented to this window
'''
layoutNameStart = '%s|' % self
existingLayouts = cmd.lsUI( controlLayouts=True, long=True )
for existingLayout in existingLayouts:
if existingLayout.startswith( layoutNameStart ):
toks = existingLayout.split( '|' )
return BaseMelLayout.FromStr( '%s|%s' % (self, toks[1]) )
def exists( self ):
return cmd.window( self.WINDOW_NAME, q=True, ex=True )
def show( self, state=True, forceDefaultSize=None ):
'''
if forceDefaultSize is None - it uses the FORCE_DEFAULT_SIZE class attribute
'''
if state:
cmd.showWindow( self )
else:
self( e=True, visible=False )
if forceDefaultSize is None:
forceDefaultSize = self.FORCE_DEFAULT_SIZE
if forceDefaultSize:
self( e=True, widthHeight=self.DEFAULT_SIZE )
def layout( self ):
'''
forces the window to re calc layouts for children
'''
curWidth = self( q=True, width=True )
self( e=True, width=curWidth+1 )
self( e=True, width=curWidth )
def processEvent( self, methodName, methodArgs, methodKwargs ):
method = getattr( self, methodName, None )
if callable( method ):
method( *methodArgs, **methodKwargs )
def close( self ):
self.Close()
###
### PROCEDURAL UI BUILDING ###
###
class UITypeError(TypeError): pass
class PyFuncLayout(MelColumnLayout):
'''
builds a default layout for a function - makes it easy to build UI for functions
call by passing a python function object on construction like so:
def sweet( this=12, isA=True, test=100 ): pass
PyFuncLayout( parentLayout, sweet )
NOTE: the UI building looks for a bunch of special attributes on the function that
can help control the presentation
_hideArgs = [] #this is a list of attribute names that won't be presented in the UI
_show = False #defaults to False - controls whether the function appears when building UI for a module (otherwise ignored)
_expand = False #defaults to False - controls whether the frame layout for function is expanded or not by default when building UI for a module (ignored otherwise)
'''
def __init__( self, parent, func ):
MelColumnLayout.__init__( self, parent )
hideArgNames = []
if hasattr( func, '_hideArgs' ):
hideArgNames = list( func._hideArgs )
self.argUIDict = {} #stores the argName->UI mapping
self.func = func #stores the function passed in
argNames, vargName, vkwargName, defaults = inspect.getargspec( func )
numDefaults = len( defaults )
numArgsWithoutDefaults = len( argNames ) - numDefaults
#pad the defaults with empty strings for args that have no default - it'll be up to the user to write appropriate python expressions
defaults = ([ '' ] * numArgsWithoutDefaults) + list( defaults )
labels = []
for argName, default in zip( argNames, defaults ):
if argName in hideArgNames:
continue
hLayout = MelHLayout( self )
lbl = MelLabel( hLayout, l=names.camelCaseToNice( argName ) )
labels.append( lbl )
ui = buildUIForObject( default, hLayout )
ui.setChangeCB( filesystem.Callback( self.changeCB, argName ) )
hLayout.setWeight( lbl, 0 )
hLayout.layout()
#finally stuff the ui into the argUIDict
self.argUIDict[ argName ] = ui
maxWidth = max( [ lbl.getWidth() for lbl in labels ] ) + 10 #10 for padding...
for lbl in labels:
lbl.setWidth( maxWidth )
MelButton( self, l='Execute %s' % names.camelCaseToNice( func.__name__ ), c=self.execute )
def changeCB( self, argName ):
common.printInfoStr( '%s arg changed!' % argName )
def getArgDict( self ):
argDict = {}
for argName, ui in self.argUIDict.iteritems():
argDict[ argName ] = ui.getValue()
#we need to get the args that have no default values and eval the values from the ui - it is assumed they're valid python expressions
argNames, vargName, vkwargName, defaults = inspect.getargspec( self.func )
numArgsWithoutDefaults = len( argNames ) - len( defaults )
for argName in argNames[ :numArgsWithoutDefaults ]:
uiStr = ui.getValue()
if not uiStr:
raise UITypeError( "No value given for %s arg" % argName )
argDict[ argName ] = eval( uiStr )
return argDict
def execute( self, *a ):
try:
self.func( **self.getArgDict() )
except UITypeError:
cmd.confirmDialog( "No value was entered for one of the args!", b='OK', db='OK')
class PyFuncWindow(BaseMelWindow):
'''
this is basically just a wrapper around the PyFuncLayout above. Its called
in a similar way:
def sweet( this=12, isA=True, test=100 ): pass
PyFuncWindow( sweet )
'''
WINDOW_NAME = 'funcWindow'
DEFAULT_MENU = None
FORCE_DEFAULT_SIZE = False
def __init__( self, func ):
PyFuncLayout( self, func )
self.setTitle( '%s Window' % names.camelCaseToNice( func.__name__ ) )
self.show()
class PyModuleLayout(MelColumnLayout):
'''
builds a window for an entire module
'''
def __init__( self, parent, module, showAll=False ):
def func(): pass
funcType = type( func )
#track the number of expanded frame layouts - we want to make sure at least one is expanded...
numExpanded = 0
self.funcUIDict = {}
for objName, obj in module.__dict__.iteritems():
if not isinstance( obj, funcType ):
continue
#skip any obj that already has UI built
if obj in self.funcUIDict:
continue
show = False
if hasattr( obj, '_show' ):
show = obj._show
#if we're not showing all, check the show state and skip accordingly
if not showAll:
if not show:
continue
expand = False
if hasattr( obj, '_expand' ):
expand = obj._expand
if expand:
numExpanded += 1
frame = MelFrameLayout( self, label=names.camelCaseToNice( objName ), cl=not expand, cll=True )
ui = PyFuncLayout( frame, obj )
self.funcUIDict[ obj ] = ui
#if there are no expanded frames - expand the first one...
if not numExpanded:
children = self.getChildren()
children[ 0 ].setCollapse( False )
class PyModuleWindow(BaseMelWindow):
'''
this is basically just a wrapper around the PyFuncLayout above. Its called
in a similar way:
def sweet( this=12, isA=True, test=100 ): pass
PyFuncWindow( sweet )
'''
WINDOW_NAME = 'moduleWindow'
DEFAULT_MENU = None
def __init__( self, module, showAll=False ):
PyModuleLayout( self, module, showAll )
self.setTitle( '%s Window' % names.camelCaseToNice( module.__name__ ) )
self.show()
#end
| Python |
from typeFactories import interfaceTypeFactory
from baseRigPrimitive import *
from apiExtensions import cmpNodes
ARM_NAMING_SCHEME = 'arm', 'bicep', 'elbow', 'wrist'
LEG_NAMING_SCHEME = 'leg', 'thigh', 'knee', 'ankle'
class SwitchableMixin(object):
'''
NOTE: we can't make this an interface class because rig part classes already have a pre-defined
metaclass... :(
'''
def __notimplemented( self ):
raise NotImplemented( "This baseclass method hasn't been implemented on the %s class" % type( self ).__name__ )
def switchToFk( self, key=False ):
'''
should implement the logic to switch this chain from IK to FK
'''
self.__notimplemented()
def switchToIk( self, key=False, _isBatchMode=False ):
'''
should implement the logic to switch this chain from FK to IK
'''
self.__notimplemented()
def setupIkFkVisibilityConditions( ikBlendAttrpath, ikControls, fkControls ):
ikControl = ikBlendAttrpath.split( '.' )[0]
visCondFk = createNode( 'condition' )
visCondFk = rename( visCondFk, '%s_fkVis#' % ikControl )
visCondIk = createNode( 'condition' )
visCondIk = rename( visCondIk, '%s_ikVis#' % ikControl )
connectAttr( ikBlendAttrpath, '%s.firstTerm' % visCondFk )
connectAttr( ikBlendAttrpath, '%s.firstTerm' % visCondIk )
setAttr( '%s.secondTerm' % visCondFk, 1 )
setAttr( '%s.secondTerm' % visCondIk, 0 )
setAttr( '%s.operation' % visCondFk, 3 ) #this is the >= operator
setAttr( '%s.operation' % visCondIk, 5 ) #this is the <= operator
for c in fkControls:
connectAttr( '%s.outColorR' % visCondFk, '%s.v' % c )
for c in ikControls:
connectAttr( '%s.outColorR' % visCondIk, '%s.v' % c )
class IkFkBase(PrimaryRigPart, SwitchableMixin):
'''
super class functionality for biped limb rigs - legs, arms and even some quadruped rigs inherit
from this class
'''
NAMED_NODE_NAMES = 'ikSpace', 'fkSpace', 'ikHandle', 'endOrient', 'poleTrigger'
def buildBase( self, nameScheme=ARM_NAMING_SCHEME, alignEnd=False ):
self.nameScheme = nameScheme
self.alignEnd = alignEnd
self.bicep, self.elbow, self.wrist = bicep, elbow, wrist = self.getSkeletonPart().getIkFkItems()
colour = self.getParityColour()
suffix = self.getSuffix()
#build the fk controls
self.fkSpace = buildAlignedNull( bicep, "fk_%sSpace%s" % (nameScheme[ 0 ], suffix) )
self.driverUpper = buildControl( "fk_%sControl%s" % (nameScheme[ 1 ], suffix), bicep, PivotModeDesc.MID, shapeDesc=ShapeDesc( 'sphere' ), colour=colour, asJoint=True, oriented=False, scale=self.scale, parent=self.fkSpace )
self.driverMid = buildControl( "fk_%sControl%s" % (nameScheme[ 2 ], suffix), elbow, PivotModeDesc.MID, shapeDesc=ShapeDesc( 'sphere' ), colour=colour, asJoint=True, oriented=False, scale=self.scale, parent=self.driverUpper )
self.driverLower = buildControl( "fk_%sControl%s" % (nameScheme[ 3 ], suffix), PlaceDesc( wrist, wrist if alignEnd else None ), shapeDesc=ShapeDesc( 'sphere' ), colour=colour, asJoint=True, oriented=False, constrain=False, scale=self.scale, parent=self.driverMid )
self.fkControls = self.driverUpper, self.driverMid, self.driverLower
attrState( self.fkControls, ('t', 'radi'), *LOCK_HIDE )
#build the ik controls
self.ikSpace = buildAlignedNull( self.wrist, "ik_%sSpace%s" % (self.nameScheme[ 0 ], suffix), parent=self.getWorldControl() )
self.ikHandle = asMObject( cmd.ikHandle( fs=1, sj=self.driverUpper, ee=self.driverLower, solver='ikRPsolver' )[0] )
self.control = limbControl = buildControl( '%sControl%s' % (self.nameScheme[ 0 ], suffix), PlaceDesc( self.wrist, self.wrist if self.alignEnd else None ), shapeDesc=ShapeDesc( 'cube' ), colour=colour, scale=self.scale, constrain=False, parent=self.ikSpace )
rename( self.ikHandle, '%sIkHandle%s' % (self.nameScheme[0], suffix) )
xform( self.control, p=True, rotateOrder='yzx' )
setAttr( '%s.snapEnable' % self.ikHandle, False )
setAttr( '%s.v' % self.ikHandle, False )
addAttr( self.control, ln='ikBlend', shortName='ikb', dv=1, min=0, max=1, at='double' )
setAttr( '%s.ikBlend' % self.control, keyable=True )
connectAttr( '%s.ikBlend' % self.control, '%s.ikBlend' % self.ikHandle )
attrState( self.ikHandle, 'v', *LOCK_HIDE )
parent( self.ikHandle, self.getPartsNode() )
parentConstraint( self.control, self.ikHandle )
#build the pole control
polePos = rigUtils.findPolePosition( self.driverLower, self.driverMid, self.driverUpper, 5 )
self.poleControl = buildControl( "%s_poleControl%s" % (self.nameScheme[ 0 ], suffix), PlaceDesc( self.elbow, PlaceDesc.WORLD ), shapeDesc=ShapeDesc( 'sphere', None ), colour=colour, constrain=False, parent=self.getWorldControl(), scale=self.scale*0.5 )
self.poleControlSpace = getNodeParent( self.poleControl )
attrState( self.poleControlSpace, 'v', lock=False, show=True )
move( polePos[0], polePos[1], polePos[2], self.poleControlSpace, a=True, ws=True, rpr=True )
move( polePos[0], polePos[1], polePos[2], self.poleControl, a=True, ws=True, rpr=True )
makeIdentity( self.poleControlSpace, a=True, t=True )
setAttr( '%s.v' % self.poleControl, True )
poleVectorConstraint( self.poleControl, self.ikHandle )
#build the pole selection trigger
self.lineNode = buildControl( "%s_poleSelectionTrigger%s" % (self.nameScheme[ 0 ], suffix), shapeDesc=ShapeDesc( 'sphere', None ), colour=ColourDesc( 'darkblue' ), scale=self.scale, constrain=False, oriented=False, parent=self.ikSpace )
self.lineStart, self.lineEnd, self.lineShape = buildAnnotation( self.lineNode )
parent( self.lineStart, self.poleControl )
delete( pointConstraint( self.poleControl, self.lineStart ) )
pointConstraint( self.elbow, self.lineNode )
attrState( self.lineNode, ('t', 'r'), *LOCK_HIDE )
setAttr( '%s.template' % self.lineStart, 1 ) #make the actual line unselectable
#setup constraints to the wrist - it is handled differently because it needs to blend between the ik and fk chains (the other controls are handled by maya)
self.endOrientParent = buildAlignedNull( self.wrist, "%s_follow%s_space" % (self.nameScheme[ 3 ], suffix), parent=self.getPartsNode() )
self.endOrient = buildAlignedNull( self.wrist, "%s_follow%s" % (self.nameScheme[ 3 ], suffix), parent=self.endOrientParent )
pointConstraint( self.driverLower, self.wrist )
orientConstraint( self.endOrient, self.wrist, mo=True )
setItemRigControl( self.wrist, self.endOrient )
setNiceName( self.endOrient, 'Fk %s' % self.nameScheme[3] )
self.endOrientSpaceConstraint = parentConstraint( self.control, self.endOrientParent, weight=0, mo=True )[ 0 ]
self.endOrientSpaceConstraint = parentConstraint( self.driverLower, self.endOrientParent, weight=0, mo=True )[ 0 ]
#constraints to drive the "wrist follow" mode
self.endOrientConstraint = parentConstraint( self.endOrientParent, self.endOrient )[0]
self.endOrientConstraint = parentConstraint( self.driverLower, self.endOrient, mo=True )[0]
addAttr( self.control, ln='orientToIk', at='double', min=0, max=1, dv=1 )
attrState( self.control, 'orientToIk', keyable=True, show=True )
endOrientAttrs = listAttr( self.endOrientConstraint, ud=True )
expression( s='%s.%s = %s.orientToIk;\n%s.%s = 1 - %s.orientToIk;' % (self.endOrientConstraint, endOrientAttrs[0], self.control, self.endOrientConstraint, endOrientAttrs[1], self.control), n='endOrientConstraint_on_off' )
endOrientSpaceAttrs = listAttr( self.endOrientSpaceConstraint, ud=True )
expression( s='%s.%s = %s.ikBlend;\n%s.%s = 1 - %s.ikBlend;' % (self.endOrientSpaceConstraint, endOrientSpaceAttrs[0], self.control, self.endOrientSpaceConstraint, endOrientSpaceAttrs[1], self.control), n='endOrientSpaceConstraint_on_off' )
#build expressions for fk blending and control visibility
self.fkVisCond = fkVisCond = shadingNode( 'condition', asUtility=True )
self.poleVisCond = poleVisCond = shadingNode( 'condition', asUtility=True )
connectAttr( '%s.ikBlend' % self.control, '%s.firstTerm' % self.fkVisCond, f=True )
connectAttr( '%s.ikBlend' % self.control, '%s.firstTerm' % self.poleVisCond, f=True )
connectAttr( '%s.outColorG' % self.poleVisCond, '%s.v' % self.lineNode, f=True )
connectAttr( '%s.outColorG' % self.poleVisCond, '%s.v' % self.poleControlSpace, f=True )
connectAttr( '%s.outColorG' % self.poleVisCond, '%s.v' % self.control, f=True )
setAttr( '%s.secondTerm' % self.fkVisCond, 1 )
driverUpper, driverMid, driverLower = self.driverUpper, self.driverMid, self.driverLower
expression( s='if ( %(limbControl)s.ikBlend > 0 && %(limbControl)s.orientToIk < 1 ) %(driverLower)s.visibility = 1;\nelse %(driverLower)s.visibility = %(fkVisCond)s.outColorG;' % locals(), n='wrist_visSwitch' )
for driver in (self.driverUpper, self.driverMid):
for shape in listRelatives( driver, s=True, pa=True ):
connectAttr( '%s.outColorR' % self.fkVisCond, '%s.v' % shape, f=True )
#add set pole to fk pos command to pole control
poleTrigger = Trigger( self.poleControl )
poleConnectNums = [ poleTrigger.connect( c ) for c in self.fkControls ]
idx_toFK = poleTrigger.setMenuInfo( None, "move to FK position",
'zooVectors;\nfloat $pos[] = `zooFindPolePosition "-start %%%s -mid %%%s -end %%%s"`;\nmove -rpr $pos[0] $pos[1] $pos[2] #;' % tuple( poleConnectNums ) )
poleTrigger.setMenuInfo( None, "move to FK pos for all keys",
'source zooKeyCommandsWin;\nzooSetKeyCommandsWindowCmd "eval(zooPopulateCmdStr(\\\"#\\\",(zooGetObjMenuCmdStr(\\\"#\\\",%%%d)),{}))";' % idx_toFK )
limbTrigger = Trigger( self.control )
handleNum = limbTrigger.connect( self.ikHandle )
poleNum = limbTrigger.connect( self.poleControl )
lowerNum = limbTrigger.connect( self.driverLower )
fkIdx = limbTrigger.createMenu( "switch to FK",
"zooAlign \"\";\nzooAlignFK \"-ikHandle %%%d -offCmd setAttr #.ikBlend 0\";\nselect %%%d;" % (handleNum, lowerNum) )
limbTrigger.createMenu( "switch to FK for all keys",
'source zooKeyCommandsWin;\nzooSetKeyCommandsWindowCmd "eval(zooPopulateCmdStr(\\\"#\\\",(zooGetObjMenuCmdStr(\\\"#\\\",%%%d)),{}))";' % fkIdx )
ikIdx = limbTrigger.createMenu( "switch to IK",
'zooAlign "";\nzooAlignIK "-ikHandle %%%d -pole %%%d -offCmd setAttr #.ikBlend 1;";' % (handleNum, poleNum) )
limbTrigger.createMenu( "switch to IK for all keys",
'source zooKeyCommandsWin;\nzooSetKeyCommandsWindowCmd "eval(zooPopulateCmdStr(\\\"#\\\",(zooGetObjMenuCmdStr(\\\"#\\\",%%%d)),{}))";' % ikIdx )
#add all zooObjMenu commands to the fk controls
for fk in self.fkControls:
fkTrigger = Trigger( fk )
c1 = fkTrigger.connect( self.ikHandle )
c2 = fkTrigger.connect( self.poleControl )
fkTrigger.createMenu( 'switch to IK',
'zooAlign "";\nstring $cs[] = `listConnections %%%d.ikBlend`;\nzooAlignIK ("-ikHandle %%%d -pole %%%d -control "+ $cs[0] +" -offCmd setAttr "+ $cs[0] +".ikBlend 1;" );' % (c1, c1, c2) )
createLineOfActionMenu( [self.control] + list( self.fkControls ), (self.elbow, self.wrist) )
#add trigger commands
Trigger.CreateTrigger( self.lineNode, Trigger.PRESET_SELECT_CONNECTED, [ self.poleControl ] )
setAttr( '%s.displayHandle' % self.lineNode, True )
#turn unwanted transforms off, so that they are locked, and no longer keyable
attrState( self.poleControl, 'r', *LOCK_HIDE )
def buildAllPurposeLocator( self, nodePrefix ):
allPurposeObj = spaceLocator( name="%s_all_purpose_loc%s" % (nodePrefix, self.getSuffix()) )[ 0 ]
attrState( allPurposeObj, 's', *LOCK_HIDE )
attrState( allPurposeObj, 'v', *HIDE )
parent( allPurposeObj, self.getWorldControl() )
return allPurposeObj
def getFkControls( self ):
return self.getControl( 'fkUpper' ), self.getControl( 'fkMid' ), self.getControl( 'fkLower' )
def getIkControls( self ):
return self.getControl( 'control' ), self.getControl( 'poleControl' ), self.getControl( 'ikHandle' )
@d_unifyUndo
def switchToFk( self, key=False ):
control, poleControl, handle = self.getIkControls()
attrName = 'ikBlend'
onValue = 1
offValue = 0
joints = self.getFkControls()
if handle is None or not objExists( handle ):
printWarningStr( "no ikHandle specified" )
return
#make sure ik is on before querying rotations
setAttr( '%s.%s' % (control, attrName), onValue )
rots = []
for j in joints:
rot = getAttr( "%s.r" % j )[0]
rots.append( rot )
#now turn ik off and set rotations for the joints
setAttr( '%s.%s' % (control, attrName), offValue )
for j, rot in zip( joints, rots ):
for ax, r in zip( ('x', 'y', 'z'), rot ):
if getAttr( '%s.r%s' % (j, ax), se=True ):
setAttr( '%s.r%s' % (j, ax), r )
alignFast( joints[2], handle )
if key:
setKeyframe( joints )
setKeyframe( '%s.%s' % (control, attrName) )
@d_unifyUndo
def switchToIk( self, key=False, _isBatchMode=False ):
control, poleControl, handle = self.getIkControls()
attrName = 'ikBlend'
onValue = 1
joints = self.getFkControls()
if handle is None or not objExists( handle ):
printWarningStr( "no ikHandle specified" )
return
alignFast( control, joints[2] )
if poleControl:
if objExists( poleControl ):
pos = findPolePosition( joints[2], joints[1], joints[0] )
move( pos[0], pos[1], pos[2], poleControl, a=True, ws=True, rpr=True )
setKeyframe( poleControl )
setAttr( '%s.%s' % (control, attrName), onValue )
if key:
setKeyframe( control, at=('t', 'r') )
if not _isBatchMode:
setKeyframe( control, at=attrName )
#end
| Python |
import vectors, cPickle, names, math, time, datetime, mayaVectors, api
import exportManagerCore
import maya.cmds as cmd
import maya.OpenMaya as OpenMaya
import maya.OpenMayaAnim as OpenMayaAnim
import bisect, os
g_defaultKeyUtilsPickle = 'd:/temp.pickle'
g_validWorldAttrs = ('translateX','translateY','translateZ','rotateX','rotateY','rotateZ')
mel = api.mel
PRIMARY_NAMES = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
PRIMARY_ROTATIONS = [-45, -90, -135, 180, 135, 90, 45]
PRIMARY_SPEEDS = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
PRIMARY_START_FRAMES = [60, 120, 180, 240, 300, 360, 420]
#SECONDARY_ROTATIONS = [-45, -90, -135, -180, 135, 90, 45]
#SECONDARY_SPEEDS = [0.85, 0.68, 0.85, 0.6, 0.85, 0.68, 0.85]
#SECONDARY_STARTS = [ 60, 120, 180, 240, 300, 360, 420 ]
#SECONDARY_NAMES = [ 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']
class MatrixAtTime(mayaVectors.MayaMatrix):
#simply stores time along with a matrix...
def __init__( self, values=(), size=4, time=None ):
if isinstance(values,MatrixAtTime):
time = values.time
values = values.as_list()
mayaVectors.MayaMatrix.__init__(self,values,4)
self.time = time
#this decorator turns off all the "slow things" when doing time change operations...
def noUpdate(f):
def actualFunc(*args):
start = time.clock()
initialAutoKeyState = cmd.autoKeyframe(q=True,state=True)
cmd.autoKeyframe(state=False)
api.mel.zooAllViews(0)
retVal = f(*args)
api.mel.zooAllViews(1)
cmd.autoKeyframe(state=initialAutoKeyState)
print 'time taken',time.clock()-start,'secs'
return retVal
return actualFunc
class Key(object):
'''this is simply a convenient abstraction of a key object in maya - which doesn't
really exist... working with key data is a pain in the ass. you can specify either
a key time or a key index when creating an instance. if both are specifed, index is
used. if time is specified, and there is no key at that time, a phantom key is
created using the curve value at that point - the index is set to -1 in this case,
and tangent data is guessed'''
def __init__( self, obj=None, attr=None, time=None, value=None, idx=None, populateTangents=True ):
#if the attrpath doesn't exist, then just create an empty key instance
self.idx = idx
self.obj, self.attr, self.time, self.value = obj, attr, time, value
self.iw, self.ow, self.ia, self.oa = 1.0, 1.0, 0, 0
self.itt, self.ott, self.lock = 'linear', 'linear', True
if obj is None or attr is None: return
#make sure the attr name is the long version of the name, its too annoying to have to deal with shortnames AND long names...
#self.attr = cmd.attributeQuery(self.attr,longName=True,node=self.obj)
#self.attrShort = cmd.attributeQuery(self.attr,shortName=True,node=self.obj)
#populating tangents is slow - so only do it when required
if populateTangents: self.populateTangents()
def copy( self ):
new = self.__class__()
new.idx = self.idx
new.obj, new.attr, new.time, new.value = self.obj, self.attr, self.time, self.value
new.iw, new.ow, new.ia, new.oa = self.iw, self.ow, self.ia, self.oa
new.itt, new.ott, new.lock = self.itt, self.ott, self.lock
return new
def get_attrpath( self ):
return '%s.%s'%(self.obj,self.attr)
attrpath = property(get_attrpath)
def populateTangents( self ):
#is there a key at the time?
attrpath = self.attrpath
if cmd.keyframe(attrpath,time=(keyTime,),query=True,keyframeCount=True):
self.value = cmd.keyframe(attrpath,time=(keyTime,),query=True,valueChange=True)[0]
self.iw,self.ow,self.ia,self.oa = cmd.keyTangent(attrpath,time=(keyTime,),query=True,inWeight=True,outWeight=True,inAngle=True,outAngle=True)
self.itt,self.ott = cmd.keyTangent(attrpath,time=(keyTime,),query=True,inTangentType=True,outTangentType=True)
self.lock = cmd.keyTangent(attrpath,time=(keyTime,),query=True,lock=True)[0]
#this is purely 'clean up after maya' code. for whatever reason maya will return a tangent type of "fixed" even though its a completely invalid tangent type... not sure what its supposed to map to, so I'm just assuming spline
if self.itt == 'fixed': self.itt = 'spline'
if self.ott == 'fixed': self.ott = 'spline'
else:
self.idx = self.get_index()
self.value = cmd.keyframe(attrpath,time=(self.time,),query=True,eval=True,valueChange=True)
index = self.idx
previousOutTT = None
previousOutTW = None
nextInTT = None
nextInTW = None
if index > 1:
previousOutTT = cmd.keyTangent(attrpath,index=(index-1,),query=True,outTangentType=True)
previousOutTW = cmd.keyTangent(attrpath,index=(index-1,),query=True,outWeight=True)
else:
previousOutTT = cmd.keyTangent(attrpath,index=(index,),query=True,outTangentType=True)
previousOutTW = cmd.keyTangent(attrpath,index=(index,),query=True,outWeight=True)
if index < cmd.keyframe(self.attr,query=True,keyframeCount=True):
nextInTT = cmd.keyTangent(attrpath,index=(index+1,),query=True,inTangentType=True)
nextInTW = cmd.keyTangent(attrpath,index=(index+1,),query=True,inWeight=True)
else:
nextInTT = cmd.keyTangent(attrpath,index=(index,),query=True,inTangentType=True)
nextInTW = cmd.keyTangent(attrpath,index=(index,),query=True,inWeight=True)
#now average the tangents
self.iw = self.ow = (previousOutTW + nextInTW )/2
def __str__( self ):
return '%.2f'% (self.time,)
def __repr__( self ):
return self.__str__()
def __cmp__( self, other, tolerance=1e-4 ):
if isinstance(other,Key): other = other.time
if abs(self.time-other) <= tolerance : return 0
if self.time - other < 0: return -1
return 1
def offset( self, amount ):
#time offsets the channel by a given time delta
self.time += amount
def get_index( self ):
'''returns the key object's index'''
return cmd.keyframe(self.attr,time=(":%f"+self.time,),query=True,keyframeCount=True)-1
class Channel(object):
'''a channel is simply a list of key objects with some convenience methods attached'''
def __init__( self, obj=None, attr=None, start=None, end=None, populateTangents=True ):
self.obj = obj
self.attr = attr
self.weighted = True
self.keys = []
#unless an attrpath has been specified, we're done...
if obj is None or attr is None: return
attrpath = '.'.join((obj,attr))
if start is None:
#get the timecount of the first key
start = cmd.keyframe(attrpath,index=(0,),query=True)[0]
if end is None:
#get the timecount of the first key
lastKeyIdx = cmd.keyframe(attrpath,keyframeCount=True,query=True)-1
end = cmd.keyframe(attrpath,index=(lastKeyIdx,),query=True)[0]
self.attr = str( cmd.attributeQuery(self.attr,longName=True,node=self.obj) )
self.attrShort = str( cmd.attributeQuery(self.attr,shortName=True,node=self.obj) )
self.weighted = cmd.keyTangent(attrpath,query=True,weightedTangents=True)
if self.weighted == 1: self.weighted = True
else: self.weighted = False
if cmd.objExists(attrpath):
times = cmd.keyframe(attrpath,time=(start,end),query=True)
values = cmd.keyframe(attrpath,time=(start,end),query=True,vc=True)
#if there are no keys - bail
if times is None: return
self.keys = [Key(obj,attr,time=k,value=v,populateTangents=False) for k,v in zip(times,values)]
if populateTangents:
#querying heaps of tangent data at once is much more efficient than throwing a query for
#each key created - so although uglier, its quite significantly faster...
iws = cmd.keyTangent(attrpath,time=(start,end),query=True,iw=True)
ows = cmd.keyTangent(attrpath,time=(start,end),query=True,ow=True)
ias = cmd.keyTangent(attrpath,time=(start,end),query=True,ia=True)
oas = cmd.keyTangent(attrpath,time=(start,end),query=True,oa=True)
itts = cmd.keyTangent(attrpath,time=(start,end),query=True,itt=True)
otts = cmd.keyTangent(attrpath,time=(start,end),query=True,ott=True)
locks = cmd.keyTangent(attrpath,time=(start,end),query=True,lock=True)
#remove all instances of 'fixed' tangent types. maya will return a type of fixed, but it throws an exception if
#you try to set a tangent type of fixed... nice...
try:
while True: itts.remove('fixed')
except ValueError: pass
try:
while True: otts.remove('fixed')
except ValueError: pass
#
for key,iw,ow,ia,oa,itt,ott,lock in zip(self.keys,iws,ows,ias,oas,itts,otts,locks):
key.iw,key.ow,key.ia,key.oa,key.itt,key.ott,key.lock = iw,ow,ia,oa,itt,ott,lock
self.keys.sort()
@classmethod
def FromChannel( cls, channel, keys=None ):
new = cls()
new.obj = channel.obj
new.attr = channel.attr
new.attrShort = channel.attrShort
new.weighted = channel.weighted
if keys is None: new.keys = [key.copy() for key in channel.keys]
else: new.keys = [key.copy() for key in keys]
return new
def copy( self ):
return Channel.FromChannel(self)
def get_attrpath( self ):
return '%s.%s'%(self.obj,self.attr)
attrpath = property(get_attrpath)
def get_start( self ):
keyTimes = [key.time for key in self.keys]
if len(keyTimes): return min(keyTimes)
start = property(get_start)
def get_end( self ):
keyTimes = [key.time for key in self.keys]
if len(keyTimes): return max(keyTimes)
end = property(get_end)
def get_values( self ):
values = []
for key in self.keys:
values.append(key.value)
return values
values = property(get_values)
def __str__( self ):
return '%s %s'%(self.attrpath, str(self.keys))
def __repr__( self ):
return self.__str__()
def __nonzero__( self ):
return bool(self.keys)
def __add__( self, other ):
assert isinstance(other,Channel)
newChannel = self.copy()
#so when adding channels, if there are two keys on the same frame, their values get added together
#TODO: if not, then find surrounding keys (if any) and do a value lerp to add to the key value
for key in other.keys:
keyAtTime = self[key.time]
if keyAtTime:
keyAtTime.keys[0].value += key.value
else:
newChannel.keys.append(key)
newChannel.keys.sort()
return newChannel
def __getitem__( self, timeValue ):
'''so this returns a slice based on a time value NOT and index. NOTE: the slice step is ignored - it
doesn't really make any sense'''
if isinstance(timeValue,slice):
start_idx = bisect.bisect_left(self.keys,timeValue.start)
end_idx = bisect.bisect(self.keys,timeValue.stop)
keys = self.keys[start_idx:end_idx]
newChannel = Channel.FromChannel(self,keys)
return newChannel
try:
idx = bisect.bisect_left(self.keys,timeValue)
key = self.keys[idx]
if abs(timeValue-key.time)<=1e-4: return Channel.FromChannel(self,[key])
except IndexError:
return Channel.FromChannel(self,[])
def __len__( self ):
return len(self.keys)
def offset( self, amount ):
#time offsets the channel by a given time delta
[key.offset(amount) for key in self.keys]
def transform( self, transformFunction ):
#transforms all key values by the given transform function. the first arg passed to the transform function is the key
#the return value should also be a key object
self.keys = [transformFunction(key) for key in self.keys]
def applyToObj( self, obj, applyAsWorld=False, clearFirst=False ):
'''applies the current channel to a given attrpath'''
tgtAttrpath = '.'.join((obj,self.attr))
if not cmd.objExists(tgtAttrpath): return
if clearFirst:
if self.start is not None:
cmd.cutKey(tgtAttrpath,t=(self.start,self.end),cl=True)
if applyAsWorld and self.hasWorld:
#apply as world - NOT DONE YET
for key in self.keys:
cmd.setKeyframe(tgtAttrpath,time=(key.time,),value=key.value,inTangentType=key.itt,outTangentType=key.ott)
cmd.keyTangent(tgtAttrpath,time=(key.time,),edit=True,inWeight=key.iw,outWeight=key.ow,inAngle=self.ia,outAngle=self.oa)
else:
#set this initial dummy keyframe so we can set the curve's (whcih may not exist) weightedness
if len( self.keys ):
cmd.setKeyframe(tgtAttrpath,time=(self.keys[0].time,))
cmd.keyTangent(tgtAttrpath,edit=True,weightedTangents=self.weighted)
#if self.weighted: print "hi i'm weighting ur tangents..."
for key in self.keys:
cmd.setKeyframe(tgtAttrpath,time=(key.time,),value=key.value,inTangentType=key.itt,outTangentType=key.ott)
#cmd.keyTangent(tgtAttrpath,time=(key.time,),edit=True,lock=key.lock,inWeight=key.iw,outWeight=key.ow,inAngle=key.ia,outAngle=key.oa)
def getTurningPoints( self ):
'''returns a list of keys that are turning points'''
if len(self.keys) < 3:
return []
turningPoints = []
keyIter = iter(self.keys)
prevKey = keyIter.next()
curKey = keyIter.next()
nextKey = keyIter.next()
while True:
try:
prevValue = prevKey.value - curKey.value
nextValue = nextKey.value - curKey.value
if ( prevValue<0 and nextValue<0 ) or ( prevValue>0 and nextValue>0 ):
#in this case nextKey is a turning point
turningPoints.append(curKey)
prevKey = curKey
curKey = nextKey
nextKey = keyIter.next()
except StopIteration:
break
return turningPoints
def keyReduce( self ):
#get the nodeType of the animCurve driving this channel
animCurve = cmd.listConnections('%s.%s'%(self.obj,self.attr),type='animCurve',destination=False)[0]
nodeType = cmd.nodeType(animCurve)
#create an array to hold the "reduced" set of keys to create - start/end and turning points are mandatory
newKeys = [self.keys[0]] + self.getTurningPoints() + [self.keys[-1]]
#create the new animCurve - we do this because asking maya to query the interpolation between keys is way easier than doing it via script
reduce = cmd.createNode(nodeType)
for key in newKeys: cmd.setKeyframe(reduce,time=(key.time,),value=key.value,inTangentType='linear',outTangentType='linear')
#
return reduce
class Clip(object):
'''creates a convenient abstraction of a collection of animation data on multiple
channels. supports adding, removing etc... if start and end aren't specified, it
uses the entire range. if channels isn't specified, assumes all keyable channels'''
def __init__( self, obj=None, start=None, end=None, channels=None, populateTangents=True ):
#create object attrs
self.obj = obj
self.channels = {}
self.world = []
if obj is None:
return
#if channels is the default value, assume all keyable channels on the node
if channels == None:
attributes = cmd.listAttr(obj,keyable=True,multi=True,scalar=True)
channels = [str(a) for a in attributes if cmd.keyframe(obj+'.'+a,query=True,keyframeCount=True)]
for channel in channels:
newChannel = Channel(obj,channel,start,end,populateTangents)
self.channels[channel] = newChannel
@classmethod
def FromClip( cls, clip, channels=None, world=None ):
new = cls()
new.obj = clip.obj
if channels is None:
for name,channel in clip.channels.iteritems():
new.channels[name] = channel.copy()
else:
for name,channel in channels.iteritems():
new.channels[name] = chan.copy()
if world is None: new.world = [mat.copy() for mat in clip.world]
else: new.world = [mat.copy() for mat in world]
return new
def copy( self ):
return Clip.FromClip(self)
def __str__( self ):
asStr = '\n'.join( map(str,self.channels.values()) )
return asStr
def __getattr__( self, attr ):
return self.channels[attr]
def __contains__( self, item ):
return item in self.channels
def get_start( self ):
starts = []
for channel in self.channels:
starts.append(channel.start)
return min(starts)
start = property(get_start)
def get_end( self ):
ends = []
for channel in self.channels:
ends.append(channel.end)
return max(ends)
end = property(get_end)
def _hasWorld( self ):
return not( not self.world )
hasWorld = property(_hasWorld)
def __add__( self, other ):
assert isinstance(other,Clip)
newClip = self.copy()
for name,channel in newClip.channels.iteritems():
if name in other.channels:
newClip.channels[name] = newClip[name]+other[name]
#deal with world matricies - so if two matricies exist on the same frame, then we need to merge them
if other.world:
newWorld = []
for matB in other.world:
matA = None
for m in newClip.world:
if m.time == matB.time: matA = m
if matA is not None:
#in this case, we need to merge the two matricies together...
posA = matA.pos
posB = matB.pos
newPos = (posA+posB)/2
quatA = vectors.Quaternion(matA)
quatB = vectors.Quaternion(matB)
newQuat = (quatA/2)*(quatB/2)
mergedMat = MatrixAtTime(newQuat,time=matB.time)
mergedMat.pos = newPos
newWorld.append( mergedMat )
else:
newWorld.append(matB)
newClip.world = newWorld
return newClip
def __getitem__( self, item ):
#so this returns a slice based on a time value NOT and index. NOTE: the slice step is ignored - it
#doesn't really make any sense
if isinstance(item,basestring):
return self.channels[item]
newChannels = {}
for name,channel in self.channels.iteritems():
newChannels[name] = channel[item]
worldTimes = [mat.time for mat in self.world]
if isinstance(item,slice):
start_idx = bisect.bisect_left(worldTimes,item.start)
end_idx = bisect.bisect(worldTimes,item.stop)
newWorld = worldTimes[start_idx:end_idx]
newClip = Clip.FromClip(self,newChannels,newWorld)
return newClip
newWorld = []
if self.hasWorld:
idx = bisect.bisect_left(worldTimes,item)
newWorld.append(self.world[idx])
abs(item-newWorld[0])<=1e-4
return Clip.FromClip(self,newChannels,newWorld)
def __len__( self ):
return len(self.keys)
def offset( self, amount ):
#time offsets the channel by a given time delta
[channel.offset(amount) for channel in self.channels.values()]
for mat in self.world:
mat.time += amount
def transform( self, transformFunction ):
#transforms all key values by the given transform function. the first arg passed to the transform function is the key
[channel.transform(transformFunction) for channel in self.channels.values()]
def get_channels( self, channelListToGet ):
resultingChannels = []
for name in channelListToGet:
resultingChannels.append(getattr(self,name))
return resultingChannels
def listKeysInOrder( self, channels=None ):
'''returns a list of the clip's keys in ascending temporal order'''
if not channels: channels = self.channels
#do a DSU sort...
keys = [(key.time,key) for key in self.keys]
keys.sort()
keys = [x[1] for x in keys]
return keys
keys = property(listKeysInOrder)
def as_frames( self, channels=None ):
'''bundles the keys in this channel into groups of unique times - we call these frames. ie: each frame has one or more keys at that time and ONLY that time
return value is a list of lists (a list of frames). each frame contains all the keys at that time'''
keys = self.listKeysInOrder(channels)
prevTime = keys[0].time
frames = [(prevTime,[keys[0]])]
curList = frames[0][1]
for key in keys:
if prevTime != key.time:
prevTime = key.time
nextFrame = (prevTime,[])
frames.append(nextFrame)
curList = nextFrame[1]
curList.append(key)
return frames
frames = property(as_frames)
def as_keys( self ):
keys = []
for channel in self.channels.values():
keys += channel.keys
return keys
keys = property(as_keys)
def get_times( self, channelStrs=None ):
#returns a set of time values for all keys in this clip - optionally only on a given list of channels
if channelStrs is None:
channelStrs = self.channels.keys() #NOTE: channels is a dict
times = set()
for channelStr in channelStrs:
if channelStr not in self:
continue
for key in self[channelStr].keys:
times.add( key.time )
return times
def applyToObj( self, obj=None, applyAsWorld=False, clearFirst=False ):
'''applies the current clip to an object - if the animation is being applied as world space, first check to make
sure the world space animation for the clip exists. then separate the transform channels out of the channels list
and apply them as world space data. then we need to apply the rest of the channels as per normal'''
if obj is None:
obj = self.obj
if applyAsWorld and self.hasWorld:
for matrix in self.world:
cmd.currentTime(matrix.time)
tfn = OpenMaya.MFnTransform( api.getMDagPath(obj) )
tfn.set( OpenMaya.MTransformationMatrix( key[0] ) )
'''nonTransformChannels = []
for channel in self.channels:
if channel.attr not in g_validWorldAttrs: nonTransformChannels.append(channel)
frames = self.as_frames(transformChannels)
for channel in self.world:
tgtAttrpath = obj +'.'+ channel.attr
channel.applyToObj(obj,applyAsWorld)
#run a euler filter over the resulting rotation animation - converting to world space
#rotations often causes all sorts of nasty euler flips
maya.mel.eval('filterCurve %s.rx %s.ry %s.rz;'%(obj,obj,obj))
for channel in transformChannels:
channel.applyToObj(obj)'''
else:
for channel in self.channels.values():
channel.applyToObj(obj,clearFirst=clearFirst)
def populateWorld( self, time=None ):
if time is None:
time = cmd.currentTime(q=True)
mat = MatrixAtTime.FromObject(self.obj,True)
mat.time = time
self.world.append(mat)
@noUpdate
def getWorld( self ):
'''saves world space matricies for each animation frame in the clip - ie for each transform key a world space matrix
is saved in the self.world list'''
orgTime = cmd.currentTime(q=True)
for time,keys in self.frames:
cmd.currentTime(time)
self.populateWorld(time)
cmd.currentTime(orgTime) #restore time
class Animation(object):
def __init__( self, objs=None, start=None, end=None, channels=None ):
self.clips = {}
#we need to store objs in a list so we can preserve ordering - when re-applying an animation clip back to a collection of objects, we don't want to have to worry about a mapping - hence ordering is important
self.objs = objs
if objs is not None:
for obj in objs:
self.clips[obj] = Clip(obj,start,end,channels)
@classmethod
def FromAnimation( cls, animation, clips=None ):
new = cls()
if clips is None:
for name,clip in animation.clips.iteritems():
new.clips[name] = clip.copy()
else:
for name,clip in clips.iteritems():
new.clips[name] = clip.copy()
return new
def copy( self ):
return Animation.FromAnimation(self)
def __str__( self ):
asStr = '\n'.join( map(str,self.clips.values()) )
return asStr
def __getattr__( self, attr ):
return self.clips[attr]
def __getitem__( self, item ):
if isinstance(item,basestring):
return self.clips[item]
newClips = {}
for name,clip in self.clips.iteritems():
newClips[name] = clip[item]
return Animation.FromAnimation(self,newClips)
def __add__( self, other ):
assert isinstance(other,Animation)
newAnim = self.copy()
for obj,clip in self.clips.iteritems():
if obj in other.clips:
newAnim.clips[obj] = newAnim[obj] + other[obj]
return newAnim
def __contains__( self, item ):
return item in self.clips
def get_start( self ):
starts = []
for clip in self.clips:
starts.append(clip.start)
return min(starts)
start = property(get_start)
def get_end( self ):
ends = []
for clip in self.clips:
ends.append(channel.end)
return max(ends)
end = property(get_end)
def _hasWorld( self ):
return not( not self.world )
hasWorld = property(_hasWorld)
def offset( self, amount ):
[clip.offset(amount) for clip in self.clips.values()]
def transform( self, transformFunction ):
#transforms all key values by the given transform function. the first arg passed to the transform function is the key
[clip.transform(transformFunction) for clip in self.clips]
def get_times( self, channels=None ):
transformTimes = set()
for clip in self.clips.values():
times = clip.get_times(channels)
transformTimes = transformTimes.union( times )
transformTimes = list(transformTimes)
transformTimes.sort()
return transformTimes
@noUpdate
def getWorld( self, objs=None, channels=None ):
clips = self.clips.values() if objs is None else [self.clips[obj] for obj in objs]
transformTimes = set()
clipTimeSets = []
for clip in clips:
times = set( clip.get_times(channels) )
transformTimes = transformTimes.union( times )
clipTimeSets.append( times )
transformTimes = list(transformTimes)
transformTimes.sort()
orgTime = cmd.currentTime(q=True)
for time in transformTimes:
cmd.currentTime(time)
for clip,clipTimeSet in zip(clips,clipTimeSets):
if time not in clipTimeSet:
continue
clip.populateWorld(time)
cmd.currentTime(orgTime) #restore time
def applyToObjs( self, objs=None, applyAsWorld=False, clearFirst=False ):
if objs is None:
for obj,clip in self.clips.iteritems():
clip.applyToObj(obj,applyAsWorld,clearFirst)
else:
for n,obj in enumerate(objs):
self.clips[ self.objs[n] ].applyToObj(obj,applyAsWorld,clearFirst)
def write( object, filepath ):
sourceSceneData = {}
sourceSceneData['file'] = cmd.file(q=True,sn=True)
sourceSceneData['mayaVersion'] = cmd.about(version=True)
sourceSceneData['datetime'] = datetime.datetime.today()
sourceSceneData['env'] = os.environ
fileobj = file(filepath,'wb')
cPickle.dump( (sourceSceneData, object), fileobj, True )
fileobj.close()
def load( filepath ):
fileobj = file(filepath,'rb')
new = cPickle.load(fileobj)
fileobj.close()
return new
def createCompassRun():
namespace = ''
worldSpaceObjs = ['leg_L','leg_R','root','arm_L','arm_R']
def propagateChanges():
pass
def generatePrimary( baseStart, baseEnd ):
generate( baseStart, baseEnd, PRIMARY_ROTATIONS, PRIMARY_SPEEDS, PRIMARY_START_FRAMES, PRIMARY_NAMES )
def generate( baseStart, baseEnd,\
rotations = PRIMARY_ROTATIONS,\
strideLengthMultipliers = PRIMARY_SPEEDS,\
starts = PRIMARY_START_FRAMES,\
directions = PRIMARY_NAMES ):
#determine which ctrl set to use
ctrlSet = names.matchNames(['body_ctrls'],cmd.ls(type='objectSet'),threshold=1)
if not ctrlSet:
raise Exception('control set not found')
ctrlSet = ctrlSet[0]
ctrls = cmd.sets(ctrlSet,q=True)
length = baseEnd-baseStart
num = len(rotations)
#does the base locomote have an asset?
vx = exportManagerCore.ExportManager()
baseAsset = vx.exists(start=baseStart,end=baseEnd)
infoNode = ''
exportSet = ''
if len(baseAsset):
baseAsset = baseAsset[0]
exportSet = baseAsset.obj
else:
#if it doesn't exist, try and create one
infoNodes = cmd.ls(type='vstInfo')
candidates = []
for node in infoNodes:
if not cmd.referenceQuery(node,inr=True): continue
if not cmd.listRelatives(node): continue
candidates.append(node)
infoNode = candidates[0]
exportSet = exportManagerCore.ExportManager.CreateExportSet( [infoNode] )
#now build the actual asset
asset = vx.createAsset(exportSet)
asset.setAttr('start', baseStart)
asset.setAttr('end', baseEnd)
asset.setAttr('name', 'N')
asset.setAttr('type', exportManagerCore.ExportComponent.kANIM)
#grab the list of ctrls we need to actually transform
toFind = [ 'upperBodyControl', 'legControl_L', 'legControl_R' ]#, 'armControl_L', 'armControl_R' ]
xformCtrls = [ name for name in names.matchNames( toFind, ctrls, parity=True, threshold=0.8 ) if name != '' ]
animation = Animation( ctrls, baseStart, baseEnd )
animation.getWorld(xformCtrls,['translateX','translateZ'])
#save the animation out - useful for doing deltas later on
#write(animation,g_defaultKeyUtilsPickle)
#build the rotation axis
axis = vectors.Vector([0, 1, 0])
for n in xrange(num):
offset = starts[n]-baseStart
tmpAnim = animation.copy()
tmpAnim.offset( offset )
#convert angles to radians, and do other static calcs
angle = rotations[n]
angle = math.radians(angle)
quat = vectors.Quaternion.AxisAngle( axis, angle )
for ctrl in xformCtrls:
clip = tmpAnim[ctrl]
#do the actual rotation around Y
mats = clip.world
translateX = clip.translateX.keys = []
translateZ = clip.translateZ.keys = []
for mat in mats:
pos = mat.get_position()
pos = pos.rotate(quat)
mat[3][:3] = pos
translateX.append( Key( time=mat.time, value=pos.x ) )
translateZ.append( Key( time=mat.time, value=pos.z ) )
#now do stride length multiplication
strideMult = strideLengthMultipliers[n]
if strideMult is not None:
def makeShorter( key ):
key.value *= strideMult
return key
clip.translateX.transform(makeShorter)
clip.translateZ.transform(makeShorter)
tmpAnim.applyToObjs(clearFirst=True)
#finally create an asset for the new anim
existing = vx.exists( start=starts[n], end=starts[n]+length, name=directions[n] )
if not len(existing):
asset = vx.createAsset( exportSet )
asset.setAttr('start', starts[n])
asset.setAttr('end', starts[n]+length)
asset.setAttr('name', directions[n])
asset.setAttr('type', exportManagerCore.ExportComponent.kANIM)
def motionList( obj, start, end ):
#creates a list of positions at each frames over a given time range
motion = []
for n in xrange(start,end+1): #add one because this is an inclusive range
curX = cmd.keyframe(obj +'.tx',t=(n,),q=True,ev=True)[0]
curY = cmd.keyframe(obj +'.ty',t=(n,),q=True,ev=True)[0]
curZ = cmd.keyframe(obj +'.tz',t=(n,),q=True,ev=True)[0]
motion.append( (curX,curY,curZ) )
return motion
def merge( directionAstart, directionAend, directionBstart, newStart ):
'''merges two different locomotes together - for example N and E to give a NE locomote'''
#determine which ctrl set to use
length = directionAend-directionAstart
ctrlSet = names.matchNames(['body_ctrls'],cmd.ls(type='objectSet'))
if not ctrlSet:
raise Exception('control set not found')
ctrlSet = ctrlSet[0]
ctrls = cmd.sets(ctrlSet,q=True)
#deal with the assets for the new animation
vx = exportManagerCore.ExportManager()
assetA = vx.exists(start=directionAstart,end=directionAend)[0]
assetB = vx.exists(start=directionBstart,end=directionBstart+length)[0]
exportSet = assetA.obj
assetC = vx.exists(start=newStart,end=newStart+length)
if not assetC:
assetC = vx.createAsset(exportSet)
assetC.setAttr('start', newStart)
assetC.setAttr('end', newStart+length)
assetC.setAttr('name', assetA.name + assetB.name)
assetC.setAttr('type', exportManagerCore.ExportComponent.kANIM)
#now start building the animations
animationA = Animation(ctrls,directionAstart,directionAend)
animationB = Animation(ctrls,directionBstart,directionBstart+length)
animationB.offset(-directionBstart+directionAstart)
animationC = animationA+animationB
animationC.offset(newStart)
#grab the list of ctrls we need to actually transform
toFind = ['upperBodyControl','legControl_L','legControl_R']
xformCtrls = [name for name in names.matchNames(toFind,ctrls,parity=True,threshold=0.8) if name != '']
for ctrl in xformCtrls:
motionA = motionList(ctrl,directionAstart,directionAend)
motionB = motionList(ctrl,directionBstart,directionBstart+length)
#make the time zero based
times = [int(time)-newStart for time in animationC[ctrl].get_times(channels=['translateX','translateZ'])]
times.sort()
print times,len(motionA),len(motionB)
for time in times:
print motionA[time],motionB[time]
newPos = vectors.Vector(motionA[time]) + vectors.Vector(motionB[time])
newPos *= 0.70710678118654757 #= math.cos(45degrees)
tx = animationC[ctrl].translateX[time]
tz = animationC[ctrl].translateZ[time]
if tx: tx.keys[0] = newPos.x
if tz: tz.keys[0] = newPos.z
animationC.applyToObjs()
#end | Python |
from filesystem import Path
import os
import sys
import dependencies
import api
import maya
import baseMelUI
import maya.cmds as cmd
def flush():
pluginPaths = map( Path, api.mel.eval( 'getenv MAYA_PLUG_IN_PATH' ).split( ';' ) ) #NOTE: os.environ is different from the getenv call, and getenv isn't available via python... yay!
#before we do anything we need to see if there are any plugins in use that are python scripts - if there are, we need to ask the user to close the scene
#now as you might expect maya is a bit broken here - querying the plugins in use doesn't return reliable information - instead we ask for all loaded
#plugins, to which maya returns a list of extension-less plugin names. We then have to map those names back to disk by searching the plugin path and
#determining whether the plugins are binary or scripted plugins, THEN we need to see which the scripted ones are unloadable.
loadedPluginNames = cmd.pluginInfo( q=True, ls=True ) or []
loadedScriptedPlugins = []
for pluginName in loadedPluginNames:
for p in pluginPaths:
possiblePluginPath = (p / pluginName).setExtension( 'py' )
if possiblePluginPath.exists():
loadedScriptedPlugins.append( possiblePluginPath[-1] )
initialScene = None
for plugin in loadedScriptedPlugins:
if not cmd.pluginInfo( plugin, q=True, uo=True ):
BUTTONS = YES, NO = 'Yes', 'NO'
ret = cmd.confirmDialog( t='Plugins in Use!', m="Your scene has python plugins in use - these need to be unloaded to properly flush.\n\nIs it cool if I close the current scene? I'll prompt to save your scene...\n\nNOTE: No flushing has happened yet!", b=BUTTONS, db=NO )
if ret == NO:
print "!! FLUSH ABORTED !!"
return
initialScene = cmd.file( q=True, sn=True )
#prompt to make new scene if there are unsaved changes...
api.mel.saveChanges( 'file -f -new' )
break
#now unload all scripted plugins
for plugin in loadedScriptedPlugins:
cmd.unloadPlugin( plugin ) #we need to unload the plugin so that it gets reloaded (it was flushed) - it *may* be nessecary to handle the plugin reload here, but we'll see how things go for now
#lastly, close all windows managed by baseMelUI - otherwise callbacks may fail...
for melUI in baseMelUI.BaseMelWindow.IterInstances():
melUI.delete()
#determine the location of maya lib files - we don't want to flush them either
mayaLibPath = Path( maya.__file__ ).up( 2 )
#flush all modules
dependencies.flush( [ mayaLibPath ] )
if initialScene and not cmd.file( q=True, sn=True ):
if Path( initialScene ).exists():
cmd.file( initialScene, o=True )
print "WARNING: You'll need to close and re-open any python based tools that are currently open..."
def reconnect():
#try to import wing
import wingdbstub
wingdbstub.Ensure()
import time
try:
debugger = wingdbstub.debugger
except AttributeError:
print "No debugger found!"
else:
if debugger is not None:
debugger.StopDebug()
time.sleep( 1 )
debugger.StartDebug()
#end
| Python |
from filesystem import Path, PresetManager, Preset, savePreset, readPreset, LOCAL, GLOBAL
import skeletonBuilder
from maya.cmds import *
from baseSkeletonBuilder import SkeletonPart, setupAutoMirror, TOOL_NAME, buildSkeletonPartContainer
from names import camelCaseToNice
import maya.cmds as cmd
import apiExtensions
import filesystem
import inspect
XTN = 'skeleton'
PRESET_MANAGER = PresetManager( TOOL_NAME, XTN )
VERSION = 0
buildSkeletonPartContainer = skeletonBuilder.buildSkeletonPartContainer
SkeletonPart = skeletonBuilder.SkeletonPart
setupAutoMirror = skeletonBuilder.setupAutoMirror
eval = __builtins__[ 'eval' ] #restore python's eval...
class NoPartsError(Exception): pass
def generatePresetContents():
lines = [ 'version=%d' % VERSION ] #always store some sort of versioning variable
hasParts = False
for part in SkeletonPart.IterAllPartsInOrder():
hasParts = True
lines.append( '<part>' )
lines.append( '%s=%s' % (part.__class__.__name__, part.getBuildKwargs()) )
for item in part:
itemParent = listRelatives( item, p=True, pa=True )
if itemParent:
itemParent = itemParent[0]
else:
itemParent = ''
rad = getAttr( '%s.radius' % item )
tx, ty, tz = xform( item, q=True, ws=True, rp=True )
rx, ry, rz = xform( item, q=True, ws=True, ro=True )
#store out the line of attributes to save for the item - NOTE: attributes are currently stored in a way that makes it possible to add/modify the attributes we need serialized reasonably easily...
lines.append( '%s,%s=radius:%s;t:%s,%s,%s;r:%s,%s,%s;' % (item, itemParent, rad, tx, ty, tz, rx, ry, rz) )
lines.append( '</part>' )
if not hasParts:
raise NoPartsError( "No parts found in scene!" )
return '\n'.join( lines )
def writePreset( presetName ):
'''
deals with serializing a skeleton to disk
'''
try:
contents = generatePresetContents()
except NoPartsError:
print "No parts found in the scene!"
return None
return savePreset( LOCAL, skeletonBuilder.TOOL_NAME, presetName, XTN, contents )
def writePresetToFile( presetFilepath ):
try:
contents = generatePresetContents()
except NoPartsError:
print "No parts found in the scene!"
return
Path( presetFilepath ).write( contents )
def loadPreset( presetName ):
p = Preset( LOCAL, skeletonBuilder.TOOL_NAME, presetName, XTN )
if not p.exists():
p = Preset( GLOBAL, skeletonBuilder.TOOL_NAME, presetName, XTN )
assert p.exists(), "Cannot find a %s preset called %s" % (XTN, presetName)
return loadPresetFile( p )
def loadPresetFile( presetFilepath ):
'''
deals with unserializing a skeleton preset definition into the scene
'''
assert presetFilepath.exists(), "No preset file found! %" % presetFilepath
itemRemapDict = {}
partList = []
def cleanUp():
#removes all items built should an exception occur
for partType, partItems in partList:
if partItems:
delete( partItems[0] )
lines = presetFilepath.read()
linesIter = iter( lines )
version = linesIter.next().strip()
try:
for line in linesIter:
line = line.strip()
#blank line? skip...
if not line:
continue
if line == '<part>':
partTypeAndBuildKwargLine = linesIter.next().strip()
toks = partTypeAndBuildKwargLine.split( '=' )
numToks = len( toks )
if numToks == 1:
partType, partBuildKwargs = toks[0], {}
elif numToks == 2:
partType, partBuildKwargs = toks
partBuildKwargs = eval( partBuildKwargs )
partItems = []
partList.append( (partType, partBuildKwargs, partItems) )
while True:
line = linesIter.next().strip()
#blank line? skip...
if not line:
continue
#are we done with the part?
if line == '</part>':
break
itemAndParent, attrInfo = line.split( '=' )
item, parent = itemAndParent.split( ',' )
attrBlocks = attrInfo.split( ';' )
#construct the attr dict
attrDict = {}
for block in attrBlocks:
if not block:
continue
attrName, attrData = block.split( ':' )
attrData = [ d for d in attrData.split( ',' ) if d ]
attrDict[ attrName ] = attrData
#build the actual joint
actualItem = apiExtensions.asMObject( createNode( 'joint', n=item ) )
#insert the item and what it actually maps to in the scene into the itemRemapDict
itemRemapDict[ item ] = actualItem
#finally append to the list of items in this part
partItems.append( (actualItem, parent, attrDict) )
except StopIteration:
cleanUp()
raise IOError( "File is incomplete!" )
except:
cleanUp()
raise
parts = []
for partType, partBuildKwargs, partItems in partList:
items = []
for (actualItem, parent, attrDict) in partItems:
actualParent = itemRemapDict.get( parent, None )
#do parenting if appropriate
if actualParent is not None:
cmd.parent( actualItem, actualParent )
#set the joint size
if 'radius' in attrDict:
size = attrDict[ 'radius' ][0]
setAttr( '%s.radius' % actualItem, float( size ) )
#move to the appropriate position
if 't' in attrDict:
tx, ty, tz = map( float, attrDict[ 't' ] )
move( tx, ty, tz, actualItem, a=True, ws=True, rpr=True )
#rotate appropriately
if 'r' in attrDict:
rx, ry, rz = map( float, attrDict[ 'r' ] )
rotate( rx, ry, rz, actualItem, a=True, ws=True )
#append to the items list - so we can instantiate the part once we've finished building the items
items.append( actualItem )
#instantiate the part and append it to the list of parts created
partClass = SkeletonPart.GetNamedSubclass( partType )
partContainer = buildSkeletonPartContainer( partClass, partBuildKwargs, items )
part = partClass( partContainer )
part.convert( partBuildKwargs )
parts.append( part )
setupAutoMirror()
for part in SkeletonPart.IterAllParts():
part.visualize()
return parts
def listPresets():
return PRESET_MANAGER.listAllPresets( True )
#end
| Python |
from baseSkeletonBuilder import *
class Hand(SkeletonPart):
HAS_PARITY = True
AUTO_NAME = False #this part will handle its own naming...
#odd indices are left sided, even are right sided
FINGER_IDX_NAMES = ( 'Thumb', 'Index', 'Mid', 'Ring', 'Pinky',
'Sixth' 'Seventh', 'Eighth', 'Ninth', 'Tenth' )
PLACER_NAMES = FINGER_IDX_NAMES
def getParity( self ):
'''
the parity of a hand comes from the limb its parented to, not the idx of
the finger part itself...
'''
parent = self.getParent()
try:
#if the parent has parity use it
parentPart = SkeletonPart.InitFromItem( parent )
except SkeletonError:
#otherwise use the instance's index for parity...
return super( self, Hand ).getParity()
return Parity( parentPart.getParity() )
def iterFingerChains( self ):
'''
iterates over each finger chain in the hand - a chain is simply a list of
joint names ordered hierarchically
'''
for base in self.bases:
children = listRelatives( base, ad=True, path=True, type='joint' ) or []
children = [ base ] + sortByHierarchy( children )
yield children
@classmethod
def _build( cls, parent=None, fingerCount=5, fingerJointCount=3, **kw ):
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
parent = getParent( parent )
parentPart = SkeletonPart.InitFromItem( parent )
#try to determine a "parity index" based on the parent part. Ideally we want to inherit the parity of the parent part
#instead of from this part's index
limbIdx = 0
if parentPart.hasParity():
limbIdx = parentPart.getParity()
#if the parent part has no parity, then use the instance's index for parity...
else:
limbIdx = self.getParity()
#for the first two hands this is an empty string - but for each additional hand pair, this is incremented. ie the
#second two hands are called Hand1, the next two hands are called Hand2 etc...
typePairCountStr = str( idx/2 ) if idx > 1 else ''
minPos, maxPos = -cls.PART_SCALE / 25.0, cls.PART_SCALE / 25.0
posRange = float( maxPos - minPos )
allJoints = []
length = partScale / 3 / fingerJointCount
lengthInc = cls.ParityMultiplier( limbIdx ) * (length / fingerJointCount)
limbName = Parity.NAMES[ limbIdx ]
for nameIdx in range( fingerCount ):
fingerName = cls.FINGER_IDX_NAMES[ nameIdx ]
prevParent = parent
for n in range( fingerJointCount ):
j = createJoint( '%s%s_%d%s' % (fingerName, typePairCountStr, n, limbName) )
cmd.parent( j, prevParent, r=True )
move( lengthInc, 0, 0, j, r=True, os=True )
if n == 0:
move( lengthInc, 0, -maxPos + (posRange * nameIdx / (fingerCount - 1)), j, r=True, os=True )
else:
setAttr( '%s.ty' % j, lock=True )
allJoints.append( j )
prevParent = j
return allJoints
def visualize( self ):
scale = self.getActualScale() / 1.5
for base in self.bases:
plane = polyPlane( w=scale, h=scale / 2.0, sx=1, sy=1, ax=(0, 1, 0), cuv=2, ch=False )[ 0 ]
cmd.parent( plane, base, relative=True )
setAttr( '%s.tx' % plane, self.getParityMultiplier() * scale / 2 )
makeIdentity( plane, a=True, t=True )
cmd.parent( listRelatives( plane, shapes=True, pa=True ), base, add=True, shape=True )
delete( plane )
def _align( self, _initialAlign=False ):
parity = self.getParity()
wrist = self.getParent()
parityMult = self.getParityMultiplier()
defactoUpVector = rigUtils.getObjectBasisVectors( wrist )[ 2 ]
for chain in self.iterFingerChains():
upVector = defactoUpVector
#if there are three joints or more in teh chain, try to determine the normal to the plane they live on
if len( chain ) >= 3:
midJoint = chain[ len( chain ) / 2 ]
upVector = getPlaneNormalForObjects( chain[ 0 ], midJoint, chain[ -1 ], defactoUpVector )
#otherwise assume the user has aligned the base joint properly
else:
upVector = rigUtils.getObjectBasisVectors( chain[ 0 ] )[ BONE_ROTATE_AXIS ]
upVector = upVector * parityMult
for n, item in enumerate( chain[ :-1 ] ):
alignAimAtItem( item, chain[ n+1 ], parity, worldUpVector=upVector )
autoAlignItem( chain[ -1 ], parity, worldUpVector=upVector )
#end
| Python |
from vectors import Vector
_MAX_RECURSE = 35
class BinarySearchTree(list):
SORT_DIMENSION = 0
def __init__( self, data ):
list.__init__( self, data )
#sort by the desired dimension
if self.SORT_DIMENSION == 0:
self.sort()
else:
sortDimension = self.SORT_DIMENSION
self.sort( key=lambda v: v[ sortDimension ] )
def getBestRange( self, value, data, breakRange=50 ): #50 is arbitrary, but smaller values than this provide either incremental improvements or possibly even performance degredation
'''
returns a 2-tuple containing minIdx, maxIdx indices into the data list, with the given
value somewhere within the range data[ minIdx:maxIdx ]
breakRange - this is the delta between minIdx and maxIdx at which the iterative searching halts
NOTE: the range returned may not be equal to the breakRange, breakRange is simply the
point at which the search iteration breaks. It is true however that the range returned
will always be greater than breakRange/2
'''
sortDimension = self.SORT_DIMENSION
minIdx = 0
maxIdx = len( data )-1
rng = maxIdx - minIdx
while rng >= breakRange:
half = minIdx + (rng / 2)
halfValue = data[ half ][ sortDimension ]
if halfValue == value: #TODO: see what the cost of this is in the general case...
return half, half
if halfValue <= value:
minIdx = half
else:
maxIdx = half
rng = maxIdx - minIdx
return minIdx, maxIdx
def getWithin( self, theVector, tolerance=1e-6, maxCount=None ):
'''
returns a list of vectors near theVector within a given tolerance - optionally limiting the
number of matches to maxCount
'''
#do some binary culling before beginning the search - the 50 number is arbitrary,
#but values less than that don't lead to significant performance improvements, and
#in fact can lead to performance degredation
minX = theVector[0] - tolerance
maxX = theVector[0] + tolerance
minIdx, maxIdx = self.getBestRange( minX, self )
#see whether we need to find a different value for the maxIdx - it may be appropriate already and if it is save some cycles by skipping the search
if self[ maxIdx ][0] <= maxX:
_x, maxIdx = self.getBestRange( maxX, self[ minIdx: ] )
maxIdx += minIdx #because we searched within self[ minIdx: ] so we need to add minIdx to maxIdx
#we have a good range for appriate x values, now check to see of that subset which y values fit our criteria
matchingY = []
minY = theVector[1] - tolerance
maxY = theVector[1] + tolerance
for i in self[ minIdx:maxIdx ]:
if minY <= i[1] <= maxY:
matchingY.append( i )
#do the same for z
matching = []
minZ = theVector[2] - tolerance
maxZ = theVector[2] + tolerance
for i in matchingY:
if minZ <= i[2] <= maxZ:
matching.append( i )
#now the matching vectors is a list of vectors that fall within the bounding box with length of 2*tolerance.
#we want to reduce this to a list of vectors that fall within the bounding sphere with radius tolerance
inSphere = []
sqTolerance = tolerance**2
for m in matching:
#this is basically inlined code to get the distance between the point we were given, and all the points
#in the matching list so we can return in distance sorted order. inlining the code is faster as is
#comparing the squared distance to the squared tolerance
sqD = (theVector[0] - m[0])**2 + (theVector[1] - m[1])**2 + (theVector[2] - m[2])**2
if sqD <= sqTolerance:
inSphere.append( (sqD, m) )
inSphere.sort()
if maxCount is not None:
inSphere = inSphere[ :maxCount ]
return [ v[1] for v in inSphere ]
def getWithinRatio( self, theVector, ratio=2 ):
global _MAX_RECURSE
tolerance = 1
matching = self.getWithin( theVector, tolerance )
itCount = 0
while not matching:
tolerance *= 1.25
itCount += 1
matching = self.getWithin( theVector, tolerance )
if itCount > _MAX_RECURSE:
return None
closestDist = (theVector - matching[0]).get_magnitude()
if len( matching ) == 1 or not closestDist:
return matching[ :1 ]
return self.getWithin( theVector, closestDist*ratio )
#end
| Python |
from baseRigPrimitive import *
class Head(PrimaryRigPart):
__version__ = 0
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'Head' ), )
CONTROL_NAMES = 'control', 'gimbal', 'neck'
def _build( self, skeletonPart, translateControls=False, **kw ):
return self.doBuild( skeletonPart.head, translateControls=translateControls, **kw )
def doBuild( self, head, neckCount=1, translateControls=False, **kw ):
scale = self.scale
partParent, rootControl = getParentAndRootControl( head )
colour = ColourDesc( 'blue' )
lightBlue = ColourDesc( 'lightblue' )
#build the head controls - we always need them
headControl = buildControl( "headControl", head,
shapeDesc=Shape_Skin( [head] + (listRelatives( head, ad=True, type='joint' ) or []) ),
colour=colour, scale=scale )
headControlSpace = getNodeParent( headControl )
headGimbal = buildControl( "head_gimbalControl", head, shapeDesc=ShapeDesc( None, 'starCircle' ), colour=colour, oriented=False, scale=scale, autoScale=True, parent=headControl, niceName='Head' )
#now find the neck joints
neckJoints = []
curParent = head
for n in range( neckCount ):
curParent = getNodeParent( curParent )
neckJoints.append( curParent )
neckJoints.reverse()
#determine an offset amount for the neck controls based on the geometry skinned to the necks and head joint
neckOffset = AX_Z.asVector() * getAutoOffsetAmount( head, neckJoints )
#build the controls for them
neckControls = []
theParent = partParent
for n, j in enumerate( neckJoints ):
c = buildControl( 'neck_%d_Control' % n, j, PivotModeDesc.BASE, ShapeDesc( 'pin', axis=AX_Z ), colour=lightBlue, scale=scale*1.5, offset=neckOffset, parent=theParent, niceName='Neck %d' % n )
if not translateControls:
attrState( c, 't', *LOCK_HIDE )
theParent = c
neckControls.append( c )
if neckCount == 1:
neckControls[ 0 ] = rename( neckControls[ 0 ], 'neckControl' )
setNiceName( neckControls[ 0 ], 'Neck' )
elif neckCount >= 2:
setNiceName( neckControls[ 0 ], 'Neck Base' )
setNiceName( neckControls[ -1 ], 'Neck End' )
if neckCount:
parent( headControlSpace, neckControls[ -1 ] )
else:
parent( headControlSpace, partParent )
#build space switching
if neckControls:
spaceSwitching.build( headControl,
(neckControls[ 0 ], partParent, rootControl, self.getWorldControl()),
space=headControlSpace, **spaceSwitching.NO_TRANSLATION )
for c in neckControls:
spaceSwitching.build( c,
(partParent, rootControl, self.getWorldControl()),
**spaceSwitching.NO_TRANSLATION )
#add right click menu to turn on the gimbal control
gimbalIdx = Trigger( headControl ).connect( headGimbal )
Trigger.CreateMenu( headControl,
"toggle gimbal control",
"string $shapes[] = `listRelatives -f -s %%%d`;\nint $vis = `getAttr ( $shapes[0] +\".v\" )`;\nfor( $s in $shapes ) setAttr ( $s +\".v\" ) (!$vis);" % gimbalIdx )
#turn unwanted transforms off, so that they are locked, and no longer keyable, and set rotation orders
gimbalShapes = listRelatives( headGimbal, s=True )
for s in gimbalShapes:
setAttr( '%s.v' % s, 0 )
setAttr( '%s.ro' % headControl, 3 )
setAttr( '%s.ro' % headGimbal, 3 )
if not translateControls:
attrState( (headControl, headGimbal), 't', *LOCK_HIDE )
controls = [ headControl, headGimbal ] + neckControls
return controls, ()
#end
| Python |
import cProfile as prof
import pstats
import os
import time
def d_profile(f):
'''
writes out profiling info on the decorated function. the profile results are dumped in a file
called something like "_profile__<moduleName>.<functionName>.txt"
'''
def newFunc( *a, **kw ):
def run(): f( *a, **kw )
baseDir = os.path.split( __file__ )[0]
tmpFile = os.path.join( baseDir, 'profileResults.tmp' )
prof.runctx( 'run()', globals(), locals(), tmpFile )
try:
module = f.__module__
except AttributeError:
module = 'NOMODULE'
dumpFile = os.path.join( baseDir, '_profile__%s.%s.txt' % (module, f.__name__) )
dumpF = file( dumpFile, 'w' )
stats = pstats.Stats( tmpFile )
stats.sort_stats( 'time', 'calls', 'name' )
stats.stream = dumpF
stats.print_stats()
stats.sort_stats( 'cumulative', 'time' )
stats.print_stats()
dumpF.close()
#remove the tmpFile
os.remove( tmpFile )
print 'LOGGED PROFILING STATS TO', dumpFile
newFunc.__name__ = f.__name__
newFunc.__doc__ = f.__doc__
return newFunc
def d_timer(f):
'''
simply reports the time taken by the decorated function
'''
def newFunc( *a, **kw ):
s = time.clock()
ret = f( *a, **kw )
print 'Time Taken by %s: %0.3g' % (f.__name__, time.clock()-s)
return ret
newFunc.__name__ = f.__name__
newFunc.__doc__ = f.__doc__
return newFunc
#end
| Python |
from skinWeightsBase import *
from filesystem import removeDupes
from maya.cmds import *
from binarySearchTree import BinarySearchTree
from mayaDecorators import d_unifyUndo
import maya.cmds as cmd
import api
import apiExtensions
mel = api.mel
iterParents = api.iterParents
VertSkinWeight = MayaVertSkinWeight
def getAllParents( obj ):
allParents = []
parent = [ obj ]
while parent is not None:
allParents.append( parent[ 0 ] )
parent = cmd.listRelatives( parent, p=True, pa=True )
return allParents[ 1: ]
def getDefaultPath():
scenePath = cmd.file(q=True, sn=True)
if not scenePath:
return DEFAULT_PATH
scenePath = Path( scenePath )
scenePath = scenePath.setExtension( EXTENSION )
return scenePath
kAPPEND = 0
kREPLACE = 1
@api.d_showWaitCursor
def saveWeights( geos, filepath=None ):
start = time.clock()
miscData = api.writeExportDict(TOOL_NAME, TOOL_VERSION)
#if filepath is None, then generate a default filepath based on the location of the file
if filepath is None:
filepath = getDefaultPath()
else: filepath = Path(filepath)
geoAndData = {}
skinPercent = cmd.skinPercent
xform = cmd.xform
#define teh data we're gathering
masterJointList = []
weightData = []
#data gathering time!
rigidBindObjects = []
for geo in geos:
skinClusters = cmd.ls( cmd.listHistory( geo ), type='skinCluster' )
if len( skinClusters ) > 1:
api.melWarning("more than one skinCluster found on %s" % geo)
continue
#so the geo isn't skinned in the traditional way - check to see if it is parented to a joint. if so,
#stuff it into the rigid bind list to be dealt with outside this loop, and continue
if not skinClusters:
dealtWith = False
for p in iterParents( geo ):
if cmd.nodeType( p ) == 'joint':
rigidBindObjects.append( (geo, p) )
masterJointList.append( p )
masterJointList = removeDupes( masterJointList )
dealtWith = True
break
if not dealtWith:
msg = "cannot find a skinCluster for %s" % geo
api.melWarning(msg)
continue
skinCluster = skinClusters[ 0 ]
masterJointList += cmd.skinCluster( skinCluster, q=True, inf=True )
masterJointList = removeDupes( masterJointList )
verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True)
for idx, vert in enumerate(verts):
jointList = skinPercent(skinCluster, vert, ib=1e-4, q=True, transform=None)
weightList = skinPercent(skinCluster, vert, ib=1e-4, q=True, value=True)
if jointList is None:
raise SkinWeightException("I can't find any joints - sorry. do you have any post skin cluster history???")
pos = xform(vert, q=True, ws=True, t=True)
vertData = VertSkinWeight( pos )
vertData.populate( geo, idx, [ masterJointList.index( j ) for j in jointList ], weightList )
weightData.append( vertData )
#deal with rigid bind objects
for geo, j in rigidBindObjects:
verts = cmd.ls( cmd.polyListComponentConversion(geo, toVertex=True), fl=True )
for idx, vert in enumerate( verts ):
jIdx = masterJointList.index( j )
pos = xform( vert, q=True, ws=True, t=True )
vertData = VertSkinWeight( pos )
vertData.populate( geo, idx, [jIdx], [1] )
weightData.append( vertData )
#sort the weightData by ascending x values so we can search faster
weightData.sort()
#turn the masterJointList into a dict keyed by index
joints = {}
for n, j in enumerate( masterJointList ):
joints[ n ] = j
#generate joint hierarchy data - so if joints are missing on load we can find the best match
jointHierarchies = {}
for n, j in joints.iteritems():
jointHierarchies[ n ] = getAllParents( j )
toWrite = miscData, joints, jointHierarchies, weightData
filepath = Path( filepath )
filepath.pickle( toWrite, False )
print 'Weights Successfully Saved to %s: time taken %.02f seconds' % (filepath, time.clock()-start)
return filepath
@api.d_progress(t='initializing...', status='initializing...', isInterruptable=True)
@d_unifyUndo
def loadWeights( objects, filepath=None, usePosition=True, tolerance=TOL, axisMult=None, swapParity=True, averageVerts=True, doPreview=False, meshNameRemapDict=None, jointNameRemapDict=None ):
'''
loads weights back on to a model given a file
'''
#nothing to do...
if not objects:
print 'No objects given...'
return
if filepath is None:
filepath = getDefaultPath()
if not filepath.exists():
print 'File does not exist %s' % filepath
return
start = time.clock()
#setup the mappings
VertSkinWeight.MESH_NAME_REMAP_DICT = meshNameRemapDict
VertSkinWeight.JOINT_NAME_REMAP_DICT = jointNameRemapDict
#cache heavily access method objects as locals...
skinPercent = cmd.skinPercent
progressWindow = cmd.progressWindow
xform = cmd.xform
#now get a list of all weight files that are listed on the given objects - and
#then load them one by one and apply them to the appropriate objects
objItemsDict = {}
for obj in objects:
items = [] #this holds the vert list passed in IF any
if obj.find('.') != -1:
items = [obj]
obj = obj.split('.')[0]
try: objItemsDict[obj].extend( items )
except KeyError: objItemsDict[obj] = items
numItems = len(objItemsDict)
curItem = 1
progressWindow(e=True, title='loading weights from file %d items' % numItems)
#load the data from the file
miscData, joints, jointHierarchies, weightData = Path( filepath ).unpickle()
#build the search tree
tree = BinarySearchTree( weightData )
findMethod = tree.getWithin
findMethodKw = { 'tolerance': tolerance }
if averageVerts:
findMethod = tree.getWithinRatio
findMethodKw = { 'ratio': tolerance }
#see if the file versions match
if miscData[ api.kEXPORT_DICT_TOOL_VER ] != TOOL_VERSION:
api.melWarning( "WARNING: the file being loaded was stored from an older version (%d) of the tool - please re-generate the file. Current version is %d." % (miscData[ api.kEXPORT_DICT_TOOL_VER ], TOOL_VERSION) )
#the miscData contains a dictionary with a bunch of data stored from when the weights was saved - do some
#sanity checking to make sure we're not loading weights from some completely different source
curFile = cmd.file(q=True, sn=True)
origFile = miscData['scene']
if curFile != origFile:
api.melWarning('the file these weights were saved in a different file from the current: "%s"' % origFile)
#remap joint names in the saved file to joint names that are in the scene - they may be namespace differences...
missingJoints = set()
for n, j in joints.iteritems():
if not cmd.objExists(j):
#see if the joint with the same leaf name exists in the scene
idxA = j.rfind(':')
idxB = j.rfind('|')
idx = max(idxA, idxB)
if idx != -1:
leafName = j[idx + 1:]
if objExists( leafName ):
joints[n] = leafName
else:
search = cmd.ls('%s*' % leafName, r=True, type='joint')
if search:
joints[n] = search[0]
print '%s remapped to %s' % (j, search[0])
#now that we've remapped joint names, we go through the joints again and remap missing joints to their nearest parent
#joint in the scene - NOTE: this needs to be done after the name remap so that parent joint names have also been remapped
for n, j in joints.iteritems():
if not cmd.objExists(j):
dealtWith = False
for jp in jointHierarchies[n]:
if cmd.objExists( jp ):
joints[n] = jp
dealtWith = True
break
if dealtWith:
print '%s remapped to %s' % (j, jp)
continue
missingJoints.add(n)
#now remove them from the list
[ joints.pop(n) for n in missingJoints ]
#axisMults can be used to alter the positions of verts saved in the weightData array - this is mainly useful for applying
#weights to a mirrored version of a mesh - so weights can be stored on meshA, meshA duplicated to meshB, and then the
#saved weights can be applied to meshB by specifying an axisMult=(-1,1,1) OR axisMult=(-1,)
if axisMult is not None:
for data in weightData:
for n, mult in enumerate(axisMult): data[n] *= mult
#we need to re-sort the weightData as the multiplication could have potentially reversed things... i could probably
#be a bit smarter about when to re-order, but its not a huge hit... so, meh
weightData = sortByIdx(weightData)
#using axisMult for mirroring also often means you want to swap parity tokens on joint names - if so, do that now.
#parity needs to be swapped in both joints and jointHierarchies
if swapParity:
for joint, target in joints.iteritems():
joints[joint] = str( names.Name(target).swap_parity() )
for joint, parents in jointHierarchies.iteritems():
jointHierarchies[joint] = [str( names.Name(p).swap_parity() ) for p in parents]
for geo, items in objItemsDict.iteritems():
#if the geo is None, then check for data in the verts arg - the user may just want weights
#loaded on a specific list of verts - we can get the geo name from those verts
skinCluster = ''
verts = cmd.ls(cmd.polyListComponentConversion(items if items else geo, toVertex=True), fl=True)
#do we have a skinCluster on the geo already? if not, build one
skinCluster = cmd.ls(cmd.listHistory(geo), type='skinCluster')
if not skinCluster:
skinCluster = cmd.skinCluster(geo,joints.values())[0]
verts = cmd.ls(cmd.polyListComponentConversion(geo, toVertex=True), fl=True)
else: skinCluster = skinCluster[0]
#if we're using position, the restore weights path is quite different
vertJointWeightData = []
if usePosition:
progressWindow( e=True, status='searching by position: %s (%d/%d)' % (geo, curItem, numItems), maxValue=len( verts ) )
vCount = -1
for vert in verts:
vCount += 1
pos = Vector( xform(vert, q=True, ws=True, t=True) )
foundVerts = findMethod( pos, **findMethodKw )
#accumulate found verts
jointWeightDict = {}
for v in foundVerts:
for joint, weight in zip( v.joints, v.weights ):
actualJoint = joints[ joint ]
weight += jointWeightDict.get( actualJoint, 0 )
jointWeightDict[ actualJoint ] = weight
#normalize the weights
weightSum = float( sum( jointWeightDict.values() ) )
if weightSum != 1:
for joint, weight in jointWeightDict.iteritems():
jointWeightDict[ joint ] = weight / weightSum
#append the data
vertJointWeightData.append( (vert, jointWeightDict.items()) )
#deal with the progress window - this isn't done EVERY vert because its kinda slow...
if vCount % 50 == 0:
progressWindow( e=True, progress=vCount )
#bail if we've been asked to cancel
if progressWindow( q=True, isCancelled=True ):
progressWindow( ep=True )
return
progressWindow( e=True, status='maya is setting skin weights...' )
setSkinWeights( skinCluster, vertJointWeightData )
#otherwise simply restore by id
else:
progressWindow( e=True, status='searching by vert name: %s (%d/%d)' % (geo, curItem, numItems), maxValue=len( verts ) )
#rearrange the weightData structure so its ordered by vertex name
weightDataById = {}
[ weightDataById.setdefault(i.getVertName(), (i.joints, i.weights)) for i in weightData ]
for vert in verts:
#progressWindow(edit=True, progress=cur / num * 100.0)
#if progressWindow(q=True, isCancelled=True):
#progressWindow(ep=True)
#return
#cur += 1
try:
jointList, weightList = weightDataById[vert]
except KeyError:
#in this case, the vert doesn't exist in teh file...
print '### no point found for %s' % vert
continue
else:
jointList = [ joints[ j ] for j in jointList ]
jointsAndWeights = zip(jointList, weightList)
skinPercent(skinCluster, vert, tv=jointsAndWeights)
#remove unused influences from the skin cluster
cmd.skinCluster( skinCluster, edit=True, removeUnusedInfluence=True )
curItem += 1
end = time.clock()
print 'time for weight load %.02f secs' % (end-start)
import profileDecorators
from maya.OpenMayaAnim import MFnSkinCluster
from maya.OpenMaya import MIntArray, MDagPathArray
#@profileDecorators.d_profile
@d_unifyUndo
def setSkinWeights( skinCluster, vertJointWeightData ):
'''
vertJointWeightData is a list of 2-tuples containing the vertex component name, and a list of 2-tuples
containing the joint name and weight. ie it looks like this:
[ ('someMesh.vtx[0]', [('joint1', 0.25), 'joint2', 0.75)]),
('someMesh.vtx[1]', [('joint1', 0.2), 'joint2', 0.7, 'joint3', 0.1)]),
... ]
'''
#convert the vertex component names into vertex indices
idxJointWeight = []
for vert, jointsAndWeights in vertJointWeightData:
idx = int( vert[ vert.rindex( '[' )+1:-1 ] )
idxJointWeight.append( (idx, jointsAndWeights) )
#get an MObject for the skin cluster node
skinCluster = apiExtensions.asMObject( skinCluster )
skinFn = MFnSkinCluster( skinCluster )
#construct a dict mapping joint names to joint indices
jApiIndices = {}
_tmp = MDagPathArray()
skinFn.influenceObjects( _tmp )
for n in range( _tmp.length() ):
jApiIndices[ str( _tmp[n].node() ) ] = skinFn.indexForInfluenceObject( _tmp[n] )
weightListP = skinFn.findPlug( "weightList" )
weightListObj = weightListP.attribute()
weightsP = skinFn.findPlug( "weights" )
tmpIntArray = MIntArray()
baseFmtStr = str( skinCluster ) +'.weightList[%d]' #pre build this string: fewer string ops == faster-ness!
for vertIdx, jointsAndWeights in idxJointWeight:
#we need to use the api to query the physical indices used
weightsP.selectAncestorLogicalIndex( vertIdx, weightListObj )
weightsP.getExistingArrayAttributeIndices( tmpIntArray )
weightFmtStr = baseFmtStr % vertIdx +'.weights[%d]'
#clear out any existing skin data - and awesomely we cannot do this with the api - so we need to use a weird ass mel command
for n in range( tmpIntArray.length() ):
removeMultiInstance( weightFmtStr % tmpIntArray[n] )
#at this point using the api or mel to set the data is a moot point... we have the strings already so just use mel
for joint, weight in jointsAndWeights:
if weight:
try:
infIdx = jApiIndices[ joint ]
except KeyError:
try:
infIdx = jApiIndices[ joint.split( '|' )[0] ]
except KeyError: continue
setAttr( weightFmtStr % infIdx, weight )
def mirrorWeightsOnSelected( tolerance=TOL ):
selObjs = cmd.ls(sl=True, o=True)
#so first we need to grab the geo to save weights for - we save geo for all objects which have
#verts selected
saveWeights( selObjs, Path('%TEMP%/tmp.weights'), mode=kREPLACE )
loadWeights( cmd.ls(sl=True), Path( '%TEMP%/tmp.weights' ), True, 2, (-1,), True )
def autoSkinToVolumeMesh( mesh, skeletonMeshRoot ):
'''
given a mesh and the root node for a hierarchy mesh volumes, this function will create
a skeleton with the same hierarchy and skin the mesh to this skeleton using the mesh
volumes to determine skin weights
'''
#grab a list of meshes under the hierarchy - we need to grab this geo, parent it to a skeleton and transfer defacto weighting to the given mesh
volumes = listRelatives( skeletonMeshRoot, ad=True, type='mesh', pa=True )
#now generate the skeleton
transforms = removeDupes( listRelatives( volumes, p=True, type='transform', pa=True ) or [] )
jointRemap = {}
for t in transforms:
select( cl=True )
jName = '%s_joint' % t
if objExists( jName ):
jName += '#'
j = joint( n=jName )
jointRemap[ t ] = j
#now do parenting
for t, j in jointRemap.iteritems():
tParent = listRelatives( t, p=True, pa=True )
if tParent:
tParent = tParent[0]
jParent = jointRemap.get( tParent, None )
else:
jParent = None
if jParent is not None:
parent( j, jParent )
#now do positioning
for t in api.sortByHierarchy( transforms ):
j = jointRemap[ t ]
pos = xform( t, q=True, ws=True, rp=True )
move( pos[0], pos[1], pos[2], j, ws=True, rpr=True )
#duplicate the geometry and parent the geo to the joints in the skeleton we just created - store the duplicates so we can delete them later
dupes = []
for t, j in jointRemap.iteritems():
dupe = apiExtensions.asMObject( duplicate( t, returnRootsOnly=True, renameChildren=True )[0] )
children = listRelatives( dupe, type='transform', pa=True ) or []
if children:
delete( children )
parent( dupe, j )
dupes.append( dupe )
f = saveWeights( map( str, dupes ) )
loadWeights( [mesh], f, usePosition=True, tolerance=0.5, averageVerts=True, jointNameRemapDict=jointRemap )
delete( dupes )
return jointRemap
def transferSkinning( sourceMesh, targetMesh ):
sourceSkinCluster = api.mel.findRelatedSkinCluster( sourceMesh )
if not sourceSkinCluster:
raise SkeletonError( "Cannot find a skin cluster on %s" % sourceMesh )
#if there isn't a skin cluster already, create one
targetSkinCluster = api.mel.findRelatedSkinCluster( targetMesh )
if not targetSkinCluster:
influences = skinCluster( sourceSkinCluster, q=True, inf=True )
targetSkinCluster = skinCluster( targetMesh, influences, toSelectedBones=True )[0]
copySkinWeights( sourceSkin=sourceSkinCluster, destinationSkin=targetSkinCluster, noMirror=True, surfaceAssociation='closestPoint', smooth=True )
return targetSkinCluster
#end
| Python |
from baseMelUI import *
from maya.mel import eval as evalMel
from filesystem import Path
from common import printErrorStr
import re
import maya
try:
#try to connect to wing - otherwise don't worry
import wingdbstub
except ImportError: pass
def setupDagProcMenu():
'''
sets up the modifications to the dagProcMenu script
'''
dagMenuScript = r'C:\Program Files\Autodesk\Maya2011\scripts\others\dagMenuProc.mel'
globalProcDefRex = re.compile( "^global +proc +dagMenuProc *\( *string *(\$[a-zA-Z0-9_]+), *string *(\$[a-zA-Z0-9_]+) *\)" )
dagMenuScriptLines = Path( dagMenuScript ).read()
dagMenuScriptLineIter = iter( dagMenuScriptLines )
newLines = []
hasDagMenuProcBeenSetup = False
for line in dagMenuScriptLineIter:
newLines.append( line )
globalProcDefSearch = globalProcDefRex.search( line )
if globalProcDefSearch:
parentVarStr, objectVarStr = globalProcDefSearch.groups()
selHierarchyRex = re.compile( 'uiRes *\( *"m_dagMenuProc.kSelectHierarchy" *\)' )
#menuItem -label (uiRes("m_dagMenuProc.kDagMenuSelectHierarchy")) -c ("select -hierarchy " + $object);
#if we're past the global proc definition for dagMenuProc start looking for the menu item to
for line in dagMenuScriptLineIter:
newLines.append( line )
if 'menuItem' in line and selHierarchyRex.search( line ):
newLines.append( '\t\t\tmenuItem -d 1;' )
newLines.append( '\t\t\tpython( "import triggeredUI" );' )
newLines.append( """\t\t\tint $killState = python( "triggeredUI.buildMenuItems( '"+ %s +"', '"+ %s +"' )" );""" % (parentVarStr, objectVarStr) )
newLines.append( '\t\t\tif( $killState ) return;' )
hasDagMenuProcBeenSetup = True
break
if not hasDagMenuProcBeenSetup:
printErrorStr( "Couldn't auto setup dagMenuProc! AWOOGA!" )
return
newScript = '\n'.join( newLines )
evalMel( newScript )
def setupZooToolBox():
#all the files for zooToolBox should live in the same directory as this script, including plug-ins
thisFile = Path( __file__ )
thisPath = thisFile.up()
existingPlugPathStr = maya.mel.eval( 'getenv MAYA_PLUG_IN_PATH;' )
existingPlugPaths = existingPlugPathStr.split( ';' )
newPlugPaths = []
pathsAlreadyInList = set()
zooPlugPathAdded = False
for path in existingPlugPaths:
path = Path( path )
if path in pathsAlreadyInList:
continue
pathsAlreadyInList.add( path )
newPlugPaths.append( path.unresolved() )
if path == thisPath:
zooPlugPathAdded = True
if not zooPlugPathAdded:
newPlugPaths.append( thisPath )
newPlugPathStr = ';'.join( newPlugPaths )
maya.mel.eval( 'putenv MAYA_PLUG_IN_PATH "%s";' % newPlugPathStr )
#now setup the dagMenuProc
setupDagProcMenu()
def loadZooPlugin( pluginName ):
try:
cmd.loadPlugin( pluginName, quiet=True )
except:
setupZooToolBox()
try:
cmd.loadPlugin( pluginName, quiet=True )
except:
maya.OpenMaya.MGlobal.displayError( 'Failed to load zooMirror.py plugin - is it in your plugin path?' )
def loadSkeletonBuilderUI( *a ):
import skeletonBuilderUI
skeletonBuilderUI.SkeletonBuilderWindow()
def loadSkinPropagation( *a ):
import refPropagation
refPropagation.propagateWeightChangesToModel_confirm()
def loadPicker( *a ):
import picker
picker.PickerWindow()
class ToolCB(object):
def __init__( self, melStr ):
self.cmdStr = melStr
def __call__( self, *a ):
evalMel( self.cmdStr )
#this describes the tools to display in the UI - the nested tuples contain the name of the tool as displayed
#in the UI, and a tuple containing the annotation string and the button press callback to invoke when that
#tool's toolbox button is pressed.
#NOTE: the press callback should take *a as its args
TOOL_CATS = ( ('rigging', (('Skeleton Builder - the new CST', "Skeleton Builder is what zooCST initially set out to be", loadSkeletonBuilderUI),
('Skinning Propagation', "Propagates skinning changes made to referenced geometry to the file it lives in", loadSkinPropagation),
('zooCST', 'The ghetto version of Skeleton Builder', None),
('zooTriggered', 'zooTriggered is one of the most powerful rigging companions around. It allows the rigger to attach name independent MEL commands to an object. These commands can be run either on the selection of the object, or by right clicking over that object.\n\nIt allows context sensitive scripted commands to be added to a character rig, which allows the rigger to create more intuitive rigs. Being able to add name independent MEL scripts to a rig can open up entire new worlds of possibilities, as does selection triggered MEL commands.', None),
#('zooTriggerator', '''zooTriggerator is an interface for building and managing triggered viewport interfaces. It builds collapsible, in-viewport folders that contain selection triggers.\n\nThey can be used to build selection triggers for complex rigs to make an easy to use interface for animators to use.''', None),
('zooKeymaster', 'keymaster gives you a heap of tools to manipulate keyframes - scaling around curve pivots, min/max scaling of curves/keys etc...', ToolCB( 'source zooKeymaster; zooKeymasterWin;' )),
('zooSurgeon', 'zooSurgeon will automatically cut up a skinned mesh and parent the cut up "proxy" objects to the skeleton. This allows for near instant creation of a fast geometrical representation of a character.', None),
('zooVisMan', 'visMan is a tool for creating and using heirarchical visibility sets in your scene. a visibility set holds a collection of items, be it components, objects or anything else that normally fits into a set. the sets can be organised heirarchically, and easily collapsed, and selected in a UI to show only certain objects in your viewports. its great for working with large sets, or breaking a character up into parts to focus on', None))),
('animation', (('zooPicker', 'Picker tool - provides a way to create buttons that select scene objects, or run arbitrary code', loadPicker),
('zooAnimStore', '', None),
('zooXferAnim', 'zooXferAnim is an animation transfer utility. It allows transfer of animation using a variety of different methods, instancing, duplication, copy/paste, import/export and tracing. Its also fully externally scriptable for integration into an existing production pipeline.', None),
('zooGraphFilter', 'zooGraphFilter provides a quick and easy way of filtering out certain channels on many objects in the graph editor.', None),
('zooKeyCommands', 'zooKeyCommands is a simple little tool that lets you run a MEL command on an object for each keyframe the object has. It basically lets you batch a command for each keyframe.', None),
('zooGreaseMonkey', 'zooGreaseMonkey is a neat little script that allows you to draw in your camera viewport. It lets you add as many frames as you want at various times in your scene. You can use it to thumbnail your animation in your viewport, you can use it to plot paths, you could even use it to do a simple 2d based animation if you wanted.', None),
('zooShots', 'zooShots is a camera management tool. It lets you create a bunch of cameras in your scene, and "edit" them together in time. The master camera then cuts between each "shot" camera. All camera attributes are maintained over the cut - focal length, clipping planes, fstop etc...\n\nThe interface allows you to associate notes with each shot, colour shots in the UI to help group like shots, shot numbering etc...', None),
('zooHUDCtrl', 'zooHUDCtrl lets you easily add stuff to your viewport HUD. It supports custom text, filename, current frame, camera information, object attribute values, and if you are using zooShots, it will also print out shot numbers to your HUD.', None))),
('general', (('zooAutoSave', '''zooAutoSave is a tool that will automatically save your scene after a certain number of selections. Maya doesn't provide a timer, so its not possible to write a time based autosave tool, but it makes more sense to save automatically after you've done a certain number of "things". You can easily adjust the threshold, and have the tool automatically start when maya starts if you wish.''', None),
#('zooReblender', '', None),
)),
('hotkeys', (('zooAlign',
'snaps two objects together - first select the master object, then the object you want to snap, then hit the hotkey',
ToolCB( 'zooHotkeyer zooAlign "{zooAlign \"-load 1\";\nstring $sel[] = `ls -sl`;\nfor( $n=1; $n<`size $sel`; $n++ ) zooAlignSimple $sel[0] $sel[$n];}" "" "-default a -alt 1 -enableMods 1 -ann aligns two objects"')),
('zooSetMenu',
'zooSetMenu us a marking menu that lets you quickly interact with all quick selection sets in your scene.',
ToolCB( "zooHotkeyer zooSetMenu \"zooSetMenu;\" \"zooSetMenuKillUI;\" \"-default y -enableMods 0 -ann zooSetMenu lets you quickly interact with selection sets in your scene through a marking menu interface\";" )),
('zooTangentWks',
'zooTangentWks is a marking menu script that provides super fast access to common tangent based operations. Tangent tightening, sharpening, change tangent types, changing default tangents etc...',
ToolCB( "zooHotkeyer zooTangentWks \"zooTangentWks;\" \"zooTangentWksKillUI;\" \"-default q -enableMods 0 -ann tangent works is a marking menu script to speed up working with the graph editor\";" )),
('zooSetkey',
'zooSetKey is a tool designed to replace the set key hotkey. It is a marking menu script that lets you perform a variety of set key based operations - such as push the current key to the next key, perform a euler filter on all selected objects etc...',
ToolCB( "zooHotkeyer zooSetkey \"zooSetkey;\" \"zooSetkeyKillUI;\" \"-default s -enableMods 0 -ann designed to replace the set key hotkey, this marking menu script lets you quickly perform all kinda of set key operations\";" )),
('zooCam',
'zooCam is a marking menu that lets you quickly swap between any camera in your scene. It is integrated tightly with zooShots, so you can quickly navigate between shot cameras, master cameras, or any other in-scene camera.',
ToolCB( "zooHotkeyer zooCam \"zooCam;\" \"zooCamKillUI;\" \"-default l -enableMods 0 -ann zooCam marking menu script for managing in scene cameras\";" )),
('toggle_shading',
'toggles viewport shading',
ToolCB( "zooHotkeyer toggleShading \"zooToggle shading;\" \"\" \"-default 1 -enableMods 1 -ann toggles viewport shading\"" )),
('toggle_texturing',
'toggles viewport texturing',
ToolCB( "zooHotkeyer toggleTexture \"zooToggle texturing;\" \"\" \"-default 2 -enableMods 1 -ann toggles viewport texturing\"" )),
('toggle_lights',
'toggles viewport lighting',
ToolCB( "zooHotkeyer toggleLights \"zooToggle lighting;\" \"\" \"-default 3 -enableMods 1 -ann toggles viewport lighting\"" )))) )
class ToolboxTab(MelColumnLayout):
def __new__( cls, parent, toolTuples ):
return MelColumnLayout.__new__( cls, parent )
def __init__( self, parent, toolTuples ):
MelColumnLayout.__init__( self, parent )
for toolStr, annStr, pressCB in toolTuples:
if pressCB is None:
pressCB = ToolCB( '%s;' % toolStr )
MelButton( self, l=toolStr, ann=annStr, c=pressCB )
class ToolboxTabs(MelTabLayout):
def __init__( self, parent ):
n = 0
for toolCatStr, toolTuples in TOOL_CATS:
ui = ToolboxTab( self, toolTuples )
self.setLabel( n, toolCatStr )
n += 1
class ToolboxWindow(BaseMelWindow):
WINDOW_NAME = 'zooToolBox'
WINDOW_TITLE = 'zooToolBox ::macaroniKazoo::'
DEFAULT_SIZE = 400, 300
FORCE_DEFAULT_SIZE = True
DEFAULT_MENU = None
def __init__( self ):
setupZooToolBox()
ToolboxTabs( self )
self.show()
#end
| Python |
import __future__
from filesystem import *
from vectors import *
import maya.OpenMaya as OpenMaya
import maya.cmds as cmd
import maya.mel
import maya.utils
import names
def getFps():
'''
returns the current fps as a number
'''
timebases = {'ntsc': 30, 'pal': 25, 'film': 24, 'game': 15, 'show': 48, 'palf': 50, 'ntscf': 60}
base = cmd.currentUnit(q=True, time=True)
return timebases[base]
class CmdQueue(list):
'''
the cmdQueue is generally used as a bucket to store a list of maya commands to execute. for whatever
reason executing individual maya commands through python causes each command to get put into the undo
queue - making tool writing a pain. so for scripts that have to execute maya commands one at a time,
consider putting them into a CmdQueue object and executing the object once you're done generating
commands... to execute a CmdQueue instance, simply call it
'''
def __init__( self ):
list.__init__(self)
def __call__( self, echo=False ):
m = mel
if echo:
m = melecho
fp = Path( "%TEMP%/cmdQueue.mel" )
f = open( fp, 'w' )
f.writelines( '%s;\n' % l for l in self )
f.close()
print fp
m.source( fp )
ui_BUTTONS = OK, CANCEL = 'OK', 'Cancel'
ui_QUESTION = YES, NO = 'Yes', 'No'
def doPrompt( **kwargs ):
'''
does a prompt dialog (all args are passed directly to the dial creation method) and returns a 2 tuple of the dial dismiss
string and the actual input value
'''
kwargs.setdefault('t', 'enter name')
kwargs.setdefault('m', 'enter name')
kwargs.setdefault('b', ui_BUTTONS)
#set the default button - buttons is always an iterable, so use the first item
kwargs.setdefault('db', kwargs['b'][0])
#throw up the dial
ans = cmd.promptDialog(**kwargs)
return ans, cmd.promptDialog(q=True, tx=True)
#there are here to follow the convention specified in the filesystem writeExportDict method
kEXPORT_DICT_SCENE = 'scene'
kEXPORT_DICT_APP_VERSION = 'app_version'
def writeExportDict( toolName=None, toolVersion=None, **kwargs ):
'''
wraps the filesystem method of the same name - and populates the dict with maya
specific data
'''
d = writeExportDict( toolName, toolVersion, **kwargs )
d[ kEXPORT_DICT_SCENE ] = cmd.file( q=True, sn=True )
d[ kEXPORT_DICT_APP_VERSION ] = cmd.about( version=True )
return d
def referenceFile( filepath, namespace, silent=False ):
filepath = Path( filepath )
cmd.file( filepath, r=True, prompt=silent, namespace=namespace )
def openFile( filepath, silent=False ):
filepath = Path( filepath )
ext = filepath.getExtension().lower()
if ext == 'ma' or ext == 'mb':
mel.saveChanges( 'file -f -prompt %d -o "%s"' % (silent, filepath) )
mel.addRecentFile( filepath, 'mayaAscii' if Path( filepath ).hasExtension( 'ma' ) else 'mayaBinary' )
def importFile( filepath, silent=False ):
filepath = Path( filepath )
ext = filepath.getExtension().lower()
if ext == 'ma' or ext == 'mb':
cmd.file( filepath, i=True, prompt=silent, rpr='__', type='mayaAscii', pr=True, loadReferenceDepth='all' )
def addExploreToMenuItems( filepath ):
if filepath is None:
return
filepath = Path( filepath )
if not filepath.exists():
filepath = filepath.getClosestExisting()
if filepath is None:
return
cmd.menuItem(l="Explore to location...", c=lambda x: mel.zooExploreTo( filepath ), ann='open an explorer window to the location of this file/directory')
cmd.menuItem(l="CMD prompt to location...", c=lambda x: mel.zooCmdTo( filepath ), ann='open a command prompt to the location of this directory')
#end | Python |
from baseMelUI import *
from apiExtensions import iterParents
from melUtils import mel, melecho
import maya.cmds as cmd
import mappingEditor
import mappingUtils
import xferAnim
import animLib
__author__ = 'mel@macaronikazoo.com'
class XferAnimForm(MelVSingleStretchLayout):
def __init__( self, parent ):
MelVSingleStretchLayout.__init__( self, parent )
self.sortBySrcs = True #otherwise it sorts by tgts when doing traces
self._clipPreset = None
self.UI_mapping = mappingEditor.MappingForm( self )
self.UI_options = MelFrameLayout( self, l="xfer options", labelVisible=True, collapsable=False, collapse=False, h=115, borderStyle='etchedIn' ) #need to specify the height for 2011 coz its ghey!
hLayout = MelHLayout( self.UI_options )
colLayout = MelColumnLayout( hLayout )
self.UI_radios = MelRadioCollection()
self.RAD_dupe = self.UI_radios.createButton( colLayout, l="duplicate nodes", align='left', sl=True, cc=self.on_update )
self.RAD_copy = self.UI_radios.createButton( colLayout, l="copy/paste keys", align='left', cc=self.on_update )
self.RAD_trace = self.UI_radios.createButton( colLayout, l="trace objects", align='left', cc=self.on_update )
colLayout = MelColumnLayout( hLayout )
self.UI_check1 = MelCheckBox( colLayout, l="instance animation" )
self.UI_check2 = MelCheckBox( colLayout, l="match rotate order", v=1 )
self.UI_check3 = MelCheckBox( colLayout, l="", vis=0, v=0 )
self.UI_check4 = MelCheckBox( colLayout, l="", vis=0, v=1 )
hLayout.layout()
hLayout = MelHLayout( self.UI_options )
self.UI_keysOnly = MelCheckBox( hLayout, l="keys only", v=0, cc=self.on_update )
self.UI_withinRange = MelCheckBox( hLayout, l="within range:", v=0, cc=self.on_update )
MelLabel( hLayout, l="start ->" )
self.UI_start = MelTextField( hLayout, en=0, tx='!' )
cmd.popupMenu( p=self.UI_start, b=3, pmc=self.buildTimeMenu )
MelLabel( hLayout, l="end ->" )
self.UI_end = MelTextField( hLayout, en=0, tx='!' )
cmd.popupMenu( p=self.UI_end, b=3, pmc=self.buildTimeMenu )
UI_button = cmd.button( self, l='Xfer Animation', c=self.on_xfer )
self.setStretchWidget( self.UI_mapping )
self.layout()
self.on_update() #set initial state
def isTraceMode( self, theMode ):
m = self.UI_radios.getSelected()
return theMode.endswith( '|'+ m )
def setMapping( self, mapping ):
self.UI_mapping.setMapping( mapping )
def setClipPreset( self, clipPreset, mapping=None ):
self._clipPreset = clipPreset
#setup the file specific UI
fileDict = clipPreset.unpickle()
add = False
delta = fileDict[ animLib.kEXPORT_DICT_CLIP_TYPE ] == animLib.kDELTA
world = fileDict.get( animLib.kEXPORT_DICT_WORLDSPACE, False )
nocreate = False
#populate the source objects from the file
self.UI_mapping.replaceSrcItems( fileDict[ animLib.kEXPORT_DICT_OBJECTS ] )
self.UI_options( e=True, l="import options" )
cmd.radioButton( self.RAD_dupe, e=True, en=True, sl=True, l="absolute times" )
cmd.radioButton( self.RAD_copy, e=True, en=True, l="current time offset" )
cmd.radioButton( self.RAD_trace, e=True, en=False, vis=False, l="current time offset" )
cmd.checkBox( self.UI_check1, e=True, l="additive key values", vis=True, v=add )
cmd.checkBox( self.UI_check2, e=True, l="match rotate order", vis=True, v=0 )
cmd.checkBox( self.UI_check3, e=True, l="import as world space", vis=True, v=world )
cmd.checkBox( self.UI_check4, e=True, l="don't create new keys", vis=True, v=nocreate )
self.on_update()
### MENU BUILDERS ###
def buildTimeMenu( self, parent, uiItem ):
cmd.menu( parent, e=True, dai=True )
cmd.setParent( parent, m=True )
cmd.menuItem( l="! - use current range", c=lambda a: cmd.textField( uiItem, e=True, tx='!' ) )
cmd.menuItem( l=". - use current frame", c=lambda a: cmd.textField( uiItem, e=True, tx='.' ) )
cmd.menuItem( l="$ - use scene range", c=lambda a: cmd.textField( uiItem, e=True, tx='$' ) )
### EVENT HANDLERS ###
def on_update( self, *a ):
sel = cmd.ls( sl=True, dep=True )
if not self._clipPreset is not None:
if self.isTraceMode( self.RAD_dupe ):
cmd.checkBox( self.UI_check1, e=True, en=True )
else:
cmd.checkBox( self.UI_check1, e=True, en=False, v=0 )
if self.isTraceMode( self.RAD_trace ):
cmd.checkBox( self.UI_keysOnly, e=True, en=True )
cmd.checkBox( self.UI_check2, e=True, v=0 )
cmd.checkBox( self.UI_check3, e=True, vis=1, v=1, l="process post-trace cmds" )
else:
cmd.checkBox( self.UI_keysOnly, e=True, en=False, v=0 )
cmd.checkBox( self.UI_check3, e=True, vis=0, v=0 )
if cmd.checkBox( self.UI_keysOnly, q=True, v=True ):
cmd.checkBox( self.UI_withinRange, e=True, en=1 )
else:
cmd.checkBox( self.UI_withinRange, e=True, en=0, v=0 )
enableRange = self.isTraceMode( self.RAD_copy ) or self.isTraceMode( self.RAD_trace )
keysOnly = cmd.checkBox( self.UI_keysOnly, q=True, v=True )
withinRange = cmd.checkBox( self.UI_withinRange, q=True, v=True )
if enableRange and not keysOnly or withinRange:
cmd.textField( self.UI_start, e=True, en=True )
cmd.textField( self.UI_end, e=True, en=True )
else:
cmd.textField( self.UI_start, e=True, en=False )
cmd.textField( self.UI_end, e=True, en=False )
def on_xfer( self, *a ):
mapping = mappingUtils.resolveMappingToScene( self.UI_mapping.getMapping() )
theSrcs = []
theTgts = []
#perform the hierarchy sort
idx = 0 if self.sortBySrcs else 1
toSort = [ (len(list(iterParents( srcAndTgt[ idx ] ))), srcAndTgt) for srcAndTgt in mapping.iteritems() if cmd.objExists( srcAndTgt[ idx ] ) ]
toSort.sort()
for idx, (src, tgt) in toSort:
theSrcs.append( src )
theTgts.append( tgt )
offset = ''
isDupe = self.isTraceMode( self.RAD_dupe )
isCopy = self.isTraceMode( self.RAD_copy )
isTraced = self.isTraceMode( self.RAD_trace )
instance = cmd.checkBox( self.UI_check1, q=True, v=True )
traceKeys = cmd.checkBox( self.UI_keysOnly, q=True, v=True )
matchRo = cmd.checkBox( self.UI_check2, q=True, v=True )
startTime = cmd.textField( self.UI_start, q=True, tx=True )
endTime = cmd.textField( self.UI_end, q=True, tx=True )
world = processPostCmds = cmd.checkBox( self.UI_check3, q=True, v=True ) #this is also "process trace cmds"
nocreate = cmd.checkBox( self.UI_check4, q=True, v=True )
if startTime.isdigit():
startTime = int( startTime )
else:
if startTime == '!': startTime = cmd.playbackOptions( q=True, min=True )
elif startTime == '.': startTime = cmd.currentTime( q=True )
elif startTime == '$': startTime = cmd.playbackOptions( q=True, animationStartTime=True )
if endTime.isdigit():
endTime = int( endTime )
else:
if endTime == '!': endTime = cmd.playbackOptions( q=True, max=True )
elif endTime == '.': endTime = cmd.currentTime( q=True )
elif endTime == '$': endTime = cmd.playbackOptions( q=True, animationEndTime=True )
withinRange = cmd.checkBox( self.UI_withinRange, q=True, v=True )
if withinRange:
traceKeys = 2
if isCopy:
offset = "*"
if self._clipPreset is not None:
#convert to mapping as expected by animLib... this is messy!
animLibMapping = {}
for src, tgts in mapping.iteritems():
animLibMapping[ src ] = tgts[ 0 ]
self._clipPreset.asClip().apply( animLibMapping )
elif isDupe:
melecho.zooXferBatch( "-mode 0 -instance %d -matchRo %d" % (instance, matchRo), theSrcs, theTgts )
elif isCopy:
melecho.zooXferBatch( "-mode 1 -range %s %s -matchRo %d" % (startTime, endTime, matchRo), theSrcs, theTgts )
elif isTraced:
xferAnim.trace( theSrcs, theTgts, traceKeys, matchRo, processPostCmds, True, startTime, endTime )
class XferAnimWindow(BaseMelWindow):
WINDOW_NAME = 'xferAnim'
WINDOW_TITLE = 'Xfer Anim'
DEFAULT_SIZE = 350, 450
DEFAULT_MENU = 'Tools'
def __init__( self, mapping=None, clipPreset=None ):
BaseMelWindow.__init__( self )
self.editor = XferAnimForm( self )
if mapping is not None:
self.editor.setMapping( mapping )
if clipPreset is not None:
self.editor.setClipPreset( clipPreset )
self.show()
#end
| Python |
try:
import wingdbstub
except ImportError: pass
from filesystem import Path
from unittest import TestCase, TestResult
from maya import cmds as cmd
import sys
import inspect
### POPULATE THE LIST OF TEST SCRIPTS ###
TEST_SCRIPTS = {}
def populateTestScripts():
global TEST_SCRIPTS
thisScriptDir = Path( __file__ ).up()
pathsToSearch = sys.path[:] + [ thisScriptDir ]
for pyPath in pathsToSearch:
pyPath = Path( pyPath )
if pyPath.isDir():
for f in pyPath.files():
if f.hasExtension( 'py' ):
if f.name().startswith( 'devTest_' ):
TEST_SCRIPTS[ f ] = []
populateTestScripts()
### POPULATE TEST_CASES ###
TEST_CASES = []
def populateTestCases():
global TEST_CASES
for script in TEST_SCRIPTS:
testModule = __import__( script.name() )
scriptTestCases = TEST_SCRIPTS[ script ] = []
for name, obj in testModule.__dict__.iteritems():
if obj is TestCase:
continue
if isinstance( obj, type ):
if issubclass( obj, TestCase ):
if obj.__name__.startswith( '_' ):
continue
TEST_CASES.append( obj )
scriptTestCases.append( obj )
populateTestCases()
def runTestCases( testCases=TEST_CASES ):
thisPath = Path( __file__ ).up()
testResults = TestResult()
reloadedTestCases = []
for test in testCases:
#find the module the test comes from
module = inspect.getmodule( test )
performReload = getattr( module, 'PERFORM_RELOAD', True )
#reload the module the test comes from
if performReload:
module = reload( module )
#find the test object inside the newly re-loaded module and append it to the reloaded tests list
reloadedTestCases.append( getattr( module, test.__name__ ) )
for ATestCase in reloadedTestCases:
testCase = ATestCase()
testCase.run( testResults )
#force a new scene
cmd.file( new=True, f=True )
OK = 'Ok'
BUTTONS = (OK,)
if testResults.errors:
print '------------- THE FOLLOWING ERRORS OCCURRED -------------'
for error in testResults.errors:
print error[0]
print error[1]
print '--------------------------'
cmd.confirmDialog( t='TEST ERRORS OCCURRED!', m='Errors occurred running the tests - see the script editor for details!', b=BUTTONS, db=OK )
else:
print '------------- %d TESTS WERE RUN SUCCESSFULLY -------------' % len( testCases )
cmd.confirmDialog( t='SUCCESS!', m='All tests were successful!', b=BUTTONS, db=OK )
return testResults
#end
| Python |
'''
Referencing in maya kinda sucks. Getting reference information from nodes/files is split across at least
3 different mel commands in typically awkward autodesk fashion, and there is a bunch of miscellaneous
functionality that just doesn't exist at all. So this module is supposed to be a collection of
functionality that alleviates this somewhat...
'''
from maya.cmds import *
from filesystem import Path
def isFileReferenced( filepath ):
return ReferencedFile.IsFilepathReferenced( filepath )
def stripNamespaceFromNamePath( name, namespace ):
'''
strips out the given namespace from a given name path.
example:
stripNamespaceFromNamePath( 'moar:ns:wow:some|moar:ns:wow:name|moar:ns:wow:path', 'ns' )
returns:
'wow:some|wow:name|wow:path'
'''
if namespace.endswith( ':' ):
namespace = namespace[ :-1 ]
cleanPathToks = []
for pathTok in name.split( '|' ):
namespaceToks = pathTok.split( ':' )
if namespace in namespaceToks:
idx = namespaceToks.index( namespace )
namespaceToks = namespaceToks[ idx+1: ]
cleanPathToks.append( ':'.join( namespaceToks ) )
return '|'.join( cleanPathToks )
def addNamespaceTokNamePath( name, namespace ):
'''
adds the given namespace to a name path.
example:
addNamespaceTokNamePath( 'some|name|path', 'ns' )
returns:
'ns:some|ns:name|ns:path'
'''
if namespace.endswith( ':' ):
namespace = namespace[ :-1 ]
namespacedToks = []
for pathTok in name.split( name, '|' ):
namespacedToks.append( '%s:%s' % (namespace, name) )
return '|'.join( namespacedToks )
class ReferencedFile(object):
@classmethod
def IterAll( cls ):
for referenceNode in ls( type='reference' ):
try:
referenceFilepath = Path( referenceQuery( referenceNode, filename=True ) )
#maya throws an exception on "shared" references - whatever the F they are. so catch and skip when this happens
except RuntimeError: continue
yield referenceFilepath
@classmethod
def IsFilepathReferenced( cls, filepath ):
for refFilepath in cls.IterAll():
if refFilepath == filepath:
return True
return False
def __init__( self, filepath ):
self._filepath = filepath
def getReferenceNode( self ):
return file( self._filepath, q=True, referenceNode=True )
def getReferenceNamespace( self ):
'''
returns the namespace for this reference - this doesn't include referenced namespaces if this reference is nested
'''
return file( self._filepath, q=True, namespace=True )
def isNested( self ):
'''
returns whether this reference is nested
'''
return referenceQuery( self.getReferenceNode(), inr=True )
def load( self ):
raise NotImplemented
def unload( self ):
raise NotImplemented
class ReferencedNode(object):
def __init__( self, node ):
self._node = node
self._isReferenced = referenceQuery( node, inr=True )
def isReferenced( self ):
return self._isReferenced
def getFilepath( self, copyNumber=False ):
'''
will return the filepath to the scene file this node comes from. If copyNumber=True then the "copy number" will
be included in the filepath - see the docs for the referenceQuery mel command for more information
'''
if not self._isReferenced:
return None
return Path( referenceQuery( self._node, filename=True, withoutCopyNumber=not copyNumber ) )
def getReferencedFile( self, copyNumber=False ):
return ReferencedFile( self.getFilepath() )
def getReferenceNode( self ):
if not self._isReferenced:
return None
return file( self.getFilepath(), q=True, referenceNode=True )
def getNamespace( self ):
raise NotImplemented
def getReferenceNamespace( self ):
'''
returns the namespace for this reference - this doesn't include referenced namespaces if this reference is nested
'''
return file( self.getFilepath( True ), q=True, namespace=True )
def getNode( self ):
return self._node
def getUnreferencedNode( self ):
'''
returns the node name as it would be in the scene the node comes from
'''
refNode = self.getReferenceNode()
return stripNamespaceFromNamePath( self._node, self.getReferenceNamespace() )
def removeEdits( self ):
raise NotImplemented
#end
| Python |
from rigPrim_ikFkBase import *
from rigPrim_stretchy import StretchRig
class QuadrupedIkFkLeg(IkFkBase):
__version__ = 0
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'QuadrupedFrontLeg' ), SkeletonPart.GetNamedSubclass( 'QuadrupedBackLeg' ) )
CONTROL_NAMES = 'control', 'poleControl', 'clavicle'
DISPLAY_NAME = 'Quadruped Leg'
def _build( self, skeletonPart, **kw ):
#this bit of zaniness is so we don't have to call the items by name, which makes it work with Arm or Leg skeleton primitives
items = list( skeletonPart )[ :3 ]
if len( skeletonPart ) == 4:
items = list( skeletonPart )[ 1:4 ]
items.append( skeletonPart[ 0 ] )
return self.doBuild( *items, **kw )
def doBuild( self, thigh, knee, ankle, clavicle, **kw ):
idx = kw[ 'idx' ]
scale = kw[ 'scale' ]
parity = Parity( idx )
parityMult = parity.asMultiplier()
nameMod = kw.get( 'nameMod', 'front' )
nameSuffix = '%s%s' % (nameMod.capitalize(), parity.asName())
colour = self.getParityColour()
#determine the root
partParent, rootControl = getParentAndRootControl( clavicle )
#build out the control for the clavicle
clavCtrl = buildControl( 'quadClavicle%s' % nameSuffix,
PlaceDesc( clavicle ),
PivotModeDesc.BASE,
ShapeDesc( 'cylinder', axis=-AIM_AXIS if parity else AIM_AXIS ),
colour, scale=scale )
clavCtrlSpace = getNodeParent( clavCtrl )
setAttr( '%s.rotateOrder' % clavCtrl, 1 )
cmd.parent( clavCtrlSpace, partParent )
#build the leg rig primitive
self.buildBase( LEG_NAMING_SCHEME )
legCtrl = self.control
legFkSpace = self.fkSpace
parent( legFkSpace, clavCtrl )
poleSpace = getNodeParent( self.poleControl )
pointConstraint( legFkSpace, legCtrl, poleSpace )
### SETUP CLAVICLE AIM ###
dummyGrp = group( em=True )
delete( pointConstraint( clavicle, dummyGrp ) )
parent( dummyGrp, rootControl )
aimVector = BONE_AIM_VECTOR * parityMult
sideClavAxis = getObjectAxisInDirection( clavCtrlSpace, BONE_AIM_VECTOR ).asVector()
sideCtrlAxis = getObjectAxisInDirection( legCtrl, BONE_AIM_VECTOR ).asVector()
aim = aimConstraint( legCtrl, clavCtrlSpace, aimVector=BONE_AIM_VECTOR, upVector=sideClavAxis, worldUpVector=sideCtrlAxis, worldUpObject=legCtrl, worldUpType='objectrotation', mo=True )[ 0 ]
aimNode = aimConstraint( dummyGrp, clavCtrlSpace, weight=0, aimVector=BONE_AIM_VECTOR )[ 0 ]
revNode = createNode( 'reverse' )
addAttr( clavCtrl, ln='autoMotion', at='float', min=0, max=1, dv=1 )
setAttr( '%s.autoMotion' % clavCtrl, keyable=True )
connectAttr( '%s.autoMotion' % clavCtrl, '%s.target[0].targetWeight' % aimNode, f=True )
connectAttr( '%s.autoMotion' % clavCtrl, '%s.inputX' % revNode, f=True )
connectAttr( '%s.outputX' % revNode, '%s.target[1].targetWeight' % aimNode, f=True )
### HOOK UP A FADE FOR THE AIM OFFSET
mt, measure, la, lb = buildMeasure( str( clavCtrlSpace ), str( legCtrl ) )
maxLen = chainLength( clavicle, ankle )
curLen = getAttr( '%s.distance' % measure )
cmd.parent( la, rootControl )
cmd.parent( mt, rootControl )
for c in [ mt, la, lb ]:
setAttr( '%s.v' % c, False )
setAttr( '%s.v' % c, lock=True )
controls = legCtrl, self.poleControl, clavCtrl
return controls, ()
def duplicateChain( start, end ):
chainNodes = getChain( start, end )
dupeJoints = []
for j in chainNodes:
dupe = duplicate( j, rr=True )[0]
children = listRelatives( dupe, pa=True )
if children:
delete( children )
if dupeJoints:
parent( dupe, dupeJoints[-1] )
dupeJoints.append( dupe )
return dupeJoints
class SatyrLeg(PrimaryRigPart, SwitchableMixin):
__version__ = 0
SKELETON_PRIM_ASSOC = ( SkeletonPart.GetNamedSubclass( 'SatyrLeg' ), )
CONTROL_NAMES = 'control', 'poleControl', 'anklePoleControl'
NAMED_NODE_NAMES = 'ikSpace', 'fkSpace', 'ikHandle', 'poleTrigger'
DISPLAY_NAME = 'Satyr Leg Rig'
def getFkJoints( self ):
part = self.getSkeletonPart()
return part[ :4 ]
def getFkControls( self ):
allControls = list( self )
return allControls[ -4: ]
@d_unifyUndo
def switchToFk( self ):
fkJoints = self.getFkJoints()
fkControls = self.getFkControls()
for j, c in zip( fkJoints, fkControls ):
alignFast( c, j )
control = self.getControl( 'control' )
setAttr( '%s.ikBlend' % control, 0 )
select( fkControls[-1] )
@d_unifyUndo
def switchToIk( self ):
fkJoints = self.getFkJoints()
control = self.getControl( 'control' )
poleControl = self.getControl( 'poleControl' )
anklePoleControl = self.getControl( 'anklePoleControl' )
polePos = findPolePosition( fkJoints[2], fkJoints[1], fkJoints[0] )
move( polePos[0], polePos[1], polePos[2], poleControl, ws=True, a=True, rpr=True )
alignFast( control, fkJoints[-1] )
alignFast( anklePoleControl, fkJoints[-2] )
setAttr( '%s.ikBlend' % control, 1 )
select( control )
def _build( self, skeletonPart, stretchy=True, **kw ):
scale = kw[ 'scale' ]
parity = self.getParity()
parityMult = parity.asMultiplier()
nameMod = kw.get( 'nameMod', 'front' )
nameSuffix = '_%s%s' % (nameMod.capitalize(), parity.asName())
colour = self.getParityColour()
originalJoints = originalThighJoint, originalKneeJoint, originalAnkleJoint, originalToeJoint = skeletonPart[:4]
getWristToWorldRotation( originalToeJoint, True )
#create a duplicate chain for the ik leg - later we create another chain for fk and constrain the original joints between them for ik/fk switching
ikJoints = ikThighJoint, ikKneeJoint, ikAnkleJoint, ikToeJoint = duplicateChain( originalThighJoint, originalToeJoint )
### IK CHAIN SETUP
#determine the root
partParent, rootControl = getParentAndRootControl( ikThighJoint )
parent( ikThighJoint, partParent )
setAttr( '%s.v' % ikThighJoint, 0 )
ikHandle = cmd.ikHandle( fs=1, sj=ikThighJoint, ee=ikAnkleJoint, solver='ikRPsolver' )[ 0 ]
footCtrl = buildControl( 'Foot%s' % nameSuffix,
#PlaceDesc( ikToeJoint, PlaceDesc.WORLD ),
ikToeJoint,
PivotModeDesc.MID,
ShapeDesc( 'cube', axis=-AIM_AXIS if parity else AIM_AXIS ),
colour, scale=scale )
footCtrlSpace = getNodeParent( footCtrl )
setAttr( '%s.rotateOrder' % footCtrl, 1 )
setAttr( '%s.v' % ikHandle, 0 )
attrState( ikHandle, 'v', *LOCK_HIDE )
#build the pivots for the foot roll/rock attributes
placers = skeletonPart.getPlacers()
if placers:
footRock_fwd = buildNullControl( 'footRock_forward_null', placers[0], parent=footCtrl )
footRock_back = buildNullControl( 'footRock_backward_null', placers[1], parent=footRock_fwd )
footRoll_inner = buildNullControl( 'footRoll_inner_null', placers[2], parent=footRock_back )
footRoll_outer = buildNullControl( 'footRoll_outer_null', placers[3], parent=footRoll_inner )
else:
footRock_fwd = buildNullControl( 'footRock_forward_null', ikToeJoint, parent=footCtrlSpace )
footRock_back = buildNullControl( 'footRock_backward_null', ikToeJoint, parent=footCtrlSpace )
footRoll_inner = buildNullControl( 'footRoll_inner_null', ikToeJoint, parent=footCtrlSpace )
footRoll_outer = buildNullControl( 'footRoll_outer_null', ikToeJoint, parent=footCtrlSpace )
toePos = xform( ikToeJoint, q=True, ws=True, rp=True )
moveIncrement = scale / 2
move( 0, -toePos[1], moveIncrement, footRock_fwd, r=True, ws=True )
move( 0, -toePos[1], -moveIncrement, footRock_back, r=True, ws=True )
move( -moveIncrement * parityMult, -toePos[1], 0, footRoll_inner, r=True, ws=True )
move( moveIncrement * parityMult, -toePos[1], 0, footRoll_outer, r=True, ws=True )
cmd.parent( footRock_back, footRock_fwd )
cmd.parent( footRoll_inner, footRock_back )
cmd.parent( footRoll_outer, footRoll_inner )
cmd.parent( footCtrl, footRoll_outer )
makeIdentity( footCtrl, a=True, t=True )
addAttr( footCtrl, ln='footRock', at='double', dv=0, min=-10, max=10 )
attrState( footCtrl, 'footRock', *NORMAL )
setDrivenKeyframe( '%s.rx' % footRock_fwd, cd='%s.footRock' % footCtrl, dv=0, v=0 )
setDrivenKeyframe( '%s.rx' % footRock_fwd, cd='%s.footRock' % footCtrl, dv=10, v=90 )
setDrivenKeyframe( '%s.rx' % footRock_back, cd='%s.footRock' % footCtrl, dv=0, v=0 )
setDrivenKeyframe( '%s.rx' % footRock_back, cd='%s.footRock' % footCtrl, dv=-10, v=-90 )
addAttr( footCtrl, ln='bank', at='double', dv=0, min=-10, max=10 )
attrState( footCtrl, 'bank', *NORMAL )
setDrivenKeyframe( '%s.rz' % footRoll_inner, cd='%s.bank' % footCtrl, dv=0, v=0 )
setDrivenKeyframe( '%s.rz' % footRoll_inner, cd='%s.bank' % footCtrl, dv=10, v=90 )
setDrivenKeyframe( '%s.rz' % footRoll_outer, cd='%s.bank' % footCtrl, dv=0, v=0 )
setDrivenKeyframe( '%s.rz' % footRoll_outer, cd='%s.bank' % footCtrl, dv=-10, v=-90 )
#setup the auto ankle
grpA = buildControl( 'ankle_auto_null', PlaceDesc( ikToeJoint, ikAnkleJoint ), shapeDesc=SHAPE_NULL, constrain=False, parent=footCtrl )
grpB = buildAlignedNull( ikAnkleJoint, 'ankle_orientation_null', parent=grpA )
orientConstraint( grpB, ikAnkleJoint )
for ax in AXES:
delete( '%s.t%s' % (ikToeJoint, ax), icn=True )
cmd.parent( ikHandle, grpA )
cmd.parent( footCtrlSpace, self.getWorldControl() )
grpASpace = getNodeParent( grpA )
grpAAutoNull = buildAlignedNull( PlaceDesc( ikToeJoint, ikAnkleJoint ), '%sauto_on_ankle_null%s' % (nameMod, nameSuffix), parent=footCtrl )
grpAAutoOffNull = buildAlignedNull( PlaceDesc( ikToeJoint, ikAnkleJoint ), '%sauto_off_ankle_null%s' % (nameMod, nameSuffix), parent=footCtrl )
grpA_knee_aimVector = betweenVector( grpAAutoNull, ikKneeJoint )
grpA_knee_aimAxis = getObjectAxisInDirection( grpAAutoNull, grpA_knee_aimVector )
grpA_knee_upAxis = getObjectAxisInDirection( grpAAutoNull, (1, 0, 0) )
grpA_knee_worldAxis = getObjectAxisInDirection( footCtrl, (1, 0, 0) )
aimConstraint( ikThighJoint, grpAAutoNull, mo=True, aim=grpA_knee_aimAxis.asVector(), u=grpA_knee_upAxis.asVector(), wu=grpA_knee_worldAxis.asVector(), wuo=footCtrl, wut='objectrotation' )
autoAimConstraint = orientConstraint( grpAAutoNull, grpAAutoOffNull, grpASpace )[0]
addAttr( footCtrl, ln='autoAnkle', at='double', dv=1, min=0, max=1 )
attrState( footCtrl, 'autoAnkle', *NORMAL )
cAttrs = listAttr( autoAimConstraint, ud=True )
connectAttr( '%s.autoAnkle' % footCtrl, '%s.%s' % (autoAimConstraint, cAttrs[0]), f=True )
connectAttrReverse( '%s.autoAnkle' % footCtrl, '%s.%s' % (autoAimConstraint, cAttrs[1]), f=True )
poleCtrl = buildControl( 'Pole%s' % nameSuffix,
PlaceDesc( ikKneeJoint, PlaceDesc.WORLD ), PivotModeDesc.MID,
shapeDesc=ShapeDesc( 'sphere', axis=-AIM_AXIS if parity else AIM_AXIS ),
colour=colour, constrain=False, scale=scale, parent=self.getPartsNode() )
poleCtrlSpace = getNodeParent( poleCtrl )
polePos = findPolePosition( ikAnkleJoint )
move( polePos[0], polePos[1], polePos[2], poleCtrlSpace, ws=True, rpr=True, a=True )
pointConstraint( ikThighJoint, footCtrl, poleCtrlSpace, mo=True )
poleVectorConstraint( poleCtrl, ikHandle )
#build the ankle aim control - its acts kinda like a secondary pole vector
anklePoleControl = buildControl( 'Ankle%s' % nameSuffix, ikAnkleJoint, shapeDesc=ShapeDesc( 'sphere' ), colour=colour, scale=scale, constrain=False, parent=grpASpace )
ankleAimVector = betweenVector( grpA, anklePoleControl )
ankleAimAxis = getObjectAxisInDirection( grpA, ankleAimVector )
ankleUpAxis = getObjectAxisInDirection( grpA, (1, 0, 0) )
ankleWorldUpAxis = getObjectAxisInDirection( anklePoleControl, (1, 0, 0) )
aimConstraint( anklePoleControl, grpA, aim=ankleAimAxis.asVector(), u=ankleUpAxis.asVector(), wu=ankleWorldUpAxis.asVector(), wuo=anklePoleControl, wut='objectrotation' )
### FK CHAIN SETUP
fkThighControl = buildControl( 'fkThigh%s' % nameSuffix, originalThighJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=partParent )
fkKneeControl = buildControl( 'fkKnee%s' % nameSuffix, originalKneeJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=fkThighControl )
fkAnkleControl = buildControl( 'fkAnkle%s' % nameSuffix, originalAnkleJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=fkKneeControl )
fkToeControl = buildControl( 'fkToe%s' % nameSuffix, originalToeJoint, PivotModeDesc.MID, 'sphere', colour, False, scale=scale, parent=fkAnkleControl )
fkControls = fkThighControl, fkKneeControl, fkAnkleControl, fkToeControl
setItemRigControl( originalThighJoint, fkThighControl )
setItemRigControl( originalKneeJoint, fkKneeControl )
setItemRigControl( originalAnkleJoint, fkAnkleControl )
addAttr( footCtrl, ln='ikBlend', at='float', min=0, max=1, dv=1, keyable=True )
for ikJ, fkC, orgJ in zip( ikJoints, fkControls, originalJoints ):
constraintNode = parentConstraint( ikJ, orgJ, w=1, mo=True )[0]
constraintNode = parentConstraint( fkC, orgJ, w=0, mo=True )[0]
ikAttr, fkAttr = listAttr( constraintNode, ud=True )
connectAttr( '%s.ikBlend' % footCtrl, '%s.%s' % (constraintNode, ikAttr) )
connectAttrReverse( '%s.ikBlend' % footCtrl, '%s.%s' % (constraintNode, fkAttr) )
ikControls = footCtrl, poleCtrl, anklePoleControl
setupIkFkVisibilityConditions( '%s.ikBlend' % footCtrl, ikControls, fkControls )
#now we need to setup right mouse button menus for ik/fk switching
footTrigger = Trigger( footCtrl )
footTrigger.createMenu( 'switch to FK', '''python( "import rigPrimitives; rigPrimitives.RigPart.InitFromItem('#').switchToFk()" )''' )
for c in fkControls:
t = Trigger( c )
t.createMenu( 'switch to IK', '''python( "import rigPrimitives; rigPrimitives.RigPart.InitFromItem('#').switchToIk()" )''' )
#setup stretch as appropriate
if stretchy:
StretchRig.Create( self._skeletonPart, footCtrl, (ikThighJoint, ikKneeJoint, ikAnkleJoint, ikToeJoint), '%s.ikBlend' % ikHandle, parity=parity, connectEndJoint=True )
for ax in CHANNELS:
delete( '%s.t%s' % (ikToeJoint, ax), icn=True )
pointConstraint( footCtrl, ikToeJoint )
buildDefaultSpaceSwitching( originalThighJoint, footCtrl, reverseHierarchy=True, space=footCtrlSpace )
buildDefaultSpaceSwitching( originalThighJoint, fkThighControl )
buildDefaultSpaceSwitching( originalToeJoint, fkToeControl, **spaceSwitching.NO_ROTATION )
controls = ikControls + fkControls
namedNodes = None, None, ikHandle, None
return controls, namedNodes
#end
| Python |
import subprocess
import marshal
import inspect
import pickle
import time
import imp
import sys
import os
import gc
from zlib import crc32
from modulefinder import ModuleFinder
import filesystem
from filesystem import Path, removeDupes
_MODULE_TYPE = type( os )
def getPythonStdLibDir():
'''
returns the root directory of the current python interpreter's root directory
'''
return Path( inspect.getfile( os ) ).up()
_LIB_PATHS = ( getPythonStdLibDir(), )
def logMessage( *a ):
print ' '.join( map( str, a ) )
logWarning = logMessage
def getDeps( aModule ):
if not isinstance( aModule, _MODULE_TYPE ):
raise TypeError( "must specify a module object" )
dependencySet = set()
getfile = inspect.getfile
def _getDeps( module ):
#grab module dependencies
for n, o in aModule.__dict__.iteritems():
try:
objectFile = Path( getfile( o ) )
#this happens on builtins... so skip em
except TypeError:
continue
if isinstance( o, _MODULE_TYPE ):
if objectFile in dependencySet:
continue
dependencySet.add( objectFile )
_getDeps( o ) #recurse
else:
dependencySet.add( objectFile )
_getDeps( aModule )
return dependencySet
def isScriptInSuperiorBranch( scriptPath ):
'''
returns whether the given scriptPath can be found in a directory searched before
the given script. Ie, if the following paths are in sys.path:
sys.path = [ 'd:/somePath', 'd:/otherPath' ]
isScriptInSuperiorBranch( 'd:/otherPath/someScript.py' )
if there is a someScript.py in d:/somePath, this function will return True
'''
if not isinstance( scriptPath, Path ):
scriptPath = Path( scriptPath )
originalPath = scriptPath
for p in sys.path:
if scriptPath.isUnder( p ):
scriptPath = scriptPath - p
break
for p in sys.path:
possibleSuperiorPath = p / scriptPath
if possibleSuperiorPath.exists():
if possibleSuperiorPath == originalPath:
return None
return possibleSuperiorPath
class DependencyNode(dict):
def addDepedency( self, callerScriptPaths ):
curDepNode = self
for callScript in callerScriptPaths[ 1: ]: #skip the first item - its always the script being walked for dependencies
#builtins have None for their paths as do modules in the stdlib if they're in a zip file, so break
#because at this point we don't care about downstream deps because we don't change the stdlib
if callScript is None:
break
curDepNode = curDepNode.setdefault( Path( callScript ), DependencyNode() )
return curDepNode
def findDependents( self, changedScriptPath ):
affected = []
for srcFile, depNode in self.iteritems():
if srcFile == changedScriptPath:
continue
if changedScriptPath in depNode:
affected.append( srcFile )
else:
if depNode: #no point recursing if the depNode is empty
affected += depNode.findDependents( changedScriptPath )
return affected
class DepFinder(ModuleFinder):
'''
simple wrapper to ModuleFinder class to discover dependencies for a given script path
NOTE: the script doesn't get executed, modulefinder just walks through the script bytecode,
looks for imports that happen, and then asks python to resolve them to locations on disk
'''
#depth of the dependency tree - by default its just a single import deep - ie it only records immediate dependencies.
#change this to None to make it arbitrary depth
#NOTE: a depth of 1 is sufficient for deep dependency parsing because the DependencyTree has a 1-depth node for each script
_DEPTH = 1
def __init__( self, scriptPath, additionalPaths=(), depth=_DEPTH, *a, **kw ):
self._depth = depth
self._depNode = DependencyNode()
self._callerStack = []
ModuleFinder.__init__( self, *a, **kw )
#add in the additional paths
preSysPath = sys.path[:]
for p in reversed( additionalPaths ):
sys.path.insert( 0, str( p ) )
#insert the path of the script
sys.path.insert( 0, str( Path( scriptPath ).up() ) )
try:
self.run_script( scriptPath )
except SyntaxError: pass
finally:
#restore the original sys.path
sys.path = preSysPath
def __contains__( self, item ):
return item in self._depNode
def __getitem__( self, item ):
return self._depNode[ item ]
def __setitem__( self, item, value ):
self._depNode[ item ] = value
def load_module( self, fqname, fp, pathname, file_info ):
if pathname:
if not isinstance( pathname, Path ):
pathname = Path( pathname )
if pathname.hasExtension( 'cmd' ):
line = fp.readline().strip()
suffix, mode, type = file_info[0], file_info[1], imp.PY_SOURCE #pretend the cmd script is a py file
assert '@setlocal' in line and '& python' in line, "Doesn't seem to be a python cmd script!"
return ModuleFinder.load_module( self, fqname, fp, pathname, file_info )
def import_hook( self, name, caller=None, fromlist=None, level=None ):
if caller is None:
return None
try:
self._callerStack.append( caller.__file__ )
return ModuleFinder.import_hook( self, name, caller, fromlist )
finally:
self._callerStack.pop()
def import_module( self, partnam, fqname, parent ):
depth = self._depth
if depth is None or len( self._callerStack ) <= depth:
r = ModuleFinder.import_module( self, partnam, fqname, parent )
if r is not None:
self._depNode.addDepedency( self._callerStack +[ r.__file__ ] )
return r
def getDependencyNode( self ):
return self._depNode
def findDependents( self, changedScriptPath ):
return self._depNode.findDependents( changedScriptPath )
def generateFileCRC( filePath ):
with file( filePath, 'rb' ) as f:
return crc32( f.read() )
class DependencyTree(DependencyNode):
_VERSION = 0
_CACHE_PATH = Path( '~/_py_dep_cache' )
@classmethod
def _convertDictDataTo( cls, theDict, keyCastMethod ):
def convToDict( theDict ):
for key in theDict.keys():
value = theDict.pop( key )
key = keyCastMethod( key )
theDict[ key ] = value
if isinstance( value, dict ):
convToDict( value )
convToDict( theDict )
return theDict
@classmethod
def ToSimpleDict( cls, theDict ):
cls._convertDictDataTo( theDict, str )
@classmethod
def FromSimpleDict( cls, theDict ):
cls._convertDictDataTo( theDict, Path )
def __new__( cls, dirsToWalk=(), dirsToExclude=(), extraSearchPaths=(), rebuildCache=False, skipLib=True ):
'''
constructs a new dependencyTree dictionary or loads an existing one from a disk cache, and
strips out files that no longer exist
'''
if not dirsToWalk:
dirsToWalk = sys.path[:]
dirsToWalk = map( Path, dirsToWalk )
dirsToExclude = map( Path, dirsToExclude )
if skipLib:
dirsToExclude += _LIB_PATHS
cache = Path( cls._CACHE_PATH )
self = None
if cache.exists() and not rebuildCache:
try:
with file( cache, 'r' ) as f:
version, self = pickle.load( f )
except: pass
else:
if version == cls._VERSION:
cls.FromSimpleDict( self ) #keys are converted to strings before pickling - so convert them back to Path instances
cls.FromSimpleDict( self._crcs )
cls.FromSimpleDict( self._stats )
#remove any files from the cache that don't exist
for f in self.keys():
if not f.exists():
self.pop( f )
else:
self = None
logWarning( 'VERSION UPDATE: forcing rebuild' )
if self is None:
self = dict.__new__( cls )
self._crcs = {}
self._stats = {}
self._dirs = dirsToWalk
self._dirsExclude = dirsToExclude
self._extraPaths = extraSearchPaths
self.freshenDependencies()
return self
def __init__( self, dirsToWalk=(), dirsToExclude=(), extraSearchPaths=(), rebuildCache=False, skipLib=True ):
dict.__init__( self )
def getFiles( self ):
files = []
for d in self._dirs:
skipDir = False
for dd in self._dirsExclude:
if d.isUnder( dd ):
skipDir = True
break
if skipDir:
continue
for dirPath, dirNames, fileNames in os.walk( d ):
dirPath = Path( dirPath )
skipDir = False
for d in self._dirsExclude:
if dirPath.isUnder( d ):
skipDir = True
break
if skipDir:
continue
for f in fileNames:
f = dirPath / f
if f.hasExtension( 'py' ):
files.append( f )
#if the cmd script looks like its a python cmd script, then add it to the list - the DepFinder class knows how to deal with these files
elif f.hasExtension( 'cmd' ):
with file( f ) as fopen:
line = fopen.readline().strip()
if '@setlocal ' in line and '& python' in line:
files.append( f )
return files
def freshenDependencies( self ):
'''
freshens the dependency tree with new files - deleted files are cleaned out of
the cache at load time, see the __new__ method for details
'''
padding = 15
start = time.clock()
files = self.getFiles()
extraSearchPaths = self._extraPaths
stats = self._stats
crcs = self._crcs
for f in files:
#do we need to re-parse dependencies? first we check the data in the file stat
checkCrc = False
currentStat = os.stat( f ).st_mtime
cachedStat = stats.get( f, None )
if cachedStat == currentStat:
continue
#store the mod time
stats[ f ] = currentStat
#if they don't match, check the crc
currentCrc = generateFileCRC( f )
cachedCrc = crcs.get( f, 0 )
if cachedCrc == currentCrc:
continue
elif cachedCrc == 0:
logMessage( 'new file:'.ljust( padding ), f )
else:
logMessage( 'stale file:'.ljust( padding ), f )
finder = DepFinder( f, extraSearchPaths )
self[ f ] = finder.getDependencyNode()
crcs[ f ] = currentCrc
self.writeCache()
logMessage( 'Time to update cache: %0.2g' % (time.clock()-start) )
logMessage()
def findDependents( self, changedScriptPath ):
'''
returns a 2-tuple of scripts that immediately rely on changedScriptPath. ie: the scripts that directly
import the queried script, and those that import the queried script by proxy. Secondary scripts are any
downstream script that imports the one in question - regardless of how far down the dependency chain it is.
ie: given scriptA, scriptB, scriptC
scriptA imports scriptB
scriptB imports scriptC
calling findDependents( scriptC ) will return scriptB as an immediate dependent, and scriptA as a
secondary dependent
'''
changedScriptPath = Path( changedScriptPath )
#make sure the script in question doesn't have a superior script
hasSuperior = isScriptInSuperiorBranch( changedScriptPath )
if hasSuperior is not None:
logWarning( 'WARNING - a superior script was found: %s. Using it for dependency query instead!' % hasSuperior )
changedScriptPath = hasSuperior
primaryAffected = set()
secondaryAffected = set()
#add the primary affected dependencies
for script, depNode in self.iteritems():
if script == changedScriptPath:
continue
#if the changedScript is in this dependency node, add the script to the list of affected
if changedScriptPath in depNode:
primaryAffected.add( script )
#don't even start looking for secondary deps if there are no primary deps...
if primaryAffected:
#returns whether it has found any new dependencies
def gatherSecondaryDependencies( theDepNode ):
stillAdding = False
for script, depNode in theDepNode.iteritems():
if script == changedScriptPath:
continue
if script in primaryAffected or script in secondaryAffected:
continue
#if its not, we had better recurse and see if it is somewhere deeper in the dependency tree for this script
else:
for sub_script in depNode.iterkeys():
if sub_script in primaryAffected or sub_script in secondaryAffected:
secondaryAffected.add( script )
stillAdding = True
return stillAdding
#keep calling gatherSecondaryDependencies until it returns False
while gatherSecondaryDependencies( self ): pass
return primaryAffected, secondaryAffected
def findDependencies( self, scriptPath, depth=None, includeFilesFromExcludedDirs=True ):
'''
returns a list of dependencies for scriptPath
'''
scriptPath = Path( scriptPath )
#make sure the script in question doesn't have a superior script
hasSuperior = isScriptInSuperiorBranch( scriptPath )
if hasSuperior is not None:
logWarning( 'WARNING - a superior script was found: %s. Using it for dependency query instead!' % hasSuperior )
scriptPath = hasSuperior
deps = set()
maxDepth = depth
def getDeps( script, depth=0 ):
if maxDepth is not None and depth >= maxDepth:
return
if script in self:
for ss in self[ script ]:
if ss in deps:
continue
deps.add( ss )
getDeps( ss, depth+1 )
getDeps( scriptPath )
#if we're not including files from excluded directories, go through the list of deps and remove files that are under any of the exlude dirs
if not includeFilesFromExcludedDirs:
depsWithoutExcludedFiles = []
for dep in deps:
shouldFileBeIncluded = True
for excludeDir in self._dirsExclude:
if dep.isUnder( excludeDir ):
shouldFileBeIncluded = False
break
if shouldFileBeIncluded:
depsWithoutExcludedFiles.append( dep )
deps = depsWithoutExcludedFiles
return list( sorted( deps ) )
def writeCache( self ):
self.ToSimpleDict( self )
self.ToSimpleDict( self._crcs )
self.ToSimpleDict( self._stats )
with open( self._CACHE_PATH, 'w' ) as f:
pickle.dump( (self._VERSION, self), f )
self.FromSimpleDict( self )
self.FromSimpleDict( self._crcs )
self.FromSimpleDict( self._stats )
def moduleNameToScript( self, moduleName ):
for scriptPath in self:
if scriptPath.name() == moduleName or moduleName in scriptPath:
if makeScriptPathRelative( scriptPath ).name() == moduleName:
return scriptPath
raise ValueError( "Module cannot be mapped to any script" )
def _depTreeStr( scriptPath, dependencyTree, depth=None ):
if not isinstance( scriptPath, Path ):
scriptPath = Path( scriptPath )
indent = ' ' #the string used to "indent" dependencies in the tree
maxDepth = depth
alreadySerialized = set()
def genLines( script, depth=0 ):
lines = []
depthPrefix = indent * depth
if maxDepth and depth >= maxDepth:
return lines
try:
scriptDeps = dependencyTree[ script ]
except KeyError:
return lines
alreadySerialized.add( script )
for s in scriptDeps:
lines.append( '%s%s' % (depthPrefix, s) )
if s in alreadySerialized:
continue
alreadySerialized.add( s )
lines += genLines( s, depth+1 )
return lines
lines = [ scriptPath ]
lines += genLines( scriptPath, 1 )
return '\n'.join( lines )
def printDepTree( scriptPath, dependencyTree, depth=None ):
logMessage( _depTreeStr( scriptPath, dependencyTree, depth ) )
def generateDepTree( rebuildCache=False ):
return DependencyTree( rebuildCache=rebuildCache )
def makeScriptPathRelative( scriptFilepath ):
'''
will attempt to transform the name of the given script into the shortest possible path relative
to the python search paths defined in sys.path.
For example, just say you have a package called "foo"
this package contains the script: "bar.py"
given the full path to bar.py this function will return:
"foo/bar.py"
'''
scriptFilepath = Path( scriptFilepath )
sysPaths = map( Path, sys.path )
bestFitPath = None
for p in sysPaths:
if scriptFilepath.isUnder( p ) or len( p ) > len( bestFitPath ):
if bestFitPath is None:
bestFitPath = p
if bestFitPath is None:
raise ValueError( "Cannot find a path under any of the paths in sys.path!" )
shortestPath = scriptFilepath - bestFitPath
return shortestPath
def packageScripts( scriptFilesToPackage, destPackageFilepath, dependencyTree ):
'''
will package all given files and import dependencies into a single zip file
'''
destPackageFilepath = Path( destPackageFilepath ).setExtension( 'zip' )
if destPackageFilepath.exists():
destPackageFilepath.delete()
filesToPackage = map( Path, scriptFilesToPackage )
for f in scriptFilesToPackage:
filesToPackage += dependencyTree.findDependencies( f, None, False )
if not filesToPackage:
return None
#remove any duplicate files...
filesToPackage = removeDupes( filesToPackage )
#this is a little hacky - but we don't want to re-distribute wingdbstub so lets check to see if its in the list of files
for f in filesToPackage:
if f.name() == 'wingdbstub':
filesToPackage.remove( f )
break
#now build the zip file
import zipfile
with zipfile.ZipFile( str( destPackageFilepath ), 'w' ) as thePackage:
for f in filesToPackage:
thePackage.write( str( f ), str( makeScriptPathRelative( f ) ) )
return destPackageFilepath
def getScriptTests( scriptFilepath, depTree=None ):
if not isinstance( scriptFilepath, Path ):
scriptFilepath = Path( scriptFilepath )
if depTree is None:
depTree = generateDepTree()
testDependencyDict = {}
for script in depTree:
if script.name().startswith( 'devTest_' ):
testDependencyDict[ script ] = depTree.findDependencies( script )
scriptTestCandidates = []
for test, testDependencies in testDependencyDict.iteritems():
if scriptFilepath in testDependencies:
scriptTestCandidates.append( test )
return scriptTestCandidates
def flush( dirsNeverToFlush=() ):
'''
flushes all loaded modules from sys.modules which causes them to be reloaded
when next imported... super useful for developing crap within a persistent
python environment
dirsNeverToFlush should be a list - scripts under any of directories in this
list won't be flushed
'''
dirsNeverToFlush = list( dirsNeverToFlush ) #these dirs never get flushed
keysToDelete = []
dirsNeverToFlush.extend( _LIB_PATHS )
flushableExtensions = 'py', 'pyc', 'pyo'
builtin_module_names = set( sys.builtin_module_names )
while True:
try:
for modName, mod in sys.modules.items():
try:
modPath = filesystem.Path( mod.__file__ )
except AttributeError: continue
#if its in the list of builtin module names, skip it - no point flushing builtins
if modName in builtin_module_names:
continue
#only flush the module if has a valid extension - binary modules don't unload properly in CPython
if modPath.getExtension() not in flushableExtensions:
continue
doFlush = True
for ignoreDir in dirsNeverToFlush:
if modPath.isUnder( ignoreDir ):
doFlush = False
break
if doFlush:
keysToDelete.append( modName )
break
#sometimes the sys.modules dict changes while the above loop is happening which causes a runtimeerror to be thrown. so just try again if it happens...
except RuntimeError:
continue
for keyToDelete in keysToDelete:
try:
del( sys.modules[ keyToDelete ] )
except KeyError: continue
#force a garbage collection
gc.collect()
#end
| Python |
def trackableTypeFactory( metaclassSuper=type ):
'''
returns a metaclass that will track subclasses. All classes of the type returned by this factory will
have the following class methods implemented:
IterSubclasses()
GetSubclasses()
GetNamedSubclass( name )
usage:
class SomeClass( metaclass=trackableTypeFactory() ): pass
class SomSubclass( SomeClass ): pass
print SomeClass.GetSubclasses()
NOTE: the metaclass that is returned inherits from the metaclassSuper arg, which defaults to type. So
if you want to mix together metaclasses, you can inherit from a subclass of type
'''
_SUB_CLASS_LIST = [] #stores the list of all subclasses in the order they're created
_SUB_CLASS_DICT = {} #makes for fast lookups of named subclasses
def IterSubclasses( cls ):
'''
iterates over all subclasses
'''
for c in _SUB_CLASS_LIST:
if c is cls: #skip the class we're calling this on
continue
if issubclass( c, cls ):
yield c
def GetSubclasses( cls ):
'''
returns a list of subclasses
'''
return list( cls.IterSubclasses() )
def GetNamedSubclass( cls, name ):
'''
returns the first subclass found with the given name
'''
return _SUB_CLASS_DICT.get( name, None )
class _TrackableType(metaclassSuper):
def __new__( cls, name, bases, attrs ):
newCls = metaclassSuper.__new__( cls, name, bases, attrs )
_SUB_CLASS_LIST.append( newCls )
_SUB_CLASS_DICT.setdefault( name, newCls ) #set default so subclass name clashes are resolved using the first definition parsed
#insert the methods above into the newCls unless the names are already taken on the newCls
if not hasattr( newCls, 'IterSubclasses' ):
newCls.IterSubclasses = classmethod( IterSubclasses )
if not hasattr( newCls, 'GetSubclasses' ):
newCls.GetSubclasses = classmethod( GetSubclasses )
if not hasattr( newCls, 'GetNamedSubclass' ):
newCls.GetNamedSubclass = classmethod( GetNamedSubclass )
return newCls
return _TrackableType
def interfaceTypeFactory( metaclassSuper=type ):
'''
returns an "Interface" metaclass. Interface classes work as you'd expect. Every method implemented
on the interface class must be implemented on subclasses otherwise a TypeError will be raised at
class creation time.
usage:
class IFoo( metaclass=interfaceTypeFactory() ):
def bar( self ): pass
subclasses must implement the bar method
NOTE: the metaclass that is returned inherits from the metaclassSuper arg, which defaults to type. So
if you want to mix together metaclasses, you can inherit from a subclass of type. For example:
class IFoo( metaclass=interfaceTypeFactory( trackableTypeFactory() ) ):
def bar( self ): pass
class Foo(IFoo):
def bar( self ): return None
print( IFoo.GetSubclasses() )
'''
class _AbstractType(metaclassSuper):
_METHODS_TO_IMPLEMENT = None
_INTERFACE_CLASS = None
def _(): pass
_FUNC_TYPE = type( _ )
def __new__( cls, name, bases, attrs ):
newCls = metaclassSuper.__new__( cls, name, bases, attrs )
#if this hasn't been defined, then cls must be the interface class
if cls._METHODS_TO_IMPLEMENT is None:
cls._METHODS_TO_IMPLEMENT = methodsToImplement = []
cls._INTERFACE_CLASS = newCls
for name, obj in attrs.items():
if type( obj ) is cls._FUNC_TYPE:
methodsToImplement.append( name )
#otherwise it is a subclass that should be implementing the interface
else:
if cls._INTERFACE_CLASS in bases:
for methodName in cls._METHODS_TO_IMPLEMENT:
#if the newCls' methodName attribute is the same method as the interface
#method, then the method hasn't been implemented. Its done this way because
#the newCls may be inheriting from multiple classes, one of which satisfies
#the interface - so we can't just look up the methodName in the attrs dict
if getattr( newCls, methodName, None ).im_func is getattr( cls._INTERFACE_CLASS, methodName ).im_func:
raise TypeError( "The class %s doesn't implement the required method %s!" % (name, methodName) )
return newCls
return _AbstractType
def trackableClassFactory( superClass=object ):
'''
returns a class that tracks subclasses. for example, if you had classB(classA)
ad you wanted to track subclasses, you could do this:
class classB(trackableClassFactory( classA )):
...
a classmethod called GetSubclasses is created in the returned class for
querying the list of subclasses
NOTE: this is a convenience function for versions of python that don't support
the metaclass class constructor keyword. Python 2.6 and before need you to
use the __metaclass__ magic class attribute to define a metaclass
'''
class TrackableClass(superClass): __metaclass__ = trackableTypeFactory()
return TrackableClass
#end
| Python |
from maya.cmds import *
def getNamespaceTokensFromReference( node ):
'''
returns a list of namespaces added to the given node via referencing
'''
if not referenceQuery( node, inr=True ):
return []
theReferenceFilepath = referenceQuery( node, filename=True )
theReferenceNode = file( theReferenceFilepath, q=True, referenceNode=True )
theReferenceNamespace = file( theReferenceFilepath, q=True, namespace=True )
#now get the parent namespaces for the reference - these are the namespaces found on the reference node
namespaces = theReferenceNode.split( ':' )
#pop the last token - its the name of the reference node
namespaces.pop()
namespaces.append( theReferenceNamespace )
return namespaces
def stripReferenceNamespaceFromNode( node ):
'''
strips off any namespaces from the given node that were added due to referencing
'''
referenceNamespaceToks = getNamespaceTokensFromReference( node )
return stripNamespaceFromNode( node, referenceNamespaceToks )
def stripNamespaceFromNode( node, namespace ):
'''
Strips off the given namespace from the given node if possible
If not possible, the original node name is returned
'''
if namespace.endswith( ':' ):
namespace = namespace[ :-1 ]
return stripNamespaceTokensFromNode( namespace.split( ':' ) )
def stripNamespaceTokensFromNode( node, namespaceToks ):
'''
Strips off the given namespace tokens from the given node if possible
If not possible, the original node name is returned
'''
numNamespaceToks = len( namespaceToks )
if not namespaceToks:
return node
#if the node name is a name path, we'll need to remove the referenced namespace tokens from each name path...
pathToks = node.split( '|' )
newPathToks = []
for pathTok in pathToks:
pathNamespaceToks = pathTok.split( ':' )
if pathNamespaceToks[ :numNamespaceToks ] == namespaceToks:
newPathToks.append( ':'.join( pathNamespaceToks[ numNamespaceToks: ] ) )
else:
newPathToks.append( pathTok )
return '|'.join( newPathToks )
def addNamespaceTokNamePath( name, namespace ):
'''
adds the given namespace to a name path.
example:
addNamespaceTokNamePath( 'some|name|path', 'ns' )
returns:
'ns:some|ns:name|ns:path'
'''
if namespace.endswith( ':' ):
namespace = namespace[ :-1 ]
namespacedToks = []
for pathTok in name.split( name, '|' ):
namespacedToks.append( '%s:%s' % (namespace, name) )
return '|'.join( namespacedToks )
#end
| Python |
from math import sqrt
class _Node(list):
'''
simple wrapper around tree nodes - mainly to make the code a little more readable (although
members are generally accessed via indices because its faster)
'''
@property
def point( self ):
return self[0]
@property
def left( self ):
return self[1]
@property
def right( self ):
return self[2]
def is_leaf( self ):
return self[1] is None and self[2] is None
class ExactMatch(Exception): pass
class KdTree():
'''
simple, fast python kd-tree implementation
thanks to:
http://en.wikipedia.org/wiki/Kd-tree
'''
DIMENSION = 3 #dimension of points in the tree
def __init__( self, data=() ):
self.performPopulate( data )
def performPopulate( self, data ):
dimension = self.DIMENSION
def populateTree( points, depth ):
if not points:
return None
axis = depth % dimension
#NOTE: this is slower than a DSU sort, but its a bit more readable, and the difference is only a few percent...
points.sort( key=lambda point: point[ axis ] )
#find the half way point
half = len( points ) / 2
node = _Node( [ points[ half ],
populateTree( points[ :half ], depth+1 ),
populateTree( points[ half+1: ], depth+1 ) ] )
return node
self.root = populateTree( data, 0 )
def getClosest( self, queryPoint, returnDistances=False ):
'''
Returns the closest point in the tree to the given point
NOTE: see the docs for getWithin for info on the returnDistances arg
'''
dimension = self.DIMENSION
distBest = (self.root[0] - queryPoint).get_magnitude() ** 2
bestList = [ (distBest, self.root[0]) ]
def search( node, depth ):
nodePoint = node[0]
axis = depth % dimension
if queryPoint[axis] < nodePoint[axis]:
nearNode = node[1]
farNode = node[2]
else:
nearNode = node[2]
farNode = node[1]
#start the search
if nearNode is not None:
search( nearNode, depth+1 )
#get the squared distance
sd = 0
for v1, v2 in zip( nodePoint, queryPoint ):
sd += (v1 - v2)**2
curBest = bestList[0][0]
#if the point is closer than the currently stored one, insert it at the head
if sd < curBest:
bestList.insert( 0, (sd, nodePoint) )
#if its an exact match, bail
if not sd:
raise ExactMatch
else:
bestList.append( (sd, nodePoint) )
# check whether there could be any points on the other side of the
# splitting plane that are closer to the query point than the current best
if farNode is not None:
if (nodePoint[ axis ] - queryPoint[ axis ])**2 < curBest:
search( farNode, depth+1 )
try:
search( self.root, 0 )
except ExactMatch: pass
if returnDistances:
return bestList[0]
return bestList[0][1]
def getWithin( self, queryPoint, threshold=1e-6, returnDistances=False ):
'''
Returns all points that fall within the radius of the queryPoint within the tree.
NOTE: if returnDistances is True then the squared distances between the queryPoint and the points in the
return list are returned. This means the return list looks like this:
[ (sqDistToPoint, point), ... ]
This can be useful if you need to do more work on the results afterwards - just be aware that the distances
in the list are squares of the actual distance between the points
'''
dimension = self.DIMENSION
axisRanges = axRangeX, axRangeY, axRangeZ = ( (queryPoint[0]-threshold, queryPoint[0]+threshold),
(queryPoint[1]-threshold, queryPoint[1]+threshold),
(queryPoint[2]-threshold, queryPoint[2]+threshold) )
sqThreshold = threshold ** 2
matches = []
def search( node, depth ):
nodePoint = node[0]
axis = depth % dimension
if queryPoint[axis] < nodePoint[axis]:
nearNode = node[1]
farNode = node[2]
else:
nearNode = node[2]
farNode = node[1]
#start the search
if nearNode is not None:
search( nearNode, depth+1 )
#test this point
if axRangeX[0] <= nodePoint[ 0 ] <= axRangeX[1]:
if axRangeY[0] <= nodePoint[ 1 ] <= axRangeY[1]:
if axRangeZ[0] <= nodePoint[ 2 ] <= axRangeZ[1]:
sd = 0
for v1, v2 in zip( nodePoint, queryPoint ):
sd += (v1 - v2)**2
if sd <= sqThreshold:
matches.append( (sd, nodePoint) )
if farNode is not None:
if (nodePoint[ axis ] - queryPoint[ axis ])**2 < sqThreshold:
search( farNode, depth+1 )
search( self.root, 0 )
matches.sort() #the best is guaranteed to be at the head of the list, but consequent points might be out of order - so order them now
if returnDistances:
return matches
return [ m[1] for m in matches ]
def getDistanceRatioWeightedVector( self, queryPoint, ratio=2, returnDistances=False ):
'''
Finds the closest point to the queryPoint in the tree and returns all points within a distance
of ratio*<closest point distance>.
This is generally more useful that using getWithin because getWithin could return an exact
match along with a bunch of points at the outer search limit and thus heavily bias the
results.
NOTE: see docs for getWithin for details on the returnDistance arg
'''
assert ratio > 1
closestDist, closest = self.getClosest( queryPoint, returnDistances=True )
if closestDist == 0:
if returnDistances:
return [ (0, closest) ]
return [ closest ]
closestDist = sqrt( closestDist )
maxDist = closestDist * ratio
return self.getWithin( queryPoint, maxDist, returnDistances=returnDistances )
#end
| Python |
import os
import sys
import cgitb
import inspect
import traceback
from filesystem import findMostRecentDefitionOf
def printMsg( *args ):
for a in args: print a,
def SHOW_IN_UI():
from wx import MessageBox, ICON_ERROR
MessageBox( 'Sorry, it seems an un-expected problem occurred.\nYour error has been reported. Good Luck!', 'An Unhandled Exception Occurred', ICON_ERROR )
DEFAULT_AUTHOR = 'mel@macaronikazoo.com'
def exceptionHandler( *args ):
'''
This is a generic exception handler that can replace the default python exception handler if
needed (ie: sys.excepthook=exceptionHandler). It will mail
'''
try:
eType, e, tb = args
except TypeError:
eType, e, tb = sys.exc_info()
printMsg( '### ERROR - Python Unhandled Exception' )
printMsg( '### ', eType.__name__, e )
#
toolName = findMostRecentDefitionOf( 'TOOL_NAME' ) or '<NO_TOOL>'
#generate the message
env = os.environ
message = 'Subject: [ERROR] %s\n\n%s\n\n%s\n\n%s' % (toolName, cgitb.text( args ), '\n'.join( sys.path ),'\n'.join( [ '%s=%s' % (k, env[ k ]) for k in sorted( env.keys() ) ] ))
#try to write a log
fLog = open( 'c:/python_tool_log_%s.txt' % toolName, 'w' )
try: fLog.write( message )
except: pass
finally: fLog.close()
#try to mail a callstack
try:
import smtplib
author = findMostRecentDefitionOf( '__author__' ) or DEFAULT_AUTHOR
svr = smtplib.SMTP( 'exchange2' )
svr.sendmail(os.environ[ 'USERNAME' ], [author, os.environ[ 'USERNAME' ]], message)
except Exception, x:
printMsg( 'ERROR: failed to mail exception dump', x )
#try to post an error dial
try:
SHOW_IN_UI()
except: pass
def d_handleExceptions(f):
'''
if you can't/don't want to setup a generic exception handler, you can decorate a function with
this to have exceptions handled
exception hanlding decorator. basically this decorator will catch any exceptions thrown by the
decorated function, and spew a useful callstack to the event log - as well as throwing up a dial
to alert of the issue...
'''
def newFunc( *a, **kw ):
try: return f( *a, **kw )
except:
exc_info = sys.exc_info()
exceptionHandler( *exc_info )
newFunc.__name__ = f.__name__
newFunc.__doc__ = f.__doc__
return newFunc
class ExceptionHandledType(type):
'''
metaclass that will wrap all callable attributes of a class with the
d_handleExceptions exception handler decorator above. this is mainly useful
for maya/modo, because neither app lets you specify your own global exception
handler - yet you want to be able to capture this exception data and turn it
into a meaningful error description that can be sent back to the tool author
'''
def __new__( cls, name, bases, attrs ):
global d_handleExceptions
newAttrs = {}
for itemName, item in attrs.iteritems():
if callable( item ): newAttrs[ itemName ] = d_handleExceptions( item )
else: newAttrs[ itemName ] = item
return type.__new__( cls, name, bases, newAttrs )
def generateTraceableStrFactory( prefix, printFunc=None ):
'''
returns 2 functions - the first will generate a traceable message string, while
the second will print the generated message string. The second is really a
convenience function, but is called enough to be worth it
you can also specify your own print function - if no print function is specified
then the print builtin is used
'''
def generateTraceableStr( *args, **kw ):
frameInfos = inspect.getouterframes( inspect.currentframe() )
_nFrame = kw.get( '_nFrame', 1 )
#frameInfos[0] contains the current frame and associated calling data, while frameInfos[1] is the frame that called this one - which is the frame we want to print data about
callingFrame, callingScript, callingLine, callingName, _a, _b = frameInfos[_nFrame]
lineStr = 'from line %s in the function %s in the script %s' % (callingLine, callingName, callingScript)
return '%s%s: %s' % (prefix, ' '.join( map( str, args ) ), lineStr)
def printTraceableStr( *args ):
msg = generateTraceableStr( _nFrame=2, *args )
if printFunc is None:
print( msg )
else:
printFunc( msg )
return generateTraceableStr, printTraceableStr
generateInfoStr, printInfoStr = generateTraceableStrFactory( '*** INFO ***: ' )
generateWarningStr, printWarningStr = generateTraceableStrFactory( '*** WARNING ***: ' )
generateErrorStr, printErrorStr = generateTraceableStrFactory( '*** ERROR ***: ' )
#end
| Python |
from vectors import Vector, Matrix, Axis, AX_X, AX_Y, AX_Z
from rigUtils import MATRIX_ROTATION_ORDER_CONVERSIONS_FROM, MATRIX_ROTATION_ORDER_CONVERSIONS_TO
from maya.cmds import *
from maya.OpenMaya import MGlobal
from mayaDecorators import d_unifyUndo
import maya
import apiExtensions
AXES = Axis.BASE_AXES
#try to load the zooMirror.py plugin
try:
loadPlugin( 'zooMirror.py', quiet=True )
except:
import zooToolbox
zooToolbox.loadZooPlugin( 'zooMirror.py' )
def getLocalRotMatrix( obj ):
'''
returns the local matrix for the given obj
'''
localMatrix = Matrix( getAttr( '%s.matrix' % obj ), 4 )
localMatrix.set_position( (0, 0, 0) )
return localMatrix
def getWorldRotMatrix( obj ):
'''
returns the world matrix for the given obj
'''
worldMatrix = Matrix( getAttr( '%s.worldMatrix' % obj ), 4 )
worldMatrix.set_position( (0, 0, 0) )
return worldMatrix
def setWorldRotMatrix( obj, matrix ):
'''
given a world matrix, will set the transforms of the object
'''
parentInvMatrix = Matrix( getAttr( '%s.parentInverseMatrix' % obj ) )
localMatrix = matrix * parentInvMatrix
setLocalRotMatrix( obj, localMatrix )
@d_unifyUndo
def setLocalRotMatrix( obj, matrix ):
'''
given a world matrix, will set the transforms of the object
'''
roo = getAttr( '%s.rotateOrder' % obj )
rot = MATRIX_ROTATION_ORDER_CONVERSIONS_TO[ roo ]( matrix, True )
#try to set the rotation - check whether all the rotation channels are settable
if getAttr( '%s.r' % obj, se=True ):
setAttr( '%s.r' % obj, *rot )
def mirrorMatrix( matrix, axis=AX_X, orientAxis=AX_X ):
'''
axis is the axis things are flipped across
orientAxis is the axis that gets flipped when mirroring orientations
'''
assert isinstance( matrix, Matrix )
mirroredMatrix = Matrix( matrix )
#make sure we've been given a Axis instances... don't bother testing, just do it, and make it absolute (non-negative - mirroring in -x is the same as mirroring in x)
mirrorAxis = abs( Axis( axis ) )
axisA = abs( Axis( orientAxis ) )
#flip all axes
axisB, axisC = axisA.otherAxes()
mirroredMatrix[ axisB ][ mirrorAxis ] = -matrix[ axisB ][ mirrorAxis ]
mirroredMatrix[ axisC ][ mirrorAxis ] = -matrix[ axisC ][ mirrorAxis ]
#the above flipped all axes - but this results in a changing of coordinate system handed-ness, so flip one of the axes back
nonMirrorAxisA, nonMirrorAxisB = mirrorAxis.otherAxes()
mirroredMatrix[ axisA ][ nonMirrorAxisA ] = -mirroredMatrix[ axisA ][ nonMirrorAxisA ]
mirroredMatrix[ axisA ][ nonMirrorAxisB ] = -mirroredMatrix[ axisA ][ nonMirrorAxisB ]
#if the input matrix was a 4x4 then mirror translation
if matrix.size == 4:
mirroredMatrix[3][ mirrorAxis ] = -matrix[3][ mirrorAxis ]
return mirroredMatrix
def getKeyableAttrs( obj ):
attrs = listAttr( obj, keyable=True )
if attrs is None:
return []
for attrToRemove in ('translateX', 'translateY', 'translateZ', \
'rotateX', 'rotateY', 'rotateZ'):
try:
attrs.remove( attrToRemove )
except ValueError: pass
return attrs
class ControlPair(object):
'''
sets up a relationship between two controls so that they can mirror/swap/match one
another's poses.
NOTE: when you construct a ControlPair setup (using the Create classmethod)
'''
#NOTE: these values are copied from the zooMirror script - they're copied because the plugin generally doesn't exist on the pythonpath so we can't rely on an import working....
FLIP_AXES = (), (AX_X, AX_Y), (AX_X, AX_Z), (AX_Y, AX_Z)
@classmethod
def GetPairNode( cls, obj ):
'''
given a transform will return the pair node the control is part of
'''
if obj is None:
return None
if objectType( obj, isAType='transform' ):
cons = listConnections( '%s.message' % obj, s=False, type='controlPair' )
if not cons:
return None
return cons[0]
if nodeType( obj ) == 'controlPair':
return obj
return None
@classmethod
@d_unifyUndo
def Create( cls, controlA, controlB=None, axis=None ):
'''
given two controls will setup the relationship between them
NOTE: if controlB isn't given then it will only be able to mirror its current
pose. This is usually desirable on "central" controls like spine, head and
neck controls
'''
#make sure we've been given transforms - mirroring doesn't make a whole lotta sense on non-transforms
if not objectType( controlA, isAType='transform' ):
return None
if controlB:
#if controlA is the same node as controlB then set controlB to None - this makes it more obvious the pair is singular
#NOTE: cmpNodes compares the actual MObjects, not the node names - just in case we've been handed a full path and a partial path that are the same node...
if apiExtensions.cmpNodes( controlA, controlB ):
controlB = None
elif not objectType( controlB, isAType='transform' ):
return None
#see if we have a pair node for the controls already
pairNode = cls.GetPairNode( controlA )
if pairNode:
#if no controlB has been given see whether the pairNode we've already got also has no controlB - if so, we're done
if not controlB:
new = cls( pairNode )
if not new.controlB:
return new
#if controlB HAS been given, check whether to see whether it has the same pairNode - if so, we're done
if controlB:
pairNodeB = cls.GetPairNode( controlB )
if pairNode == pairNodeB:
return cls( pairNode )
#otherwise create a new one
pairNode = createNode( 'controlPair' )
connectAttr( '%s.message' % controlA, '%s.controlA' % pairNode )
if controlB:
connectAttr( '%s.message' % controlB, '%s.controlB' % pairNode )
#name the node
nodeName = '%s_mirrorConfig' if controlB is None else '%s_%s_exchangeConfig' % (controlA, controlB)
pairNode = rename( pairNode, nodeName )
#instantiate it and run the initial setup code over it
new = cls( pairNode )
new.setup( axis )
return new
def __init__( self, pairNodeOrControl ):
self.node = pairNode = self.GetPairNode( pairNodeOrControl )
self.controlA = None
self.controlB = None
cons = listConnections( '%s.controlA' % pairNode, d=False )
if cons:
self.controlA = cons[0]
cons = listConnections( '%s.controlB' % pairNode, d=False )
if cons:
self.controlB = cons[0]
#make sure we have a control A
if self.controlA is None:
raise TypeError( "Could not find controlA - need to!" )
def __eq__( self, other ):
if isinstance( other, ControlPair ):
other
return self.node == other.node
def __ne__( self, other ):
return not self.__eq__( other )
def __hash__( self ):
return hash( self.node )
def getAxis( self ):
return Axis( getAttr( '%s.axis' % self.node ) )
@d_unifyUndo
def setAxis( self, axis ):
setAttr( '%s.axis' % self.node, axis )
def getFlips( self ):
axes = getAttr( '%s.flipAxes' % self.node )
return list( self.FLIP_AXES[ axes ] )
@d_unifyUndo
def setFlips( self, flips ):
if isinstance( flips, int ):
setAttr( '%s.flipAxes' % self.node, flips )
def getWorldSpace( self ):
return getAttr( '%s.worldSpace' % self.node )
@d_unifyUndo
def setWorldSpace( self, state ):
setAttr( '%s.worldSpace' % self.node, state )
def isSingular( self ):
if self.controlB is None:
return True
#a pair is also singular if controlA is the same as controlB
#NOTE: cmpNodes does a rigorous comparison so it will catch a fullpath and a partial path that point to the same node
if apiExtensions.cmpNodes( self.controlA, self.controlB ):
return True
return False
def neverDoT( self ):
return getAttr( '%s.neverDoT' % self.node )
def neverDoR( self ):
return getAttr( '%s.neverDoR' % self.node )
def neverDoOther( self ):
return getAttr( '%s.neverDoOther' % self.node )
@d_unifyUndo
def setup( self, axis=None ):
'''
sets up the initial state of the pair node
'''
if axis:
axis = abs( Axis( axis ) )
setAttr( '%s.axis' % self.node, axis )
#if we have two controls try to auto determine the orientAxis and the flipAxes
if self.controlA and self.controlB:
worldMatrixA = getWorldRotMatrix( self.controlA )
worldMatrixB = getWorldRotMatrix( self.controlB )
#so restPoseB = restPoseA * offsetMatrix
#restPoseAInv * restPoseB = restPoseAInv * restPoseA * offsetMatrix
#restPoseAInv * restPoseB = I * offsetMatrix
#thus offsetMatrix = restPoseAInv * restPoseB
offsetMatrix = worldMatrixA.inverse() * worldMatrixB
AXES = AX_X.asVector(), AX_Y.asVector(), AX_Z.asVector()
flippedAxes = []
for n in range( 3 ):
axisNVector = Vector( offsetMatrix[ n ][ :3 ] )
#if the axes are close to being opposite, then consider it a flipped axis...
if axisNVector.dot( AXES[n] ) < -0.8:
flippedAxes.append( n )
for n, flipAxes in enumerate( self.FLIP_AXES ):
if tuple( flippedAxes ) == flipAxes:
setAttr( '%s.flipAxes' % self.node, n )
break
#this is a bit of a hack - and not always true, but generally singular controls built by skeleton builder will work with this value
elif self.controlA:
setAttr( '%s.flipAxes' % self.node, 1 )
self.setWorldSpace( False )
def mirrorMatrix( self, matrix ):
matrix = mirrorMatrix( matrix, self.getAxis() )
for flipAxis in self.getFlips():
matrix.setRow( flipAxis, -Vector( matrix.getRow( flipAxis ) ) )
return matrix
@d_unifyUndo
def swap( self, t=True, r=True, other=True ):
'''
mirrors the pose of each control, and swaps them
'''
#if there is no controlB, then perform a mirror instead...
if not self.controlB:
self.mirror()
return
worldSpace = self.getWorldSpace()
#do the other attributes first - the parent attribute for example will change the position so we need to set it before setting transforms
if other:
if not self.neverDoOther():
if not self.isSingular():
for attr in getKeyableAttrs( self.controlA ):
attrPathA = '%s.%s' % (self.controlA, attr)
attrPathB = '%s.%s' % (self.controlB, attr)
if objExists( attrPathA ) and objExists( attrPathB ):
attrValA = getAttr( attrPathA )
attrValB = getAttr( attrPathB )
#make sure the attributes are settable before trying setAttr
if getAttr( attrPathA, se=True ):
setAttr( attrPathA, attrValB )
if getAttr( attrPathB, se=True ):
setAttr( attrPathB, attrValA )
#do rotation
if r:
if not self.neverDoR():
if worldSpace:
getMatrix = getWorldRotMatrix
setMatrix = setWorldRotMatrix
else:
getMatrix = getLocalRotMatrix
setMatrix = setLocalRotMatrix
worldMatrixA = getMatrix( self.controlA )
worldMatrixB = getMatrix( self.controlB )
newB = self.mirrorMatrix( worldMatrixA )
newA = self.mirrorMatrix( worldMatrixB )
setMatrix( self.controlA, newA )
setMatrix( self.controlB, newB )
#do position
if t:
if not self.neverDoT():
axis = self.getAxis()
if worldSpace:
newPosA = xform( self.controlB, q=True, ws=True, rp=True )
newPosB = xform( self.controlA, q=True, ws=True, rp=True )
else:
newPosA = list( getAttr( '%s.t' % self.controlB )[0] )
newPosB = list( getAttr( '%s.t' % self.controlA )[0] )
newPosA[ axis ] = -newPosA[ axis ]
newPosB[ axis ] = -newPosB[ axis ]
if worldSpace:
if getAttr( '%s.t' % self.controlA, se=True ):
move( newPosA[0], newPosA[1], newPosA[2], self.controlA, ws=True, rpr=True )
if getAttr( '%s.t' % self.controlB, se=True ):
move( newPosB[0], newPosB[1], newPosB[2], self.controlB, ws=True, rpr=True )
else:
if getAttr( '%s.t' % self.controlA, se=True ):
setAttr( '%s.t' % self.controlA, *newPosA )
if getAttr( '%s.t' % self.controlB, se=True ):
setAttr( '%s.t' % self.controlB, *newPosB )
@d_unifyUndo
def mirror( self, controlAIsSource=True, t=True, r=True, other=True ):
'''
mirrors the pose of controlA (or controlB if controlAIsSource is False) and
puts it on the "other" control
NOTE: if controlAIsSource is True, then the pose of controlA is mirrored
and put on to controlB, otherwise the reverse is done
'''
if self.isSingular():
control = otherControl = self.controlA
else:
if controlAIsSource:
control = self.controlB
otherControl = self.controlA
else:
control = self.controlA
otherControl = self.controlB
#do the other attributes first - the parent attribute for example will change the position so we need to set it before setting transforms
if other:
if not self.neverDoOther():
if not self.isSingular():
for attr in getKeyableAttrs( otherControl ):
attrPath = '%s.%s' % (control, attr)
otherAttrPath = '%s.%s' % (otherControl, attr)
if objExists( attrPath ):
setAttr( attrPath, getAttr( otherAttrPath ) )
worldSpace = self.getWorldSpace()
#do rotation
if r:
if not self.neverDoR():
if worldSpace:
getMatrix = getWorldRotMatrix
setMatrix = setWorldRotMatrix
else:
getMatrix = getLocalRotMatrix
setMatrix = setLocalRotMatrix
matrix = getMatrix( otherControl )
newMatrix = self.mirrorMatrix( matrix )
setMatrix( control, newMatrix )
#do position
if t:
if not self.neverDoT():
if worldSpace:
pos = xform( otherControl, q=True, ws=True, rp=True )
pos[ self.getAxis() ] = -pos[ self.getAxis() ]
move( pos[0], pos[1], pos[2], control, ws=True, rpr=True )
else:
pos = list( getAttr( '%s.t' % otherControl )[0] )
pos[ self.getAxis() ] = -pos[ self.getAxis() ]
setAttr( '%s.t' % control, *pos )
@d_unifyUndo
def match( self, controlAIsSource=True, t=True, r=True, other=True ):
'''
pushes the pose of controlA (or controlB if controlAIsSource is False) to the
"other" control
NOTE: if controlAIsSource is True, then the pose of controlA is mirrored and
copied and put on to controlB, otherwise the reverse is done
'''
#if this is a singular pair, bail - there's nothing to do
if self.isSingular():
return
#NOTE:
#restPoseB = restPoseA * offsetMatrix
#and similarly:
#so restPoseB * offsetMatrixInv = restPoseA
if controlAIsSource:
worldMatrix = getWorldRotMatrix( self.controlA )
control = self.controlB
else:
worldMatrix = getWorldRotMatrix( self.controlB )
control = self.controlA
newControlMatrix = self.mirrorMatrix( worldMatrix )
setWorldRotMatrix( control, newControlMatrix, t=False )
setWorldRotMatrix( control, worldMatrix, r=False )
def getPairNodesFromObjs( objs ):
'''
given a list of objects, will return a minimal list of pair nodes
'''
pairs = set()
for obj in objs:
pairNode = ControlPair.GetPairNode( obj )
if pairNode:
pairs.add( pairNode )
return list( pairs )
def getPairsFromObjs( objs ):
return [ ControlPair( pair ) for pair in getPairNodesFromObjs( objs ) ]
def getPairsFromSelection():
return getPairsFromObjs( ls( sl=True ) )
def iterPairAndObj( objs ):
'''
yields a 2-tuple containing the pair node and the initializing object
'''
pairNodesVisited = set()
for obj in objs:
pairNode = ControlPair.GetPairNode( obj )
if pairNode:
if pairNode in pairNodesVisited:
continue
pair = ControlPair( pairNode )
yield pair, obj
pairNodesVisited.add( pairNode )
@d_unifyUndo
def setupMirroringFromNames( mandatoryTokens=('control', 'ctrl') ):
'''
sets up control pairs for all parity based controls in the scene as determined by their names.
'''
import names
#stick the tokens in a set and ensure they're lower-case
mandatoryTokens = set( [ tok.lower() for tok in mandatoryTokens ] )
visitedTransforms = set()
for t in ls( type='transform' ):
if t in visitedTransforms:
continue
visitedTransforms.add( t )
tName = names.Name( t )
if tName.get_parity() is names.Parity.NONE:
continue
containsMandatoryToken = False
for tok in tName.split():
if tok.lower() in mandatoryTokens:
containsMandatoryToken = True
break
if not containsMandatoryToken:
continue
otherT = names.Name( tName ).swap_parity() #swap_parity changes the parity of the instance - Name objects are mutable... ugh! should re-write it
if otherT:
if objExists( str( otherT ) ):
visitedTransforms.add( str( otherT ) )
#sort the controls into left and right - we want the left to be controlA and right to be controlB
controlPairs = [(tName.get_parity(), tName), (otherT.get_parity(), otherT)]
controlPairs.sort()
leftT, rightT = str( controlPairs[0][1] ), str( controlPairs[1][1] )
ControlPair.Create( leftT, rightT )
print 'creating a control pair on %s -> %s' % (leftT, rightT)
#end
| Python |
from baseSkeletonBuilder import *
class Leg(SkeletonPart):
HAS_PARITY = True
PLACER_NAMES = 'footTip', 'footInner', 'footOuter', 'heel'
@property
def thigh( self ): return self[ 0 ]
@property
def knee( self ): return self[ 1 ]
@property
def ankle( self ): return self[ 2 ]
@property
def toe( self ): return self[ 3 ] if len( self ) > 3 else None
@classmethod
def _build( cls, parent=None, buildToe=True, toeCount=0, **kw ):
idx = Parity( kw[ 'idx' ] )
partScale = kw[ 'partScale' ]
parent = getParent( parent )
root = getRoot()
height = xform( root, q=True, ws=True, rp=True )[ 1 ]
dirMult = idx.asMultiplier()
parityName = idx.asName()
sidePos = dirMult * partScale / 10.0
upPos = partScale / 20.0
fwdPos = -(idx / 2) * partScale / 5.0
footHeight = height / 15.0 if buildToe else 0
kneeOutMove = dirMult * partScale / 35.0
kneeFwdMove = partScale / 20.0
thigh = createJoint( 'thigh%s' % parityName )
cmd.parent( thigh, parent, relative=True )
move( sidePos, -upPos, fwdPos, thigh, r=True, ws=True )
knee = createJoint( 'knee%s' % parityName )
cmd.parent( knee, thigh, relative=True )
move( 0, -(height - footHeight) / 2.0, kneeFwdMove, knee, r=True, ws=True )
ankle = createJoint( 'ankle%s' % parityName )
cmd.parent( ankle, knee, relative=True )
move( 0, -(height - footHeight) / 2.0, -kneeFwdMove, ankle, r=True, ws=True )
jointSize( thigh, 2 )
jointSize( ankle, 2 )
allJoints = []
if buildToe:
toe = createJoint( 'toeBase%s' % parityName )
cmd.parent( toe, ankle, relative=True )
move( 0, -footHeight, footHeight * 3, toe, r=True, ws=True )
allJoints.append( toe )
jointSize( toe, 1.5 )
for n in range( toeCount ):
toeN = createJoint( 'toe_%d_%s' % (n, parityName) )
allJoints.append( toeN )
#move( dirMult * partScale / 50.0, 0, partScale / 25.0, toeN, ws=True )
cmd.parent( toeN, toe, relative=True )
rotate( 0, dirMult * 15, 0, thigh, r=True, ws=True )
return [ thigh, knee, ankle ] + allJoints
def _buildPlacers( self ):
placers = []
scale = getItemScale( self.ankle )
p = buildEndPlacer()
p = parent( p, self.toe, r=True )[0]
move( 0, 0, scale/3, p, r=True )
move( 0, 0, 0, p, moveY=True, a=True, ws=True )
placers.append( p )
p = buildEndPlacer()
p = parent( p, self.ankle, r=True )[0]
setAttr( '%s.ty' % p, -scale/1.5 )
move( 0, 0, 0, p, moveY=True, a=True, ws=True )
placers.append( p )
p = buildEndPlacer()
p = parent( p, self.ankle, r=True )[0]
setAttr( '%s.ty' % p, scale/1.5 )
move( 0, 0, 0, p, moveY=True, a=True, ws=True )
placers.append( p )
p = buildEndPlacer()
p = parent( p, self.ankle, r=True )[0]
move( 0, 0, -scale/3, p, r=True )
move( 0, 0, 0, p, moveY=True, a=True, ws=True )
placers.append( p )
return placers
def _align( self, _initialAlign=False ):
normal = getPlaneNormalForObjects( self.thigh, self.knee, self.ankle )
normal *= self.getParityMultiplier()
parity = self.getParity()
alignAimAtItem( self.thigh, self.knee, parity, worldUpVector=normal )
alignAimAtItem( self.knee, self.ankle, parity, worldUpVector=normal )
if self.toe:
alignAimAtItem( self.ankle, self.toe, parity, upVector=ENGINE_UP, upType='scene' )
else:
autoAlignItem( self.ankle, parity, upVector=ENGINE_UP, upType='scene' )
for i in self.getOrphanJoints():
alignItemToLocal( i )
def visualize( self ):
pass
def getIkFkItems( self ):
return self.thigh, self.knee, self.ankle
#end
| Python |
from filesystem import Path, removeDupes, Callback
from api import mel
from names import getCommonPrefix
from baseMelUI import *
import maya.cmds as cmd
import mappingEditor
import skinWeights
import meshUtils
import rigUtils
import time
import api
def isMesh( item ):
shapes = cmd.listRelatives( item, shapes=True, pa=True )
if shapes is None:
return None
for s in shapes:
if cmd.nodeType( s ) == 'mesh':
return s
class LockJointsLayout(MelForm):
SUSPEND_UPDATE = False
def __init__( self, parent ):
MelForm.__init__( self, parent )
self._mesh = None
self._prefix = ''
class JointList(MelObjectScrollList):
def itemAsStr( tsl, item ):
locked = cmd.getAttr( '%s.liw' % item )
prefix = '# ' if locked else ' '
return '%s%s' % (prefix, item.replace( self._prefix, '' ))
self.UI_tsl = JointList( self, ams=True, sc=self.on_selectJoint, dcc=self.on_dcc )
self.POP_tsl = cmd.popupMenu( b=3, p=self.UI_tsl, pmc=self.build_tslMenu )
self.UI_lock = cmd.button( l="lock", c=self.on_lock )
self.UI_unlock = cmd.button( l="unlock", c=self.on_unlock )
self.UI_lockAll = cmd.button( l="LOCK ALL", c=self.on_lockAll )
self.UI_unlockAll = cmd.button( l="UNLOCK ALL", c=self.on_unlockAll )
self( e=True,
af=((self.UI_tsl, 'top', 0),
(self.UI_tsl, 'left', 0),
(self.UI_tsl, 'right', 0),
(self.UI_lock, 'left', 0),
(self.UI_unlock, 'right', 0),
(self.UI_lockAll, 'left', 0),
(self.UI_lockAll, 'bottom', 0),
(self.UI_unlockAll, 'right', 0),
(self.UI_unlockAll, 'bottom', 0)),
ap=((self.UI_lock, 'right', 0, 50),
(self.UI_unlock, 'left', 0, 50),
(self.UI_lockAll, 'right', 0, 50),
(self.UI_unlockAll, 'left', 0, 50)),
ac=((self.UI_tsl, 'bottom', 0, self.UI_lock),
(self.UI_lock, 'bottom', 0, self.UI_lockAll),
(self.UI_unlock, 'bottom', 0, self.UI_unlockAll)) )
self.setSelectionChangeCB( self.on_selectionChange )
self.on_selectionChange()
@classmethod
def Update( cls ):
for inst in cls.IterInstances():
inst.syncSelection()
def iterSelected( self ):
return iter( self.UI_tsl.getSelectedItems() )
def attachToMesh( self, mesh ):
self._mesh = mesh
self._skinCluster = mel.findRelatedSkinCluster( mesh )
joints = cmd.skinCluster( self._skinCluster, q=True, inf=True )
self._prefix = getCommonPrefix( joints )
self.UI_tsl.setItems( joints )
self.on_updateState()
def updateJointState( self, joint ):
self.UI_tsl.update()
def setLockStateForSelected( self, state=True, updateUI=True ):
for j in self.iterSelected():
cmd.setAttr( '%s.liw' % j, state )
if updateUI:
self.on_updateState()
def setLockStateForAll( self, state=True, updateUI=True ):
for j in self.UI_tsl:
cmd.setAttr( '%s.liw' % j, state )
if updateUI:
self.on_updateState()
def smoothBetweenSelectedJoints( self ):
'''
performs a flood smooth between the selected joints
'''
#grab initial state
initialLockState = [ cmd.getAttr( '%s.liw' % j ) for j in self.UI_tsl ]
initMode = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, sao=True )
initOpacity = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, opacity=True )
initValue = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, value=True )
self.setLockStateForAll( True, False )
self.setLockStateForSelected( False, False )
#perform the smooth
cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, sao='smooth' )
j = self.iterSelected().next()
if j is not None:
cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, value=1, opacity=1, clear=True )
#restore state
cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, sao=initMode )
cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, opacity=initOpacity )
cmd.artAttrSkinPaintCtx( cmd.currentCtx(), e=True, value=initValue )
for j, state in zip( self.UI_tsl, initialLockState ):
cmd.setAttr( '%s.liw' % j, state )
def syncSelection( self ):
'''
syncs the list selection with the existing paint skin weights UI
'''
cur = cmd.artAttrSkinPaintCtx( cmd.currentCtx(), q=True, inf=True )
if cur is None:
return
self.UI_tsl.clearSelection()
self.UI_tsl.selectByValue( cur )
### MENU BUILDERS ###
def build_tslMenu( self, *a ):
cmd.setParent( a[ 0 ], m=True )
cmd.menu( a[ 0 ], e=True, dai=True )
numSelected = sum(( 1 for j in self.iterSelected() ))
cmd.menuItem( l="Select Verts For Joint", c=self.on_selectVerts )
if numSelected > 1:
cmd.menuItem( l="Select Verts Shared By Selected", c=self.on_selectIntersectingVerts )
cmd.menuItem( l="Select Whole Mesh", c=self.on_selectMesh )
cmd.menuItem( d=True )
#cmd.menuItem( l="Smooth Between Selected Joints", c=self.on_smooth )
### EVENT HANDLERS ###
def on_selectionChange( self, *a ):
self.syncSelection()
sel = cmd.ls( sl=True )
for s in sel:
mesh = isMesh( s )
#its already setup! bail!
if self._mesh == mesh:
return
if mesh:
self.attachToMesh( mesh )
return
def on_updateState( self, *a ):
if self.SUSPEND_UPDATE:
return
self.UI_tsl.update()
def on_selectJoint( self, *a ):
if cmd.currentCtx() == 'artAttrSkinContext':
selJ = self.iterSelected().next()
if selJ is None:
return
mel.artSkinSelectInfluence( 'artAttrSkinPaintCtx', selJ, selJ )
def on_dcc( self, *a ):
cmd.select( cl=True )
for j in self.iterSelected():
cmd.select( j, add=True )
def on_lock( self, *a ):
self.setLockStateForSelected()
def on_unlock( self, *a ):
self.setLockStateForSelected( False )
def on_lockAll( self, *a ):
self.setLockStateForAll()
def on_unlockAll( self, *a ):
self.setLockStateForAll( False )
def on_selectVerts( self, *a ):
selJoints = self.UI_tsl.getSelectedItems()
if not selJoints:
return
verts = []
for j in selJoints:
verts += meshUtils.jointVertsForMaya( j )
if verts:
cmd.hilite( [ self._mesh ] )
cmd.select( verts )
mel.artAttrSkinToolScript( 4 )
def on_selectIntersectingVerts( self, *a ):
selJoints = self.UI_tsl.getSelectedItems()
if not selJoints:
return
allVerts = []
jointVerts = {}
for j in selJoints:
jointVerts[ j ] = verts = meshUtils.jointVertsForMaya( j )
allVerts += verts
allVerts = set( allVerts )
commonVerts = []
for j, jVerts in jointVerts.iteritems():
commonVerts += allVerts.intersection( set( jVerts ) )
if commonVerts:
cmd.hilite( [ self._mesh ] )
cmd.select( commonVerts )
mel.artAttrSkinToolScript( 4 )
def on_selectMesh( self, *a ):
cmd.hilite( unHilite=True )
cmd.select( self._mesh )
mel.artAttrSkinToolScript( 4 )
def on_smooth( self, *a ):
self.smoothBetweenSelectedJoints()
class LockJointsWindow(BaseMelWindow):
WINDOW_NAME = 'lockWeightEditor'
WINDOW_TITLE = 'weight locker'
DEFAULT_SIZE = 300, 400
DEFAULT_MENU = None
FORCE_DEFAULT_SIZE = True
def __new__( cls, **kw ):
return BaseMelWindow.__new__( cls, resizeToFitChildren=True, maximizeButton=False, sizeable=True )
def __init__( self ):
BaseMelWindow.__init__( self )
self.editor = LockJointsLayout( self )
self.show()
class SectionLabel(MelHSingleStretchLayout):
def __init__( self, parent, label ):
MelHSingleStretchLayout.__init__( self, parent )
MelSeparator( self, w=25, h=20 )
MelLabel( self, l=label, h=20 )
s = MelSeparator( self, h=20 )
self.setStretchWidget( s )
self.layout()
class Spacer(MelLabel):
def __new__( cls, parent, size=10 ):
return MelLabel.__new__( cls, parent, w=size, h=size, l='' )
def __init__( self, parent, size=10 ):
MelLabel.__init__( self, parent, size )
class SkinButtonsLayout(MelHLayout):
def __init__( self, parent ):
MelHLayout.__init__( self, parent )
a = self.UI_skinOff = MelButton( self, l='Turn Skinning Off', c=self.on_skinOff )
b = self.UI_skinOn = MelButton( self, l='Turn Skinning On', c=self.on_skinOn )
c = MelButton( self, l='Reset All Skin Clusters', c=self.on_resetSkin )
self.updateSkinButtons()
self.layout()
def updateSkinButtons( self ):
state = rigUtils.getSkinClusterEnableState()
self.UI_skinOn( e=True, en=not state )
self.UI_skinOff( e=True, en=state )
### EVENT HANDLERS ###
def on_skinOff( self, e=None ):
rigUtils.disableSkinClusters()
self.updateSkinButtons()
def on_skinOn( self, e=None ):
rigUtils.enableSkinClusters()
self.updateSkinButtons()
def on_resetSkin( self, e=None ):
for sc in ls( typ='skinCluster' ):
rigUtils.resetSkinCluster( sc )
class WeightsToOtherLayout(MelHLayout):
def __init__( self, parent ):
MelHLayout.__init__( self, parent )
self.UI_toParent = MelButton( self, l='Weighting To Parent Joint', ann='Transfers weighting from all selected joints to their respective parents', c=self.on_toParent )
self.UI_toOther = MelButton( self, l='Weighting To Last Selected Joint', ann='Transfers the weighting from the selected joints to the joint that was selected last', c=self.on_toOther )
self.layout()
### EVENT HANDLERS ###
def on_toParent( self, e=None ):
sel = cmd.ls( sl=True, type='transform' ) or []
for s in sel:
meshUtils.weightsToOther( s )
def on_toOther( self, e=None ):
sel = cmd.ls( sl=True, type='transform' ) or []
lastSelectedJoint = sel.pop()
for s in sel:
meshUtils.weightsToOther( s, lastSelectedJoint )
class MeshMappingEditor(mappingEditor.MappingEditor):
WINDOW_NAME = 'skinWeightsMeshMapper'
WINDOW_TITLE = 'Mesh Re-Map Editor'
class JointMappingEditor(mappingEditor.MappingEditor):
WINDOW_NAME = 'skinWeightsJointMapper'
WINDOW_TITLE = 'Joint Re-Map Editor'
class SkinWeightsLayout(MelColumnLayout):
LBL_MESH_REMAP_BUTTON_HASMAP = "define mesh re-mapping (map defined)"
LBL_MESH_REMAP_BUTTON_NOMAP = "define mesh re-mapping"
LBL_JOINT_REMAP_BUTTON_HASMAP = "define joint re-mapping (map defined)"
LBL_JOINT_REMAP_BUTTON_NOMAP = "define joint re-mapping"
def __init__( self, parent, *a, **kw ):
MelColumnLayout.__init__( self, parent, *a, **kw )
SectionLabel( self, 'store options' )
hLayout = MelHSingleStretchLayout( self )
self.UI_fileLbl = MelLabel( hLayout, l="weight file (optional)" )
self.UI_file = MelTextField( hLayout )
hLayout.setStretchWidget( self.UI_file )
hLayout.layout()
MelPopupMenu( self.UI_file, pmc=self.build_popup )
self.UI_storeA = MelButton( self, l="store selection to file", c=self.on_storeA )
#self.UI_storeB = MelButton( self, l="store joint volumes to file", c=self.on_storeB )
Spacer( self )
SectionLabel( self, 'restore options' )
hLayout = MelHSingleStretchLayout( self )
self.UI_average = MelCheckBox( hLayout, l="average found verts", v=1 )
self.UI_ratioLbl = MelLabel( hLayout, l="max ratio" )
self.UI_ratio = MelFloatField( hLayout, v=2, w=50 )
hLayout.setStretchWidget( self.UI_ratio )
hLayout.layout()
self.UI_mirror = MelCheckBox( self, l="mirror on restore", v=0 )
self.UI_meshMapping = MelButton( self, l=self.LBL_MESH_REMAP_BUTTON_NOMAP, c=self.on_meshMap )
self.UI_jointMapping = MelButton( self, l=self.LBL_JOINT_REMAP_BUTTON_NOMAP, c=self.on_jointMap )
self.UI_meshMapping.hide()
self.UI_jointMapping.hide()
#SectionLabel( mainLayout, 'restore options' )
#self.UI_restoreById = MelCheckBox( mainLayout, l="restore by id", v=0, cc=self.on_changeRestoreMode )
self.UI_restore = MelButton( self, l="restore from tmp file", c=self.on_restore )
self.on_changeRestoreMode()
def getMeshRemapDict( self ):
try:
return self._UI_meshMap.getMapping().asFlatDict()
except AttributeError:
return None
def getJointRemapDict( self ):
try:
return self._UI_jointMap.getMapping().asFlatDict()
except AttributeError:
return None
### MENU BUILDERS ###
def build_popup( self, parent, *a ):
cmd.setParent( parent, m=True )
cmd.menu( parent, e=True, dai=True )
thisFile = Path( cmd.file( q=True, sn=True ) )
#if the file doesn't exist, then use teh cwd
if not thisFile.exists():
thisFile = thisFile.getcwd() / "tmp.ma"
dir = thisFile.up()
curFile = Path( cmd.textField( self.UI_file, q=True, tx=True ) )
for f in dir.files():
if f.hasExtension( skinWeights.EXTENSION ):
cmd.menuItem( l=f.name(), cb=f==curFile, c=api.Callback( cmd.textField, self.UI_file, e=True, tx=f ) )
cmd.menuItem( d=True )
cmd.menuItem( l="browse", c=self.on_browseWeightFile )
cmd.menuItem( d=True )
cmd.menuItem( l="clear", c=lambda *a: cmd.textField( self.UI_file, e=True, tx='' ) )
if curFile.exists():
cmd.menuItem( d=True )
api.addExploreToMenuItems( curFile )
### EVENT HANDLERS ###
def on_changeRestoreMode( self, *a ):
#if self.UI_restoreById.getValue():
#self.UI_average.disable()
##self.UI_doPreview.disable()
#self.UI_ratio.disable()
#self.UI_mirror.disable()
#self.UI_meshMapping.enable()
#self.UI_jointMapping.disable()
#else:
self.UI_average.enable()
#self.UI_doPreview.enable()
self.UI_ratio.enable()
self.UI_mirror.enable()
self.UI_meshMapping.disable()
self.UI_jointMapping.enable()
def on_meshMap( self, *a ):
try:
mapping = self._UI_meshMap.getMapping()
self._UI_meshMap = MeshMappingEditor()
self._UI_meshMap.editor.setMapping( mapping )
self._UI_meshMap.editor.ALLOW_MULTI_SELECTION = False
except AttributeError:
filepath = self.getFilepath()
data = WeightSaveData( filepath.unpickle() )
meshes = list( data.getUsedMeshes() )
sceneMeshes = cmd.ls( typ='mesh' )
if sceneMeshes:
sceneMeshes = cmd.listRelatives( sceneMeshes, p=True, pa=True )
mapping = names.Mapping( meshes, sceneMeshes, threshold=0.1 )
self._UI_meshMap = MeshMappingEditor()
self._UI_meshMap.editor.setMapping( mapping )
self._UI_meshMap.editor.ALLOW_MULTI_SELECTION = False
self.on_mappingUIStatus()
def on_jointMap( self, *a ):
try:
mapping = self._UI_jointMap.getMapping()
self._UI_jointMap = MeshMappingEditor()
self._UI_jointMap.editor.setMapping( mapping )
self._UI_jointMap.editor.ALLOW_MULTI_SELECTION = False
except AttributeError:
filepath = self.getFilepath()
data = WeightSaveData( filepath.unpickle() )
joints = list( data.getUsedJoints() )
sceneJoints = cmd.ls( typ='joint' )
mapping = names.Mapping( joints, sceneJoints, threshold=0.1 )
self._UI_jointMap = JointMappingEditor()
self._UI_jointMap.editor.setMapping( mapping )
self._UI_jointMap.editor.ALLOW_MULTI_SELECTION = False
self.on_mappingUIStatus()
def on_browseWeightFile( self, *a ):
startDir = getDefaultPath().up()
filepath = cmd.fileDialog( directoryMask= startDir / "/*.weights" )
if filepath:
cmd.textField( self.UI_file, e=True, tx=filepath )
def on_storeA( self, *a ):
kw = {}
if self.UI_file.getValue():
kw[ 'filepath' ] = Path( self.UI_file.getValue() )
skinWeights.saveWeights( cmd.ls( sl=True ), **kw )
def on_storeB( self, *a ):
kw = {}
if self.UI_file.getValue():
kw[ 'filepath' ] = Path( self.UI_file.getValue() )
joints = cmd.ls( type='joint', r=True )
jointMeshes = removeDupes( cmd.listRelatives( joints, ad=True, pa=True, type='mesh' ) )
skinWeights.saveWeights( jointMeshes, **kw )
def on_restore( self, *a ):
filepath = None
if self.UI_file.getValue():
filepath = Path( self.UI_file.getValue() )
skinWeights.loadWeights( cmd.ls( sl=True ),
filepath,
True, #not self.UI_restoreById.getValue(),
self.UI_ratio.getValue(),
(-1,) if self.UI_mirror.getValue() else None,
averageVerts=self.UI_average.getValue(),
doPreview=False, #self.UI_doPreview.getValue(),
meshNameRemapDict=self.getMeshRemapDict(),
jointNameRemapDict=self.getJointRemapDict() )
def on_mappingUIStatus( self, *a ):
#do we have a mesh re-map?
try:
self._UI_meshMap
self.UI_meshMapping( e=True, l=self.LBL_MESH_REMAP_BUTTON_HASMAP )
except AttributeError:
self.UI_meshMapping( e=True, l=self.LBL_MESH_REMAP_BUTTON_NOMAP )
#do we have a joint re-map?
try:
self.UI_jointMapping( e=True, l=self.LBL_JOINT_REMAP_BUTTON_HASMAP )
except AttributeError:
self.UI_jointMapping( e=True, l=self.LBL_JOINT_REMAP_BUTTON_NOMAP )
class SkinWeightsWindow(BaseMelWindow):
WINDOW_NAME = 'weightSave'
WINDOW_TITLE = 'weight save'
DEFAULT_SIZE = 425, 375
DEFAULT_MENU = None
HELP_MENU = WINDOW_NAME, 'hamish@valvesoftware.com', None
FORCE_DEFAULT_SIZE = False
def __init__( self ):
BaseMelWindow.__init__( self )
scroll = MelScrollLayout( self )
col = MelColumnLayout( scroll, rs=5 )
SkinWeightsLayout( col )
Spacer( col )
SectionLabel( col, 'Skinning Control' )
SkinButtonsLayout( col )
Spacer( col )
SectionLabel( col, 'Weight Transfer' )
WeightsToOtherLayout( col )
Spacer( col )
SectionLabel( col, 'Transfer Skinning' )
def tmp( *a ):
sel = cmd.ls( sl=True )
if len( sel ) > 1:
src = sel.pop( 0 )
for tgt in sel:
skinWeights.transferSkinning( src, tgt )
MelButton( col, l='Transfer From Source to Target', c=tmp )
self.show()
self.layout()
#end
| Python |
import os
from consoleChroma import Good
from filesystem import Path, removeDupes
from dependencies import generateDepTree, makeScriptPathRelative
_THIS_FILE = Path( os.path.abspath( __file__ ) )
_PYTHON_TOOLS_TO_PACKAGE = _THIS_FILE.up() / 'pythonToolsToPackage.txt'
_PACKAGE_DIR_NAME = 'zooToolboxPy'
_PACKAGE_DIR = _THIS_FILE.up( 2 ) / _PACKAGE_DIR_NAME
def cleanPackageDir():
if _PACKAGE_DIR.exists():
_PACKAGE_DIR.delete()
_PACKAGE_DIR.create()
def buildPackage( dependencyTree=None ):
if not _PYTHON_TOOLS_TO_PACKAGE.exists():
raise ValueError( "Cannot find %s file!" % _PYTHON_TOOLS_TO_PACKAGE.name() )
modulesToPackage = []
for toolName in _PYTHON_TOOLS_TO_PACKAGE.read():
if toolName:
if toolName.startswith( '#' ):
continue
elif toolName.startswith( '//' ):
continue
modulesToPackage.append( toolName )
cleanPackageDir()
if dependencyTree is None:
dependencyTree = generateDepTree()
filesToPackage = []
for moduleName in modulesToPackage:
moduleScriptPath = dependencyTree.moduleNameToScript( moduleName )
filesToPackage += dependencyTree.findDependencies( moduleScriptPath, None, False )
if not filesToPackage:
return None
#remove any duplicate files...
filesToPackage = removeDupes( filesToPackage )
#this is a little hacky - but we don't want to re-distribute wingdbstub so lets check to see if its in the list of files
for f in filesToPackage:
if f.name() == 'wingdbstub':
filesToPackage.remove( f )
break
print >> Good, "Found dependencies - %d files" % len( filesToPackage )
for f in filesToPackage:
relativePath = makeScriptPathRelative( f )
packagedPath = _PACKAGE_DIR / relativePath
if len( relativePath ) > 1:
packagedPath.up().create()
f.copy( packagedPath )
print 'copying ----> %s' % f
#now zip up the files into a package
cmdStr = '7z a -r ..\\%s\\zooToolBoxPy.7z ..\\%s\\' % (_PACKAGE_DIR_NAME, _PACKAGE_DIR_NAME)
os.system( cmdStr )
#now write a simple mel script to load the toolbox UI
cmdStr = """global proc zooToolBox() { return; }"""
bootstrapMelScript = _PACKAGE_DIR / 'zooToolBox.mel'
bootstrapMelScript.write( cmdStr )
if __name__ == '__main__':
buildPackage()
#end
| Python |
from baseMelUI import *
from filesystem import *
import maya.cmds as cmd
import api
ui = None
class PresetOptionMenu(MelOptionMenu):
def __init__( self, parent, tool, extension, *a, **kw ):
MelOptionMenu.__init__( self, parent, *a, **kw )
self.setChangeCB( self.on_change )
self._manager = PresetManager( tool, extension )
self._presets = {}
self.update()
def update( self ):
self.clear()
for locale, presets in self._manager.listAllPresets( True ).iteritems():
for preset in presets:
self.append( preset.name() )
self._presets[ preset.name() ] = preset
def getValue( self ):
valueStr = MelOptionMenu.getValue( self )
return self._presets.get( valueStr, None )
### EVENT HANDLERS ###
def on_change( self, *a ):
self.sendEvent( 'presetChanged', self.getValue() )
class PresetLayout(MelFormLayout):
ALLOW_MULTI_SELECTION = True
def __new__( cls, parent, *a, **kw ):
return MelForm.__new__( cls, parent )
def __init__( self, parent, tool, locale=LOCAL, ext=DEFAULT_XTN ):
MelForm.__init__( self, parent )
self.tool = tool
self.locale = locale
self.ext = ext
self.presetManager = PresetManager(tool, ext)
self.populate()
def populate( self ):
children = self( q=True, ca=True )
if children is not None:
for c in children:
cmd.deleteUI( c )
other = self.other()
otherLbl = "<-- %s" % other
cmd.setParent( self )
self.UI_lbl_title = cmd.text(l='Managing "%s" presets' % self.ext)
self.UI_lbl_presets = cmd.text(l="%s presets" % self.locale)
self.UI_button_swap = cmd.button(h=18, l="view %s presets" % other, c=self.swap)
self.UI_tsl_presets = cmd.textScrollList(allowMultiSelection=self.ALLOW_MULTI_SELECTION, sc=self.updateButtonStatus)
self.UI_button_1 = cmd.button(l="move to %s" % other, c=self.move)
self.UI_button_2 = cmd.button(l="copy to %s" % other, c=self.copy)
self.UI_button_3 = cmd.button(l="rename", c=self.rename)
self.UI_button_4 = cmd.button(l="delete", c=self.delete)
self.POP_filemenu = cmd.popupMenu(b=3, p=self.UI_tsl_presets, pmc=self.popup_filemenu)
self( e=True,
af=((self.UI_lbl_title, "top", 5),
(self.UI_lbl_title, "left", 5),
(self.UI_lbl_presets, "left", 10),
(self.UI_button_swap, "right", 5),
(self.UI_tsl_presets, "left", 5),
(self.UI_tsl_presets, "right", 5),
(self.UI_button_1, "left", 5),
(self.UI_button_2, "right", 5),
(self.UI_button_3, "left", 5),
(self.UI_button_3, "bottom", 5),
(self.UI_button_4, "right", 5),
(self.UI_button_4, "bottom", 5)),
ac=((self.UI_lbl_presets, "top", 10, self.UI_lbl_title),
(self.UI_button_swap, "top", 7, self.UI_lbl_title),
(self.UI_button_1, "bottom", 0, self.UI_button_3),
(self.UI_button_swap, "left", 10, self.UI_lbl_presets),
(self.UI_tsl_presets, "top", 10, self.UI_lbl_presets),
(self.UI_tsl_presets, "bottom", 5, self.UI_button_1),
(self.UI_button_2, "bottom", 0, self.UI_button_4)),
ap=((self.UI_button_1, "right", 0, 50),
(self.UI_button_2, "left", 0, 50),
(self.UI_button_3, "right", 0, 50),
(self.UI_button_4, "left", 0, 50)) )
self.updateList()
def other( self ):
'''
returns the "other" locale
'''
return LOCAL if self.locale == GLOBAL else GLOBAL
def updateList( self ):
'''
refreshes the preset list
'''
presets = self.presetManager.listPresets(self.locale)
cmd.textScrollList(self.UI_tsl_presets, e=True, ra=True)
self.presets = presets
for p in presets:
cmd.textScrollList(self.UI_tsl_presets, e=True, a=p[-1])
self.updateButtonStatus()
def updateButtonStatus( self, *args ):
selected = self.selected()
numSelected = len(selected)
if numSelected == 0:
cmd.button(self.UI_button_1, e=1, en=0)
cmd.button(self.UI_button_2, e=1, en=0)
cmd.button(self.UI_button_3, e=1, en=0)
cmd.button(self.UI_button_4, e=1, en=0)
elif numSelected == 1:
cmd.button(self.UI_button_1, e=1, en=1)
cmd.button(self.UI_button_2, e=1, en=1)
cmd.button(self.UI_button_3, e=1, en=1)
cmd.button(self.UI_button_4, e=1, en=1)
else:
cmd.button(self.UI_button_1, e=1, en=1)
cmd.button(self.UI_button_2, e=1, en=1)
cmd.button(self.UI_button_3, e=1, en=0)
cmd.button(self.UI_button_4, e=1, en=1)
def selected( self ):
'''
returns the selected presets as Path instances - if nothing is selected, an empty list is returned
'''
try:
selectedIdxs = [idx-1 for idx in cmd.textScrollList(self.UI_tsl_presets, q=True, sii=True)]
selected = [self.presets[n] for n in selectedIdxs]
return selected
except TypeError: return []
def getSelectedPresetNames( self ):
selected = cmd.textScrollList( self.UI_tsl_presets, q=True, si=True ) or []
return [ Path( s ).name() for s in selected ]
def getSelectedPresetName( self ):
try: return self.getSelectedPresetNames()[ 0 ]
except IndexError:
return None
def copy( self, *args ):
files = []
for s in self.selected():
files.append( s.copy() )
self.sendEvent( 'presetsCopied', files )
def delete( self, *args ):
files = self.selected()
for s in files:
s.delete()
self.updateList()
self.sendEvent( 'presetsDeleted', files )
def move( self, *args ):
files = []
movedFiles = []
for s in self.selected():
ff = s.move()
movedFiles.append( ff )
self.updateList()
self.sendEvent( 'presetsMoved', files )
def rename( self, *args ):
'''
performs the prompting and renaming of presets
'''
selected = self.selected()[0]
ans, newName = api.doPrompt(m='new name', tx=selected.name())
if ans != api.OK:
return
if not newName.endswith('.'+ self.ext):
newName += '.'+ self.ext
renamedPreset = selected.rename( newName )
self.updateList()
self.sendEvent( 'presetRenamed', selected, renamedPreset )
def swap( self, *args ):
'''
performs the swapping from the local to global locale
'''
self.locale = self.other()
self.populate()
def syncall( self, *a ):
'''
syncs to ALL global presets for the current tool - NOTE: this syncs to all global preset dirs in
the mod hierarchy...
'''
dirs = getPresetDirs(self.locale, self.tool)
for dir in dirs:
#P4Data(dir).sync()
print 'syncing to %s...' % dir.resolve().asdir()
self.updateList()
def on_notepad( self, filepath ):
filepath = Path( filepath )
subprocess.Popen( 'notepad "%s"' % filepath.asNative(), cwd=filepath.up() )
def popup_filemenu( self, parent, *args ):
cmd.menu(parent, e=True, dai=True)
cmd.setParent(parent, m=True)
other = self.other()
items = self.selected()
numItems = len(items)
if numItems:
cmd.menuItem(l='copy to %s' % other, c=self.copy)
cmd.menuItem(l='move to %s' % other, c=self.move)
if len(items) == 1:
filepath = items[0].resolve()
cmd.menuItem(d=True)
cmd.menuItem(l='open in notepad', c=lambda *x: self.on_notepad( filepath ))
cmd.menuItem(d=True)
api.addExploreToMenuItems(filepath)
cmd.menuItem(d=True)
cmd.menuItem(l='delete', c=self.delete)
#if the file is a global file, display an option to sync to presets
if self.locale == GLOBAL:
if numItems: cmd.menuItem(d=True)
cmd.menuItem(l='sync to presets', c=self.syncall)
#if no files are selected, prompt the user to select files
if numItems == 0: cmd.menuItem(en=False, l='select a preset file')
PresetForm = PresetLayout
class PresetWindow(BaseMelWindow):
WINDOW_NAME = 'presetWindow'
WINDOW_TITLE = 'Preset Manager'
DEFAULT_SIZE = 275, 325
DEFAULT_MENU = 'Perforce'
FORCE_DEFAULT_SIZE = True
def __new__( cls, *a, **kw ):
return BaseMelWindow.__new__( cls )
def __init__( self, tool, locale=LOCAL, ext=DEFAULT_XTN ):
BaseMelWindow.__init__( self )
self.editor = PresetForm( self, tool, locale, ext )
cmd.setParent( self.getMenu( self.DEFAULT_MENU ), m=True )
cmd.menuItem(l='Sync to Global Presets', c=lambda *a: self.editor.syncall())
self.show()
def presetsCopied( self, presets ):
pass
def presetsDeleted( self, presets ):
pass
def presetsMoved( self, presets ):
pass
def presetRenamed( self, preset, renamedPreset ):
pass
PresetUI = PresetWindow
def load( tool, locale=LOCAL, ext=DEFAULT_XTN ):
'''
this needs to be called to load the ui properly in maya
'''
global ui
ui = PresetUI(tool, locale, ext)
#end
| Python |
from baseMelUI import *
from animLib import *
import presetsUI
import xferAnimUI
__author__ = 'mel@macaronikazoo.com'
def getSelectedChannelBoxAttrNames():
attrNames = cmd.channelBox( 'mainChannelBox', q=True, sma=True ) or []
attrNames += cmd.channelBox( 'mainChannelBox', q=True, ssa=True ) or []
attrNames += cmd.channelBox( 'mainChannelBox', q=True, sha=True ) or []
return attrNames
class AnimLibClipLayout(MelForm):
SLIDER_VISIBLE = { kPOSE: True,
kANIM: False }
def __new__( cls, parent, library, locale, clipPreset ):
return MelHLayout.__new__( cls, parent )
def __init__( self, parent, library, locale, clipPreset ):
MelForm.__init__( self, parent )
self.clipPreset = clipPreset
self.name = self.clipPreset.niceName
self.isActive = False
self.preClip = {}
self.objs = []
self.mapping = {}
self.type = self.clipPreset.getType()
self.optionsLayout = self.getParentOfType( AnimLibLayout )
#cache the apply method locally - mainly for brevity in subsequent code...
self.apply = clipPreset.apply
#read the clip and cache some data...
self.blended = None
self.build()
def build( self ):
'''
populates the top level form with ui widgets
'''
self.UI_icon = MelIconButton( self, l=self.name(), image=str(self.clipPreset.icon.resolve()), w=kICON_W_H[0], h=kICON_W_H[1], c=self.onApply, sourceType='python', ann="click the icon to apply the clip, or use the slider to partially apply it. if you don't like the icon, right click and choose re-generate icon" )
typeLbl = ClipPreset.TYPE_LABELS[ self.clipPreset.getType() ]
self.UI_lbl = MelLabel( self, l='%s clip: %s' % (typeLbl, self.name()), font='boldLabelFont', ann="this is the clip's name. right click and choose rename to change the clip's name" )
#setup the slider
self.UI_slider = MelFloatSlider( self, v=0, min=0, max=1, ann='use the slider to partially apply a clip, or click the icon to apply it completely' )
self.UI_slider.setPreChangeCB( self.preDrag )
self.UI_slider.setChangeCB( self.onDrag )
self.UI_slider.setPostChangeCB( self.postDrag )
self.UI_slider.DISABLE_UNDO_ON_DRAG = True
self.UI_slider.setVisibility( self.SLIDER_VISIBLE[ self.type ] )
MelPopupMenu( self, pmc=self.buildMenu )
#do layout
self( e=True,
af=((self.UI_icon, 'left', 0),
(self.UI_lbl, 'top', 2),
(self.UI_lbl, 'right', 0),
(self.UI_slider, 'top', 20),
(self.UI_slider, 'right', 0)),
ac=((self.UI_lbl, 'left', 10, self.UI_icon),
(self.UI_slider, 'left', 0, self.UI_icon)) )
def unpickle( self ):
return self.clipPreset.unpickle()
@property
def clipObjs( self ):
return self.unpickle()[ 'objects' ]
@property
def clipInstance( self ):
return self.unpickle()[ 'clip' ]
def onApply( self, slam=False ):
opts = self.optionsLayout.getOptions()
opts[ 'slam' ] = slam
if opts[ 'attrSelection' ]:
attributes = cmd.channelBox( 'mainChannelBox', q=True, sma=True ) or cmd.channelBox( 'mainChannelBox', q=True, sha=True ) or None
else:
attributes = None
self.apply( cmd.ls(sl=True), attributes, **opts )
def buildMenu( self, parent, *args ):
cmd.setParent( parent, m=True )
cmd.menu( parent, e=True, dai=True )
cmd.menuItem( l=self.name(), boldFont=True )
if self.clipPreset.locale == LOCAL:
cmd.menuItem( l='publish to global -->', c=self.onPublish )
def onIcon(*x):
generateIcon(self.clipPreset)
self.refreshIcon()
cmd.menuItem( l='re-generate icon', c=onIcon )
cmd.menuItem( d=True )
cmd.menuItem( l='delete', c=lambda *x: self.delete() )
cmd.menuItem( l='rename', c=self.onRename )
cmd.menuItem( d=True )
cmd.menuItem( l='slam clip into scene', c=self.onSlam )
cmd.menuItem( l='select items in clip', c=self.onSelect )
cmd.menuItem( l='map names manually', c=self.onMapping )
cmd.menuItem( d=True )
cmd.menuItem( l='edit clip', c=self.onEdit )
cmd.menuItem( d=True )
api.addExploreToMenuItems(self.clipPreset)
def onPublish( self, *args ):
movedPreset = self.clipPreset.move()
self.delete()
self.sendEvent( 'populateClips' )
def onSelect( self, arg ):
objs = self.clipPreset.getClipObjects()
existingObjs = []
sceneTransforms = cmd.ls( typ='transform' )
for o in objs:
if not cmd.objExists( o ):
newO = names.matchNames( [o], sceneTransforms, threshold=kDEFAULT_MAPPING_THRESHOLD )[ 0 ]
if not cmd.objExists( newO ):
print 'WARNING :: %s NOT FOUND IN SCENE!!!' % o
continue
existingObjs.append( newO )
print 'WARNING :: re-mapping %s to %s' % (o, newO)
else:
existingObjs.append( o )
cmd.select( existingObjs )
def onSlam( self, arg ):
self.onApply( True )
def onMapping( self, *args ):
mapping = Mapping( cmd.ls(sl=True), self.clipObjs )
#convert the mapping to the type of mapping expected by the xfer anim editor - ie a single source maps to a list of targets instead of a single target...
xferAnimMapping = {}
for src, tgt in mapping.iteritems():
xferAnimMapping[ src ] = [ tgt ]
xferAnimUI.XferAnimWindow( mapping=xferAnimMapping, clipPreset=self.clipPreset )
def onEdit( self, *args ):
AnimClipChannelEditorWindow( self.clipPreset )
def onRename( self, *args ):
ans, name = api.doPrompt(t='new name', m='enter new name', tx=self.name())
if ans != api.OK:
return
self.clipPreset = self.clipPreset.rename( name )
self.clear()
self.populateUI()
def preDrag( self ):
self.autoKeyBeginState = cmd.autoKeyframe( q=True, state=True )
cmd.autoKeyframe( e=True, state=False )
opts = self.optionsLayout.getOptions()
if opts[ 'attrSelection' ]:
attributes = cmd.channelBox( 'mainChannelBox', q=True, sma=True ) or cmd.channelBox( 'mainChannelBox', q=True, sha=True ) or None
else:
attributes = None
self.objs = objs = cmd.ls( sl=True )
tgts = names.matchNames( self.clipObjs, objs, threshold=kDEFAULT_MAPPING_THRESHOLD )
self.mapping = mapping = Mapping( tgts, self.clipObjs )
self.preClip = self.clipInstance.__class__( objs, *self.clipInstance.generatePreArgs() )
self.blended = self.clipInstance.blender( self.preClip, self.clipInstance, mapping, attributes )
def onDrag( self, value ):
value = float( value )
self.blended( value )
def postDrag( self, value ):
cmd.autoKeyframe( e=True, state=self.autoKeyBeginState )
value = float( value )
self.blended( value )
self.reset()
def refreshIcon( self ):
self.UI_icon.refresh()
def delete( self ):
self.clipPreset.delete()
MelForm.delete( self )
def reset( self ):
self.UI_slider.reset( False )
class AnimClipChannelEditorLayout(MelVSingleStretchLayout):
def __init__( self, parent, clipPreset ):
MelVSingleStretchLayout.__init__( self, parent )
self.clipPreset = clipPreset
self.presetDict = presetDict = clipPreset.unpickle()
self.clipDict = clipDict = presetDict[ 'clip' ]
self._dirty = False
#build the UI
hLayout = MelHLayout( self )
vLayout = MelVSingleStretchLayout( hLayout )
self.UI_objList = UI_objList = MelObjectScrollList( vLayout )
UI_removeObjs = MelButton( vLayout, l='Remove Selected Objects' )
vLayout.setStretchWidget( UI_objList )
vLayout.layout()
vLayout = MelVSingleStretchLayout( hLayout )
self.UI_attrList = UI_attrList = MelObjectScrollList( vLayout )
UI_removeAttrs = MelButton( vLayout, l='Remove Selected Attributes' )
vLayout.setStretchWidget( UI_attrList )
vLayout.layout()
UI_objList.allowMultiSelect( True )
UI_attrList.allowMultiSelect( True )
hLayout.expand = True
hLayout.layout()
self.setStretchWidget( hLayout )
#populate the object list
for obj in clipDict:
UI_objList.append( obj )
#build callbacks for the lists
def objSelected():
objs = UI_objList.getSelectedItems()
if not objs:
return
UI_attrList.clear()
attrsAlreadyAdded = set()
for obj in objs:
attrDict = clipDict[ obj ]
for attrName, attrValue in attrDict.iteritems():
if attrName in attrsAlreadyAdded:
continue
self.UI_attrList.append( attrName )
attrsAlreadyAdded.add( attrName )
if attrDict:
self.UI_attrList.selectByIdx( 0, True )
UI_objList.setChangeCB( objSelected )
def removeObjs( *a ):
objs = UI_objList.getSelectedItems()
if not objs:
return
performUpdate = False
for obj in objs:
if obj in clipDict:
self._dirty = True
performUpdate = True
clipDict.pop( obj )
if performUpdate:
UI_objList.clear()
UI_attrList.clear()
for obj in clipDict:
UI_objList.append( obj )
if clipDict:
UI_objList.selectByIdx( 0, True )
UI_removeObjs.setChangeCB( removeObjs )
def removeAttrs( *a ):
objs = UI_objList.getSelectedItems()
if not objs:
return
attrs = UI_attrList.getSelectedItems()
if not attrs:
return
performUpdate = False
for obj in objs:
subDict = clipDict[ obj ]
for attr in attrs:
self._dirty = True
performUpdate = True
if attr in subDict:
subDict.pop( attr )
if performUpdate:
objSelected()
UI_removeAttrs.setChangeCB( removeAttrs )
#set the initial state
if len( self.UI_objList ):
UI_objList.selectByIdx( 0, True )
#build the save/cancel UI...
hLayout = MelHLayout( self )
MelButton( hLayout, l='Save', c=self.on_save )
MelButton( hLayout, l='Cancel', c=lambda *a: self.sendEvent( 'delete' ) )
hLayout.layout()
self.setDeletionCB( self.on_cancel )
self.layout()
def askToSave( self ):
#check to see if changes were made, and if so, ask if the user wants to save them...
if self._dirty:
BUTTONS = YES, NO, CANCEL = 'Yes', 'No', 'Cancel'
ret = cmd.confirmDialog( t='Overwrite Clip?',
m='Are you sure you want to overwrite the %s clip called %s?' % (ClipPreset.TYPE_LABELS[ self.clipPreset.getType() ],
self.clipPreset.name().split( '.' )[0]),
b=BUTTONS, db=CANCEL )
if ret == CANCEL:
return False
elif ret == YES:
self.clipPreset.pickle( self.presetDict )
self._dirty = False
return True
### EVENT HANDLERS ###
def on_cancel( self, *a ):
self.askToSave()
def on_save( self, *a ):
if self.askToSave():
self.sendEvent( 'delete' )
class AnimClipChannelEditorWindow(BaseMelWindow):
WINDOW_NAME = 'animClipEditor'
WINDOW_TITLE = 'Anim Clip Editor'
DEFAULT_MENU = None
DEFAULT_SIZE = 400, 250
FORCE_DEFAULT_SIZE = False
def __init__( self, clipPreset ):
BaseMelWindow.__init__( self )
AnimClipChannelEditorLayout( self, clipPreset )
self.show()
class AnimLibLocaleLayout(MelVSingleStretchLayout):
def __init__( self, parent, clipManager, locale ):
MelVSingleStretchLayout.__init__( self, parent )
self._locale = locale
self._clipManager = clipManager
self._filterStr = None
self._libraries = None
if locale == GLOBAL:
hLayout = MelHLayout( self )
MelLabel( hLayout, l='global clips' )
MelButton( hLayout, l='sync global clips', c=self.on_sync )
hLayout.layout()
else:
MelLabel( self, l='local clips' )
scroll = MelScrollLayout( self )
self.UI_clips = MelColumnLayout( scroll )
self.setStretchWidget( scroll )
self.layout()
MelPopupMenu( self, pmc=self.buildMenu )
def setLibraries( self, libraries ):
self._libraries = libraries
self.populate()
def getClips( self ):
clips = {}
for library in self._libraries:
clips[ library ] = self._clipManager.getLibraryClips( library )[ self._locale ]
return clips
def populate( self ):
self.UI_clips.clear()
filterStr = self._filterStr
clips = self.getClips()
for library, clips in clips.iteritems():
for clip in clips:
clipName = clip.niceName()
addClip = False
if filterStr:
if filterStr in clipName:
addClip = True
else:
addClip = True
if addClip:
AnimLibClipLayout( self.UI_clips, library, self._locale, clip )
def getFilter( self ):
return self._filterStr
def setFilter( self, filterStr ):
self._filterStr = filterStr
self.populate()
def buildMenu( self, parent, *args ):
cmd.setParent( parent, m=True )
cmd.menu( parent, e=True, dai=True )
cmd.menuItem( l='new pose clip', c=lambda *x: self.sendEvent( 'newClip', kPOSE ) )
cmd.menuItem( l='new anim clip', c=lambda *x: self.sendEvent( 'newClip', kANIM ) )
def on_sync( self, *a ):
#p4run( 'sync', *self._clipManager.getPresetDirs( GLOBAL ) )
self.populate()
self.sendEvent( 'populateLibraries' )
class AnimLibLayout(MelHSingleStretchLayout):
def __init__( self, parent ):
MelHSingleStretchLayout.__init__( self, parent )
AnimClipChannelEditorWindow.Close()
self._clipManager = clipManager = ClipManager()
vLayout = MelVSingleStretchLayout( self )
MelLabel( vLayout, l='clip libraries' )
hLayout = MelHSingleStretchLayout( vLayout )
MelLabel( hLayout, l='filter' )
self.UI_filter = MelTextField( hLayout, cc=self.on_filter )
MelButton( hLayout, l='clear', c=lambda *a: self.UI_filter.clear() )
hLayout.setStretchWidget( self.UI_filter )
hLayout.layout()
self.UI_libraries = MelObjectScrollList( vLayout, ams=True )
self.UI_libraries.setChangeCB( self.on_selectLibrary )
self.UI_newLibrary = MelButton( vLayout, l='new library', w=150, c=self.on_newLibrary )
vLayout.setStretchWidget( self.UI_libraries )
vLayout.layout()
#this is the layout for everything on the right side of the library list
paneLayout = MelVSingleStretchLayout( self )
#add clip filter UI
hLayout = MelHSingleStretchLayout( paneLayout )
MelSpacer( hLayout )
MelLabel( hLayout, l='filter clips' )
self.UI_filterClips = MelTextField( hLayout, cc=self.on_filterClips )
MelButton( hLayout, l='clear', c=lambda *a: self.UI_filterClips.clear() )
hLayout.setStretchWidget( self.UI_filterClips )
hLayout.layout()
#add the libraries
self.UI_panes = MelHLayout( paneLayout )
self.UI_panes.expand = True
self.UI_local = AnimLibLocaleLayout( self.UI_panes, clipManager, LOCAL )
self.UI_global = AnimLibLocaleLayout( self.UI_panes, clipManager, GLOBAL )
self.UI_panes.layout()
#add the load options
hLayout = MelHRowLayout( paneLayout )
self.UI_opt_currentTime = MelCheckBox( hLayout, l='load clip at current time', v=True )
self.UI_opt_additive = MelCheckBox( hLayout, l='load additively' )
#self.UI_opt_currentTime = MelCheckBox( hLayout, l='load additively in world', en=False )
self.UI_opt_attrSelection = MelCheckBox( hLayout, l='use attribute selection', v=BaseClip.kOPT_DEFAULTS[ BaseClip.kOPT_ATTRSELECTION ] )
hLayout.layout()
#add the "new" buttons
hLayout = MelHLayout( paneLayout )
MelButton( hLayout, l='new pose clip', c=self.on_newPose )
MelButton( hLayout, l='new anim clip', c=self.on_newAnim )
hLayout.layout()
paneLayout.setStretchWidget( self.UI_panes )
paneLayout.layout()
self.setStretchWidget( paneLayout )
self.setExpand( True )
self.layout()
self.populateLibraries()
self.setDeletionCB( self.on_close )
def populateLibraries( self ):
UI_libraries = self.UI_libraries
UI_libraries.clear()
libraryNames = self._clipManager.getLibraryNames()
for library in libraryNames:
UI_libraries.append( library )
if libraryNames:
self.UI_libraries.selectByIdx( 0, True )
self.UI_libraries.setFocus()
def populateClips( self ):
self.UI_local.populate()
self.UI_global.populate()
def getOptions( self ):
opts = {}
opts[ BaseClip.kOPT_OFFSET ] = cmd.currentTime( q=True ) if self.UI_opt_currentTime.getValue() else 0
opts[ BaseClip.kOPT_ADDITIVE ] = self.UI_opt_additive.getValue()
opts[ BaseClip.kOPT_ATTRSELECTION ] = self.UI_opt_attrSelection.getValue()
return opts
def getLocalVisibility( self ):
return self.UI_local.getVisibility()
def setLocalVisibility( self, showState ):
#if the global is currently invisible, turn it on - no point having neither local or global invisible...
if not self.UI_global.getVisibility():
self.setGlobalVisibility( True )
self.UI_local.setVisibility( showState )
self.UI_panes.setWeight( self.UI_local, int( showState ) )
self.UI_panes.layout()
def getGlobalVisibility( self ):
return self.UI_global.getVisibility()
def setGlobalVisibility( self, showState ):
#if the local is currently invisible, turn it on - no point having neither local or global invisible...
if not self.UI_local.getVisibility():
self.setLocalVisibility( True )
self.UI_global.setVisibility( showState )
self.UI_panes.setWeight( self.UI_global, int( showState ) )
self.UI_panes.layout()
def newClip( self, clipType ):
theLibrary = self.UI_libraries.getSelectedItems()
if not theLibrary:
return
theLibrary = theLibrary[0]
BUTTONS = OK, CANCEL = 'OK', 'Cancel'
typeLabel = ClipPreset.TYPE_LABELS[ clipType ]
ans = cmd.promptDialog( t='enter %s name' % typeLabel, m='enter the %s name:' % typeLabel, b=BUTTONS, db=OK )
if ans == CANCEL:
return
kwargs = {}
opts = self.getOptions()
if opts.get( 'attrSelection', False ):
kwargs[ 'attrs' ] = getSelectedChannelBoxAttrNames() or None
if clipType == kANIM:
kwargs = { 'startFrame': cmd.playbackOptions( q=True, min=True ),
'endFrame': cmd.playbackOptions( q=True, max=True ) }
objs = cmd.ls( sl=True )
name = cmd.promptDialog( q=True, tx=True )
newClip = ClipPreset( LOCAL, theLibrary, name, clipType )
newClip.write( objs, **kwargs )
#add the clip to the UI
self.UI_local.populate()
### EVENT HANDLERS ###
def on_close( self, *a ):
AnimClipChannelEditorWindow.Close()
def on_selectLibrary( self, *a ):
sel = self.UI_libraries.getSelectedItems()
if sel:
self.UI_local.setLibraries( sel )
self.UI_global.setLibraries( sel )
def on_newLibrary( self, *a ):
BUTTONS = OK, CANCEL = 'OK', 'Cancel'
ans = cmd.promptDialog( t='enter library name', m='enter the library name:', b=BUTTONS, db=OK )
if ans == CANCEL:
return
name = cmd.promptDialog( q=True, tx=True )
self._clipManager.createLibrary( name )
self.populateLibraries()
self.UI_libraries.clearSelection()
self.UI_libraries.selectByValue( name )
self.UI_local.setLibraries( name )
self.UI_global.setLibraries( name )
def on_newPose( self, *args ):
self.newClip( kPOSE )
def on_newAnim( self, *args ):
self.newClip( kANIM )
def on_filter( self, *a ):
self.UI_libraries.setFilter( self.UI_filter.getValue() )
#if there are no selected items, check to see if there are any items and if so select the first one
if not self.UI_libraries.getSelectedIdxs():
if self.UI_libraries.getItems():
self.UI_libraries.selectByIdx( 0, True )
def on_filterClips( self, *a ):
filterStr = self.UI_filterClips.getValue()
self.UI_local.setFilter( filterStr )
self.UI_global.setFilter( filterStr )
class AnimLibWindow(BaseMelWindow):
WINDOW_NAME = 'animLibraryWindow'
WINDOW_TITLE = 'Animation Library'
DEFAULT_SIZE = 750, 400
FORCE_DEFAULT_SIZE = True
DEFAULT_MENU = 'Show'
HELP_MENU = TOOL_NAME, __author__, None
def __init__( self ):
BaseMelWindow.__init__( self )
showMenu = self.getMenu( self.DEFAULT_MENU )
showMenu( e=True, pmc=self.buildShowMenu )
self.UI_editor = AnimLibLayout( self )
self.show()
def buildShowMenu( self, *w ):
showMenu = self.getMenu( self.DEFAULT_MENU )
showMenu.clear()
MelMenuItem( showMenu, l='Show Local Clips', cb=self.UI_editor.getLocalVisibility(), c=self.on_showLocal )
MelMenuItem( showMenu, l='Show Global Clips', cb=self.UI_editor.getGlobalVisibility(), c=self.on_showGlobal )
def on_showLocal( self, *a ):
state = int( a[0] )
self.UI_editor.setLocalVisibility( state )
def on_showGlobal( self, *a ):
state = int( a[0] )
self.UI_editor.setGlobalVisibility( state )
AnimLibUI = AnimLibWindow
def load():
#first make sure there is a default library...
tmp = ClipManager().createLibrary( 'default' )
AnimLibUI()
#end | Python |
"""Documentation about all HELPER function"""
import helper
import document
from nltk.stem import PorterStemmer
stemmer = PorterStemmer()
import nltk.data
sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')
#Gunakan WordPunctTokenizar agar dipisah berdasarkan punctuation
from nltk.tokenize import WordPunctTokenizer
word_tokenizer = WordPunctTokenizer()
import math
class DocumentQueryProcessing:
document_collection_file = ""
stop_list = ""
total_document = 0
one_term_tuples = []
term_frequency_dict = {}
document_frequency_dict = {}
term_weighting_code = ""
document_term_weighting_code = ""
query_term_weighting_code = ""
document_tf_max = -1
document_list = {}
#Menyimpan total term untuk sebuah dokumen
total_term_per_document = {}
#Path inverted file disimpan
inverted_file_saved_path = ""
#Menyimpan boolean value apakah memakai stemming atau tidak
is_use_stemming = True
#term_weighting_code berupa string e.g. lnc.ltc
def __init__(self, document_collection_file, stop_list, is_use_stemming, term_weighting_code, inverted_file_saved_path):
self.document_collection_file = document_collection_file
self.stop_list = stop_list
self.term_weighting_code = term_weighting_code
self.document_term_weighting_code = self.term_weighting_code[0:3]
self.query_term_weighting_code = self.term_weighting_code[4:7]
self.inverted_file_saved_path = inverted_file_saved_path
self.is_use_stemming = is_use_stemming
def lowerCase(self, doc):
doc.lowerCase()
def documentTokenization(self, doc):
document_list_token = doc.titleTokenization() + doc.authorTokenization() + doc.contentTokenization()
document_list_token = [helper.punctuation.sub("", word) for word in document_list_token]
document_list_token = [word for word in document_list_token if word.strip()]
return document_list_token
def stopWordsRemoval(self, document_list_token):
f_stop_words = open(self.stop_list, 'r')
stop_words_list = []
for line in f_stop_words:
stop_words_list.append(line[:len(line)-1])
#print "STOPWORDS :"
#print stop_words_list
document_list_token = [word for word in document_list_token if word not in stop_words_list]
return document_list_token
#Lakukan stemming dengan PorterStemmer
def stemming(self, document_list_token):
for i in range(len(document_list_token)):
document_list_token[i] = stemmer.stem(document_list_token[i])
def updateDFDict(self):
for k in self.term_frequency_dict:
if k in self.document_frequency_dict:
self.document_frequency_dict[k] += 1
else:
self.document_frequency_dict[k] = 1
#Apply tf pada one_term(tuple 5 di inverted file yang tfnya adalah raw_tf)
def getApplyTF(self, tf_code, one_term):
if tf_code == "n":
return one_term[2]
elif tf_code == "l":
return 1 + math.log10(one_term[2])
elif tf_code == "b":
if one_term[2] >0 :
return 1
else:
return 0
elif tf_code == "a":
if self.document_tf_max > 0:
return 0.5 + 0.5*(one_term[2]*1.0/self.document_tf_max)
else:
return 0.5 + 0.5*(one_term[2]*1.0)
#Apply idf pada one_term
def getApplyIDF(self, idf_code, one_term):
if idf_code == "n":
return 1.0
elif idf_code == "t":
if one_term[3] > 0:
return math.log10(self.total_document/one_term[3])
else:
return math.log10(self.total_document)
pass
#Melakukan term weighting pada one_term_tuples dengan document id dari first_index ke second_index
def normalization(self, one_term_tuples, first_index, second_index):
divider = 0.0
for i in range(first_index, second_index+1):
divider += (1.0 * one_term_tuples[i][4] * one_term_tuples[i][4])
divider = math.sqrt(divider)
for i in range(first_index, second_index+1):
if divider > 0:
one_term_tuples[i][4] /= divider
#Melakukan term-weighting pada one_term_tuples
#term_weighting_code terdiri dari 3 code untuk document term weighting
def doDocumentTermWeighting(self, one_term_tuples, term_weighting_code):
#print "document term_weighting code : ", term_weighting_code
for one_term in one_term_tuples:
#First apply the tf
one_term[4] = self.getApplyTF(term_weighting_code[0], one_term)
#Then multiply it with idf
one_term[4] *= self.getApplyIDF(term_weighting_code[1], one_term)
#Apply the normalization
if term_weighting_code[2] == "c":
first_index = 0
for doc_id in self.total_term_per_document:
second_index = first_index + self.total_term_per_document[doc_id] - 1
self.normalization(one_term_tuples, first_index, second_index)
first_index = second_index + 1
def documentCollectionProcessing(self):
#Baca input document_collection
f_document = open(self.document_collection_file, 'r');
document_id = ''
title = ''
author = ''
content = ''
current_state = ''
self.total_document = 0
for line in f_document:
#format pengenal
if (line[0] == '.'):
#id document
if (line[1] == 'I'):
self.total_document += 1
#Kasus sudah membaca 1 dokumen, lakukan processing
if (document_id != ''):
#print "doc id terakhir : ", document_id
document_id = document_id[:len(document_id)-1]
#Inisialisasi object 1 dokumen
one_document = document.Document(document_id, title, author, content)
#Masukkan ke list dokumen
self.document_list[one_document.id] = one_document
#Set lowerCase
self.lowerCase(one_document)
#Lakukan Tokenization
document_list_token = self.documentTokenization(one_document)
#print document_list_token
#Lakukan StopwordsRemoval
document_list_token = self.stopWordsRemoval(document_list_token)
#print "AFTER STOPWORDS :"
#print document_list_token
#Lakukan Stemming
if self.is_use_stemming:
self.stemming(document_list_token)
#print document_list_token
#Ubah term_list ke term_frequency_dictionary
self.term_frequency_dict = helper.termListToTermFrequencyDictionary(document_list_token)
#print self.term_frequency_dict
#Isi total panjang per dokumen
self.total_term_per_document[document_id] = len(self.term_frequency_dict)
self.document_tf_max = -1
for k in self.term_frequency_dict:
if self.document_tf_max < self.term_frequency_dict[k]:
self.document_tf_max = self.term_frequency_dict[k]
self.one_term_tuples.append([k, document_id, self.term_frequency_dict[k], 1, 0.1])
#Update document_frequency_dict
self.updateDFDict()
#print self.document_frequency_dict
#break
document_id = ''
title = ''
author = ''
content = ''
current_state = 'I'
document_id = line[3:]
elif (line[1] == 'T'):
current_state = 'T'
elif (line[1] == 'A'):
current_state = 'A'
elif (line[1] == 'W'):
current_state = 'W'
else:
if (current_state == 'T'):
title += line
elif (current_state == 'A'):
author += line
elif (current_state == 'W'):
content += line
#Hitung juga dokument yang terakhir
if (document_id != ''):
#print "doc id terakhir : ", document_id
document_id = document_id[:len(document_id)-1]
#Inisialisasi object 1 dokumen
one_document = document.Document(document_id, title, author, content)
#Masukkan ke list dokumen
self.document_list[one_document.id] = one_document
#Set lowerCase
self.lowerCase(one_document)
#Lakukan Tokenization
document_list_token = self.documentTokenization(one_document)
#print document_list_token
#Lakukan StopwordsRemoval
document_list_token = self.stopWordsRemoval(document_list_token)
#print "AFTER STOPWORDS :"
#print document_list_token
#Lakukan Stemming
if self.is_use_stemming:
self.stemming(document_list_token)
#print document_list_token
#Ubah term_list ke term_frequency_dictionary
self.term_frequency_dict = helper.termListToTermFrequencyDictionary(document_list_token)
#print self.term_frequency_dict
#Isi total panjang per dokumen
self.total_term_per_document[document_id] = len(self.term_frequency_dict)
for k in self.term_frequency_dict:
if self.document_tf_max < self.term_frequency_dict[k]:
self.document_tf_max = self.term_frequency_dict[k]
self.one_term_tuples.append([k, document_id, self.term_frequency_dict[k], 1, 0.1])
#Update document_frequency_dict
self.updateDFDict()
#print self.one_term_tuples
#print "\n\n\n\n"
#print self.document_frequency_dict
#Update the document frequency in one_term_tuples
for one_term in self.one_term_tuples:
one_term[3] = self.document_frequency_dict[one_term[0]]
#Update term-weighting code
#print "Document tf-max : ", self.document_tf_max
#print "Total document : ", self.total_document
#print self.one_term_tuples
#Lakukan normalization di document term weighting
self.doDocumentTermWeighting(self.one_term_tuples, self.document_term_weighting_code)
#print "AFTER"
#print self.one_term_tuples
#Save the one_term_tuples to inverted file
self.save_to_inverted_file()
def save_to_inverted_file(self):
#sort the one_term_tuples first
self.one_term_tuples = sorted(self.one_term_tuples, key = lambda one_term: one_term[0])
f_inverted_file = open(self.inverted_file_saved_path, 'w')
f_inverted_file.writelines("term doc_id raw_tf df weight\n")
for one_term in self.one_term_tuples:
f_inverted_file.writelines("%s %s %.4f %.4f %.4f\n" %(one_term[0], one_term[1], one_term[2], one_term[3], one_term[4]))
f_inverted_file.close()
pass
def queryProcessing(self, query):
#First, Set lowerCase
query = query.lower()
#Second, Tokenize the query via sentence tokenizer
query_sentence_list_token = sentence_tokenizer.tokenize(query)
#print query_sentence_list_token
#Tokenize again the sentence via word tokenizer
query_list_token = []
for sentence in query_sentence_list_token:
query_list_token += word_tokenizer.tokenize(sentence)
query_list_token = [helper.punctuation.sub("", word) for word in query_list_token]
query_list_token = [word for word in query_list_token if word.strip()]
#Third, do StopWordsRemoval
query_list_token = self.stopWordsRemoval(query_list_token)
#Fourth, do Stemming via PorterStemmer
if self.is_use_stemming:
self.stemming(query_list_token)
#Buat term_frequency dictionary untuk query
query_term_frequency_dict = helper.termListToTermFrequencyDictionary(query_list_token)
#print query_term_frequency_dict
return query_term_frequency_dict
# testing
if __name__ == '__main__':
document_collection_file = 'simple_document_collection.txt'
#query_list_file = 'query_list.txt'
stop_list_file = 'stoplist.txt'
term_weighting_code = "lnc.ltc"
inverted_file_saved_path = "D:\\SEMESTER 7\\IR\\TUBES1\\freedom_ir\\freedom_inverted_file.txt"
inverted_file_saved_path = "freedom_inverted_file.txt"
is_use_stemming = True
document_query_processing = DocumentQueryProcessing(document_collection_file, stop_list_file, is_use_stemming, term_weighting_code, inverted_file_saved_path)
document_query_processing.documentCollectionProcessing()
#print stemmer.stem('cooking')
#print stemmer.stem('cookery')
query = """What problems and concerns are there in making up descriptive titles?
What difficulties are involved in automatically retrieving articles from
approximate titles?
What is the usual relevance of the content of articles to their titles?"""
#print document_query_processing.queryProcessing(query)
| Python |
'''
Created on Oct 30, 2012
@author: dolphinigle
'''
import document_query_processing as dqp
import comparison as cmpr
import relevanceFeedback as rf
import evaluator as eva
class Controller():
'''Responsible as a gate between view and engine.
Created once 'Commence War' (or process) is clicked.
Will be used to ask for action on interactive and experimental
queries.'''
#Finish
def __init__(self,
stopword_filename, # Will be None if not given
inverted_index_filename, # Will be None if not given
document_collection_filename, # Will be None if not given
query_filename, # Will be None if not given
relevance_judgment_filename, # Will be None if not given
is_use_stemming, # 1 if stemming should be used, otherwise 0
doc_tf_type, # String representing tf type: 'binary', 'log', 'raw', or 'augmented'
query_tf_type, # idem above
doc_is_use_idf, # 1 if idf should be used, or 0.
query_is_use_idf, # idem above
doc_is_normalized, # 1 if normalized should be used, or 0
query_is_normalized): # idem abovve
# TODO(irvan): Novan it's your task
#Simpan nama relevance judgment file untuk nanti
self.relevance_judgment_filename = relevance_judgment_filename
print 'Initializing...'
term_weighting_code = ""
#Set doc_tf
if doc_tf_type == "binary":
term_weighting_code += "b"
elif doc_tf_type == "log":
term_weighting_code += "l"
elif doc_tf_type == "augmented":
term_weighting_code += "a"
elif doc_tf_type == "raw":
term_weighting_code += "n"
if doc_is_use_idf:
term_weighting_code += "t"
else:
term_weighting_code += "n"
if doc_is_normalized:
term_weighting_code += "c"
else:
term_weighting_code += "n"
term_weighting_code += "."
if query_tf_type == "binary":
term_weighting_code += "b"
elif query_tf_type == "log":
term_weighting_code += "l"
elif query_tf_type == "augmented":
term_weighting_code += "a"
elif query_tf_type == "raw":
term_weighting_code += "n"
if query_is_use_idf:
term_weighting_code += "t"
else:
term_weighting_code += "n"
if query_is_normalized:
term_weighting_code += "c"
else:
term_weighting_code += "n"
self.dqp_instance = dqp.DocumentQueryProcessing(document_collection_filename, stopword_filename, is_use_stemming, \
term_weighting_code, inverted_index_filename)
self.dqp_instance.documentCollectionProcessing()
#Instance untuk comparison dan menghitung ranking
self.cmpr_instance = cmpr.Comparison(self.dqp_instance)
self.cmpr_instance.searchFileQuery(inverted_index_filename, query_filename)
#
#print "query twm : ", self.dqp_instance.query_term_weighting_code
#x = self.cmpr_instance.calcQueryVector(self.dqp_instance.query_term_weighting_code, "" , True)
#print "EAAA"
#y = self.cmpr_instance.calcDocumentVector()
#print "EAAA"
#self.cmpr_instance.calcAllRank(x, y, 0.0)
#print "EAAA"
self.cmpr_instance.calcAllRank(self.cmpr_instance.calcQueryVector(self.dqp_instance.query_term_weighting_code), self.cmpr_instance.calcDocumentVector(), 0.0)
#Finish
def SaveResultToFile(self, filename):
self.retrieval_result_file = filename
'''The user asks you to save the experimental results to the given filename'''
# TODO(irvan): Novan.
print 'Save result to file %s' % filename
self.cmpr_instance.writeRetrievalResult(filename)
def SavePerformanceToFile(self, filename):
self.evaluation_file = filename
'''Saves performance result to the given filename'''
# TODO(irvan): Novan
print 'Save performance to file %s' % filename
ev = eva.Evaluator(self.retrieval_result_file, self.relevance_judgment_filename)
ev.writeResult(self.evaluation_file)
#ev = Evaluator('result.txt', 'rel.txt')
#ev.writeResult('evaluation.txt')
#Finish
def ExecuteInteractiveQuery(self, query):
'''Executes a query in interactive mode and return a list of results
More exactly, the return type will be a list of documents in order from the
most relevant, second relevant, etc. Each document should be a 3-tuple,
the first element is the title of the document (if present), the second
should be the content of the document, and the third should be the doc id
of the document.
See current return value for example'''
#return [
# ('judul_1', 'isi_dokumen_pertama\nCeritanya pada suatu hari ada seorang anak', 32),
# ('judul 2', 'Hey gw ganteng lho', 6),
# ('Cinderella', 'Pada suatu hari ada seorang ganteng bernama Irvan', 7)]
document_relevant_id_list = []
self.cmpr_instance.searchOneQuery( self.dqp_instance.inverted_file_saved_path, query)
document_relevant_id_list = self.cmpr_instance.calcAllRank(self.cmpr_instance.calcQueryVector(self.dqp_instance.query_term_weighting_code), self.cmpr_instance.calcDocumentVector(), 0.0)[0][1]
#print "document_relevant_id_list : ", document_relevant_id_list
#print type(document_relevant_id_list[0])
#Make document from document_id
document_relevant_list = []
for document_id in document_relevant_id_list:
one_document_tuple = (self.dqp_instance.document_list[str(document_id)].title, self.dqp_instance.document_list[str(document_id)].author + " " + self.dqp_instance.document_list[str(document_id)].content, document_id)
document_relevant_list.append(one_document_tuple)
#print "document_relevant_list : "
#print document_relevant_list
return document_relevant_list
#Finish
def ExecuteInteractiveQueryWithRelevanceFeedback(
self, query, relevant_documents, irrelevant_documents, method, **kwargs):
'''Executes a query in interactive mode using relevance feedback and return
the result.
The format is the same with ExecuteInteractiveQuery
relevant and irrelevant documents are list of document IDs of the
documents.
relevant_documents must already be sorted from the most to the least relevant.
idem irrelevant documents
method is a string of either "rochio", "ide_regular", or "ide_dec_hi"
If method is rochio, kwargs['beta'] and kwargs['gamma'] will contain the
beta and gamma values for the method.'''
# if method == 'rochio':
# Rochio(method, kwargs['beta'], kwargs['alpha'])
#
#print 'Relv Feedback'
#print relevant_documents
#print irrelevant_documents
#print method
#print kwargs
#return [
# ('judul_1', 'Relevance Feedback\nfdsfdfasdf Pak On Lee', 33),
# ('judul 2', 'Hey gw ganteng lho', 6),
# ('Cinderella', 'Pada suatu hari ada seorang ganteng bernama Irvan', 7)]
rf_instance = rf.relevanceFeedback(query, relevant_documents, irrelevant_documents, self.dqp_instance.inverted_file_saved_path, self.cmpr_instance)
document_relevant_id_list = []
if method == "rochio":
document_relevant_id_list = rf_instance.calculate("rocchio", kwargs['beta'], kwargs['gamma'])
elif method == "ide_regular":
document_relevant_id_list = rf_instance.calculate("ide", 1, 1)
elif method == "ide_dec_hi":
document_relevant_id_list = rf_instance.calculate("dechi", 1, 1)
print "document relevant oleh feedback : ", document_relevant_id_list
#Make document from document_id
document_relevant_list = []
for document_id in document_relevant_id_list:
one_document_tuple = (self.dqp_instance.document_list[str(document_id)].title, self.dqp_instance.document_list[str(document_id)].author + " " + self.dqp_instance.document_list[str(document_id)].content, document_id)
document_relevant_list.append(one_document_tuple)
return document_relevant_list
| Python |
import math
from collections import defaultdict
import document_query_processing
class Comparison:
def __init__(self, dqp):
self.inv_dict = defaultdict(list)
self.query_list = []
self.term_list = []
self.term_list_size = 0
self.total_term = 0
self.result = []
self.dqp = dqp
def is_number(self, s):
try:
float(s)
return True
except ValueError:
return False
"""searchFileQuery(string,string)"""
def searchFileQuery(self, inverted_file_name, query_file_name):
inverted_file = open(inverted_file_name, 'r')
query_file = open(query_file_name, 'r')
s = []
inverted_file.readline() # header skip
for line in inverted_file.readlines():
kata = ""
stat = []
for word in line.split(' '):
if(self.is_number(word) == False):
if kata != "":
kata += " "
kata += word
else:
stat.append(float(word))
docid = stat[0]
rawtf = stat[1]
df = stat[2]
weight = stat[3]
s.append((kata, (int(docid),float(rawtf),float(df),float(weight)) ))
self.inv_dict = defaultdict(list)
for k,v in s:
self.inv_dict[k].append(v)
self.total_term = len(self.inv_dict)
self.term_list = []
for x in self.inv_dict:
#print x,self.inv_dict[x]
if x not in self.term_list:
self.term_list.append(x)
self.term_list_size = len(self.term_list)
query = ""
self.query_list = []
for line in query_file.readlines():
if line[0] == '.': # not query
if query != "":
self.query_list.append(self.dqp.queryProcessing(query))
query = ""
else: # query
query += line
self.query_list.append(self.dqp.queryProcessing(query))
#print self.query_list
"""searchOneQuery(string,string,string)"""
def searchOneQuery(self, inverted_file_name, query_string):
inverted_file = open(inverted_file_name, 'r')
s = []
inverted_file.readline() # header skip
for line in inverted_file.readlines():
kata = ""
stat = []
for word in line.split(' '):
if(self.is_number(word) == False):
if kata != "":
kata += " "
kata += word
else:
stat.append(float(word))
docid = stat[0]
rawtf = stat[1]
df = stat[2]
weight = stat[3]
s.append((kata, (int(docid),float(rawtf),float(df),float(weight)) ))
self.inv_dict = defaultdict(list)
for k,v in s:
self.inv_dict[k].append(v)
self.total_term = len(self.inv_dict)
self.term_list = []
for x in self.inv_dict:
#print x,self.inv_dict[x]
if x not in self.term_list:
self.term_list.append(x)
self.term_list_size = len(self.term_list)
query = query_string
self.query_list = []
self.query_list.append(self.dqp.queryProcessing(query))
# print self.query_list
def calcDocumentVector(self):
# return list of document vector
# print self.dqp.total_document
ret = [0]*self.dqp.total_document
#print self.term_list_size
for i in range(len(ret)):
ret[i]=[0]*self.term_list_size
idx = 0
#print ret
for term in self.inv_dict:
for termstat in self.inv_dict[term]:
# ret[docid][term] = weight
ret[termstat[0]-1][idx] = termstat[3]
idx += 1
#print "Banyak document =", len(ret)
#print "Document Vector =", ret
return ret
def vectorSize(self,vector):
# return size of a vector
size = 0
for x in vector:
size += x * x
return math.sqrt(size)
def calcQueryVector(self, query_code):
# return query vector
# ambil tf dari query, df dari dokumen
tf_code = query_code[0]
idf_code = query_code[1]
norm_code = query_code[2]
ret = [0]*len(self.query_list)
for i in range(len(ret)):
ret[i]=[0]*self.term_list_size
#idx = 0
#for query in self.query_list:
#for term in query:
#if term in self.inv_dict:
#for termstat in self.inv_dict[term]:
#print termstat[0]
#ret[idx][term_list.index(term)] = termstat[4]
idx = 0
tf_max = [0]*len(self.query_list) # max tf for each query
for query_dict in self.query_list:
for query in query_dict:
if query_dict[query] >= tf_max[idx]:
tf_max[idx] = query_dict[query]
idx += 1
idx = 0
#print "tf_max =",tf_max
#print "QUERY_LIST = ",self.query_list
for query in self.query_list:
#print "Query=",query
for term in query:
# tf x idf = query[term] * idf
#print "Term =", term
#print "TERM LIST = ", self.term_list
if term not in self.term_list:
continue
termid = self.term_list.index(term)
tf = query[term]
if tf_code == "n":
pass
elif tf_code == "l":
tf = 1 + math.log10(tf)
elif tf_code == "b":
if tf > 0:
tf = 1
else:
tf = 0
elif tf_code == "a":
return 0.5 + 0.5*(tf*1.0/tf_max[idx])
ret[idx][termid] = tf
#print "TERMSTAT"
#print "INV_DICT",self.inv_dict
for termstat in self.inv_dict[term]:
#print termstat
#print termstat[0], termid
#if termstat[0] == termid:
#print "masuk"
if idf_code == "n":
ret[idx][termid] *= 1
elif idf_code == "t":
if termstat[2] > 0:
ret[idx][termid] = math.log10(self.dqp.total_document/termstat[2])
else:
ret[idx][termid] = math.log10(self.dqp.total_document)
idx += 1
#print "RET (before norm) = ", ret
if norm_code == "c":
for i in range(len(ret)):
normalizer = self.vectorSize(ret[i])
#print normalizer
for j in range(len(ret[i])):
if normalizer==0:
continue
ret[i][j] /= normalizer
#print "RET (after norm) = ", ret
# print ret
# print "Query vector=", ret
return ret
"""calcSimilarity(list<int>,list<int>)"""
def calcSimilarity(self, query, document):
# Sim(Q,D) = Q.D/(|Q|.|D|)
sim = 0
for i in range(len(query)):
sim += query[i] * document[i]
return sim
def calcSimiDict(self, query_dict, document):
sim = 0
#print self.term_list
for term in query_dict:
sim += query_dict[term] * document[self.term_list.index(term)]
return sim
def calcRank(self, query, documents, threshold):
# return list of rank of documents relevancy to one query, sorted descending by weight
ret = []
docsize = len(documents)
# print "DOCUMENTS = ", documents
for i in range(docsize):
sim = self.calcSimilarity(query, documents[i])
if sim < threshold:
continue
ret.append((i+1, sim))
#print ret
ret = sorted(ret, key = lambda ret: ret[1]) # sort ascending
ret = [x[0] for x in ret]
ret.reverse()
#print ret
return ret
def reCalcAllRank(self, q1, documents, threshold):
ret = []
docsize = len(documents)
for i in range(docsize):
sim = self.calcSimiDict(q1, documents[i])
if sim < threshold:
continue
ret.append((i+1, sim))
ret = sorted(ret, key = lambda ret: ret[1]) # sort ascending
ret = [x[0] for x in ret]
ret.reverse()
#print ret
return ret
def calcAllRank(self, queries, documents, threshold):
ret = []
querysize = len(queries)
for i in range(querysize):
ret.append((i+1, self.calcRank(queries[i], documents, threshold)))
self.result = ret
return ret
def writeRetrievalResult(self, file_name):
# write relevant result, sorted descending by rank
f = open(file_name, 'w')
#print self.result
for res in self.result:
for docid in res[1]:
f.writelines(str(res[0]) + " " + str(docid) + "\n")
def createWeightDict(self, query):
# list of list query vector [[1,1,1,0,0,0],[1,2,2]]
# dict (term:weight)
qv = self.calcQueryVector(self.dqp.query_term_weighting_code)
ret = {}
j = 0
query_term_dict = self.dqp.queryProcessing(query)
for i in self.term_list:
if qv[0][j] == 0:
if i in query_term_dict:
ret[i] = 0
else:
pass
else:
ret[i] = qv[0][j]
j += 1
#print ret
return ret
if __name__ == '__main__':
#document_collection_file = 'simple_document_collection.txt'
#document_collection_file = 'document_collection.txt'
document_collection_file = 'simple_document_collection.txt'
query_list_file = 'query_list.txt'
stop_list_file = 'stoplist.txt'
term_weighting_code = 'lnc.ltc'
inverted_file_saved_path = 'inverted_file_document_collection.txt'
is_use_stemming = True
qproc = document_query_processing.DocumentQueryProcessing(document_collection_file, stop_list_file, is_use_stemming, term_weighting_code, inverted_file_saved_path)
qproc.documentCollectionProcessing()
comp = Comparison(qproc)
#comp.searchFileQuery('inverted_file_document_collection.txt', 'simple_query_list.txt')
comp.searchOneQuery('testcase/inverted_file.txt', 'red big car')
#comp.calcAllRank(comp.calcQueryVector("ltc"), comp.calcDocumentVector(), 0.0)
comp.writeRetrievalResult('retrieval_result.txt')
#comp.createWeightDict('red big car')
q1 = {'red':0.7,'big':0.8,'car':0.4}
comp.reCalcAllRank(q1, comp.calcDocumentVector(), 0.0)
| Python |
import document_query_processing as dqp
#Dipanggil saat ada tombol lakukan indexing ditekan pada PAGE 1
#inverted_file_saved_path : path+filename dari inverted file yang ingin disimpan(string)
#document_collection_file : File koleksi dokumen(format SMART)(string)
#query_list_file : Koleksi query(format SMART)(string)
#relevance_judgement_file : File relevance judgement(string)
#stop_list : Nama File yang menyimpan stop list
#use_stemming : boolean(true jika memakai Porter stemmer, false jika tidak)
#term_weighting_mode : e.g "lnc.ltc"
#Fungsi ini membuat inverted_file, in memory retrieval result(query dan document relevant menurut document) dan performansi
def doIndexing(inverted_file_saved_path, document_collection_file, query_list_file, relevance_judgement_file, \
stop_list, is_use_stemming, term_weighting_mode):
document_query_processing = dqp.DocumentQueryProcessing(document_collection_file, stop_list,\
is_use_stemming, term_weighting_mode, inverted_file_saved_path)
document_query_processing.documentCollectionProcessing()
pass
#Dipanggil saat tombol "retrieval" ditekan pada PAGE 2(Interactive)
#query adalah string pada textbox
#Fungsi ini return list of document id relevant berdasar ranking, e.g. [25, 10, 2]
def doRetrievalOneQuery(query):
pass
#Dipanggil saat tombol "retrieval with relevance feedback" ditekan pada PAGE 2
#list_of_relevant_document_id adalah list dari id document yang dianggap relevant, e.g. [1, 2, 4]
#list_of_relevant_document_id adalah list dari id document yang dianggap relevant, e.g. [3, 5]
#method adalah string yang dilempar berupa cara penanganan relevance feedback, method adalah anggota dari himpunan string : {"rochio", "ide_regular", "ide_dec_hi"}
#Untuk method == "rochio" beta dan gama adalah nilai beta dan gamma dari user(float)
#Element yang ada pada list relevant dan non relevant sudah harus terurut berdasarkan rangking, dari rangking 1 seterusnya.
#Fungsi ini return list of document id relevant berdasar ranking, e.g. [25, 10, 2]
def doRetrievalWithRelevanceFeedBack(list_of_relevant_document_id, list_of_non_relevant_document_id, method, beta, gamma):
pass
if __name__ == '__main__':
document_collection_file = 'simple_document_collection.txt'
query_list_file = 'query_list.txt'
relevance_judgement_file = ""
stop_list_file = 'stoplist.txt'
term_weighting_code = "lnc.ltc"
inverted_file_saved_path = "D:\\SEMESTER 7\\IR\\TUBES1\\freedom_ir\\freedom_inverted_file.txt"
is_use_stemming = False
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.