我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.parent()。
def add_top_level_ctrl(origCtrl, type, geo, *args): """ creates a new ctrl, orients it to the geo and parent constrains the orig ctrl rig under itself :param origCtrl: the control we're working from :param type: the ctrl type of shape see zbw_rig.createControl for options :param geo: the geo to orient to :param args: :return: topCtrl (the new ctrl), grp (the top ctrl grp freeze grp) """ # THIS IS THE XTRA CTRL LAYER, THIS ORIENTS CTRL AND CONNECTS ORIG CTRL TO THE NEW CTRL origCtrlPos = cmds.xform(origCtrl, q=True, ws=True, rp=True) topCtrl = rig.createControl(name="{0}_moveCtrl".format(origCtrl.rpartition("_")[0]), type=type, axis="z", color="yellow") grp = rig.groupFreeze(topCtrl) cmds.xform(grp, ws=True, t=origCtrlPos) nc = cmds.normalConstraint(geo, grp, worldUpType="vector", upVector=(0, 1, 0)) cmds.delete(nc) pc = cmds.parentConstraint(topCtrl, origCtrl, mo=True) sc = cmds.scaleConstraint(topCtrl, origCtrl, mo=True) return(topCtrl, grp)
def _output_node(source, type, suffix): newname = lib.unique(name=source.rsplit("_", 1)[0] + suffix) node = cmds.createNode(type) node = [cmds.listRelatives(node, parent=True) or node][0] node = cmds.rename(node, newname) try: cmds.parent(node, source) match_transform(node, source) except Exception: cmds.warning("Could not create %s" % node) cmds.delete(node) return node
def follicle(shape, u=0, v=0, name=""): """Attach follicle to "shape" at specified "u" and "v" values""" type = cmds.nodeType(shape) assert type in ("mesh", "nurbsSurface"), ( "follicle() works on polygonal meshes and nurbs") src, dst = { "mesh": (".outMesh", ".inputMesh"), "nurbsSurface": (".local", ".inputSurface") }[type] follicle = cmds.createNode("follicle", name=name + "Shape") transform = cmds.listRelatives(follicle, parent=True)[0] cmds.setAttr(follicle + ".parameterU", u) cmds.setAttr(follicle + ".parameterV", v) cmds.connectAttr(follicle + ".outTranslate", transform + ".translate") cmds.connectAttr(follicle + ".outRotate", transform + ".rotate") cmds.connectAttr(shape + ".worldMatrix[0]", follicle + ".inputWorldMatrix") cmds.connectAttr(shape + src, follicle + dst, force=True) return transform
def orient_to_world(joints): """Orients the given joints with the world. @param joints: Joints to orient. """ for joint in joints: children = _unparent_children(joint) print children parent = cmds.listRelatives(joint, parent=True, path=True) orig_joint = joint.split('|')[-1] if parent: joint = cmds.parent(joint, world=True)[0] cmds.joint(joint, e=True, oj='none', zso=True) if parent: joint = cmds.parent(joint, parent)[0] print 'Renaming {0} to {1}'.format(joint, orig_joint) joint = cmds.rename(joint, orig_joint) _reparent_children(joint, children) if joints: cmds.select(joints)
def create_node(node_dictionary, parent=None): """Create the Maya node described by the given data dictionary. :param node_dictionary: The data dictionary generated by one of the load/get functions. :param parent: The node to parent the created node to. """ node = cmds.createNode(node_dictionary['nodeType'], name=node_dictionary['name']) if parent: cmds.parent(node, parent) cmds.setAttr('{0}.t'.format(node), *node_dictionary['translate']) cmds.setAttr('{0}.r'.format(node), *node_dictionary['rotate']) cmds.setAttr('{0}.s'.format(node), *node_dictionary['scale']) cmds.setAttr('{0}.rotateOrder'.format(node), node_dictionary['rotateOrder']) cmds.setAttr('{0}.rotateAxis'.format(node), *node_dictionary['rotateAxis']) if node_dictionary['nodeType'] == 'joint': cmds.setAttr('{0}.jointOrient'.format(node), *node_dictionary['jointOrient']) cmds.setAttr('{0}.radius'.format(node), node_dictionary['radius']) cmds.setAttr('{0}.side'.format(node), node_dictionary['side']) cmds.setAttr('{0}.type'.format(node), node_dictionary['type']) cmds.setAttr('{0}.otherType'.format(node), node_dictionary['otherType'], type='string') cmds.setAttr('{0}.jointTypeX'.format(node), node_dictionary['jointTypeX']) cmds.setAttr('{0}.jointTypeY'.format(node), node_dictionary['jointTypeY']) cmds.setAttr('{0}.jointTypeZ'.format(node), node_dictionary['jointTypeZ']) for child in node_dictionary.get('children', []): create_node(child, node)
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 get_stack_parent(node): """Get the parent of the transform stack belonging to the given node. :param node: Node to query. :return: The parent node or None if there is no parent. """ previous_parent = cmds.listRelatives(node, parent=True, path=True) if not previous_parent: return None previous_parent = previous_parent[0] while previous_parent and STACK_ATTRIBUTE in (cmds.listAttr(previous_parent, ud=True) or []): parent = cmds.listRelatives(previous_parent, parent=True, path=True) if parent: parent = parent[0] previous_parent = parent return previous_parent
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 curve_to_hair(curve_shape, hair_system): curve = cmds.listRelatives(curve_shape, parent=True, f=True)[0] curve_name = curve.split('|')[-1] # Create follicle follicle_shape = cmds.createNode('follicle') follicle = cmds.listRelatives(follicle_shape, parent=True, f=True)[0] follicle = cmds.rename(follicle, curve_name + '_follicle#') follicle_shape = cmds.listRelatives(follicle, shapes=True, f=True)[0] cmds.connectAttr(curve + '.worldMatrix', follicle_shape + '.startPositionMatrix') cmds.connectAttr(curve_shape + '.local', follicle_shape + '.startPosition') # # Create output curve out_curve_shape = cmds.createNode('nurbsCurve') out_curve = cmds.listRelatives(out_curve_shape, parent=True, f=True)[0] out_curve = cmds.rename(out_curve, curve_name + '_out#') out_curve_shape = cmds.listRelatives(out_curve, shapes=True, f=True)[0] cmds.connectAttr(follicle + '.outCurve', out_curve_shape + '.create') # Add follicle to hair system add_follicle(follicle_shape, hair_system) return [[follicle, follicle_shape], [out_curve, out_curve_shape]]
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 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 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 insertGroupAbove(obj, *args): 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]) return(grp)
def makeSequence(obj = "", name = "", frameStart = 0, frameEnd = 1, step = 1): """duplicate selected geo based on settings from UI""" dupes = [] numCopies = (frameEnd-frameStart)/step #check here if we want to create more than 25 duplicates? confirm = cmds.confirmDialog(t="Confirm", m= "This will create %d copies of %s. \nFrames: %d to %d\nFor dense meshes, this could get heavy\nAre you sure you want to do this?"%(numCopies, obj, frameStart, frameEnd), button = ["Yes", "No"], cancelButton = "No") if confirm == "Yes": for frame in range(frameStart, frameEnd + 1, step): cmds.currentTime(frame, edit=True) dupe = cmds.duplicate(obj, n="%s_%d"%(name, frame), ic = False, un = False) dupes.append(dupe) if dupes: grp = cmds.group(em = True, n = "%s_GRP"%name) for dupe in dupes: cmds.parent(dupe, grp) #cmds.currentTime(currentFrame, e=True)
def applyBrush(curve, parent): ''' Simply applies the paint effects brush to the curve with the settings we want. ''' mc.AttachBrushToCurves(curve) stroke = mc.ls(sl=True)[0] stroke = mc.parent(stroke,parent)[0] mc.setAttr(stroke+'.displayPercent',92) mc.setAttr(stroke+'.sampleDensity',0.5) mc.setAttr(stroke+'.inheritsTransform',0) mc.setAttr(stroke+'.translate',0,0,0) mc.setAttr(stroke+'.rotate',0,0,0) return stroke
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 toLocators(bakeOnOnes=False, space='world', spaceInt=None, constrainSource=False): ''' Creates locators, and bakes their position to selection. Creates connections to the source objects, so they can be found later to bake back. ''' if spaceInt and 0 <= spaceInt <= 2: space = ['world', 'camera', 'last'][spaceInt] sel = mc.ls(sl=True) parent = None if space == 'camera': parent = utl.getCurrentCamera() elif space == 'last': parent = sel[-1] sel = sel[:-1] mc.select(sel) matchBakeLocators(parent=parent, bakeOnOnes=bakeOnOnes, constrainSource=constrainSource)
def match_transform(src, dst): """Transform `src` to `dst`, taking worldspace into account Arguments: src (str): Absolute path to source transform dst (str): Absolute path to destination transform """ try: parent = cmds.listRelatives(src, parent=True)[0] except Exception: parent = None node_decompose = cmds.createNode("decomposeMatrix") node_multmatrix = cmds.createNode("multMatrix") connections = { dst + ".worldMatrix": node_multmatrix + ".matrixIn[0]", node_multmatrix + ".matrixSum": node_decompose + ".inputMatrix", node_decompose + ".outputTranslate": src + ".translate", node_decompose + ".outputRotate": src + ".rotate", node_decompose + ".outputScale": src + ".scale", } if parent: connections.update({ parent + ".worldInverseMatrix": node_multmatrix + ".matrixIn[1]" }) for s, d in connections.iteritems(): cmds.connectAttr(s, d, force=True) cmds.refresh() cmds.delete([node_decompose, node_multmatrix])
def parent_group(source, transferTransform=True): """Create and transfer transforms to parent group""" assert cmds.objExists(source), "%s does not exist" % source assert cmds.nodeType(source) == "transform", ( "%s must be transform" % source) parent = cmds.listRelatives(source, parent=True) if transferTransform: group = cmds.createNode("transform", n="%s_parent" % source) match_transform(group, source) try: cmds.parent(source, group) except Exception: cmds.warning("Failed to parent child under new parent") cmds.delete(group) if parent: cmds.parent(group, parent[0]) else: cmds.select(source) group = cmds.group(n="%s_parent" % source) return group
def enhanced_parent(child, parent): if "shape" in cmds.nodeType(child, inherited=True): cmds.parent(relative=True, shape=True) else: cmds.parent(child, parent)
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 __init__(self, parent=None): self.children = [] self._parent = parent if parent is not None: parent.add_child(self)
def parent(self): """Get the parent of node""" return self._parent
def row(self): """Get the index of the node relative to the parent""" if self._parent is not None: return self._parent.children.index(self) return 0
def duplicate_chain(start, end, prefix='', suffix='', search_for='', replace_with=''): """ Duplicates the transform chain starting at start and ending at end. :param start: The start transform. :param end: The end transform. :return: A list of the duplicated joints, a list of the original joints that were duplicated """ joint = end joints = [] original_joints = [] while joint: name = '{0}{1}{2}'.format(prefix, joint, suffix) if search_for or replace_with: name = name.replace(search_for, replace_with) original_joints.append(joint) duplicate_joint = cmds.duplicate(joint, name=name, parentOnly=True)[0] if joints: cmds.parent(joints[-1], duplicate_joint) joints.append(duplicate_joint) if joint == start: break joint = cmds.listRelatives(joint, parent=True, path=True) if joint: joint = joint[0] else: raise RuntimeError('{0} is not a descendant of {1}'.format(end, start)) joints.reverse() original_joints.reverse() return joints, original_joints
def _unparent_children(joint): """Helper function to unparent any children of the given joint. @param joint: Joint whose children to unparent. @return: A list of the unparented children. """ children = cmds.listRelatives(joint, children=True, path=True) or [] return [cmds.parent(child, world=True)[0] for child in children]
def _reparent_children(joint, children): """Helper function to reparent any children of the given joint. @param joint: Joint whose children to reparent. @param children: List of transforms to reparent """ for child in children: cmds.parent(child, joint)
def template_joints(joints=None, reorient_children=True, reset_orientation=True): if joints is None: joints = cmds.ls(sl=True, type='joint') if not joints: raise RuntimeError('No joint selected to orient.') if reorient_children: children = cmds.listRelatives(fullPath=True, allDescendents=True, type='joint') joints.extend(children) red, green, blue = create_shaders() orient_group = cmds.createNode('transform', name=ORIENT_GROUP) manips = [] for joint in joints: if reset_orientation: cmds.makeIdentity(joint, apply=True) cmds.joint(joint, edit=True, orientJoint='xyz', secondaryAxisOrient='yup', children=False, zeroScaleOrient=True) if not cmds.listRelatives(joint, children=True): zero_orient([joint]) continue group, manip = create_orient_manipulator(joint, blue) manips.append(manip) cmds.parent(group, orient_group) cmds.parentConstraint(joint, group) cmds.setAttr(joint + '.template', 1) cmds.select(manips)
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_curves(curves): for curve in curves: create_curve(curve) # Now parent the curves for curve in curves: if curve.get('parent'): parent = curve['parent'] if cmds.objExists(parent): cmds.parent(curve['name'], parent) # Then create the stacks for curve in curves: if curve.get('stack'): create_transform_stack(curve['name'], curve['stack'])
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 test_duplicate_chain(self): for i in range(5): cmds.joint(p=(0, i, 0)) cmds.select(cl=True) for i in range(5): cmds.joint(p=(i+1, 0, 0)) cmds.parent('joint6', 'joint2') joints, original_joints = shortcuts.duplicate_chain('joint1', 'joint5', search_for='joint', replace_with='dupejoint') self.assertEqual(5, len(joints)) self.assertListEqual(['dupejoint{0}'.format(x) for x in range(1, 6)], joints) self.assertListEqual(['joint{0}'.format(x) for x in range(1, 6)], original_joints)
def _createInsideSphere(name, radius, parent): node = cmds.sphere(r=radius * .999)[0] cmds.parent(node, parent) cmds.rename(node, name) return node
def _createCurve(name, angle, cvs, parent): node = cmds.curve(d=1, p=cvs) cmds.parent(node, parent) name += '_n%03d' if angle < 0. else '_p%03d' cmds.rename(node, name % abs(round(angle))) return node
def create_joint_chain(positions, **kwargs): '''Create a joint chain from a list of om.MVectors''' aim_vects = [b - a for a, b in zip(positions, positions[1:])] aim_vects.append(aim_vects[-1]) joints = [create_joint(pos, aim, **kwargs) for pos, aim, in zip(positions, aim_vects)] for parent, child in zip(joints, joints[1:]): cmds.parent(child, parent) cmds.setAttr(joints[-1] + '.jointOrient', 0, 0, 0) # Zero out the last joint in the chain return joints
def new_strand(hair_system=None): if not hair_system: selection = cmds.ls(sl=True, dag=True, leaf=True, type='hairSystem') if selection: hair_system = selection[0] start = om.MVector(0, 0, 0) end = om.MVector(0, 0, 24) start_loc = cmds.spaceLocator(name='strand_start#')[0] end_loc = cmds.spaceLocator(name='strand_end#')[0] cmds.xform(end_loc, ws=True, translation=end) tta = cmds.createNode('transformsToArrays') cmds.connectAttr(start_loc + '.worldMatrix', tta + '.inTransforms[0].inMatrix') cmds.connectAttr(end_loc + '.worldMatrix', tta + '.inTransforms[1].inMatrix') pcc = cmds.createNode('pointCloudToCurve') cmds.connectAttr(tta + '.outPositionPP', pcc + '.inArray') expand_grp = cmds.group([start_loc, end_loc], name='strand_expand_grp#') curve, curve_shape = curve_between(start, end, name='strand_curve#') cmds.connectAttr(pcc + '.outCurve', curve_shape + '.create') root_grp = cmds.group(empty=True, name='strand_grp#') cmds.parent([expand_grp, curve], root_grp) follicle_nodes, out_curve_nodes = add_curve_to_system(curve_shape, hair_system) follicle_shape = follicle_nodes[1] cmds.setAttr(follicle_shape + '.pointLock', 3) cmds.setAttr(follicle_shape + '.sampleDensity', 24)
def createJointFromObj(objs = [], *args): """ creates a joint at obj location/orientation. Can be arg[list] or selection :param objs: a list of objects to operate on :param args: :return: """ if not objs: objs = cmds.ls(sl=True, type="transform") if objs: for obj in objs: pos = cmds.xform(obj, q=True, ws=True, rp=True) rot = cmds.xform(obj, q=True, ws=True, ro=True) jnt = cmds.joint(name="{0}_JNT".format(obj)) grp = cmds.group(jnt, n="{0}_JNT_GRP".format(obj)) if cmds.listRelatives(grp, p=True): cmds.parent(grp, w=True) cmds.xform(grp, ws=True, t=pos) cmds.xform(grp, ws=True, ro=rot) else: cmds.warning("You need to select object(s)")
def createSpaceBuffers(*args): """ selection 1,2 = source parent, source obj selection 3 = target obj create two groups parented - named after source p,o snap them to source obj parentConstrain pGrp to sourceparent, oGrp to sourceobj connectAttrs of oGrp to target obj(make sure values are zeroed) """ sel = cmds.ls(sl=True) src1 = sel[0] # parent of Ctrl (or thing you want to relate it to) src2 = sel[1] # ctrl tgt = sel[2] # joint (should be in a group) tgtGrp = cmds.group(em=True, name="{0}_spaceBuffer".format(src2)) tgtParGrp = cmds.group(em=True, name="{0}_spaceBuffer".format(src1)) cmds.parent(tgtGrp, tgtParGrp) src1PC = cmds.parentConstraint(src1, tgtParGrp) src2PC = cmds.parentConstraint(src2, tgtGrp) if cmds.getAttr("{0}.t".format(tgt))[0]==(0,0,0): cmds.connectAttr("{0}.t".format(src2), "{0}.t".format(tgt)) else: print "{0} had non-zero translate values! Skipping connection.".format(tgt) if cmds.getAttr("{0}.r".format(tgt))[0]==(0,0,0): cmds.connectAttr("{0}.r".format(src2), "{0}.r".format(tgt)) else: print "{0} had non-zero rotate values! Skipping connection.".format(tgt)
def parentChain(*args): #parent chain (select objs, child first. WIll parent in order selected) sel = cmds.ls(sl=True) sizeSel = len(sel) for x in range(0, sizeSel-1): cmds.parent(sel[x], sel[x+1])
def parentCheck(obj): """ checks whether there's a parent and if so returns it (otherwise returns None)""" if obj: plist = cmds.listRelatives(obj, p=True) if plist: return(plist)[0] return(None)
def swapDupe(obj, target, delete = True, name="", *args): """ replaces an target with a duplicate of the obj select the object you want to duplicate, then the target(s), delete bool, name optional [obj] is the object to duplicate [target] is the target to match and delete(?) [delete] is bool to tell whether to delete the target or not [name] is string to rename to """ if not name: name = obj # get pos, rot, scale of target pos = cmds.xform(target, q=True, ws=True, rp=True) rot = cmds.xform(target, q=True, ws=True, ro=True) scl = cmds.getAttr("{0}.scale".format(target)) # duplicate the object and rename to name, if no name just use unique names dupe = cmds.duplicate(obj, name=name, returnRootsOnly=True, renameChildren=True) cmds.xform(dupe, ws=True, t=pos) cmds.xform(dupe, ws=True, ro=rot) cmds.xform(dupe, ws=True, s=scl[0]) parent = cmds.listRelatives(target, parent=True) if parent: cmds.parent(dupe, parent[0]) if delete: cmds.delete(target) return(dupe[0])
def doubleProxyCtrlGrp(ctrl = "", *args): """ creates a pair of groups parent constrained to selected ctrl (and it's group). Basically is proxy to switch spaces (from rig part space to world space) for direct connections. ctrl should be located in place with a group above (group frozen) Args: ctrl (string): the name of the ctrl(transform) to create the proxy for. Assumes a group above (group freeze) Returns: string, string: returns the names of the created ctrl group and the created parent group """ # grab the ctrl (must have group above)? ctrlParent = parentCheck(ctrl) if not ctrlParent: cmds.error("doubleProxyGrp: don't have a parent group on the ctrl!") return # create groups for the proxy ctrlGrp = cmds.group(empty=True, n="{0}_proxyCtrl".format(ctrl)) parGrp = cmds.group(empty=True, n="{0}_proxyGrp".format(ctrlParent)) # snap groups to the parent and child snapTo(ctrlParent, parGrp) snapTo(ctrl, ctrlGrp) cmds.parent(ctrlGrp, parGrp) # constrain groups cmds.parentConstraint(ctrlParent, parGrp, mo=True) cmds.parentConstraint(ctrl, ctrlGrp, mo=True) # return groups return(ctrlGrp, parGrp)
def groupFreeze(obj="", suffix = "GRP", *arg): """ takes an object in worldspace and snaps a group to it, then parents obj to that group i.e. zeros out the obj's translates and rotations Args: obj (string): the object to put under the group (to zero it's transforms) Returns: string: returns the new group """ grp = cmds.group(empty=True, name="{0}_{1}".format(obj, suffix)) snapTo(obj, grp) cmds.parent(obj, grp) return(grp)
def get_soft_selection(): """ should be a softSelection already selected (components). This returns list of cmpts and list of weights :return: list of components, and list of weights """ # Grab the soft selection selection = om.MSelectionList() softSelection = om.MRichSelection() om.MGlobal.getRichSelection(softSelection) softSelection.getSelection(selection) dagPath = om.MDagPath() component = om.MObject() # Filter Defeats the purpose of the else statement iter = om.MItSelectionList(selection, om.MFn.kMeshVertComponent) elements, weights = [], [] while not iter.isDone(): iter.getDagPath(dagPath, component) dagPath.pop() # Grab the parent of the shape node node = dagPath.fullPathName() fnComp = om.MFnSingleIndexedComponent(component) getWeight = lambda i: fnComp.weight(i).influence() if fnComp.hasWeights() else 1.0 for i in range(fnComp.elementCount()): elements.append('%s.vtx[%i]' % (node, fnComp.element(i))) weights.append(getWeight(i)) iter.next() return elements, weights
def createWireDef(*args): #clusterList = [] #rebuiltCrv = "" #get geo and curve geo = cmds.ls(sl=True)[0] crv = cmds.ls(sl=True)[1] rebuiltCrv = rebuildCrv(crv) name = cmds.textFieldGrp(widgets["nameTFG"],q=True, tx=True) defName = "wire_"+ name wireDef = cmds.wire(geo, w = rebuiltCrv, n= defName, gw=True) wireGroup = wireDef[1] + "Group" cmds.setAttr(wireGroup + ".v", 0) clusterList = clstrOnCurve(rebuiltCrv) #print clusterList ctrlGrp = createControls(clusterList) masterGrp = cmds.group(n=name+"_GRP", em=True) cmds.parent(ctrlGrp, masterGrp) cmds.parent(wireGroup, masterGrp) cmds.addAttr(masterGrp, ln="xxWireDeformerCtrlsXX", at="bool", k=True) cmds.setAttr(masterGrp + ".xxWireDeformerCtrlsXX", l=True) cmds.addAttr(masterGrp, ln = 'envelope', at = "float", dv = 1, min=0, max=1, k=True) cmds.addAttr(masterGrp, ln = 'DropoffDistance', at = 'float', dv = 1, min = 0, max = 15, k = True) cmds.addAttr(masterGrp, ln = 'tension', at = 'float', dv = 1, min = -10, max = 10, k = True) cmds.addAttr(masterGrp, ln = 'rot', at = 'float', min = 0, max = 1, k =True) cmds.addAttr(masterGrp, ln = 'scl', at = 'float', dv = 1, min = 0, max = 3, k = True) cmds.connectAttr(masterGrp + ".envelope", wireDef[0] + ".envelope") cmds.connectAttr(masterGrp + ".DropoffDistance", wireDef[0] + ".dropoffDistance[0]") cmds.connectAttr(masterGrp + ".tension", wireDef[0] + ".tension") cmds.connectAttr(masterGrp + ".rot", wireDef[0] + ".rotation") cmds.connectAttr(masterGrp + ".scl", wireDef[0] + ".scale[0]") cmds.select(masterGrp, r = True) incrementName()
def create_object(verts_pos, face_verts): """ Function creates an object with mesh given by vertice and face data. :type face_verts: Python list :type verts_pos: Python list """ shark_mesh = om.MObject() points = om.MFloatPointArray() # An array that is storing positions od vertices. Do not include id of vertices for vert in verts_pos: # add every point to Maya float points array p = om.MFloatPoint(vert[0], vert[2], -vert[1]) points.append(p) face_connects = om.MIntArray() # an array for vertice numbers per face. face_counts = om.MIntArray() # an array for total number of vertices per face for verts in face_verts: # In Maya mesh is created on a base of two arrays: list of vertice numbers and list of numbers of vertices # of faces. Vertice numbers from the first list are not grouped by faces, this is just a one dimmension array. # Based on this list only it would be impossible to recreate mesh, becouse number of vertices in faces may vary # (in this example every face have 3 vertices, but this is not obligatory). # The second array stores the number of vertices of faces. From this list Mata gets a number of vertices of a # face, let's call it N, then assigns next N vertices to this face. The process is repeated for every face. face_connects.append(verts[0]) # Append vertices of face. face_connects.append(verts[1]) face_connects.append(verts[2]) face_counts.append(len(verts)) # append the number of vertices for this face mesh_fs = om.MFnMesh() mesh_fs.create(points, face_counts, face_connects, parent=shark_mesh) mesh_fs.updateSurface() node_name = mesh_fs.name() cmds.polySoftEdge(node_name, a=30, ch=1) # Automatically soften the edges of the mesh # assign new mesh to default shading group cmds.sets(node_name, e=True, fe='initialShadingGroup') return cmds.listRelatives(node_name, fullPath=True, parent=True) # node name stores a name of Shape node. # Most functions need a Transform node. Ths line returns it.
def create_and_animate_trees(): """ Function uses the create_palm() support function to create and animate some palm trees. It was created to show how to create basic geometry objects, use instances and use modificators. """ palm1 = create_palm(diameter=1.3, segs_num=20, leafs_num=9, bending=34, id_num=1, anim_start=11, anim_end=26) palm2 = create_palm(diameter=1.6, segs_num=20, leafs_num=9, bending=34, id_num=2, anim_start=40, anim_end=45) palm3 = create_palm(diameter=1.1, segs_num=18, leafs_num=9, bending=24, id_num=3, anim_start=20, anim_end=35) palm4 = create_palm(diameter=1.1, segs_num=24, leafs_num=9, bending=24, id_num=4, anim_start=25, anim_end=40) cmds.currentTime(55) # The removal of history had strange effect when it was applied before tree animation # Next line is intended to avoid a bug. If the history has to be deleted with a cmds.delete function. If it # would not be modified then the bend modifictor would have to be moved wit an object or it would affect an object # in different ways then desired during a changes in its position. The problem is, that during that an evaluation # of commands may take some time and the removing of history resulted in not deformed mesh or a partialy # deformed mesh. This is why cmds.refresh() ommand was used. cmds.refresh(f=True) cmds.delete(palm1, ch=True) cmds.rotate(0.197, 105, 0.558, palm1, absolute=True) # Rotate the palm cmds.move(-8.5, -4.538, 18.1, palm1, absolute=True) # Position the palm cmds.parent(palm1, 'land', relative=True) # Rename it cmds.delete(palm2, ch=True) cmds.rotate(-16.935, 74.246, -23.907, palm2) cmds.move(29.393, -3.990, 4.526, palm2) cmds.parent(palm2, 'land', relative=True) cmds.delete(palm3, ch=True) cmds.move(24.498, -3.322, 36.057, palm3) cmds.rotate(0.023, 0.248, -1.950, palm3) cmds.parent(palm3, 'land', relative=True) cmds.delete(palm4, ch=True) cmds.move(4.353, -1.083, 22.68, palm4) cmds.rotate(-150, -102.569, 872.616, palm4) cmds.parent(palm4, 'land', relative=True)