我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.getAttr()。
def clone_special(*args): """Clone in localspace, and preserve user-defined attributes""" for transform in cmds.ls(selection=True, long=True): if cmds.nodeType(transform) != "transform": cmds.warning("Skipping '%s', not a `transform`" % transform) continue shape = _find_shape(transform) type = cmds.nodeType(shape) if type not in ("mesh", "nurbsSurface", "nurbsCurve"): cmds.warning("Skipping '{transform}': cannot clone nodes " "of type '{type}'".format(**locals())) continue cloned = commands.clone(shape, worldspace=False) new_transform = cmds.listRelatives(cloned, parent=True, fullPath=True)[0] new_transform = cmds.rename(new_transform, new_transform.rsplit(":", 1)[-1]) for attr in cmds.listAttr(transform, userDefined=True) or list(): try: cmds.addAttr(new_transform, longName=attr, dataType="string") except Exception: continue value = cmds.getAttr(transform + "." + attr) cmds.setAttr(new_transform + "." + attr, value, type="string") # Connect visibility cmds.connectAttr(transform + ".visibility", new_transform + ".visibility")
def offset_orient(joints, amount, axis): """Offsets the orient by the given amount @param joints: Joints to orient. @param amount: Amount to offset by. @param axis: Which axis X, Y or Z """ for joint in joints: children = _unparent_children(joint) attribute = '{0}.jointOrient{1}'.format(joint, axis) orient = cmds.getAttr(attribute) orient += amount cmds.setAttr(attribute, orient) _reparent_children(joint, children) if joints: cmds.select(joints)
def mirror(joint, search_for, replace_with): joints = [joint, ] + (cmds.listRelatives(joint, ad=True, path=True) or []) for joint in joints: mirrored_joint = joint.replace(search_for, replace_with) if cmds.objExists(mirrored_joint): translate = list(cmds.getAttr('{0}.t'.format(joint))[0]) parent = cmds.listRelatives(joint, parent=True, path=True) if parent and search_for not in parent[0]: translate[2] *= -1.0 else: translate = [x * -1.0 for x in translate] cmds.setAttr('{0}.t'.format(mirrored_joint), *translate) rotate = cmds.getAttr('{0}.r'.format(joint))[0] cmds.setAttr('{0}.r'.format(mirrored_joint), *rotate) scale = cmds.getAttr('{0}.s'.format(joint))[0] cmds.setAttr('{0}.s'.format(mirrored_joint), *scale)
def __init__(self, controls=None, **kwargs): """Constructor :param controls: A list of dictionaries describing the contorls nodes that need to be created. See cmt.rig.control.dump. { '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, 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)), } """ super(Component, self).__init__(**kwargs) self.controls = controls or [] self.control_list = fields.ListField(name='controls', value=[control['name'] for control in self.controls], help_text='Controls that will be created.', parent=self)
def assert_hierarachies_match(self): self.assertEqual(7, len(cmds.ls(type='joint'))) # Make sure the joint orients are the same translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')] rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')] orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')] for orient, new_orient in zip(self.orients, orients): self.assertListAlmostEqual(orient, new_orient) for translate, new_translate in zip(self.translates, translates): self.assertListAlmostEqual(translate, new_translate) for rotate, new_rotate in zip(self.rotates, rotates): self.assertListAlmostEqual(rotate, new_rotate) # The geometry should not have been exported self.assertFalse(cmds.objExists(self.cube)) self.assertTrue(cmds.objExists(self.group)) self.assertEqual('joint1', cmds.listRelatives(self.group, children=True)[0])
def playblast_snapshot(path = None,format = None, compression = None, hud = None, offscreen = None, range=None, scale = None): current_image_format = cmds.getAttr("defaultRenderGlobals.imageFormat") cmds.setAttr("defaultRenderGlobals.imageFormat", 32) # *.png if range is None: range = playback_selection_range() print range if range is None: start = cmds.playbackOptions( q=True,min=True ) end = cmds.playbackOptions( q=True,max=True ) range = [start, end] cmds.playblast(frame =int((range[0] + range[1])/2), cf = path, fmt="image", orn=hud, os=offscreen, wh = scene_resolution(), p=scale, v=False) cmds.setAttr("defaultRenderGlobals.imageFormat", current_image_format)
def ResetSceneAnim(): # Loop through them all SceneJoints = cmds.ls(type="joint") # Loop for name in SceneJoints: # Disconnect if required ResetBoneKeyframes(DagPathFromJoint(name, False).transform()) # Check for undo if (cmds.objExists(name + ".seanimUndoT")): # Reset to it ResetTranslation = cmds.getAttr(name + ".seanimUndoT")[0] ResetScale = cmds.getAttr(name + ".seanimUndoS")[0] ResetRotation = cmds.getAttr(name + ".seanimUndoR")[0] # Apply cmds.setAttr(name + ".t", ResetTranslation[0], ResetTranslation[1], ResetTranslation[2]) cmds.setAttr(name + ".scale", ResetScale[0], ResetScale[1], ResetScale[2]) cmds.setAttr(name + ".r", 0, 0, 0) cmds.setAttr(name + ".jo", ResetRotation[0], ResetRotation[1], ResetRotation[2]) # Remove notetracks if cmds.objExists("SENotes"): # Delete cmds.delete("SENotes") # Processes a joint, creating it's rest position, and returning a dag path
def array_builder(self, attrName): frame = attrName.split('.')[-1] if pm.frameLayout(frame, exists=True): pm.deleteUI(frame) pm.frameLayout(frame, collapse=False) pm.rowLayout(numberOfColumns=2) acmd = partial(self.add_multiInstance, attrName) rcmd = partial(self.rem_multiInstance, attrName) pm.button(label='New Item', command=acmd) pm.button(label='Remove Last Item', command=rcmd) pm.setParent('..') array_length = pm.getAttr(attrName, s=True) for i in xrange(array_length): index_attr = '{}[{}]'.format(attrName, i) pm.attrControlGrp( attribute=index_attr, label=index_attr.split('.')[-1]) pm.setParent('..')
def create_hair_system(nucleus=None): '''Create a hair system, add it to the specified nucleus or active nucleus''' if not nucleus: nucleus = get_nucleus() hair_system = cmds.createNode('hairSystem') cmds.connectAttr('time1.outTime', hair_system + '.currentTime') index = cmds.getAttr(nucleus + '.inputActive', size=True) input_active = '{}.inputActive[{}]'.format(nucleus, index) input_start = '{}.inputActiveStart[{}]'.format(nucleus, index) output_object = '{}.outputObjects[{}]'.format(nucleus, index) cmds.setAttr(hair_system + '.active', 1) cmds.connectAttr(hair_system + '.currentState', input_active) cmds.connectAttr(hair_system + '.startState', input_start) cmds.connectAttr(output_object, hair_system + '.nextState') cmds.connectAttr(nucleus + '.startFrame', hair_system + '.startFrame') return hair_system
def read(node): """Return user-defined attributes from `node` """ data = dict() for attr in cmds.listAttr(node, userDefined=True) or list(): try: value = cmds.getAttr(node + "." + attr) except: # Some attributes cannot be read directly, # such as mesh and color attributes. These # are considered non-essential to this # particular publishing pipeline. value = None data[attr] = value return data
def fileLoad(*args): sel = cmds.ls(sl=True) origTexture = sel[0] ctrls = sel[1:] # get path path = cmds.getAttr("{0}.fileTextureName".format(origTexture)) if not path: cmds.warning("No file present in {0}. Cancelling!".format(origTexture)) return for ctrl in ctrls: ctrlFile = cmds.connectionInfo("{0}.fileTexture".format(ctrl), sfd=True).partition(".")[0] # add path to ctrl file cmds.setAttr("{0}.fileTextureName".format(ctrlFile), path, type="string")
def positionsAlongCurve(crv="", numPts = 3, *args): """ returns list of numPts evenly distributed world positions along given nurbs crv """ if not crv: return if isType(crv, "nurbsCurve"): posList = [] shp = cmds.listRelatives(crv, s=True)[0] poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo") cmds.connectAttr("{}.local".format(shp), "{}.inputCurve".format(poc)) cmds.setAttr("{}.turnOnPercentage".format(poc), 1) lineLen = cmds.arclen(crv, ch=False) dist = float(numPts)/lineLen for x in range(0, numPts+1): perc = 1.0/numPts cmds.setAttr("{}.parameter".format(poc),x*perc) print x*perc pos = cmds.getAttr("{}.position".format(poc))[0] posList.append(pos) cmds.delete(poc) return(posList)
def createJointsAlongCurve(crv="", numJnts=3, *args): jnts = [] crvShp = cmds.listRelatives(crv, s=True)[0] poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo") cmds.connectAttr("{}.local".format(crvShp), "{}.inputCurve".format(poc)) cmds.setAttr("{}.turnOnPercentage".format(poc), 1) lineLen = cmds.arclen(crv) dist = float(numJnts)/lineLen for x in range(0, numJnts+1): perc = 1.0/numJnts cmds.setAttr("{}.parameter".format(poc),x*perc) print x*perc pos = cmds.getAttr("{}.position".format(poc))[0] jnt = cmds.joint(p=pos) jnts.append(jnt) # add one joint at the end to orient return(jnts)
def orientJointChain(*args): #---------------- this doens't actually work. dot doesn't represent the relationship btw orients cmds.joint(jnts[0], e=True, oj="xyz", secondaryAxisOrient="ydown", ch=True, zso=True) #print cmds.getAttr("{}.jointOrient".format(cmds.ls(sl=True)[0])) for y in range(1, len(jnts)): v1 = cmds.getAttr("{}.jointOrient".format(jnts[0]))[0] v2 = cmds.getAttr("{}.jointOrient".format(jnts[y]))[0] dotN = mth.dotN(v1, v2) # figure out how to reverse joint orientation if dotN < 0: print jnts[y], "dot neg" # reorient (inverse secondary axis) # for jnt in jnts: # print mth.dotN(cmds.getAttr("{}.jointOrient".format(jnts[0]))[0], cmds.getAttr("{}.jointOrient".format(jnt))[0])
def randomizeFloats(*args): sel = cmds.ls(sl=True) attrs = getChannels() minn = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v1=True) maxx = cmds.floatFieldGrp(widgets["floatFFG"], q=True, v2=True) rel = cmds.checkBox(widgets["floatCB"], q=True, v=True) for obj in sel: for attr in attrs: if (cmds.attributeQuery(attr, node=obj, exists=True)): rand = getRandomFloat(minn, maxx) current = 0.0 if rel: current = cmds.getAttr("{0}.{1}".format(obj, attr)) newVal = rand + current cmds.setAttr("{0}.{1}".format(obj, attr), newVal)
def get_channel_attributes(obj, chnl): """ gets and returns attributes of given channel on given object """ attrType = cmds.attributeQuery(chnl, node=obj, at=True) hasMin = cmds.attributeQuery(chnl, node=obj, mne=True) hasMin = cmds.attributeQuery(chnl, node=obj, mne=True) hasMax = cmds.attributeQuery(chnl, node=obj, mxe=True) attrMin = None if hasMin: attrMin = cmds.attributeQuery(chnl, node=obj, min=True) attrMax = None if hasMax: attrMax = cmds.attributeQuery(chnl, node=obj, max=True) value = cmds.getAttr("{0}.{1}".format(obj, chnl)) inConnection = cmds.listConnections("{0}.{1}".format(obj, chnl), plugs=True, destination=False, source=True) outConnection = cmds.listConnections("{0}.{1}".format(obj, chnl), plugs=True, destination=True, source=False) locked = cmds.getAttr("{0}.{1}".format(obj, chnl), lock=True) return (attrType, hasMin, attrMin, hasMax, attrMax, value, inConnection, outConnection, locked)
def toggle_sel_shape_vis(*args): """toggles the selected transforms' shape visibility""" sel = cmds.ls(sl=True, type="transform") if sel: for obj in sel: shp = cmds.listRelatives(obj, s=True) if not shp: return () for s in shp: currVal = cmds.getAttr("{0}.visibility".format(s)) newVal = 0 if currVal == 0: newVal = 1 elif currVal == 1: newVal = 0 cmds.setAttr("{0}.visibility".format(s), newVal)
def JntSegScl(*args): """turns on/off selected jnts seg scale compensate attr""" jnts = cmds.ls(sl=True, type="joint") if not jnts: cmds.warning("No joints selected!") return () for jnt in jnts: currVal = cmds.getAttr("{0}.segmentScaleCompensate".format(jnt)) if currVal == 0: newVal = 1 elif currVal == 1: newVal = 0 cmds.setAttr("{0}.segmentScaleCompensate".format(jnt), newVal)
def read(node): """Return user-defined attributes from `node`""" data = dict() for attr in cmds.listAttr(node, userDefined=True) or list(): try: value = cmds.getAttr(node + "." + attr) except ValueError: # Some attributes cannot be read directly, # such as mesh and color attributes. These # are considered non-essential to this # particular publishing pipeline. value = None data[attr] = value return data
def getNodeAttributes(node): ''' Get Maya node attributes ''' attributes = cmds.listAttr(node) attr = {} attr['nodeName'] = node attr['nodeType'] = cmds.nodeType(node) for attribute in attributes: if '.' in attribute: continue try: val = cmds.getAttr(node + '.' + attribute) except RuntimeError: continue attr[attribute] = val return attr
def getAttribFromNode(self, name, attr, aType, default=None): #name mast be shape transformOnly = ['visibility'] fAttr = '.'.join([name, attr]) value = default if cmds.attributeQuery( attr, node=name, exists=True ) and not attr.lower() in transformOnly: value = cmds.getAttr( fAttr ) else: trnsfrm = self.getTransform(name) if trnsfrm: if cmds.attributeQuery( attr, node=trnsfrm, exists=True ): fAttr = '.'.join([trnsfrm, attr]) value = cmds.getAttr( fAttr ) if not value is None: if isinstance(value, list): if isinstance(value[0], tuple): value = list(value[0]) try: value = aType(value) except: pass return value
def snap(node, snapTo): #duplicate the node we want snap dup = mc.duplicate(node, parentOnly=True)[0] #unlock translates and rotates for a in ('.t','.r'): for b in 'xyz': mc.setAttr(dup+a+b, lock=False) mc.parentConstraint(snapTo, dup) for a in ('.t','.r'): for b in ('x','y','z'): try: mc.setAttr(node+a+b, mc.getAttr(dup+a+b)) except StandardError: pass mc.delete(dup)
def getMirrorMap(nodes=None): ''' Returns a map of all paired nodes within a puppet ''' puppets = getPuppets(nodes) puppets = mc.ls(puppets, long=True)[0] allNodes = mc.ls('*.mirrorIndex', o=True, long=True, recursive=True) found = {} pairs = {} for node in allNodes: for puppet in puppets: if not node.startswith(puppet): continue value = mc.getAttr('{}.mirrorIndex'.format(node)) if value in found.keys(): pairs[found[value]] = node pairs[node] = found[value] continue found[value] = node return pairs
def flipPose(nodes, *args): nodes = mc.ls(nodes, long=True) flipPairs = getMirrorPairs(nodes) flipSingles = [x for x in nodes if x not in flipPairs.keys()] #do the singles: for node in flipSingles: for axis in getMirrorAxis(node): plug = '{}.{}'.format(node,axis) if mc.getAttr(plug, keyable=True): try: utl.setAnimValue(plug, mc.getAttr(plug)*-1.0) except:pass #do the pairs done = [] for node, mirror in flipPairs.items(): if node not in done: copyPose(node, mirror, flip=True) done.append(mirror)
def isNodeVisible(node): ''' Simply return whether or not the node can be seen. ''' if not mc.attributeQuery('visibility', node=node, exists=True): return False if not mc.getAttr(node+'.v'): return False if mc.attributeQuery('intermediateObject', node=node, exists=True): if mc.getAttr(node+'.intermediateObject'): return False if not mc.getAttr(node+'.lodVisibility'): return False if mc.getAttr(node+'.overrideEnabled') and not mc.getAttr(node+'.overrideVisibility'): return False parent = mc.listRelatives(node, parent=True, pa=True) if parent: return isNodeVisible(parent[0]) return True
def isWorldSpaceControl(obj): #first, if the object itself doesn't inherit transforms, it's a world space node. if not mc.getAttr(obj+'.inheritsTransform'): return True #walk up the hierarchy testing for any rotation value on x or z, or inherit transform parent = mc.listRelatives(obj, parent=True) while(parent): if not mc.getAttr(parent[0]+'.inheritsTransform'): return True for attr in ('.rx','.rz'): if mc.getAttr(parent[0]+attr) != 0: return False parent = mc.listRelatives(parent, parent=True) return True
def colorShape(obj, rgb=None, hsv=None): if not rgb: if hsv and len(hsv) == 3: rgb = colorsys.hsv_to_rgb(*hsv) else: raise RuntimeError('colorShape requires an rgb or hsv input.') mc.setAttr('{}.overrideEnabled'.format(obj), 1) mc.setAttr('{}.overrideRGBColors'.format(obj), 1) mc.setAttr('{}.overrideColorRGB'.format(obj), *rgb) shapes = mc.listRelatives(obj, shapes=True, pa=True) for shape in shapes: #if mc.getAttr('{}.overrideEnabled'.format(shape)): mc.setAttr('{}.overrideEnabled'.format(shape), 1) mc.setAttr('{}.overrideRGBColors'.format(shape), 1) mc.setAttr('{}.overrideColorRGB'.format(shape), *rgb)
def main(): sel = mc.ls(sl=True) if not sel: return for each in sel: plug = each+'.v' try: locked = mc.getAttr(plug, lock=True) if locked: mc.setAttr(plug, lock=False) if mc.getAttr(plug): mc.setAttr(plug, 0) else: mc.setAttr(plug, 1) if locked: mc.setAttr(plug, lock=True) except: pass
def get_skey_from_scene(): skey = cmds.getAttr('defaultObjectSet.tacticHandler_skey') return skey
def process(self, instance): from maya import cmds missing = list() for member in ("controls_SET", "out_SET"): if member not in instance: missing.append(member) assert not missing, "\"%s\" is missing members: %s" % ( instance, ", ".join("\"" + member + "\"" for member in missing)) # Ensure all output has IDs. # As user may inadvertently add to the out_SET without # realising, and some of the new members may be non-meshes, # or meshes without and ID missing = list() for node in cmds.sets("out_SET", query=True) or list(): # Only check transforms with shapes that are meshes shapes = cmds.listRelatives(node, shapes=True) 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))
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))
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