我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.ls()。
def add_bookmark(type, value): ''' ????????????? :param type: ?????????? :param value: ?????? :return: ''' option_var_name = get_bookmark_option_var_name(type) ls = cmds.optionVar(q=option_var_name) if ls == 0: ls = [] if value not in ls: ls.append(value) cmds.optionVar(ca=option_var_name) [cmds.optionVar(sva=(option_var_name, i)) for i in ls] return
def delete_bookmark(ui, value): ''' ??????????? :param type: ?????????? :param value: ?????? :return: ''' if ui.radio_bookmark_file.isChecked(): type = 'file' elif ui.radio_bookmark_directory.isChecked(): type = 'directory' option_var_name = get_bookmark_option_var_name(type) ls = cmds.optionVar(q=option_var_name) if ls != 0: if value in ls: ls.remove(value) cmds.optionVar(ca=option_var_name) [cmds.optionVar(sva=(option_var_name, i)) for i in ls] return
def add_rectnt_file(file_path, file_type): ''' ???????????? :param file_path: :param file_type: :return: ''' optvar = cmds.optionVar opt_list = 'RecentFilesList' opt_type = 'RecentFilesTypeList' max_size = optvar(q='RecentFilesMaxSize') ls = optvar(q=opt_list) # ??????????? for i, x in enumerate(ls): if file_path == x: optvar(rfa=[opt_list, i]) optvar(rfa=[opt_type, i]) optvar(sva=[opt_list, file_path]) optvar(sva=[opt_type, file_type]) if len(optvar(q=opt_list)) > max_size: optvar(rfa=[opt_list, 0]) optvar(rfa=[opt_type, 0])
def execute(my): # get the search key from the delivered package search_key = my.get_package_value("search_key") # get the sobject from the server sobject = my.server.get_by_search_key(search_key) if not sobject: raise Exception("SObject with search key [%s] does not exist" % \ search_key) # code and verify in maya that the node is in session code = sobject.get('code') if not cmds.ls(code): raise Exception("Cannot checkin: [%s] does not exist" % code) my.set_output_value('sobject', sobject)
def _maintained_selection_context(): """Maintain selection during context Example: >>> scene = cmds.file(new=True, force=True) >>> node = cmds.createNode("transform", name="Test") >>> cmds.select("persp") >>> with maintained_selection(): ... cmds.select("Test", replace=True) >>> "Test" in cmds.ls(selection=True) False """ previous_selection = cmds.ls(selection=True) try: yield finally: if previous_selection: cmds.select(previous_selection, replace=True, noExpand=True) else: cmds.select(deselect=True, noExpand=True)
def shape_from_element(element): """Return shape of given 'element' Supports components, meshes, and surfaces """ try: # Get either shape or transform, based on element-type node = cmds.ls(element, objectsOnly=True)[0] except Exception: cmds.warning("Could not find node in %s" % element) return None if cmds.nodeType(node) == 'transform': try: return cmds.listRelatives(node, shapes=True)[0] except Exception: cmds.warning("Could not find shape in %s" % element) return None else: return node
def set_defaults(*args): """Set currently selected values from channel box to their default value If no channel is selected, default all keyable attributes. """ for node in cmds.ls(selection=True): selected_channels = read_selected_channels() for channel in (selected_channels or cmds.listAttr(node, keyable=True)): try: default = cmds.attributeQuery(channel, node=node, listDefault=True)[0] except Exception: continue else: cmds.setAttr(node + "." + channel, default)
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 _clone(worldspace=False): """Clone selected objects in viewport Arguments: worldspace (bool): Whether or not to append a transformGeometry to resulting clone. """ clones = list() for node in cmds.ls(selection=True, long=True): shape = _find_shape(node) type = cmds.nodeType(shape) if type not in ("mesh", "nurbsSurface", "nurbsCurve"): cmds.warning("Skipping '{node}': cannot clone nodes " "of type '{type}'".format(**locals())) continue cloned = commands.clone(shape, worldspace=worldspace) clones.append(cloned) if not clones: return # Select newly created transform nodes in the viewport transforms = list() for clone in clones: transform = cmds.listRelatives(clone, parent=True, fullPath=True)[0] transforms.append(transform) cmds.select(transforms, replace=True)
def process(self, instance): from maya import cmds from avalon import maya with maya.maintained_selection(): cmds.select(instance, replace=True) nodes = cmds.file( constructionHistory=True, exportSelected=True, preview=True, force=True, ) self.assemblies[:] = cmds.ls(nodes, assemblies=True) if not self.assemblies: raise Exception("No assembly found.") if len(self.assemblies) != 1: self.assemblies = '"%s"' % '", "'.join(self.assemblies) raise Exception( "Multiple assemblies found: %s" % self.assemblies )
def process(self, instance): from maya import cmds invalid = list() for mesh in cmds.ls(instance, type="mesh", long=True): faces = cmds.polyListComponentConversion(mesh, toVertexFace=True) locked = cmds.polyNormalPerVertex(faces, query=True, freezeNormal=True) invalid.append(mesh) if any(locked) else None # On locked normals, indicate that validation has failed # with a friendly message for the user. assert not invalid, ( "Meshes found with locked normals: %s" % invalid) self.log.info("The normals of \"%s\" are correct." % instance)
def getObjects(self, model, includeShapes=True): """Get the objects of the component. Args: model(dagNode): The root of the component. includeShapes (boo): If True, will include the shapes. Returns: list of dagNode: The list of the objects. """ objects = {} if includeShapes: children = pm.listRelatives(model, ad=True) else: children = pm.listRelatives(model, ad=True, typ='transform') pm.select(children) for child in pm.ls(self.fullName + "_*", selection=True): objects[child[child.index( self.fullName + "_") + len(self.fullName + "_"):]] = child return objects
def getObjects3(self, model): """ NOTE: Experimental function Get the objects of the component. This version only get the transforms by Name using Maya Cmds Args: model(dagNode): The root of the component. Returns: list of dagNode: The list of the objects. """ objects = {} for child in cmds.ls(self.fullName + "_*", type="transform"): if pm.PyNode(child).getParent(-1) == model: objects[child[child.index( self.fullName + "_") + len(self.fullName + "_"):]] = child return objects
def make_position_planar(*args): sel = cmds.ls(sl=True, type='joint') if len(sel) <= 3: raise RuntimeError('Select 3 joints to make a plane and then additional joints to move onto that plane.') a, b, c = [get_position(sel[i]) for i in range(3)] ab = (b - a).normal() ac = (c - a).normal() normal = (ab ^ ac).normal() joints = sel[3:] for joint in joints: children = _unparent_children(joint) p = get_position(joint) pa = a - p dot = pa*normal p = p + (normal*dot) cmds.xform(joint, ws=True, t=(p.x, p.y, p.z)) _reparent_children(joint, children) if sel: cmds.select(sel)
def dump(root=None, file_path=None): """Dump the hierarchy data starting at root to disk. :param root: Root node of the hierarchy. :param file_path: Export json path. :return: The hierarchy data that was exported. """ if root is None: root = cmds.ls(sl=True) if root: root = root[0] else: return if file_path is None: file_path = cmds.fileDialog2(fileFilter='Skeleton Files (*.json)', dialogStyle=2, caption='Export Skeleton', fileMode=0, returnFilter=False) if file_path: file_path = file_path[0] else: return data = get_data(root) fh = open(file_path, 'w') json.dump(data, fh, indent=4) fh.close() logger.info('Exported skeleton to %s', file_path) return data, file_path
def create_selected(self): """Create the curves selected in the curve list.""" curves = [] sel = cmds.ls(sl=True) target = sel[0] if sel else None for item in self.control_list.selectedItems(): text = item.text() control_file = os.path.join(CONTROLS_DIRECTORY, '{0}.json'.format(text)) fh = open(control_file, 'r') data = json.load(fh) fh.close() curve = create_curve(data) if target: cmds.delete(cmds.parentConstraint(target, curve)) curves.append(curve) if curves: cmds.select(curves)
def setUp(self): self.group = cmds.createNode('transform', name='skeleton_grp') cmds.select(cl=True) j1 = cmds.joint(p=(0, 10, 0)) cmds.joint(p=(1, 9, 0)) cmds.joint(p=(2, 8, 0)) j = cmds.joint(p=(3, 9, 0)) cmds.joint(p=(4, 6, 0)) cmds.joint(p=(5, 5, 0)) cmds.joint(p=(6, 3, 0)) self.cube = cmds.polyCube()[0] cmds.parent(self.cube, j) cmds.parent(j1, self.group) self.translates = [cmds.getAttr('{0}.t'.format(x))[0] for x in cmds.ls(type='joint')] self.rotates = [cmds.getAttr('{0}.r'.format(x))[0] for x in cmds.ls(type='joint')] self.orients = [cmds.getAttr('{0}.jo'.format(x))[0] for x in cmds.ls(type='joint')]
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 get_unused_utility_nodes(): u"""????????????????????? :return: ?????????????????? :rtype: list of unicode """ utility_node_types = cmds.listNodeTypes("utility") utility_nodes = [] for ul in utility_node_types: nodes = cmds.ls(type=ul) if not nodes: continue utility_nodes.extend(nodes) unused = [] for u in utility_nodes: if not [x for x in cmds.listConnections(u) if x != "defaultRenderUtilityList1"]: unused.append(u) return unused
def get_unused_shading_engines(): u"""????ShadingEngine??????? :return: ????ShadingEngine???? :rtype: list of unicode """ shading_engines = cmds.ls(type="shadingEngine") unused_shading_engines = [] for s in shading_engines: if s in _DEFAULT_SHADING_ENGINES: continue unused = True for c in cmds.listConnections(s): node_type = cmds.nodeType(c) if "shader" in cmds.getClassification(node_type)[0]: unused = False break if unused: unused_shading_engines.append(s) return unused_shading_engines
def BT_DoSetup(): sets = cmds.ls(sl = True, type = 'objectSet') if len(sets) <= 0: cmds.warning("Select a set.") return False set = sets[0] unitResult = BT_SetUnits() if unitResult: QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Units set to centimetres.", "Okay") result = BT_Setup(set = set) if not result: QtGui.QMessageBox.warning(BT_GetMayaWindow(), "Blend Transforms", "Problem with setup. May already be connected.", "Okay") return False print('Success!') return True
def read_sequence(): rate = FPS.get(cmds.currentUnit(q=True, time=True), 25) shots = cmds.ls(type='shot') or [] per_track = {} for shot in shots: track_no = cmds.shot(shot, q=True, track=True) if track_no not in per_track: per_track[track_no] = [] per_track[track_no].append(shot) timeline = otio.schema.Timeline() timeline.global_start_time = otio.opentime.RationalTime(0, rate) for track_no in reversed(sorted(per_track.keys())): track_shots = per_track[track_no] timeline.tracks.append(_read_track(track_shots)) return timeline
def SelectKeyframes(): # Clear current selection cmds.select(clear=True) # Get a list of bones boneList = cmds.ls(type = 'joint') # Iterate and select ones with frames on loc/rot/scale for bone in boneList: # Check for loc keysTranslate = cmds.keyframe(bone + ".translate", query=True, timeChange=True) keysRotate = cmds.keyframe(bone + ".rotate", query=True, timeChange=True) keysScale = cmds.keyframe(bone + ".scale", query=True, timeChange=True) # Check for frames if keysTranslate is not None: if len(keysTranslate) >= 1: cmds.select(bone, add=True) if keysRotate is not None: if len(keysRotate) >= 1: cmds.select(bone, add=True) if keysScale is not None: if len(keysScale) >= 1: cmds.select(bone, add=True) # Cleans namespaces
def NamespaceClean(): # Get a list of bones boneList = cmds.ls(type = 'joint') # Loop for bone in boneList: # Check if it has a namespace if bone.find(":") > -1: # We got one, prepare to clean resultSplit = bone.split(":") # Get the last one newName = resultSplit[len(resultSplit)-1] # Rename it try: # Do it cmds.rename(bone, newName) except: # Continue pass
def cross_stitch(stitches=108, stitch_points=8, u_offset=0, tangent_offset=0, normal_fn=None): '''Create cross stitching between two curves''' a, b = cmds.ls(sl=True, dag=True, leaf=True) if not normal_fn: normal_fn = partial(sphere_normal, center=MVector(0, 0, 0)) half_stitches = int(stitches * 0.5) u_offset_a = u_offset u_offset_b = u_offset + 1.0 / (half_stitches * 2) a0, a1 = MVector(*point_at_parameter(a, 0)), MVector(*point_at_parameter(a, u_offset_b)) tangent_offset += (a0-a1).length() * 0.3 print tangent_offset points = stitch_curves(a, b, half_stitches, stitch_points, u_offset_a, tangent_offset, normal_fn) cmds.curve(point=points) points = stitch_curves(a, b, half_stitches, stitch_points, u_offset_b, tangent_offset, normal_fn) cmds.curve(point=points)
def add_curve_to_system(curve_shape, hair_system=None): if hair_system is None: selection = cmds.ls(sl=True, dag=True, leaf=True, type='hairSystem') if selection: hair_system = selection[0] else: hair_system = create_hair_system() follicle_nodes, out_curve_nodes = curve_to_hair(curve_shape, hair_system) follicles_grp = hair_system + 'Follicles' if not cmds.objExists(follicles_grp): cmds.group(empty=True, name=follicles_grp) cmds.parent(follicle_nodes[0], follicles_grp) outcurves_grp = hair_system + 'OutputCurves' if not cmds.objExists(outcurves_grp): cmds.group(empty=True, name=outcurves_grp) cmds.parent(out_curve_nodes[0], outcurves_grp) return follicle_nodes
def populateCrvField(tfgKey="", *args): if tfgKey not in ["cntrPivTFBG", "cntrPiv2TFBG", "upLoc2TFBG", "upLocTFBG"]: sel = cmds.ls(sl=True) if sel and len(sel)!=1: cmds.warning("only select the curve you want to rig up!") else: if rig.isType(sel[0], "nurbsCurve"): cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0]) else: cmds.warning("That's not a curve!") else: sel = cmds.ls(sl=True) if sel and len(sel)!=1: cmds.warning("only select the object you want to rig up!") else: cmds.textFieldButtonGrp(widgets[tfgKey], e=True, tx=sel[0]) if tfgKey == "upLocTFBG": cmds.textFieldButtonGrp(widgets["upLoc2TFBG"], e=True, tx=sel[0]) if tfgKey == "cntrPivTFBG": cmds.textFieldButtonGrp(widgets["cntrPiv2TFBG"], e=True, tx=sel[0])
def getObj(*args): #get selection and put it in the widgets["objTFG"] clearList() sel = cmds.ls(sl=True, type="transform") if (sel and (len(sel)==1)): cmds.textFieldGrp(widgets["objTFG"], e=True, tx=sel[0]) else: cmds.warning("you must select one object with the \"follow\" attribute") #------------maybe add attr onto end of obj text, then you don't have to get it later if you needed to ??? #now create a button for each value in the "follow" attr #channels = cmds.channelBox ('mainChannelBox', query=True, selectedMainAttributes=True) enumValueStr = cmds.attributeQuery("follow", node=sel[0], listEnum=True)[0] values = enumValueStr.split(":") for i in range(0,len(values)): #pick a random color? r = random.uniform(0.5,1) g = random.uniform(0.5,1) b = random.uniform(0.5,1) color = (r, g, b) #here create the button cmds.button(l=values[i], w=125, p=widgets["bottomRCLO"], bgc=color, h=50, c=partial(switchMatchSpace, i))
def huddleExec(*args): """ from first selection, moves the next selected objects closer or farther from first selection based on slider values (as a percentage) """ factor = cmds.floatSliderGrp(widgets["slider"], q=True, v=True) sel = cmds.ls(sl=True, type="transform") center = sel[0] objs = sel[1:] centerPos = cmds.xform(center, q=True, ws=True, rp=True) centerVec = om.MVector(centerPos[0], centerPos[1], centerPos[2]) for obj in objs: objPos = cmds.xform(obj, ws=True, q=True, rp=True) objVec = om.MVector(objPos[0], objPos[1], objPos[2]) diffVec = objVec-centerVec scaledVec = diffVec * factor newVec = scaledVec + centerVec cmds.xform(obj, ws=True, t=(newVec[0], newVec[1], newVec[2]))
def move_pivot(end, *args): """ Args: end (int): parameter value (0 or 1 from buttons) the point on curve will return, start or end *args: """ check = False sel = cmds.ls(sl=True, exactType = "transform") if sel: for x in sel: check = rig.isType(x, "nurbsCurve") if check: # get curve info pos = cmds.pointOnCurve(x, parameter = end, position = True) cmds.xform(x, ws=True, piv=pos) else: cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x))
def reparameter(*args): """ reparameterizes curves to be from 0-1 Args: Returns: """ sel = cmds.ls(sl=True, exactType = "transform") check = False newCrvs = [] if sel: for x in sel: check = rig.isType(x, "nurbsCurve") if check: crv = x newCrv = cmds.rebuildCurve(crv, constructionHistory=False, rebuildType = 0, keepControlPoints=True, keepRange = 0, replaceOriginal=True, name = "{0}_RB".format(crv))[0] # reconnect parents and children of orig curve else: cmds.warning("{0} is not a nurbsCurve object. Skipping!".format(x)) cmds.select(sel, r=True)
def getNormalizedTangent(pt = ""): """ gets normalized tan of selected (or given) list of cvs """ if cmds.objectType(pt) != "nurbsCurve": return crv = pt.partition(".")[0] print pt, crv cvs = cmds.ls("{0}.cv[*]".format(crv), fl=True) denom = len(cvs) num = float(pt.partition("[")[2].rpartition("]")[0]) pr = num/denom tan = cmds.pointOnCurve(crv, pr=pr, nt=True) return(tan)
def align_along_curve(*args): """ aligns and objet along a curve at given param Args: *args: Returns: void """ sel = cmds.ls(sl=True, type="transform") if len(sel) != 2: cmds.warning("You need to select curve then object to align!") return() crv = sel[0] obj = sel[1] if not rig.isType(crv, "nurbsCurve"): cmds.warning("select curve first, THEN object") return() param = cmds.floatFieldGrp(widgets["alExFFG"], q=True, v1=True) rig.align_to_curve(crv, obj, param)
def randRemovePercent(keepNum, *args): """gives each object the percentage chance to be removed. So will remove a variable number of objs""" sel = cmds.ls(sl=True, fl=True) remNum = (100.0 - keepNum)/100.00 #print remNum, "remove percent" count = 0 ch = [] if sel: for obj in sel: x = random.uniform(0,1) if x < (remNum): # print x, "--->", remNum ch.append(obj) count = count + 1 newSel = [g for g in sel if g not in ch] cmds.select(newSel, r=True) print count, "objects removed" #print len(sel), "objects remaining"
def insertGroupAbove(*args): sel = cmds.ls(sl=True) for obj in sel: par = cmds.listRelatives(obj, p=True) grp = cmds.group(em=True, n="{}_Grp".format(obj)) # grp = nameCheck(grp) pos = cmds.xform(obj, q=True, ws=True, rp=True) rot = cmds.xform(obj, q=True, ws=True, ro=True) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) cmds.parent(obj, grp) if par: cmds.parent(grp, par[0])
def freezeAndConnect(*args): sel = cmds.ls(sl=True) ctrlOrig = sel[0] for x in range(1, len(sel)): obj = sel[x] ctrl = cmds.duplicate(ctrlOrig, n = "{}Ctrl".format(obj))[0] pos = cmds.xform(obj, ws=True, q=True, rp=True) rot = cmds.xform(obj, ws=True, q=True, ro=True) grp = cmds.group(em=True, n="{}Grp".format(ctrl)) cmds.parent(ctrl, grp) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) cmds.parentConstraint(ctrl, obj)
def selectComponents(*args): sel = cmds.ls(sl=True) if sel: for obj in sel: shape = cmds.listRelatives(obj, s=True)[0] if cmds.objectType(shape) == "nurbsCurve": cmds.select(cmds.ls("{}.cv[*]".format(obj), fl=True)) elif cmds.objectType(shape) == "mesh": cmds.select(cmds.ls("{}.vtx[*]".format(obj), fl=True)) else: return
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 capReplace(*args): sel = cmds.ls(sl=True, type="transform") if sel < 2: cmds.warning("You don't have two things selected (cap and one ctrl minimum)!") return newCap = sel[0] ctrls = sel[1:] for ctrl in ctrls: oldCap = cmds.connectionInfo("{0}.capRig".format(ctrl), sfd=True).partition(".")[0] dupe = rig.swapDupe(newCap, oldCap, delete=True, name=oldCap) cmds.connectAttr("{0}.rotateCap".format(ctrl), "{0}.rotateY".format(dupe)) cmds.connectAttr("{0}.message".format(dupe), "{0}.capRig".format(ctrl)) cmds.setAttr("{0}.v".format(dupe), 1) # if not already, parent cap replace obj in folder and hide par = cmds.listRelatives(newCap, p=True) if not par or par[0] != "pastaRigSetupComponents_Grp": cmds.parent(newCap, "pastaRigSetupComponents_Grp") cmds.setAttr("{0}.v".format(newCap), 0) cmds.select(ctrls, r=True)
def addBaseCap(*args): sel = cmds.ls(sl=True, type="transform") if sel < 2: cmds.warning("You don't have two things selected (cap and one ctrl minimum)!") return newCap = sel[0] ctrls = sel[1:] for ctrl in ctrls: tempCap = cmds.connectionInfo("{0}.tempBaseCap".format(ctrl), sfd=True).partition(".")[0] dupe = rig.swapDupe(newCap, tempCap, delete=True, name="{0}_baseCap".format(ctrl)) cmds.setAttr("{0}.v".format(dupe), 1) cmds.connectAttr("{0}.rotateBaseCap".format(ctrl), "{0}.rotateY".format(dupe)) cmds.connectAttr("{0}.message".format(dupe), "{0}.tempBaseCap".format(ctrl)) # if not already, parent cap replace obj in folder and hide par = cmds.listRelatives(newCap, p=True) if not par or par[0] != "pastaRigSetupComponents_Grp": cmds.parent(newCap, "pastaRigSetupComponents_Grp") cmds.setAttr("{0}.v".format(newCap), 0) cmds.select(ctrls, r=True)
def addGroupAbove(obj="none", suff="none", *args): """name of existing obj, new group suffix. New group will be oriented to the object BELOW it""" #FIX THE OBJ, SUFIX TO BE EITHER SELECTED OR ENTERED sel = cmds.ls(sl=True, type = "transform") for obj in sel: suff = "_new" name = obj + suff + "_GRP" #get worldspace location of existing obj loc = cmds.xform(obj, q=True, ws=True, rp=True) #create new group, name it, move it to new postion in ws and Orient it grp = cmds.group(empty=True, name=name) cmds.move(loc[0], loc[1], loc[2], grp, ws=True) oc = cmds.orientConstraint(obj, grp) cmds.delete(oc) #check if there's a parent to the old group par = cmds.listRelatives(obj, p=True) print(par) if par: cmds.parent(grp, par) cmds.parent(obj, grp)
def getValues(*args): try: obj = cmds.ls(sl=True, transforms = True)[0] #currentFrame = cmds.currentTime(q = True) step = cmds.intFieldGrp(widgets['stepIFG'], q = True, v1 = True) frmVal = cmds.radioButtonGrp(widgets["frmRBG"], q=True, sl=True) suffix = cmds.textFieldGrp(widgets["sufTFG"], q = True, tx = True) name = "%s_%s"%(obj, suffix) if frmVal == 1: frameStart = int(cmds.playbackOptions(query=True, min=True)) frameEnd = int(cmds.playbackOptions(query=True, max=True)) else: frameStart = cmds.intFieldGrp(widgets["frmRngIFG"], q = True, v1 = True) frameEnd = cmds.intFieldGrp(widgets["frmRngIFG"], q = True, v2 = True) makeSequence(obj, name, frameStart, frameEnd, step) except: cmds.warning("Select one object with a transform")
def import_animation(*args): """imports the anim (from rand selection of list items) onto selected objs""" lo, hi = cmds.intFieldGrp(widgets["rangeIFG"], q=True, v=True) rand = cmds.radioButtonGrp(widgets["randRBG"], q=True, sl=True) clips = cmds.textScrollList(widgets["animTSL"], q=True, si=True) path = cmds.textFieldButtonGrp(widgets["impPathTFG"], q=True, tx=True) options = {"targetTime":3, "time": 1, "option":"insert", "connect":1} delKeys = cmds.checkBoxGrp(widgets["delCBG"], q=True, v1=True) sel = cmds.ls(sl=True) for obj in sel: startF = cmds.currentTime(q=True) if rand == 1: startF = random.randint(lo, hi) cmds.currentTime(startF) if delKeys: delete_later_keys(obj, startF) cmds.select(obj, r=True) myClip = random.choice(clips) animPath = "{0}/{1}".format(path, myClip) cmds.file(animPath, i = True, type = "animImport", ignoreVersion = True, options = "targetTime={0};time={1};copies=1;option={2};pictures=0;connect={3};".format(options["targetTime"], startF, options["option"], options["connect"]), preserveReferences=True) cmds.select(sel, r=True)
def setValues(*args): """sets the values from window on all selected objs for appropriate channels""" sel = cmds.ls(sl=True) attrs = cmds.checkBoxGrp(widgets["transCBG"], q=True, va3=True) trans = attrs[0] rots = attrs[1] scls = attrs[2] for obj in sel: if cmds.objectType(obj)=="transform": if trans: t = cmds.floatFieldGrp(widgets["trnFFG"], q=True, v=True) cmds.setAttr("{}.translate".format(obj), t[0], t[1], t[2]) if rots: r = cmds.floatFieldGrp(widgets["rotFFG"], q=True, v=True) cmds.setAttr("{}.rotate".format(obj), r[0],r[1], r[2]) if scls: s = cmds.floatFieldGrp(widgets["sclFFG"], q=True, v=True) cmds.setAttr("{}.scale".format(obj), s[0], s[1], s[2])
def options_pass(*args): xfersDo, shpsDo = cmds.checkBoxGrp(widgets["shapeCBG"], q=True, valueArray2=True) inputs, outputs = cmds.checkBoxGrp(widgets["inOutCBG"], q=True, valueArray2=True) sel = cmds.ls(sl=True) if len(sel) != 2: cmds.warning("You don't have two things selected! (source, then target)") return() srcX = sel[0] tgtX = sel[1] if xfersDo: transfer_connections_do(srcX, tgtX, inputs, outputs) if shpsDo: # options for checkbox would go here. . . srcShp = cmds.listRelatives(srcX, s=True)[0] tgtShp = cmds.listRelatives(tgtX, s=True)[0] transfer_connections_do(srcShp, tgtShp, inputs, outputs)
def getObjectList(*args): """gets the list of object of type txt""" objs = [] objText = getTypeText() if objText in typeList: objs = cmds.ls(type=objText) else: cmds.warning("This instance of Maya doesn't recognize that type of object: {0}!".format(objText)) return() if objs: #---------------- check if we're promoting shapes #---------------- if yes, send out list to see which elements are shapes and promote them, return a new list into obj ie. objs = promoteList(objs), this will return either the same list or an ammended list addObjectsToScrollList(objs) else: cmds.warning("No objects found of type: {0}".format(objText))
def selMovePatch(verts, weights, *args): """take a selection of verts (could be soft) and randomly move them up""" #cutoffRaw = cmds.intSliderGrp(widgets["selvpercISG"], q=True, v=True) #cutoff = cutoffRaw/100.0 cycles = cmds.intFieldGrp(widgets["patchiterIFG"], q= True, v1 = True) xmin = cmds.floatFieldGrp(widgets["patchmovexFFG"], q=True, v1= True) xmax = cmds.floatFieldGrp(widgets["patchmovexFFG"], q=True, v2= True) ymin = cmds.floatFieldGrp(widgets["patchmoveyFFG"], q=True, v1= True) ymax = cmds.floatFieldGrp(widgets["patchmoveyFFG"], q=True, v2= True) zmin = cmds.floatFieldGrp(widgets["patchmovezFFG"], q=True, v1= True) zmax = cmds.floatFieldGrp(widgets["patchmovezFFG"], q=True, v2= True) sel = cmds.ls(sl=True) #####HERE GET VERTS TO SELECT (WITH MULT VALUES) for x in range(0,cycles): #print "doing pass %s"%x #rand = random.uniform(0, 1) #if rand <= cutoff: randx = random.uniform(xmin, xmax) randy = random.uniform(ymin, ymax) randz = random.uniform(zmin, zmax) for y in range(0, len(verts)): cmds.move(randx * weights[y],randy* weights[y], randz* weights[y], verts[y], verts[y], r=True)