def createPad(cls, *args): if args: inputObject = args[0] else: inputObject = pm.selected() if type(inputObject) != list: inputObject = [inputObject] pads = [] for obj in inputObject: pm.select(cl = True) paddingGroup = pm.group(em = True) upperPaddingGroup = pm.group(em = True) pm.parent(paddingGroup, upperPaddingGroup) movePivot = pm.parentConstraint(obj, upperPaddingGroup, mo = False) pm.delete(movePivot) pm.parent(obj, paddingGroup) pm.makeIdentity(apply = True, t = True, r = True, s = True, n = 0) pm.rename(paddingGroup, obj + '_sdkPad') pm.rename(upperPaddingGroup, obj + '_offsetPad') pads.append(upperPaddingGroup) return pads
def _buildDrivers(name, xforms, controls, **kwargs): ctrl_orient = kwargs.get('ctrl_orient', None) # Create IK joints joints = createNodeChain(xforms, node_func=partial( pm.createNode, 'joint'), prefix='ikj_') for joint in joints: pm.makeIdentity(joint, apply=True) # Place control curve controls[0].getParent().setTransformation(xforms[-1].getMatrix(ws=True)) if ctrl_orient: pm.rotate(controls[0].getParent(), ctrl_orient) # Create IK chain ik_handle, _ = pm.ikHandle(n="Ik_{}_handle".format(name), sj=joints[0], ee=joints[-1]) ik_handle.setParent(controls[0]) # Constrain end driver joint pm.orientConstraint(controls[0], joints[-1], mo=True) # Hide intermediate nodes for node in joints + [ik_handle]: node.visibility.set(False) return joints
def orientJoint(joint, aim_loc, aim_axis=(1, 0, 0), up_axis=(0, 1, 0), world_up=(0, 1, 0)): joint = pm.ls(joint)[0] children = joint.listRelatives() if children: for child in children: child.setParent(None) target = pm.createNode('transform') target.setTranslation(aim_loc, ws=True) pm.delete( pm.aimConstraint(target, joint, aimVector=aim_axis, upVector=up_axis, worldUpVector=world_up)) pm.delete(target) if children: for child in children: child.setParent(joint) pm.makeIdentity(joint, apply=True)
def transfer_shape(source, target, flip=True): """it will replace the shape of selected number 2 with the shapes of selected number 1""" target_shape = target.getShape(noIntermediate=True) target_shape_orig = get_orig_shape(target_shape) dup = pymel.duplicate(source, rc=1)[0] tmp = pymel.createNode('transform') pymel.parent(tmp, dup) pymel.xform(tmp, t=(0, 0, 0), ro=(0, 0, 0), scale=(1, 1, 1)) pymel.parent(tmp, w=1) for sh in dup.getShapes(noIntermediate=True): pymel.parent(sh, tmp, r=1, s=1) pymel.delete(dup) temp_grp_negScale = pymel.createNode('transform') pymel.parent(tmp, temp_grp_negScale) if flip: temp_grp_negScale.scaleX.set(-1) pymel.parent(tmp, target) pymel.delete(temp_grp_negScale) pymel.makeIdentity(tmp, t=True) # this brings translate values at 0 before scale freezing pymel.makeIdentity(tmp, apply=True, t=True, r=True, s=True) pymel.parent(tmp, w=1) color_info, vis_master = get_previous_controller_info(target) shapes_has_been_deleted = False for sh in tmp.getShapes(): if target_shape_orig: adapt_to_orig_shape(sh, target.getShape()) else: if not shapes_has_been_deleted: shapesDel = target.getShapes() if shapesDel: pymel.delete(shapesDel) shapes_has_been_deleted = True pymel.parent(sh, target, r=1, s=1) pymel.rename(sh.name(), target.name() + "Shape") if color_info[0]: if color_info[1]: sh.overrideEnabled.set(True) sh.overrideRGBColors.set(1) sh.overrideColorRGB.set(color_info[2]) else: sh.overrideEnabled.set(True) sh.overrideRGBColors.set(0) sh.overrideColor.set(color_info[2]) else: sh.overrideEnabled.set(False) if vis_master: vis_master.connect(sh.visibility) pymel.delete(tmp)
def makePinCtrl(h=0.5, name="PIN_CTRL", axis=(0, 0, 1)): """Creates a simple cone control shape - good for controlling stretchy splines and the like. Args: - h: height of the ctrl. Default=0.5 - name: name of the object. Deault='PIN_CTRL' - axis: the local top-bottom axis of the cone. Default=(0, 0, 1)""" #v = pmc.dt.Vector(axis) #cone = pmc.cone(d=1, sections=4, pivot=(-h/2*axis), # ax=axis, r=h/4, hr=4) pts = ((0, 0, 0), (h / 4, 0, h), (-h / 4, 0, h), (0, h / 4, h), (0, -h / 4, h)) curves = [] for i in range(len(pts)): for n in range(i + 1, len(pts)): ps = (pts[i], pts[n]) c = pmc.curve(d=1, p=ps) curves.append(c) pmc.select(curves) ctrl = mergeShapes() ctrl.rename(name) # edit orientation a = pmc.angleBetween(euler=True, v1=(0, 0, 1), v2=axis) ctrl.rotate.set(a) pmc.makeIdentity(ctrl, apply=True, r=True) return ctrl
def createControlCurve(name=None, shape='FK', size=1.0, color=None): """ Creates a curve using predefined parameters. Parameters ---------- name : str Desired curve name in Maya ctrlType : str Shape type, as defined in rig.ControlShapes (the default is 'FK') size : float Curve radius, in Maya scene units (the default is 1.0) color : tuple Tuple of RGB values in 0.0 to 1.0 range. Set to None to use Maya's default color. """ shape_args = CONTROL_SHAPES.get(shape.lower(), CONTROL_SHAPES['fk']) if name: shape_args.update({'name': name}) if not color: color = CONTROL_COLORS.get(name[-2:].lower(), None) crv = pm.curve(**shape_args) setColor(crv, color) crv.setScale([size, size, size]) pm.makeIdentity(crv, apply=True) return crv
def freeze_transform(transform): """Freeze the default attributes of transform node even if the some of the attributes are locked. After freezing the status reset the transform status @param transform: The transform node that is being evaluated """ # Get the current lock status of the default attributes defaultLockStatus = get_default_lock_status(transform) transform = force_pynode(transform) childrenLockStatus = {} # Check to see if there are any children if transform.getChildren(ad=1, type="transform"): # Iterate through all the children for childTransform in transform.getChildren(ad=1, type="transform"): # Get the lock status of the children and store it in the dictonary childrenLockStatus[childTransform] = get_default_lock_status(childTransform) # Unlock the child transform status unlock_default_attribute(childTransform) # Unlock default status unlock_default_attribute(transform) # Freeze the tranform pm.makeIdentity(transform, n=0, s=1, r=1, t=1, apply=True) # Reset the children lock status for childTransform in childrenLockStatus: set_lock_status(childTransform, childrenLockStatus[childTransform]) set_lock_status(transform, defaultLockStatus)
def locatorGrid(width, height, depth, offset, centered=True): '''Create a grid of locators to test upon Args: width (int): Width of the grid height (int): Height of the grid offset (float): Adds an offset multiplier to the locator positions centered (bool): determines whether it's centered in world space Returns (pm.PyNode): The top group of the locator grid Usage: locatorGrid(5,5,5,2) ''' if not pm.objExists('locatorGrid'): grp=pm.group(em=True,n='locatorGrid') for d in range(0,depth): for w in range(0,width): for h in range(0,height): loc = pm.polyCube(w=.5, h=.5, d=.5, ch=0)[0] pm.move(loc,(w*offset,h*offset,d*offset), rpr=True) loc.setParent(grp) if loc.getShape().type() == "locator": loc.localScale.set(.2,.2,.2) if centered: pm.xform(grp, cp=1) pm.move(grp, (0, 0, 0), rpr=1) pm.makeIdentity(grp, apply=True, r=1,s=1,t=1) return grp
def _create_label(self): labels = pm.textCurves(ch=0, f="Arial", t=self.label, name="TEMP") label = pm.duplicate(labels[0])[0] pm.delete(labels) label.scale.set([self.label_scale, self.label_scale, self.label_scale]) pm.makeIdentity(label, apply=True, t=True) shapes = label.listRelatives(ad=True, s=True) for shape in shapes: shape.rename("%s_%s" % (self.prefix, shape.name())) pm.parent(shapes, label, shape=True, relative=True) label.centerPivots() label.rename("Text_%s" % self.prefix) label.overrideEnabled.set(1) self.control_group.display >> label.overrideDisplayType self.control_group.display >> label.visibility pm.delete(label.listRelatives(ad=True, type="transform")) temp_loc = pm.spaceLocator() temp_loc.tx.set(self.label_offset[0]) temp_loc.ty.set(self.label_offset[1]) pm.delete(pm.pointConstraint(temp_loc, label, maintainOffset=False)) pm.delete(temp_loc) pm.parent(label, self.control_group, absolute=True)
def addCurlJnt(side, finger): # create curl jnt baseJnt = pm.PyNode(side+finger+'_a_jnt') loc = pm.PyNode(baseJnt.replace('_a_jnt', 'Cup_loc')) parJnt = baseJnt.getParent() # orient loc so x is aimed to baseJnt if '_rt' in side: temp_con = pm.aimConstraint(baseJnt, loc, aim=(-1,0,0), u=(0,0,1), wuo=parJnt, wut='objectrotation') else: temp_con = pm.aimConstraint(baseJnt, loc, aim=(1,0,0), u=(0,0,1), wuo=parJnt, wut='objectrotation') pm.delete(temp_con) # create jnt pm.select(cl=True) curlJnt = pm.joint(n=side+finger+'Cup_jnt') curlJnt.radius.set(baseJnt.radius.get()) mat = loc.getMatrix(ws=True) curlJnt.setMatrix(mat, ws=True) parJnt | curlJnt pm.makeIdentity(curlJnt, r=True, a=True) # find offset matrix for baseJnt currMat = baseJnt.getMatrix() offMat = currMat * curlJnt.getMatrix().inverse() txOffset = offMat.translate[0] # change parent for baseJnt curlJnt | baseJnt txMd = baseJnt.tx.inputs()[0] txMd.input2X.set(txOffset) return curlJnt
def bdMirrorRight(self): print "Mirroring left to right" leftGroup = pm.ls("left:" + self.templateType + "*grp")[0] rightGroup = pm.ls("right:" + self.templateType + "*grp")[0] leftGroupPos = leftGroup.getRotatePivot(space="world") leftGroupPos[0] = -1.0 * leftGroupPos[0] rightGroup.setTranslation(leftGroupPos, space="world") leftGrpChildren = leftGroup.listRelatives(f=True, ad=True, type="transform") rightGrpChildren = rightGroup.listRelatives(f=True, ad=True, type="transform") i = 0 for target in leftGrpChildren: targetPos = target.getRotatePivot(space="object") targetPos = [-2.0 * targetPos[0], 0, 0] rightGrpChildren[i].translateBy(targetPos, space="object") pm.makeIdentity(rightGrpChildren[i], apply=True, translate=True, rotate=True, scale=True) i += 1 i = 0 for target in leftGrpChildren: mdNode = pm.createNode("multiplyDivide", name=target + "_X_MD") mdNode.input2X.set(-1) target.translateX.connect(mdNode.input1X) mdNode.outputX.connect(rightGrpChildren[i].translateX) target.translateY.connect(rightGrpChildren[i].translateY) target.translateZ.connect(rightGrpChildren[i].translateZ) target.scaleX.connect(rightGrpChildren[i].scaleX) target.scaleY.connect(rightGrpChildren[i].scaleY) target.scaleZ.connect(rightGrpChildren[i].scaleZ) i += 1
def create_background_sphere(name): '''Create a sphere aligned to aiSkyDomeLight shape''' xform, _ = pmc.polySphere(radius=995) shape = xform.getShape() xform.rename('HDR_Reflector') # align sphere to aiSkyDomeLight xform.rotateY.set(71.5) uv_count = pmc.polyEvaluate(shape, uv=True) pmc.polyFlipUV( '{}.map[0:{}]'.format(str(shape), uv_count), flipType=0, local=True ) pmc.delete(xform, ch=True) pmc.makeIdentity(xform, apply=True) # set defaults shape.doubleSided.set(False) shape.castsShadows.set(False) shape.receiveShadows.set(False) shape.opposite.set(True) shape.aiSelfShadows.set(0) shape.aiOpaque.set(0) shape.aiVisibleInDiffuse.set(0) shape.aiVisibleInGlossy.set(0) return xform, shape
def makeCube(): squareCrv = dtLib.makeSquare() squareCrv2 = dtLib.makeSquare() squareCrv2.setRotation([90, 0,0]) squareCrv2.setTranslation([0,0.5,-0.5]) pm.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1) crvs = squareCrv2.getShapes() for current in crvs: pm.parent(current, squareCrv, relative=True, shape=True) pm.delete(squareCrv2) pm.select(squareCrv) dupCrv = pm.duplicate() dupCrv[0].setRotation([180, 0, 0]) dupCrv[0].setTranslation([0,0,-1]) pm.makeIdentity(apply=True, translate=True, rotate=True, scale=True, normal=1) crvs = dupCrv[0].getShapes() for current in crvs: pm.parent(current, squareCrv, relative=True, shape=True) pm.delete(dupCrv) #中央にピポットを移動 pm.select(squareCrv) pm.xform(cp=True) return pm.selected()
def _build(self, *args): """ Builds the joints on the curve. """ # naming convention asset = self.asset side = self.side part = self.part joints = self.joints suffix = self.suffix if self.gui: asset = self.asset_name.text() side = self.side.currentText() part = self.part_name.text() joints = self.joints_box.value() suffix = self.suffix.currentText() try: curve = pm.ls(sl=True)[0] curve_name = NameUtils.get_unique_name(asset, side, part, "crv") self.curve = pm.rename(curve, curve_name) except IndexError: pm.warning("Please select a curve") return length_of_curve = pm.arclen(self.curve) equal_spacing = length_of_curve / float(joints) # clear the selection pm.select(cl=True) # # create the joints curve_joints = list() for x in xrange(int(joints) + 1): name = NameUtils.get_unique_name(asset, side, part, suffix) joint = pm.joint(n=name) curve_joints.append(joint) joint_position = (x * equal_spacing) pm.move(0, joint_position, 0) # rename last joint last_joint = curve_joints[-1] pm.rename(last_joint, last_joint + "End") root_joint = pm.selected()[0].root() end_joint = pm.ls(sl=True)[0] solver = 'ikSplineSolver' # attach joints to curve ik_name = NameUtils.get_unique_name(asset, side, part, "ikHandle") self.ikHandle = pm.ikHandle(sj=root_joint, ee=end_joint, sol=solver, c=self.curve, pcv=True, roc=True, ccv=False, n=ik_name) joint_chain = pm.ls(root_joint, dag=True) # delete history pm.makeIdentity(root_joint, apply=True) # cleanup self._cleanup()
def build_flexi_jnts(self, follicles): """ Args: None Returns (None) """ follicle_prefix = '%s_flexiPlane_' % self.flexiPlaneNameField.getText() jntGRP_name = self.flexiPlaneNameField.getText() + '_flexiPlane_JNT_GRP' pm.group( em = True, name = jntGRP_name ) for index,follicle in enumerate(follicles): jnt_name = self.format_string.format(PREFIX = self.flexiPlaneNameField.getText(), INDEX = 'flexiPlane_jnt%03d' % (index+1), SUFFIX = 'JNT') jnt_offset_name = jnt_name.replace('_JNT','Offset_GRP') tweek_ctrlCon_name = self.format_string.format(PREFIX = self.flexiPlaneNameField.getText(), INDEX = 'flexiPlane_tweak%03d' % (index+1), SUFFIX = 'CTRLCon_GRP') pm.joint( p = ( follicle.translateX.get(), 0, 0 ), n = jnt_name ) pm.select(jnt_name, r=True) offSetGRP.add_offset_grps() pm.parent( jnt_offset_name, jntGRP_name ) pm.select( clear = True ) tweak_ctrl_con = pm.PyNode(tweek_ctrlCon_name) joint_offset = pm.PyNode(jnt_offset_name) pm.parentConstraint( tweek_ctrlCon_name, jnt_offset_name ) pm.setAttr(jnt_name + '.rotateZ', -90) pm.makeIdentity( jnt_name, apply=True, translate=True, rotate=True )
def FootCrv ( size=1, name='footCrv') : ctrlName = pm.curve (d = 1 , p = ( (0.00443704, -0.677552, 0) ,(0.144546, -0.530692, 0) ,(0.352021, 0.0542797, 0) ,(0.348132, 0.276213, 0) ,(0.448607, 0.414713, 0) ,(0.322616, 0.478526, 0) ,(0.256431, 0.302266, 0) ,(0.180984, 0.356473, 0) ,(0.32057, 0.570811, 0) ,(0.17346, 0.659144, 0) ,(0.0855168, 0.404945, 0) ,(0.0139709, 0.433904, 0) ,(0.106305, 0.743462, 0) ,(-0.107758, 0.761677, 0) ,(-0.0858926, 0.450201, 0) ,(-0.16749, 0.440366, 0) ,(-0.230299, 0.787238, 0) ,(-0.496683, 0.690941, 0) ,(-0.336863, 0.360119, 0) ,(-0.394508, 0.133506, 0) ,(-0.159134, -0.138775, 0) ,(-0.28817, -0.523902, 0) ,(-0.195119, -0.663426, 0) ,(0.00443704, -0.677552, 0) ), k = (0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23) , name = name) ctrlName.scale.set(size,size,size) pm.makeIdentity (ctrlName , apply=True , s=True) return ctrlName
def arrows4(name, radius, normal, color): r = radius points = [(0.25*r, 0*r, 0.75*r), (0*r, 0*r, 1*r), (-.25*r, 0*r, 0.75*r), (0.25*r, 0*r, 0.75*r), (0*r, 0*r, 1*r), (0*r, 0*r, -1*r), (0.25*r, 0*r, -.75*r), (-.25*r, 0*r, -.75*r), (0*r, 0*r, -1*r), (0*r, 0*r, 0*r), (-1*r, 0*r, 0*r), (-.75*r, 0*r, 0.25*r), (-.75*r, 0*r, -.25*r), (-1*r, 0*r, 0*r), (1*r, 0*r, 0*r), (0.75*r, 0*r, -.25*r), (0.75*r, 0*r, 0.25*r), (1*r, 0*r, 0)] a = pm.curve(point=points, name=name, degree=1, worldSpace=True) u.aimNormal(a, normal=normal) pm.makeIdentity(a,apply=True) a.getShape().overrideEnabled.set(True) a.getShape().overrideColor.set(color) return a
def makeDuplicateJointTree(topJoint, toReplace=None, replaceWith=None, freeze=True): """ make a duplicate of the hierarhcy starting at topJoint, delete any non-joint nodes, and ensure joints are properly connected. Return a dictionary of {parentJoint:[branchJnt1, branchJnt2...]} for all branches in the tree. The topmost node branch's key is None """ topJoint = pm.PyNode(topJoint) result = [] dups = pm.duplicate(topJoint, rc=True) #parent to world if dups[0].getParent(): dups[0].setParent(world=True) for node in dups[0].listRelatives(ad=True): if not isinstance(node, pm.nodetypes.Joint): pm.delete(node) else: if toReplace and replaceWith: replaceInName(node, toReplace, replaceWith) if freeze: pm.makeIdentity(node, apply=True, r=True, s=True, t=True, n=True) result.append(node) #ensure joints are connected fixInverseScale(result) #the top node isn't in the result list yet result.append(dups[0]) #usually it's in reverse order result.reverse() return result
def run(self): selected = pm.ls(sl=1) if not selected: self.fail_check(u"先手动选中模型大组") return # get all xforms top_node = pm.ls(sl=1)[0] hierarchy_xfroms = top_node.getChildren(allDescendents=True, type="transform") hierarchy_xfroms.append(top_node) # freeze directly locked_attr_list = [] for xform in hierarchy_xfroms: pm.move(0, 0, 0, [xform + '.scalePivot', xform + '.rotatePivot']) # check locked attrs base_attributes = [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz' ] for attr in base_attributes: if xform.getAttr(attr, lock=True): locked_attr_name = "%s.%s" % (xform, attr) locked_attr_node = pm.PyNode(locked_attr_name) locked_attr_node.unlock() locked_attr_list.append(locked_attr_node) # freeze them try: pm.makeIdentity(xform, apply=True, translate=True, rotate=True, scale=True, n=0, pn=1) except RuntimeError, e: self.error_list.append(xform.longName())
def main(): sel = pm.ls(os=True, fl=True) if len(sel) != 3: pm.warning("Select 3 vertices in order of origin, z, and x") return shape = sel[0].node() transformNode = pm.listRelatives(shape, parent=True)[0] piv = pm.xform(transformNode, q=True, ws=True, rp=True) p0 = sel[0].getPosition() p1 = sel[1].getPosition() p2 = sel[2].getPosition() Z = p1 - p0 X = p2 - p0 Y = Z ^ X Z.normalize() X.normalize() Y.normalize() P = pm.datatypes.Point(piv[0], piv[1], piv[2]) M = pm.datatypes.Matrix( X.x, X.y, X.z, 0, Y.x, Y.y, Y.z, 0, Z.x, Z.y, Z.z, 0, P.x, P.y, P.z, 1) pm.xform(transformNode, matrix=M.inverse()) pm.select(transformNode, r=True) pm.makeIdentity(apply=True, t=True, r=True, s=False, n=False) pm.xform(transformNode, ws=True, piv=(0, 0, 0)) pm.xform(transformNode, matrix=M)
def rig_makeCtrlLabel(label): '''Creates a control that is displayed in customized choice of letters Args: label (string): the name of the desired control/visual display text Returns (pm.nt.Transform): returns the display control object Example Usage: rig_makeCtrlLabel("display") ''' if not pm.objExists(label + "_CTRL"): txt_crv=pm.PyNode( pm.textCurves(ch=0,t=label,f="Courier")[0] ) curves=[] i=1 for crvShp in pm.ls(txt_crv.getChildren(ad=True), et="nurbsCurve"): crvTrm = crvShp.getParent() crvShp.getParent().setParent(w=True) pm.makeIdentity(crvShp.getParent(),apply=True,s=1,r=1,t=1,n=0) crvTrm.rename("display_%02d_CRV" % i) curves.append(crvTrm) i+=1 displayCtrl=rig_combineCurves(curves,label+'_CTRL') pm.delete(txt_crv) displayCtrl.centerPivots() pm.move(displayCtrl, (0,0,0), rpr=True) pm.makeIdentity(displayCtrl,apply=True,s=1,r=1,t=1,n=0) displayGrp=pm.group(em=1,n=(label + "Offset_GRP")) displayCtrl.setParent(displayGrp) for displayCtrlShape in displayCtrl.listRelatives(shapes=True, fullPath=True): pm.setAttr(displayCtrlShape + ".overrideEnabled", 1) pm.setAttr(displayCtrlShape + ".overrideColor",17) rig_ctrlLock([displayCtrl], ["tx","ty","tz","rx","ry","rz","sx","sy","sz","v"], setKeyable=False, lock=True) return displayCtrl else: pm.error("That control already exists smarty pants!\n")
def addDigitCmd( prefix='index_', suffix=None, side=LEFT_SIDE, joints=4, parent=None ): if parent is not None: _parent = ParentDesc( parent ) joint_list = [] length = 0.074 for i in range( 1,joints+1 ): name = i == joints and 'END' or str(i) try: _joint = JointDesc( name, (length, 0, 0), (0, 0, -10), False, _parent ) except NameError: _joint = JointDesc( name, (0, 0, 0), (0, 0, 0), False ) _joint.suffix = suffix or ('_l','_r')[side] _joint.prefix = prefix joint_list.append( _joint.build() ) _parent = _joint length = length/1.618 pm.select( joint_list[0], r=1 ) pm.makeIdentity( joint_list[0], apply=True, r=1 ) return joint_list
def add_ref_joint(self, loc, vis_attr=None, width=.5): """Add a visual reference joint to a locator or root of the guide Args: loc (dagNode): locator or guide root vis_attr (attr list, optional): attribute to activate or deactivate the visual ref. Should be a list [attr1, attr2] width (float, optional): icon width """ add_ref_joint = icon.sphere(loc, self.getName("joint"), width=width, color=[0, 1, 0], m=loc.getMatrix(worldSpace=True)) pm.parent(add_ref_joint, world=True) pm.makeIdentity(add_ref_joint, apply=True, t=False, r=False, s=True, n=0) for shp in add_ref_joint.getShapes(): if vis_attr: node.createMulNode(vis_attr[0], vis_attr[1], shp.attr("visibility")) shp.isHistoricallyInteresting.set(False) loc.addChild(shp, add=True, shape=True) pm.delete(add_ref_joint)
def circle(self, joint): a = 0.25 b = 0.3432 p0 = Point(a + 0.005,0 , -a - 0.005) p1 = Point(b + 0.05, 0, 0) p2 = Point(a + 0.005, 0, a + 0.005) p3 = Point(0, 0, b) p4 = Point(-a - 0.005, 0, a + 0.005) p5 = Point(-b - 0.05, 0, 0) p6 = Point(-a - 0.005, 0, -a - 0.005) p7 = Point(0, 0, - b) points = [p0, p1, p2, p3, p4, p5, p6, p7, p0, p1, p2] pts = [] for point in points: pts.append(point.getPoint()) pm.curve(per = True, d = 3, p = pts, k = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) pm.parent("%s" % str(pm.ls(sl = True)[0]), "%s" % str(joint), relative = True) pm.parent("%s" % str(pm.ls(sl = True)[0]), world = True) pm.makeIdentity(r = True) curve = "%s" % str(pm.ls(sl = True)[0]) g = 0 while g < 8: pm.moveVertexAlongDirection(curve + ".cv[" + str(g) + "]", d = [0,1,0], m = -0.08) g += 1 group = pm.group(curve) pm.orientConstraint(curve, joint, mo = True) handle = joint + "IK" pm.pointConstraint(curve, handle, mo = True)
def SphereCrv(size=0.5, name='sphereCrv'): ctrlName = pm.curve( d=1, p=((0, 1, 0), (-0.382683, 0.92388, 0), (-0.707107, 0.707107, 0), (-0.92388, 0.382683, 0), (-1, 0, 0), (-0.92388, -0.382683, 0), (-0.707107, -0.707107, 0), (-0.382683, -0.92388, 0), (0, -1, 0), (0.382683, -0.92388, 0), (0.707107, -0.707107, 0), (0.92388, -0.382683, 0), (1, 0, 0), (0.92388, 0.382683, 0), (0.707107, 0.707107, 0), (0.382683, 0.92388, 0), (0, 1, 0), (0, 0.92388, 0.382683), (0, 0.707107, 0.707107), (0, 0.382683, 0.92388), (0, 0, 1), (0, -0.382683, 0.92388), (0, -0.707107, 0.707107), (0, -0.92388, 0.382683), (0, -1, 0), (0, -0.92388, -0.382683), (0, -0.707107, -0.707107), (0, -0.382683, -0.92388), (0, 0, -1), (0, 0.382683, -0.92388), (0, 0.707107, -0.707107), (0, 0.92388, -0.382683), (0, 1, 0), (0.382683, 0.92388, 0), (0.707107, 0.707107, 0), (0.92388, 0.382683, 0), (1, 0, 0), (0.92388, 0, 0.382683), (0.707107, 0, 0.707107), (0.382683, 0, 0.92388), (0, 0, 1), (-0.382683, 0, 0.92388), (-0.707107, 0, 0.707107), (-0.92388, 0, 0.382683), (-1, 0, 0), (-0.92388, 0, -0.382683), (-0.707107, 0, -0.707107), (-0.382683, 0, -0.92388), (0, 0, -1), (0.382683, 0, -0.92388), (0.707107, 0, -0.707107), (0.92388, 0, -0.382683), (1, 0, 0)), k=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52), name=name) ctrlName.scale.set(size, size, size) pm.makeIdentity(ctrlName, apply=True, s=True) return ctrlName
def freeze_transform(transform): """Freeze the default attributes of transform node even if the some of the attributes are locked. After freezing the status reset the transform status @param transform: The transform node that is being evaluated """ # Get the current lock status of the default attributes defaultLockStatus = get_default_lock_status(transform) transform = force_pynode(transform) childrenLockStatus = {} # Check to see if there are any children if transform.getChildren(ad=1, type="transform"): # Iterate through all the children for childTransform in transform.getChildren(ad=1, type="transform"): # Get the lock status of the children and store it in the dictonary childrenLockStatus[childTransform] = get_default_lock_status( childTransform) # Unlock the child transform status unlock_default_attribute(childTransform) # Unlock default status unlock_default_attribute(transform) # Freeze the tranform pm.makeIdentity(transform, n=0, s=1, r=1, t=1, apply=True) # Reset the children lock status for childTransform in childrenLockStatus: set_lock_status(childTransform, childrenLockStatus[childTransform]) set_lock_status(transform, defaultLockStatus)
def generateCon(conName=None, scale=1.0, color=0): """ generate a nurbs curve controller """ if not conName: _logger.warn("No Controller Name provided. example: conName='diamond' ") return conToCreate = consDict.get(conName, None) if not conToCreate: _logger.error("Control does not exist in the pickle file") return tempDictStr = json.dumps(conToCreate, indent=4) _logger.debug("conToCreate: {0}".format(tempDictStr)) periodic = True if conToCreate.get('form') == 'periodic' else False degree = conToCreate.get('degree') cvs = conToCreate.get('cvs') knots = conToCreate.get('knots') # create the curve crv = pm.curve(d=degree, p=cvs, k=knots, per=periodic) crv.scale.set((scale, scale, scale)) pm.makeIdentity(crv, apply=True, t=False, r=0, s=1, n=0) crv.getShape().overrideEnabled.set(1) crv.getShape().overrideColor.set(color) return crv
def orientXform(xform, aim_loc, aim_axis=(1, 0, 0), up_axis=(0, 1, 0), world_up=(0, 1, 0), freeze=False): xform = pm.ls(xform)[0] children = xform.listRelatives() if children: for child in children: child.setParent(None) target = pm.createNode('transform') target.setTranslation(aim_loc, ws=True) pm.delete( pm.aimConstraint(target, xform, aimVector=aim_axis, upVector=up_axis, worldUpVector=world_up)) pm.delete(target) if freeze: pm.makeIdentity(xform, apply=True) if children: for child in children: child.setParent(xform)
def set_target_ctrl(flange_loc): """ """ pm.xform('target_CTRL', t=flange_loc, ws=True) # Freeze translate attribute pm.makeIdentity('target_CTRL', apply=True, translate=True)
def saveTestJoint(parentJoint, systemType): """ @param parentJoint: the parent joint @param systemType: The test joint associated with the class """ # joint -e -oj yzx -secondaryAxisOrient zup -ch -zso; joint_info = {} if libFile.exists(TEST_JOINTS_INFO): joint_info = libFile.load_json(TEST_JOINTS_INFO) currentJointData = [] parentJoint = pm.PyNode(parentJoint) childJoints = parentJoint.listRelatives(ad=1, type="joint") childJoints.reverse() childJoints.insert(0, parentJoint) for joint in childJoints: if not joint.getChildren(): joint.jointOrient.set(0, 0, 0) parent = joint.getParent() pm.makeIdentity(joint, normal=False, scale=False, rotate=True, translate=False, apply=True, preserveNormals=True) joint.setParent(w=1) info = {"name": joint.shortName(), "orient": list(joint.jointOrient.get()), "position": list(joint.getTranslation(space="world"))} currentJointData.append(info) if parent: joint.setParent(parent) joint_info[systemType] = currentJointData libFile.write_json(TEST_JOINTS_INFO, joint_info)
def crv_combine(toggles=False, rename=None): '''Combines a curve and gives you the ability to have combinations of shapes Args: toggles (boolean): allows you to have attributes to toggle the shapes nodes on and off rename (boolean): determines whether you rename the resulting curve+shapes or not Returns: (pm.nt.Transform): transform of the resulting curve Usage: crv_combine(toggles=True) crv_combine(toggles=True, rename='global') crv_combine(rename='halo') ''' sel=pm.ls(sl=True) master=sel[0] for obj in sel[1:]: obj.setParent(None) pm.makeIdentity(obj, apply=True, t=True,r=True,s=True,n=False) obj.getShape().setParent(master,s=True,r=True) if toggles: crv_shapeToggle(master, map(str,sel)) pm.delete(sel[1:]) if rename is not None: print 'Renaming resulting object!' master.rename(rename+'_CTRL') for shape,i in zip(master.getShapes(),range(len(master.getShapes()))): shape.rename(rename+'%02d'%i+'Shape') return master
def unity_pivot(): sl = pm.ls(sl=True, transforms=True) for obj in sl: # rotate pivot seems to be the same as translate pivot p = pm.xform(obj, q=True, objectSpace=True, rotatePivot=True) # get original translation tx = obj.tx.get() ty = obj.ty.get() tz = obj.tz.get() # negative local pivot ox = float(p[0]) * -1 oy = float(p[1]) * -1 oz = float(p[2]) * -1 # set object negative local pivot obj.tx.set(ox) obj.ty.set(oy) obj.tz.set(oz) # freeze translate pm.makeIdentity(obj, apply=True, t=True, n=True, pn=True) # set object back to original position obj.tx.set(float(tx) + float(p[0])) obj.ty.set(float(ty) + float(p[1])) obj.tz.set(float(tz) + float(p[2]))
def box(name, radius, normal, color): r = radius points = [(-1*r, -1*r,-1*r), (-1*r, -1*r, 1*r), ( 1*r, -1*r, 1*r), ( 1*r, -1*r,-1*r), (-1*r, -1*r,-1*r), (-1*r, 1*r,-1*r), (-1*r, 1*r, 1*r), (-1*r, -1*r, 1*r), (-1*r, 1*r, 1*r), ( 1*r, 1*r, 1*r), ( 1*r, -1*r, 1*r), ( 1*r, 1*r, 1*r), ( 1*r, 1*r,-1*r), ( 1*r, -1*r,-1*r), ( 1*r, 1*r,-1*r), (-1*r, 1*r,-1*r)] b = pm.curve( point=points, name=name, degree=1, worldSpace=True) u.aimNormal(b, normal=normal) pm.makeIdentity(b,apply=True) b.getShape().overrideEnabled.set(True) b.getShape().overrideColor.set(color) return b
def mirrorXfoFromTo(xfo_from, xfo_to): # create temp nodes grp1 = pm.group(em=True) grp2 = pm.group(grp1) grp3 = pm.group(em=True) xfo_from | grp2 pm.makeIdentity() grp3 | grp2 grp3.sx.set(-1) grp1.sx.set(-1) ''' # get original parent of xfo_rt so we can set it back later parent_rt = xfo_to.getParent() # snap xfo_rt to grp1's xfo grp1 | xfo_to pm.makeIdentity(xfo_to) if parent_rt: parent_rt | xfo_to else: xfo_to.setParent(None) ''' worldXfo = grp1.getMatrix(worldSpace=True) xfo_to.setMatrix(worldXfo, worldSpace=True) # delete temp nodes pm.delete(grp1, grp2, grp3) pm.select(xfo_to)
def makeIdentity_safe(obj, translate=False, rotate=False, scale=False, apply=False, **kwargs): """ Extended pymel.makeIdentity method that won't crash for idiotic reasons. """ from . import libAttr affected_attrs = [] # Ensure the shape don't have any extra transformation. if apply: if translate: libAttr.unlock_translation(obj) affected_attrs.extend([ obj.translate, obj.translateX, obj.translateY, obj.translateZ ]) if rotate: libAttr.unlock_rotation(obj) affected_attrs.extend([ obj.rotate, obj.rotateX, obj.rotateY, obj.rotateZ ]) if scale: libAttr.unlock_scale(obj) affected_attrs.extend([ obj.scale, obj.scaleX, obj.scaleY, obj.scaleZ ]) # Make identify will faile if attributes are connected... with libAttr.context_disconnected_attrs(affected_attrs, hold_inputs=True, hold_outputs=False): pymel.makeIdentity(obj, apply=apply, translate=translate, rotate=rotate, scale=scale, **kwargs)
def mirror(self, axis='X'): """ Mirror a transform according to given axis. """ for subject in self.transform: # get the name if (pm.PyNode(subject).name()).startswith('r__'): _name = '{}'.format(str(subject).replace('r__', 'l__')) elif (pm.PyNode(subject).name()).startswith('l__'): _name = '{}'.format( str(pm.PyNode(subject)).replace('l__', 'r__')) else: _name = None # temp unlock all user defined attributes locks_attr_list = adbAttr.NodeAttr(self.transform).getLock_attr() # Unlock all att_to_unlock = [ 'tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v' ] for att in att_to_unlock: pm.PyNode(subject).setAttr(att, lock=False, keyable=True) # mirror function dup = pm.duplicate(subject, rr=True, name=_name)[0] offset_grp = pm.group(name='dup_grp', em=True) pm.makeIdentity(dup, n=0, s=1, r=1, t=1, apply=True, pn=1) pm.parent(dup, offset_grp) if axis == 'x': pm.PyNode(offset_grp).scaleX.set(-1) elif axis == 'y': pm.PyNode(offset_grp).scaleY.set(-1) elif axis == 'z': pm.PyNode(offset_grp).scaleZ.set(-1) elif axis == 'X': pm.PyNode(offset_grp).scaleX.set(-1) elif axis == 'Y': pm.PyNode(offset_grp).scaleY.set(-1) elif axis == 'Z': pm.PyNode(offset_grp).scaleZ.set(-1) pm.parent(dup, world=True) pm.makeIdentity(dup, n=0, s=1, r=1, t=1, apply=True, pn=1) pm.delete(offset_grp) # relock attribute for attrs in locks_attr_list: if attrs: for att in attrs: pm.PyNode(subject).setAttr(att, lock=True, channelBox=True, keyable=False) pm.PyNode(dup).setAttr(att, lock=True, channelBox=True, keyable=False)
def createJointOffset(Offset): if Offset == "": Offset = "Offset" selectJoints = pm.selected() for joint in selectJoints: offsetObjName = "" if prefix.getSelect() == 1: #置き換え offsetObjName = re.sub(r"^[a-zA-Z]*?_",Offset+"_",str(joint)) elif prefix.getSelect() == 2: #追加 offsetObjName = str(Offset) + "_" + str(joint) offsetObj = pm.group(em = True,name = offsetObjName) jointName = re.sub(r"^[a-zA-Z]*?_","Rig_",offsetObjName) pm.circle( name=jointName ) pm.select(jointName,r=30) # 回転の軸がなんでこれで(Z)いいのかわからないので確認する。 pm.rotate(0,0,90,r = True) pm.scale(2,2,2) pm.makeIdentity(apply=True,t=1,r=1,s=1,n=0,pn=1) pm.parent(jointName,offsetObj) #AにBをコンストレイント! pm.parentConstraint(joint,offsetObj, weight=1) #必要のないコンストレイントノードの削除 delNode = offsetObj.listRelatives(c=True,ad=True,type='constraint') pm.delete(delNode)
def transfer_shape(source, target, snap_to_target=True, fix_name=False): """ Reparent a shape node from one parent to another @param source: The source dag which contains the shape @param target: The source dag which will have the new shape the shape @param snap_to_target: Should be we reparent with world space or object space @param fix_name: Should we match the name of the shape to the new target @return: """ source = force_pynode(source) target = force_pynode(target) if snap_to_target: snap(source, target) pm.makeIdentity(source, apply=1) if source.getShape().type() != "locator": try: pm.cluster(source) pm.delete(source, ch=1) except RuntimeError: logger.warning("Cannot cluster {}".format(source)) oldShape = source.getShape() pm.parent(oldShape, target, shape=1, relative=1) if fix_name: fix_shape_name(target) return oldShape
def orientCtrl_constrain(control, joint): control_name = renameCtrl(joint, control) control_group = pm.group(control, n=control_name + '_grp') control_group.rotateZ.set(90) pm.makeIdentity(control_group, apply=True) parentConstraint = pm.parentConstraint(joint, control_group) pm.delete(parentConstraint)
def makeBulgeCtrl(handle, ctrCtrl, n, names, rotOrder): """Make inner control for softmod. Diamond for the softMod handle itself""" ctrlGrpRotMat = mu.rotMat(ctrCtrl.controlGroup.get().matrix) hCtrl = jc.makeCtrlShape(n.format(type=names["control"]), rotOrder, shape="diamond") for sh in hCtrl.getShapes(): ctrCtrl.create.inputs()[0].radius >> sh.create.inputs()[0].radius pmc.scale(sh.cv, .8, .8, .8) hCtrl.setParent(ctrCtrl) pmc.makeIdentity(hCtrl) # handle xforms must be ctrl in ctrCtrlGrp AND ctrCtrl space but without # any of their actual xforms parGrp = ctrCtrl.getParent() handleXform = mu.xformFromSpaces([ ctrlGrpRotMat.inverse(), ctrCtrl.inverseMatrix, parGrp.inverseMatrix, hCtrl.m, parGrp.matrix, ctrCtrl.matrix, ctrlGrpRotMat ], n.format(type="xforms"), rotOrder) handleXform.outputTranslate >> handle.t handleXform.outputRotate >> handle.r handleXform.outputScale >> handle.s return hCtrl
def mirrorShapes(self, obj): """ mirror Shapes from a _L or _R geometry to the other :obj object to apply mirrored shapes """ obj = pym.PyNode(obj) self.__reset__() mirrTM = pym.createNode("transform", n="mirror") lDups = [] for key, attr in self.__attrs__.iteritems(): attr.set(1.0) dup = pym.duplicate(self.defNode, n=mirrorLR(key)) lDups.append(dup) pym.parent(dup, mirrTM) attr.set(0.0) mirrTM.scaleX.set(-1.0) for dup in lDups: pym.parent(dup, w=1, a=1) pym.makeIdentity(dup, a=1, pn=1) pym.delete(mirrTM) shapes = lDups + [obj] bsN = pym.blendShape(*shapes)[0] bsN.rename(obj.name() + "_BS") pym.delete(*lDups) self.__restore__()
def main(): sel = pm.ls(os=True, fl=True) if len(sel) != 3: pm.warning("Select 3 vertices in order of origin, z, and x") return shape = sel[0].node() transformNode = pm.listRelatives(shape, parent=True)[0] piv = pm.xform(transformNode, q=True, ws=True, rp=True) p0 = sel[0].getPosition() p1 = sel[1].getPosition() p2 = sel[2].getPosition() Z = p1 - p0 X = p2 - p0 Y = Z ^ X Z.normalize() X.normalize() Y.normalize() P = pm.datatypes.Point(piv[0], piv[1], piv[2]) M = pm.datatypes.Matrix(X.x, X.y, X.z, 0, Y.x, Y.y, Y.z, 0, Z.x, Z.y, Z.z, 0, P.x, P.y, P.z, 1) pm.xform(transformNode, matrix=M.inverse()) pm.select(transformNode, r=True) pm.makeIdentity(apply=True, t=True, r=True, s=False, n=False) pm.xform(transformNode, ws=True, piv=(0, 0, 0)) pm.xform(transformNode, matrix=M)
def replace_controller_shape(cls): selection = pm.ls(sl=1) if len(selection) < 2: return objects = selection[0] joints = selection[1] shape = pm.listRelatives(objects, s=True) joint_shape = pm.listRelatives(joints, s=True) parents = pm.listRelatives(objects, p=True) if len(parents): temp_list = pm.parent(objects, w=True) objects = temp_list temp_list = pm.parent(objects, joints) objects = temp_list[0] pm.makeIdentity(objects, apply=True, t=1, r=1, s=1, n=0) temp_list = pm.parent(objects, w=True) objects = temp_list[0] if len(joint_shape): pm.delete(joint_shape) for i in range(0, len(shape)): name = "%sShape%f" % (joints, (i + 1)) shape[i] = pm.rename(shape[i], name) temp_list = pm.parent(shape[i], joints, r=True, s=True) shape[i] = temp_list[0] pm.delete(objects) pm.select(joints)
def create_nurbs(self): self.nurbs = pm.nurbsPlane(name='geo_' + self.ribbon_name, pivot=[0, 0, 0], axis=[0, 1, 0], width=1, lengthRatio=self.ribbon_segment, degree=3, ch=False)[0] self.nurbs.setRotation([0, 90, 0], space='world') pm.makeIdentity(self.nurbs, a=True, rotate=True) # rebuild nurbs to reduce CVs pm.rebuildSurface(self.nurbs, replaceOriginal=True, rebuildType=0, endKnots=1, keepRange=0, keepControlPoints=0, keepCorners=0, spansU=1, degreeU=1, spansV=self.ribbon_segment, degreeV=3, ch=False)
def add_controller_shape(cls): selection = pm.ls(sl=1) if len(selection) < 2: return objects = [] for i in range(0, (len(selection) - 1)): objects.append(selection[i]) joints = selection[len(selection) - 1] for i in range(0, len(objects)): parents = pm.listRelatives(objects[i], p=True) if len(parents) > 0: temp_list = pm.parent(objects[i], w=1) objects[i] = temp_list[0] temp_list = pm.parent(objects[i], joints) objects[i] = temp_list[0] pm.makeIdentity(objects[i], apply=True, t=1, r=1, s=1, n=0) temp_list = pm.parent(objects[i], w=True) objects[i] = temp_list[0] shapes = pm.listRelatives(objects, s=True, pa=True) for i in range(0, len(shapes)): temp_list = pm.parent(shapes[i], joints, r=True, s=True) shapes[i] = temp_list[0] joint_shapes = pm.listRelatives(joints, s=True, pa=True) for i in range(0, len(joint_shapes)): name = "%sShape%f" % (joints, (i + 1)) temp = ''.join(name.split('|', 1)) pm.rename(joint_shapes[i], temp) pm.delete(objects) pm.select(joints)
def makePVconstraint(): """function to create a pole vector constraint for an IK chain. Select ikHandle and control object to be used""" sel = pmc.ls(sl=True) if len(sel) is not 2: pmc.error("Select ikHandle and control object, in that order.") h = sel[0] ctrl = sel[1] midJoint = h.getJointList()[-1] orient = abs(midJoint.jointOrient.get().normal()) v = [] for d in orient: if d > .99: v.append(0) else: v.append(1) v = pmc.datatypes.Vector(v) if orient != midJoint.jointOrient.get().normal(): v = -v g = pmc.group(em=True, n=ctrl.name() + "_GRP") g.setParent(midJoint) ctrl.setParent(g) pmc.makeIdentity(g) pmc.makeIdentity(ctrl) g.translate.set(v) g.setParent(None)
def ScaleMinus(): v = .9 b = pm.ls(sl=True)[0] a = pm.listRelatives(b, s=1) TmpTrans = [] newShp = [] for i in a: tmtr = pm.createNode('transform', n=('temp' + i)) pm.parent(i, tmtr, r=True, s=True) #nshape = pm.duplicate(i,n=('temp'+i)) pm.xform(tmtr, s=(v, v, v)) pm.makeIdentity(tmtr, apply=True, t=1, r=1, s=1) newShp.append(i) TmpTrans.append(tmtr) pm.select(cl=True) for i in newShp: pm.select(i) pm.rename(i, b + '_Shape_00') pm.select(b, add=True) pm.parent(r=True, s=True) pm.delete(TmpTrans) pm.select(b)
def AlignBindNode(self, **kws): ''' Overwrite the default behaviour: Align the newly made BindNode as required for this bind ''' parentNode = self.SourceNode.listRelatives(p=True)[0] if parentNode: #Parent the BindNode to the Source Driver Node pm.parent(self.BindNode['Root'], self.SourceNode.listRelatives(p=True)[0]) else: pm.parent(self.BindNode['Root'], self.SourceNode) self.BindNode['Main'].rotateOrder.set(self.SourceNode.rotateOrder.get()) self.BindNode['Root'].rotateOrder.set(self.DestinationNode.rotateOrder.get()) #Positional Alignment if self.Settings.AlignToControlTrans: pm.delete(pm.pointConstraint(self.SourceNode, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) pm.delete(pm.pointConstraint(self.DestinationNode, self.BindNode['Root'])) if self.Settings.AlignToSourceTrans: pm.delete(pm.pointConstraint(self.SourceNode, self.BindNode['Root'])) pm.makeIdentity(self.BindNode['Root'], apply=True, t=1, r=0, s=0) #Rotation Alignment if parentNode: pm.orientConstraint(self.SourceNode, self.BindNode['Root']) if self.Settings.AlignToControlRots: pm.delete(pm.orientConstraint(self.DestinationNode, self.BindNode['Main'])) if self.Settings.AlignToSourceRots: pm.delete(pm.orientConstraint(self.SourceNode, self.BindNode['Main']))
def create_curveSphere(name, radius): circGrp = pm.group(n=name, em=True) circ1 = pm.circle(nr=[1, 0, 0], ch=True)[0] circ2 = pm.circle(nr=[1, 0, 0], ch=True)[0] circ3 = pm.circle(nr=[1, 0, 0], ch=True)[0] circs = [circ1, circ2, circ3] circGrp.overrideEnabled.set(1) circGrp.overrideColorRGB.set(1, 1, 0) circGrp.overrideRGBColors.set(1) pm.xform(circGrp, s=[radius, radius, radius]) pm.xform(circ2, ro=[0, 90, 0]) pm.xform(circ3, ro=[0, 0, 90]) pm.makeIdentity([circ1, circ2, circ3], a=True, t=True, r=True, s=True, n=False) circ1_shape = pm.listRelatives(circ1, s=True)[0] circ2_shape = pm.listRelatives(circ2, s=True)[0] circ3_shape = pm.listRelatives(circ3, s=True)[0] pm.parent([circ1_shape, circ2_shape, circ3_shape], circGrp, r=True, s=True) pm.delete([circ1, circ2, circ3]) return circGrp
def offsetCreator(list, name='offset'): returnList = [] for object in list: # get the objectsParent objectParent = object.getParent() # create a empty transform node and parent it to the object to position and orient offset = pm.createNode('transform', n=name + '_' + object) pm.parentConstraint(object, offset) pm.delete(pm.listRelatives(offset, type='parentConstraint')) pm.makeIdentity(offset, apply=True, t=True, r=True, s=True) pm.delete(offset, ch=True) # if the object has a parent, parent the offset under the object parents, and the parent the object under the offset if objectParent: pm.parent(offset, objectParent) pm.makeIdentity(offset, apply=True, t=True, r=True, s=True) pm.parent(object, offset) # if the object doesnt have a parent it means that it is already in worldspace, in which case, just parent the object to the offset elif objectParent is None: pm.parent(object, offset) returnList.append(offset) return returnList
def createShapeFromPoints(points, knots = None, degree = 1, radius = None, **kwargs): """ Creates a new shape from a list of points. :param list points: list of tuple of float :param list knots: list of int :param uint degree: :param int radius: :returns: :py:class:`pm.nt.Transform` """ curveArgs = {} curveArgs['point'] = points curveArgs['degree'] = degree if knots: curveArgs['knot'] = knots curve = pm.modeling.curve(**curveArgs) if radius: curve.setScale(radius, radius, radius) pm.makeIdentity(curve, apply = True) return curve
def HandCrv( size=1, name='handCrv') : ctrlName = pm.curve (d = 1 , p = ( (-0.100562 , 1.31677 , 0 ), ( 0.122399 , 1.31664 , 0 ), ( 0.299532 , 1.446367 , 0 ), ( 0.319319 , 1.568869 , 0 ), ( 0.417828 , 1.688667 , 0 ), ( 0.594046 , 1.669517 , 0 ), ( 0.550214 , 1.893314 , 0 ), ( 0.383986 , 1.878861 , 0 ), ( 0.246061 , 1.70714 , 0 ), ( 0.207006 , 1.724846 , 0 ), ( 0.215157 , 1.842864 , 0 ), ( 0.380575 , 2.182962 , 0 ), ( 0.191945 , 2.281101 , 0 ), ( 0.0856495 , 1.873534 , 0 ), ( 0.00886914 , 1.874275 , 0 ), ( 0.030434 , 2.364695 , 0 ), ( -0.209958 , 2.343528 , 0 ), ( -0.0939414 , 1.867589 , 0 ), ( -0.170241 , 1.819424 , 0 ), ( -0.349394 , 2.178222 , 0 ), ( -0.525161 , 2.058232 , 0 ), ( -0.293742 , 1.758312 , 0 ), ( -0.22419 , 1.425819 , 0 ), ( -0.100562 , 1.31677 , 0 ) ), k = (0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 , 12 ,13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 , 21 , 22 , 23), name = name ) ctrlName.scale.set(size,size,size) pm.makeIdentity (ctrlName , apply=True , s=True) return ctrlName
def gimbal(**kwargs): final = pm.nt.Transform(name = 'Gimbal') circle1 = pm.modeling.circle( constructionHistory = False, normal = kwargs['normal'] if 'normal' in kwargs else [0, 1, 0], radius = kwargs['radius'] if 'radius' in kwargs else 1 )[0] circle2 = pm.duplicate(circle1, returnRootsOnly = True)[0] circle2.rotateBy((90, 0, 0)) circle3 = pm.duplicate(circle1, returnRootsOnly = True)[0] circle3.rotateBy((0, 0, 90)) for circle in [circle1, circle2, circle3]: pm.makeIdentity(circle, apply = True) shape = circle.getShape() pm.parent(shape, final, shape = True, relative = True) shape.rename('{0}Circle1Shape'.format(final.nodeName())) pm.delete(circle) return final
def alignToVector(xform, aim_x=(1, 0, 0), aim_y=(0, 1, 0), freeze=False): """ Rotates transform so that axes align with specified world-space directions. Parameters ---------- xform : pm.nt.Transform Transform to rotate. aim_x : tuple, optional World-space direction for the x-axis of `xform`. aim_y : tuple, optional World-space direction for the y-axis of `xform`. If not orthogonal to `aim_x`, the y-axis will attempt to be as close as possible to this vector. freeze : bool, optional Freeze transformation if True. Default is False. """ xform = pm.ls(xform)[0] xf_node = pm.createNode('transform') pm.move(xf_node, xform.getTranslation(ws=True)) aim_node = pm.createNode('transform') pm.move(aim_node, xform.getTranslation(space='world') + aim_x) pm.delete(pm.aimConstraint(aim_node, xf_node, worldUpVector=aim_y), aim_node) xform.setRotation(xf_node.getRotation(ws=True), ws=True) pm.delete(xf_node) if freeze: pm.makeIdentity(xform, apply=True)
def mirror_pairs(pairs): # Modify control shapes for source, target in pairs: # Copy shapes source_copy = pc.duplicate(source)[0] mgear.core.attribute.setKeyableAttributes( source_copy, ["tx", "ty", "tz", "ro", "rx", "ry", "rz", "sx", "sy", "sz"]) # Delete children except shapes for child in source_copy.getChildren(): if child.nodeType() != "nurbsCurve": pc.delete(child) # Mirror pc.select(clear=True) grp = pc.group(world=True) pc.parent(source_copy, grp) grp.scaleX.set(-1) # Reparent, freeze transforms and match color pc.parent(source_copy, target) pc.makeIdentity(source_copy, apply=True, t=1, r=1, s=1, n=0) pc.parent(source_copy, target.getParent()) targetColor = mgear.core.curve.get_color(target) if targetColor: mgear.core.curve.set_color(source_copy, targetColor) # Replace shape mgear.rigbits.replaceShape(source_copy, [target]) # Clean up pc.delete(grp) pc.delete(source_copy)
def curve2Joints(cv, jntSize=10): '''create joints along a curve on every control point ''' cvDup = pm.PyNode(mc.duplicate(cv)[0]) #clean up the cvDup and setup the curve ready pm.delete(cvDup, ch=True) pm.makeIdentity(cvDup, apply=True, t=1, r=1, s=1, n=0) cvShape = cvDup.getShape() #get the position of all the CVs cvPosList = cvShape.getCVs() #get the position of one CV by index cv1 = cvShape.getCV(0) #get the number of CVs numCV = cvShape.numCVs() pm.select(d=True) jntList = [] for pos in cvPosList: newJnt = pm.joint(p=pos, radius=jntSize) jntList.append(str(newJnt)) for jnt in jntList: pm.joint(jnt, sao='yup', zso=1, e=1, oj='xyz') pm.delete(cvDup) return jntList
def mirror_curve(selection=pm.selected(), mirror_side='left'): """this will mirror the curves on the axis given""" _flipX_matrix = pm.datatypes.Matrix[[-1.0, -0.0, -0.0, -0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] _flipY_matrix = pm.datatypes.Matrix[[1.0, 0.0, 0.0, 0.0], [0.0, -1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] _flipZ_matrix = pm.datatypes.Matrix[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, -1.0, 0.0], [0.0, 0.0, 0.0, 1.0]] for ev in selection: if not (isinstance(ev, pm.nodetypes.Transform) and 1 == len(ev.getShapes())): pass else: new_curve = pm.createNode("nurbsCurve", n=ev.name() + "_mirrored") ev.getShape().worldSpace[0].connect(new_curve.create) pm.delete(new_curve, ch=True) source_matrix = ev.getMatrix(worldSpace=True) new_curve.getParent().setMatrix(source_matrix * _flipX_matrix, worldSpace=True) pm.makeIdentity(new_curve, apply=True, rotate=True)
def createSpineShapes(): spineCurves = ["hipShape", "splitShape", "chestShape"] if pm.objExists("spineShapes"): spineGroup = pm.ls("spineShapes") else: spineGroup = pm.group(em=True, name="spineShapes") if pm.objExists("miscGroup_bnd"): spineGroup.setParent("miscGroup_bnd") yTrans = 0 for spine in spineCurves: if not pm.objExists(spine): crv = pm.curve(name=spine, degree=1, p=[(10, 1, 10), (-10, 1, 10), (-10, 1, -10), (10, 1, -10), (10, 1, 10), (10, -1, 10), (-10, -1, 10), (-10, 1, 10), (-10, -1, 10), (-10, -1, -10), (-10, 1, -10), (-10, -1, -10), (10, -1, -10), (10, 1, -10), (10, -1, -10), (10, -1, 10)]) pm.xform(crv, translation=(0, yTrans, 0), scale=(1, 2, 1)) crv.makeIdentity(apply=True) pm.makeIdentity(spine, apply=True) yTrans += 10 crv.setOverrideColor(crv, 17) crv.setParent(spineGroup) else: pm.warning("%s already exists" % spine) pm.select(clear=True) for spine in spineCurves: if pm.objExists(spine): pm.select(spine, add=True)
def add_text_shape(ctrl, text): text_curve = pm.PyNode( pm.textCurves(ch=False, font="Arial Black", text=text, name='text_curve')[0] ) text_curve_length = text_curve.boundingBox()[1][0] #max X text_curve_height = text_curve.boundingBox()[1][1] #max Y shapes = pm.listRelatives(text_curve, ad=True, type="shape") pm.xform(text_curve, piv=[0,text_curve_height,0], ws=True) pm.move(text_curve, 0, -text_curve_height , 0) scale = 1 / text_curve_length pm.scale(text_curve, scale, scale, scale) pm.makeIdentity(text_curve, apply=True, t=True, r=True, s=True) display_attr = ("%s_text_display"%text) if not ctrl.hasAttr(display_attr): ctrl.addAttr(display_attr, at='bool', k=True, dv=1) for s in shapes: pm.parent(s, ctrl, s=True, r=True) s.rename('%sText'%text) pm.connectAttr("%s.%s" %(ctrl.name(), display_attr), s.visibility) pm.delete(text_curve)