def process(self, instance):
from maya import cmds
nodes = list(instance)
nodes += cmds.listRelatives(instance, allDescendents=True) or list()
missing = list()
for node in nodes:
# Only check transforms with shapes that are meshes
if not cmds.nodeType(node) == "transform":
continue
shapes = cmds.listRelatives(node,
shapes=True,
type="mesh") or list()
meshes = cmds.ls(shapes, type="mesh")
if not meshes:
continue
try:
self.log.info("Checking '%s'" % node)
cmds.getAttr(node + ".mbID")
except ValueError:
missing.append(node)
assert not missing, ("Missing ID attribute on: %s"
% ", ".join(missing))
python类getAttr()的实例源码
def process(self, instance):
from maya import cmds
image_prefix = cmds.getAttr("defaultRenderGlobals.imageFilePrefix")
if image_prefix:
self.log.warning("There was an image prefix: '%s'\n"
"Image prefixes are automatically managed by "
"the pipeline, one is not required and will not "
"be taken into account." % image_prefix)
def get_shape(node, intermediate=False):
"""Get the shape node of a tranform
This is useful if you don't want to have to check if a node is a shape node
or transform. You can pass in a shape node or transform and the function
will return the shape node.
:param node: node The name of the node.
:param intermediate: intermediate True to get the intermediate shape
:return: The name of the shape node.
"""
if cmds.nodeType(node) == 'transform':
shapes = cmds.listRelatives(node, shapes=True, path=True)
if not shapes:
shapes = []
for shape in shapes:
is_intermediate = cmds.getAttr('%s.intermediateObject' % shape)
if intermediate and is_intermediate and cmds.listConnections(shape, source=False):
return shape
elif not intermediate and not is_intermediate:
return shape
if shapes:
return shapes[0]
elif cmds.nodeType(node) in ['mesh', 'nurbsCurve', 'nurbsSurface']:
is_intermediate = cmds.getAttr('%s.intermediateObject' % node)
if is_intermediate and not intermediate:
node = cmds.listRelatives(node, parent=True, path=True)[0]
return get_shape(node)
else:
return node
return None
def create_orient_manipulator(joint, material):
joint_scale = cmds.jointDisplayScale(query=True)
joint_radius = cmds.getAttr('{0}.radius'.format(joint))
radius = joint_scale * joint_radius
children = cmds.listRelatives(joint, children=True, path=True)
if children:
p1 = cmds.xform(joint, q=True, ws=True, t=True)
p1 = OpenMaya.MPoint(*p1)
p2 = cmds.xform(children[0], q=True, ws=True, t=True)
p2 = OpenMaya.MPoint(*p2)
radius = p1.distanceTo(p2)
arrow_cvs = [[-1, 0, 0], [-1, 2, 0], [-2, 2, 0], [0, 4, 0], [2, 2, 0], [1, 2, 0], [1, 0, 0], [-1, 0, 0]]
arrow_cvs = [[x[0]*radius, x[1]*radius, x[2]*radius] for x in arrow_cvs]
shape = cmds.curve(name='{0}_zForward'.format(joint), degree=1, point=arrow_cvs)
# shape = cmds.sphere(n='{0}_zForward'.format(joint), p=(0, 0, 0), ax=(0, 0, -1), ssw=0, esw=180, r=radius, d=3, ut=0, tol=0.01, s=8, nsp=4, ch=0)[0]
# cmds.setAttr('{0}.sz'.format(shape), 0)
# cmds.select(shape)
# cmds.hyperShade(assign=material)
group = cmds.createNode('transform', name='{0}_grp'.format(shape))
cmds.parent(shape, group)
cmds.makeIdentity(shape, apply=True)
cmds.addAttr(shape, longName=MESSAGE_ATTRIBUTE, attributeType='message')
cmds.connectAttr('{0}.message'.format(joint), '{0}.{1}'.format(shape, MESSAGE_ATTRIBUTE))
for attr in ['tx', 'ty', 'tz', 'ry', 'rz', 'v']:
cmds.setAttr('{0}.{1}'.format(shape, attr), lock=True, keyable=False)
return group, shape
def create_arrow(jointName):
curve = cmds.curve(name='%s_ForwardDirection' % jointName, degree=1, point=[(-1, 0, 0), (-1, 2, 0), (-2, 2, 0), (0, 4, 0), (2, 2, 0), (1, 2, 0), (1, 0, 0), (-1, 0, 0)])
group = cmds.group()
cmds.xform(objectSpace=True, pivots=(0, 0, 0))
jointScale = cmds.jointDisplayScale(query=True)
jointRadius = cmds.getAttr('%s.radius' % jointName)
jointScale *= jointRadius
cmds.xform(scale=(jointScale, jointScale, jointScale))
return group
def dump(curves=None, stack=False):
"""Get a data dictionary representing all the given curves.
:param curves: Optional list of curves.
:return: A json serializable list of dictionaries containing the data required to recreate the curves.
"""
if curves is None:
curves = cmds.ls(sl=True) or []
data = []
for node in curves:
shape = shortcuts.get_shape(node)
if cmds.nodeType(shape) == 'nurbsCurve':
control = {
'name': node,
'cvs': cmds.getAttr('{0}.cv[*]'.format(node)),
'degree': cmds.getAttr('{0}.degree'.format(node)),
'form': cmds.getAttr('{0}.form'.format(node)),
'xform': cmds.xform(node, q=True, ws=True, matrix=True),
'knots': get_knots(node),
'pivot': cmds.xform(node, q=True, rp=True),
'overrideEnabled': cmds.getAttr('{0}.overrideEnabled'.format(node)),
'overrideRGBColors': cmds.getAttr('{0}.overrideRGBColors'.format(node)),
'overrideColorRGB': cmds.getAttr('{0}.overrideColorRGB'.format(node))[0],
'overrideColor': cmds.getAttr('{0}.overrideColor'.format(node)),
}
if stack:
control['stack'] = get_stack_count(node)
control['parent'] = get_stack_parent(node)
data.append(control)
if curves:
cmds.select(curves)
return data
def get_knots(curve):
"""Gets the list of knots of a curve so it can be recreated.
:param curve: Curve to query.
:return: A list of knot values that can be passed into the curve creation command.
"""
curve = shortcuts.get_shape(curve)
info = cmds.createNode('curveInfo')
cmds.connectAttr('{0}.worldSpace'.format(curve), '{0}.inputCurve'.format(info))
knots = cmds.getAttr('{0}.knots[*]'.format(info))
cmds.delete(info)
return knots
def set_color(self):
"""Open a dialog to set the override RGB color of the selected nodes."""
nodes = cmds.ls(sl=True) or []
if nodes:
color = cmds.getAttr('{0}.overrideColorRGB'.format(nodes[0]))[0]
color = QtGui.QColor(color[0]*255, color[1]*255, color[2]*255)
color = QtWidgets.QColorDialog.getColor(color, self, 'Set Curve Color')
if color.isValid():
color = [color.redF(), color.greenF(), color.blueF()]
for node in nodes:
cmds.setAttr('{0}.overrideEnabled'.format(node), True)
cmds.setAttr('{0}.overrideRGBColors'.format(node), True)
cmds.setAttr('{0}.overrideColorRGB'.format(node), *color)
def constraint_data(constraint):
"""Gets the parentConstraint data dictionary of the given constraint.
The data dictionary can be used as input into the Component.
:param constraint: Name of a parentConstraint node.
:return: The parentConstraint data dictionary.
"""
data = {
'drivers': cmds.parentConstraint(constraint, q=True, targetList=True),
'driven': cmds.listConnections('{0}.constraintParentInverseMatrix'.format(constraint), d=False)[0],
'maintain_offset': False,
'skip_tx': False,
'skip_ty': False,
'skip_tz': False,
'skip_rx': False,
'skip_ry': False,
'skip_rz': False,
}
offset = cmds.getAttr('{0}.target[0].targetOffsetTranslate'.format(constraint))[0]
offset += cmds.getAttr('{0}.target[0].targetOffsetRotate'.format(constraint))[0]
for value in offset:
if abs(value) > 0.000001:
data['maintain_offset'] = True
break
for x in 'xyz':
connection = cmds.listConnections('{0}.t{1}'.format(data['driven'], x), d=False)
if not connection or connection[0] != constraint:
data['skip_t{0}'.format(x)] = True
connection = cmds.listConnections('{0}.r{1}'.format(data['driven'], x), d=False)
if not connection or connection[0] != constraint:
data['skip_r{0}'.format(x)] = True
return data
def test_component_execute(self):
comp = Component()
comp.set_data({
'sphere_name': 'test',
'radius': 5.5,
})
comp.execute()
self.assertTrue(cmds.objExists('test'))
self.assertEqual(5.5, cmds.getAttr('polySphere1.radius'))
def test_execute_component_with_array_of_containers(self):
data = {
'spheres': [
{'sphere_name': 'sphere1', 'radius': 2.5},
{'sphere_name': 'sphere2', 'radius': 5.0},
]
}
comp = ContainerComponent()
comp.set_data(data)
comp.execute()
self.assertTrue(cmds.objExists('sphere1'))
self.assertEqual(2.5, cmds.getAttr('polySphere1.radius'))
self.assertTrue(cmds.objExists('sphere2'))
self.assertEqual(5.0, cmds.getAttr('polySphere2.radius'))
def test_instantiate_component_from_constructor(self):
name = 'blah_blah'
comp = Component(sphere_name=name, radius=10.0)
self.assertFalse(cmds.objExists(name))
comp.execute()
self.assertTrue(cmds.objExists(name))
self.assertEqual(10.0, cmds.getAttr('polySphere1.radius'))
def snapshot(path = None, width = 96, height = 96):
current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat")
cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png
#path = "/Users/liorbenhorin/Library/Preferences/Autodesk/maya/2015-x64/scripts/pipeline/thumb.png"
cmds.playblast(cf = path, fmt="image", frame = cmds.currentTime( query=True ), orn=False, wh = [width,height], p=100, v=False)
cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
if os.path.isfile(path):
return path
else:
return False
def scene_resolution():
return [cmds.getAttr("defaultResolution.width"),cmds.getAttr("defaultResolution.height")]
def _apply(self, *args):
selected = cmds.textScrollList(self.text_scroll, q=True, si=True)
fov = cmds.textFieldGrp(self.text_field, q=True, tx=True)
if not selected or not fov:
return
camera = selected[0]
vfa = cmds.getAttr(camera + ".verticalFilmAperture")
focal_length = 0.5 * vfa / math.tan(float(fov) / 2.0 / 57.29578) / 0.03937
cmds.setAttr(camera + ".focalLength", focal_length)
cmds.textFieldGrp(self.result_field, e=True, tx=round(focal_length, 3))
def __init__(self, node):
u"""initialize
:param path: ??????
:type path: unicode
"""
super(FileInfo, self).__init__()
self.node = node
self.thumbnail = Column(0, "")
self.name = Column(1, node)
self.file_type = Column(2, cmds.getAttr(node + ".fileTextureName").replace("a11889", "tm8r"))
def get_outputs(self):
"""Return width x height defined by the combination of settings
Returns:
dict: width and height key values
"""
mode = self.mode.currentText()
panel = lib.get_active_editor()
if mode == self.ScaleCustom:
width = self.width.value()
height = self.height.value()
elif mode == self.ScaleRenderSettings:
# width height from render resolution
width = cmds.getAttr("defaultResolution.width")
height = cmds.getAttr("defaultResolution.height")
elif mode == self.ScaleWindow:
# width height from active view panel size
if not panel:
# No panel would be passed when updating in the UI as such
# the resulting resolution can't be previewed. But this should
# never happen when starting the capture.
width = 0
height = 0
else:
width = cmds.control(panel, query=True, width=True)
height = cmds.control(panel, query=True, height=True)
else:
raise NotImplementedError("Unsupported scale mode: "
"{0}".format(mode))
scale = [width, height]
percentage = self.percent.value()
scale = [math.floor(x * percentage) for x in scale]
return {"width": scale[0], "height": scale[1]}
def BT_Setup(set = None):
if not set:
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
if not transforms:
return False
if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
else:
return False
btNode = cmds.createNode("BlendTransforms")
cmds.setAttr(set +'.Blend_Node', btNode, type = "string")
for i in range(0, len(transforms)):
baseMatrix = cmds.xform(transforms[i], q = True, m = True)
baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
baseRotOffset = [0.0, 0.0, 0.0]
if cmds.objectType(transforms[i], isType = 'joint'):
baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]
btAttr = 'transforms[' +str(i) +'].baseMatrix'
btScaleAttr = 'transforms[' +str(i) +'].baseScale'
btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'
BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
return True
def BT_DisconnectSetup(set = None):
if not set:
return False
if not BT_IsSetupConnected(set = set):
cmds.warning('Setup already disconnected!')
return False
btNode = cmds.getAttr(set +'.Blend_Node')
if not btNode or not cmds.objExists(btNode):
return False
numOutputs = cmds.getAttr(btNode +'.output', size = True)
print numOutputs
tempMult = None
for i in range(0, numOutputs):
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1')
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1')
conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True)
if conns:
tempMult = cmds.createNode('multiplyDivide')
cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale')
cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1')
cmds.select(cl = True)
return True
def BT_Setup(set = None):
if not set:
return False
transforms = cmds.listConnections(set +'.dagSetMembers')
if not transforms:
return False
if not cmds.attributeQuery('Blend_Node', n = set, ex = True):
cmds.addAttr(set, ln = 'Blend_Node', k = False, h = True, dt = 'string')
else:
return False
btNode = cmds.createNode("BlendTransforms")
cmds.setAttr(set +'.Blend_Node', btNode, type = "string")
for i in range(0, len(transforms)):
baseMatrix = cmds.xform(transforms[i], q = True, m = True)
baseScale = cmds.getAttr(transforms[i] +'.scale')[0]
baseRotOffset = [0.0, 0.0, 0.0]
if cmds.objectType(transforms[i], isType = 'joint'):
baseRotOffset = cmds.getAttr(transforms[i] +'.jointOrient')[0]
btAttr = 'transforms[' +str(i) +'].baseMatrix'
btScaleAttr = 'transforms[' +str(i) +'].baseScale'
btRotOffsetAttr = 'transforms[' +str(i) +'].baseRotOffset'
BT_MatrixValuesToNode(values = baseMatrix, node = btNode, attr = btAttr)
BT_Double3ValuesToNode(values = baseScale, node = btNode, attr = btScaleAttr)
BT_Double3ValuesToNode(values = baseRotOffset, node = btNode, attr = btRotOffsetAttr)
BT_ConnectOutputs(index = i, node = btNode, transform = transforms[i])
return True