Python pymel.core.getAttr() Examples
The following are 24
code examples of pymel.core.getAttr().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pymel.core
, or try the search function
.
Example #1
Source File: fcurve.py From mgear_core with MIT License | 6 votes |
def getFCurveValues(fcv_node, division, factor=1): """Get X values evenly spaced on the FCurve. Arguments: fcv_node (pyNode or str): The FCurve to evaluate. division (int): The number of division you want to evaluate on the FCurve. factor (float): Multiplication factor. Default = 1. (optional) Returns: list of float: The values in a list float. >>> self.st_value = fcu.getFCurveValues(self.settings["st_profile"], self.divisions) """ incr = 1 / (division - 1.0) values = [] for i in range(division): pm.setAttr(fcv_node + ".input", i * incr) values.append(pm.getAttr(fcv_node + ".output") * factor) return values
Example #2
Source File: anim_utils.py From mgear_core with MIT License | 6 votes |
def recordNodesMatrices(nodes, desiredTime): """get the matrices of the nodes provided and return a dict of node:matrix Args: nodes (list): of nodes Returns: dict: node:node matrix """ nodeToMat_dict = {} for fk in nodes: fk = pm.PyNode(fk) nodeToMat_dict[fk.name()] = fk.getAttr("worldMatrix", time=desiredTime) return nodeToMat_dict
Example #3
Source File: auxiliary.py From anima with MIT License | 6 votes |
def check_sequence_name(self): """checks sequence name and asks the user to set one if maya is in UI mode and there is no sequence name set """ sequencer = pm.ls(type='sequencer')[0] sequence_name = sequencer.getAttr('sequence_name') if sequence_name == '' and not pm.general.about(batch=1) \ and not self.batch_mode: result = pm.promptDialog( title='Please enter a Sequence Name', message='Sequence Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' ) if result == 'OK': sequencer.setAttr( 'sequence_name', pm.promptDialog(query=True, text=True) )
Example #4
Source File: limb.py From anima with MIT License | 6 votes |
def make_stretchy(self): #check joints """ """ self._scaleMD = pm.createNode("multiplyDivide", n=self.limbName + "_scaleMD") pm.connectAttr(self.curve.curveInfo.arcLength, self.scaleMD.input1X) pm.setAttr(self.scaleMD.input2X, self.curve.arclen) pm.setAttr(self.scaleMD.operation, 2) for jnt in self.joints.jointChain: factor = pm.createNode("multiplyDivide", n="factor_" + jnt) pm.connectAttr(self.scaleMD.outputX, factor.input1X) pm.setAttr(factor.input2X, (pm.getAttr(jnt.ty))) pm.connectAttr(factor.outputX, jnt.ty)
Example #5
Source File: sharedShape.py From fossil with BSD 3-Clause "New" or "Revised" License | 5 votes |
def getVisGroup(obj): ''' Returns ('name', int:level) if it's in a group, otherwise an empty tuple. ''' zero = core.dagObj.zero(obj, apply=False, make=False) if zero: obj = zero visCon = listConnections(obj.visibility.name(), p=True, s=True, d=False) if visCon: node = visCon[0].node() attr = visCon[0].longName() # This returns the long attr name, not the node at all, where .attrName() returns the short name. shape = get(create=False) level = 1 if nodeType(node) == 'condition' and attr == 'outColorR': #con = listConnections(node + '.firstTerm', p=True, s=True, d=False) con = node.firstTerm.listConnections(p=True, s=True, d=False) if con: level = int(getAttr(node + '.secondTerm')) #node = shortName(con[0].node()) attr = con[0].longName() # longName() returns the long attribute name, not the node (technically they are the same here). return attr, level # Verify the shape is sharedShape via uuid (as of 2017, pymel tosses an error) if mel.ls(node, uuid=True)[0] == mel.ls(shape, uuid=True)[0]: return attr, level return ()
Example #6
Source File: rigutils.py From DynRigBuilder with MIT License | 5 votes |
def duplicateJointChain(rootJoint, replace=None, suffix=None): """ Duplicate the given joint chain. :param rootJoint: `PyNode` root joint of the given joint chain :param replace: `tuple` or `list` (old string, new string) rename the duplicated joint chain by replacing string in given joint name :param suffix: `string` rename the duplicated joint chain by adding suffix to the given joint name :return: `list` list of joints in the duplicated joint chain. ordered by hierarchy """ srcJnts = getJointsInChain(rootJoint) dupJnts = [] if not replace and not suffix: raise ValueError("Please rename the duplicated joint chain.") for i, srcJnt in enumerate(srcJnts): newName = srcJnt.name() if replace: newName = newName.replace(replace[0], replace[1]) if suffix: newName = "{0}_{1}".format(newName, suffix) dupJnt = pm.duplicate(srcJnt, n=newName, po=1)[0] dupJnts.append(dupJnt) for attr in ['t', 'r', 's', 'jointOrient']: pm.setAttr("{0}.{1}".format(dupJnt.name(), attr), pm.getAttr("{0}.{1}".format(srcJnt.name(), attr))) if i>0: dupJnt.setParent(dupJnts[i-1]) # # for i, srcJnt in enumerate(srcJnts): # if i==0: continue # srcPar = pm.listRelatives(srcJnt, p=1) # if srcPar: # dupJnts[i].setParent(srcPar[0].name().replace(replace[0], replace[1])) return dupJnts
Example #7
Source File: splinerig.py From DynRigBuilder with MIT License | 5 votes |
def _getAttrFromScaffold(self, scaffoldTop): if scaffold.getScaffoldType(scaffoldTop) != "spline": return for attr in self.rigAttrs: setattr(self, attr["ln"], pm.getAttr("{0}.{1}".format(scaffoldTop, attr["ln"]))) scaffLocs = scaffold.getScaffoldLocs(scaffoldTop) self.startPos = scaffold.getLocPosition(scaffLocs[0]) self.endPos = scaffold.getLocPosition(scaffLocs[-1]) self.metaPos = scaffold.getMetaPivotPosition(scaffoldTop)
Example #8
Source File: curve.py From anima with MIT License | 5 votes |
def arclen(self): self._arcLen = pm.getAttr(self.curveInfo.arcLength) return self._arcLen
Example #9
Source File: curve.py From anima with MIT License | 5 votes |
def spans(self): self._spans = pm.getAttr(self.curveNode.spans) return self._spans
Example #10
Source File: curve.py From anima with MIT License | 5 votes |
def degree(self): self._degree = pm.getAttr(self.curveNode.degree) return self._degree
Example #11
Source File: joint.py From anima with MIT License | 5 votes |
def orient_joint(self, joint, aimAxis=[1, 0, 0], upAxis=[0, 0, 1], worldUpType="vector", worldUpVector=[0, 1, 0]): #joint should be pm.nt.Joint type if not isinstance(joint, pm.nt.Joint): raise TypeError("%s sholud be an instance of pm.nt.Joint Class" % joint) jointUnder = self.jointUnder(joint) if jointUnder is None: return 0 temporalGroup = DrawNode(Shape.transform, 'temporalGroup') pm.parent(jointUnder, temporalGroup.drawnNode) pm.setAttr(joint.jointOrient, (0, 0, 0)) if worldUpType == "object": aimConst = pm.aimConstraint(jointUnder, joint, aimVector=aimAxis, upVector=upAxis, worldUpType=worldUpType, worldUpObject=worldUpVector) elif worldUpType == "vector": aimConst = pm.aimConstraint(jointUnder, joint, aimVector=aimAxis, upVector=upAxis, worldUpType=worldUpType, worldUpVector=worldUpVector) pm.delete(aimConst) pm.parent(jointUnder, joint) pm.setAttr(joint.jointOrient, (pm.getAttr(joint.rotate))) pm.setAttr((joint.rotate), [0, 0, 0]) pm.delete(temporalGroup.drawnNode)
Example #12
Source File: joint.py From anima with MIT License | 5 votes |
def _getPosition(self, position): # Checks the type of the Position and Return Position vector if isinstance(position, pm.dt.Vector): self._jointPos = position elif isinstance(position, pm.dt.Point): self._jointPos = position elif isinstance(position, pm.nt.Transform): self._jointPos = pm.getAttr(position.translate) elif not isinstance(position, pm.dt.Vector): self._jointPos = pm.dt.Vector(0, 0, 0) return self._jointPos # PROPERTIES
Example #13
Source File: camera_tools.py From anima with MIT License | 5 votes |
def create_3dequalizer_points(width, height): """creates 3d equalizer points under the selected camera :param width: The width of the plate :param height: The height of the plate """ width = float(width) height = float(height) # get the text file path = pm.fileDialog() # parse the file from anima import utils man = utils.C3DEqualizerPointManager() man.read(path) # get the camera cam_shape = get_selected_camera() pm.getAttr("defaultResolution.deviceAspectRatio") pm.getAttr("defaultResolution.pixelAspect") frustum_curve = create_frustum_curve(cam_shape) for point in man.points: # create a locator loc = create_camera_space_locator(frustum_curve) loc.rename('p%s' % point.name) # animate the locator for frame in point.data.keys(): pm.currentTime(frame) frame_data = point.data[frame] local_x = frame_data[0] / width - 0.5 local_y = frame_data[1] / width - 0.5 * height / width loc.tx.set(local_x) loc.ty.set(local_y) loc.tx.setKey() loc.ty.setKey()
Example #14
Source File: auxiliary.py From anima with MIT License | 5 votes |
def unsetup(self): """deletes the barn door setup """ if self.light: try: pm.delete( self.light.attr(self.message_storage_attr_name).inputs() ) except AttributeError: pass pm.scriptJob( k=int(self.light.getAttr(self.custom_data_storage_attr_name)) ) else: # try to delete the by using the barndoor group found_light = False for node in pm.ls(sl=1, type='transform'): # list all lights and try to find the light that has this group for light in pm.ls(type=pm.nt.Light): light_parent = light.getParent() if light_parent.hasAttr(self.message_storage_attr_name): if node in light_parent.attr( self.message_storage_attr_name).inputs(): self.light = light_parent found_light = True self.unsetup() # if the code comes here than this node is not listed in any # lights, so delete it if it contains the string # "barndoor_preview_curves" in its name if not found_light \ and "barndoor_preview_curves" in node.name(): pm.delete(node)
Example #15
Source File: auxiliary.py From anima with MIT License | 5 votes |
def get_cacheable_nodes(): """returns the cacheable nodes from the current scene :return: """ from anima.ui.progress_dialog import ProgressDialogManager from anima.env.mayaEnv import MayaMainProgressBarWrapper wrp = MayaMainProgressBarWrapper() pdm = ProgressDialogManager(dialog=wrp) pdm.close() # list all cacheable nodes cacheable_nodes = [] tr_list = pm.ls(tr=1, type='transform') caller = pdm.register(len(tr_list), 'Searching for Cacheable Nodes') for tr in tr_list: if tr.hasAttr('cacheable') and tr.getAttr('cacheable'): # check if any of its parents has a cacheable attribute has_cacheable_parent = False for parent in tr.getAllParents(): if parent.hasAttr('cacheable'): has_cacheable_parent = True break if not has_cacheable_parent: # only include direct references ref = tr.referenceFile() if ref is not None and ref.parent() is None: # skip cacheable nodes coming from layout if ref.version and ref.version.task.type \ and ref.version.task.type.name.lower() == 'layout': caller.step() continue cacheable_nodes.append(tr) caller.step() return cacheable_nodes
Example #16
Source File: auxiliary.py From anima with MIT License | 5 votes |
def store_user_options(self): """stores user options """ # query active model panel active_panel = self.get_active_panel() # store show/hide display options for active panel self.reset_user_view_options_storage() for flag in self.display_flags: try: val = pm.modelEditor(active_panel, **{'q': 1, flag: True}) self.user_view_options['display_flags'][flag] = val except TypeError: pass # store hud display options hud_names = pm.headsUpDisplay(lh=1) for hud_name in hud_names: val = pm.headsUpDisplay(hud_name, q=1, vis=1) self.user_view_options['huds'][hud_name] = val for camera in pm.ls(type='camera'): camera_name = camera.name() per_camera_attr_dict = {} for attr in self.cam_attribute_names: per_camera_attr_dict[attr] = camera.getAttr(attr) self.user_view_options['camera_flags'][camera_name] = \ per_camera_attr_dict
Example #17
Source File: auxiliary.py From anima with MIT License | 5 votes |
def set_range_from_shot(shot): """sets the playback range from a shot node in the scene :param shot: Maya Shot """ min_frame = shot.getAttr('startFrame') max_frame = shot.getAttr('endFrame') pm.playbackOptions( ast=min_frame, aet=max_frame, min=min_frame, max=max_frame )
Example #18
Source File: auxiliary.py From anima with MIT License | 5 votes |
def export_blend_connections(): """Exports the connection commands from selected objects to the blendShape of another object. The resulted text file contains all the MEL scripts to reconnect the objects to the blendShape node. So after exporting the connection commands you can export the blendShape targets as another maya file and delete them from the scene, thus your scene gets lite and loads much more quickly. """ selection_list = pm.ls(tr=1, sl=1, l=1) dialog_return = pm.fileDialog2(cap="Save As", fm=0, ff='Text Files(*.txt)') filename = dialog_return[0] print(filename) print("\n\nFiles written:\n--------------------------------------------\n") with open(filename, 'w') as fileId: for i in range(0, len(selection_list)): shapes = pm.listRelatives(selection_list[i], s=True, f=True) main_shape = "" for j in range(0, len(shapes)): if pm.getAttr(shapes[j] + '.intermediateObject') == 0: main_shape = shapes break if main_shape == "": main_shape = shapes[0] con = pm.listConnections(main_shape, t="blendShape", c=1, s=1, p=1) cmd = "connectAttr -f %s.worldMesh[0] %s;" % ( ''.join(map(str, main_shape)), ''.join(map(str, con[0].name())) ) print("%s\n" % cmd) fileId.write("%s\n" % cmd) print("\n------------------------------------------------------\n") print("filename: %s ...done\n" % filename)
Example #19
Source File: anim_utils.py From mgear_core with MIT License | 5 votes |
def get_host_from_node(control): """Returns the host control name from the given control Args: control (str): Rig control Returns: str: Host UI control name """ # get host control namespace = getNamespace(control).split("|")[-1] host = cmds.getAttr("{}.uiHost".format(control)) return "{}:{}".format(namespace, host)
Example #20
Source File: anim_utils.py From mgear_core with MIT License | 5 votes |
def get_ik_fk_controls(control, blend_attr): """ Returns the ik and fk controls related to the given control blend attr Args: control (str): uihost control to interact with blend_attr (str): attribute containing control list Returns: dict: fk and ik controls list on a dict """ ik_fk_controls = {"fk_controls": [], "ik_controls": []} controls_attribute = blend_attr.replace("_blend", "_ctl") try: controls = cmds.getAttr("{}.{}".format(control, controls_attribute)) except ValueError: if control == "world_ctl": _msg = "New type attributes using world as host are not supported" raise RuntimeError(_msg) attr = "{}_{}_ctl".format(blend_attr.split("_")[0], control.split(":")[-1].split("_")[1]) controls = cmds.getAttr("{}.{}".format(control, attr)) # filters the controls for ctl in controls.split(","): if len(ctl) == 0: continue ctl_type = ctl.split("_")[2] # filters ik controls if "ik" in ctl_type or "upv" in ctl_type: ik_fk_controls["ik_controls"].append(ctl) # filters fk controls elif "fk" in ctl_type: ik_fk_controls["fk_controls"].append(ctl) return ik_fk_controls
Example #21
Source File: attribute.py From mgear_core with MIT License | 5 votes |
def setRotOrder(node, s="XYZ"): """Set the rotorder of the object. Arguments: node (dagNode): The object to set the rot order on. s (str): Value of the rotorder. Possible values : ("XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX") """ a = ["XYZ", "YZX", "ZXY", "XZY", "YXZ", "ZYX"] if s not in a: mgear.log("Invalid Rotorder : " + s, mgear.sev_error) return False # Unless Softimage there is no event on the rotorder parameter to # automatically adapt the angle values # So let's do it manually using the EulerRotation class er = datatypes.EulerRotation([pm.getAttr(node + ".rx"), pm.getAttr(node + ".ry"), pm.getAttr(node + ".rz")], unit="degrees") er.reorderIt(s) node.setAttr("ro", a.index(s)) node.setAttr("rotate", er.x, er.y, er.z)
Example #22
Source File: modeling.py From SIWeightEditor with MIT License | 4 votes |
def marge_run(self): objects = common.search_polygon_mesh(self.objects, serchChildeNode=True, fullPath=True) #print 'marge target :', objects if len(objects) < 2: self.marged_mesh = objects return True skined_list = [] no_skin_list = [] parent_list = [cmds.listRelatives(obj, p=True, f=True) for obj in objects] for obj in objects: skin = cmds.ls(cmds.listHistory(obj), type='skinCluster') if skin: skined_list.append(obj) else: no_skin_list.append(obj) if no_skin_list and skined_list: skined_mesh = skined_list[0] for no_skin_mesh in no_skin_list: weight.transfer_weight(skined_mesh, no_skin_mesh, transferWeight=False, returnInfluences=False, logTransfer=False) if skined_list: marged_mesh = pm.polyUniteSkinned(objects)[0] pm.polyMergeVertex(marged_mesh, d=0.001) target_mesh = pm.duplicate(marged_mesh)[0] weight.transfer_weight(str(marged_mesh), str(target_mesh), transferWeight=True, returnInfluences=False, logTransfer=False) else: marged_mesh = pm.polyUnite(objects, o=True)[0] pm.polyMergeVertex(marged_mesh, d=0.001) target_mesh = pm.duplicate(marged_mesh)[0] #pm.delete(objects) for obj in objects: if pm.ls(obj): pm.delete(obj) pm.delete(marged_mesh) all_attr_list = [['.sx', '.sy', '.sz'], ['.rx', '.ry', '.rz'], ['.tx', '.ty', '.tz']] for p_node in parent_list: if cmds.ls(p_node, l=True): all_lock_list = [] for attr_list in all_attr_list: lock_list = [] for attr in attr_list: lock_list.append(pm.getAttr(target_mesh+attr, lock=True)) pm.setAttr(target_mesh+attr, lock=False) all_lock_list.append(lock_list) pm.parent(target_mesh, p_node[0]) for lock_list, attr_list in zip(all_lock_list, all_attr_list): for lock, attr in zip(lock_list, attr_list): #continue #print 'lock attr :', lock, target_mesh, attr pm.setAttr(target_mesh+attr, lock=lock) break pm.rename(target_mesh, objects[0]) pm.select(target_mesh) self.marged_mesh = str(target_mesh) return True
Example #23
Source File: sharedShape.py From fossil with BSD 3-Clause "New" or "Revised" License | 4 votes |
def connect( obj, name_level ): ''' Hook the given obj's visibility to the `name` attribute on the sharedShape. If the attr doesn't exist, it will be made. Optionanal `level` will determine when the `obj` will become visible. For example, 2 will not be visible at 1, but will at 2 and higher. ''' name, level = name_level # Probably should just update this eventually to be 3 params orig = obj zero = core.dagObj.zero(obj, apply=False, make=False) if zero: obj = zero shape = get() if not shape: warning('Unable to add vis control, no object exists named "main" or tagged with ".fossilMainControl"') return log.debug('Applying vis control to {}, was given {} using {}'.format(obj, orig, shape)) plug = shape + '.' + name if not cmds.objExists( plug ): cmds.addAttr( shape, ln=name, at='short', min=0, max=level, dv=1 ) cmds.setAttr( shape + '.' + name, cb=True ) elif cmds.getAttr( shape + '.' + name, type=True) not in ['bool', 'double', 'float', 'long', 'short']: warning( '{0} is not a good name for a vis group since the sharedShape has an attr already that is of the wrong type'.format(name) ) return if cmds.addAttr(plug, q=True, max=True) < level: cmds.addAttr(plug, e=True, max=level) if level == 1: connectAttr( plug, obj.visibility.name(), f=True) else: connectAttr( getConditionNode(plug, level).outColorR, obj.visibility, f=True) obj.visibility.setKeyable(False) # If we have a main controller, put the container in a subgroup to make # the main group more organized. visGroupName = '_vis_' + name if not find(orig): use(orig) if isinstance(orig, nodeApi.RigController): if shortName(orig.container.getParent()) != visGroupName: orig.setGroup(visGroupName)
Example #24
Source File: modeling.py From SISideBar with MIT License | 4 votes |
def marge_run(self): objects = common.search_polygon_mesh(self.objects, serchChildeNode=True, fullPath=True) print objects #print objects if len(objects) < 2: self.marged_mesh = objects return True skined_list = [] no_skin_list = [] parent_list = [cmds.listRelatives(obj, p=True, f=True) for obj in objects] for obj in objects: skin = cmds.ls(cmds.listHistory(obj), type='skinCluster') if skin: skined_list.append(obj) else: no_skin_list.append(obj) if no_skin_list and skined_list: skined_mesh = skined_list[0] for no_skin_mesh in no_skin_list: weight.transfer_weight(skined_mesh, no_skin_mesh, transferWeight=False, returnInfluences=False, logTransfer=False) if skined_list: marged_mesh = pm.polyUniteSkinned(objects)[0] pm.polyMergeVertex(marged_mesh, d=0.001) target_mesh = pm.duplicate(marged_mesh)[0] weight.transfer_weight(str(marged_mesh), str(target_mesh), transferWeight=True, returnInfluences=False, logTransfer=False) else: marged_mesh = pm.polyUnite(objects, o=True)[0] pm.polyMergeVertex(marged_mesh, d=0.001) target_mesh = pm.duplicate(marged_mesh)[0] #pm.delete(objects) for obj in objects: if pm.ls(obj): pm.delete(obj) pm.delete(marged_mesh) all_attr_list = [['.sx', '.sy', '.sz'], ['.rx', '.ry', '.rz'], ['.tx', '.ty', '.tz']] for p_node in parent_list: if cmds.ls(p_node, l=True): all_lock_list = [] for attr_list in all_attr_list: lock_list = [] for attr in attr_list: lock_list.append(pm.getAttr(target_mesh+attr, lock=True)) pm.setAttr(target_mesh+attr, lock=False) all_lock_list.append(lock_list) pm.parent(target_mesh, p_node[0]) for lock_list, attr_list in zip(all_lock_list, all_attr_list): for lock, attr in zip(lock_list, attr_list): continue pm.setAttr(target_mesh[0]+attr, lock=lock) break pm.rename(target_mesh, objects[0]) pm.select(target_mesh) self.marged_mesh = str(target_mesh) return True