我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用maya.cmds.connectAttr()。
def transfer_outgoing_connections(src, dst): """Connect outgoing connections from `src` to `dst` Connections that cannot be made are ignored. Arguments: src (str): Absolute path to source node dst (str): Absolute path to destination node """ for destination in cmds.listConnections(src, source=False, plugs=True) or []: for source in cmds.listConnections(destination, destination=False, plugs=True) or []: try: cmds.connectAttr(source.replace(src, dst), destination, force=True) except RuntimeError: continue
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 combine_curves(curve_shapes): pnt_attr_nodes = [] for node in curve_shapes: pa = cmds.createNode('pointAttributeToArray') cmds.connectAttr(node + '.worldSpace', pa + '.inGeometry') cmds.setAttr(pa + '.pointPosition', 1) cmds.setAttr(pa + '.pointTangent', 1) pnt_attr_nodes.append(pa) positions = cmds.createNode('combineArrays') tangents = cmds.createNode('combineArrays') for i, pa in enumerate(pnt_attr_nodes): cmds.connectAttr(pa + '.outPositionPP', (positions + '.inArrays[{}]').format(i)) cmds.connectAttr(pa + '.outTangentPP', (tangents + '.inArrays[{}]').format(i)) return positions, tangents
def create_hair_system(nucleus=None): '''Create a hair system, add it to the specified nucleus or active nucleus''' if not nucleus: nucleus = get_nucleus() hair_system = cmds.createNode('hairSystem') cmds.connectAttr('time1.outTime', hair_system + '.currentTime') index = cmds.getAttr(nucleus + '.inputActive', size=True) input_active = '{}.inputActive[{}]'.format(nucleus, index) input_start = '{}.inputActiveStart[{}]'.format(nucleus, index) output_object = '{}.outputObjects[{}]'.format(nucleus, index) cmds.setAttr(hair_system + '.active', 1) cmds.connectAttr(hair_system + '.currentState', input_active) cmds.connectAttr(hair_system + '.startState', input_start) cmds.connectAttr(output_object, hair_system + '.nextState') cmds.connectAttr(nucleus + '.startFrame', hair_system + '.startFrame') return hair_system
def 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 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 softWave(sftmod, arrow, ctrl, *args): # add values to positions in graph positions = [0.0, 0.3, 0.6, 0.9, 0.95] values = [1.0, -0.3, 0.1, -0.05, 0.01] for i in range(len(positions)): cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_Position".format(sftmod, i), positions[i]) cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_FloatValue".format(sftmod, i), values[i]) cmds.setAttr("{0}.falloffCurve[{1}].falloffCurve_Interp".format(sftmod, i), 2) cmds.addAttr(arrow, ln="WaveAttrs", at="enum", k=True) cmds.setAttr("{0}.WaveAttrs".format(arrow), l=True) # expose these on the control for j in range(5): cmds.addAttr(arrow, ln="position{0}".format(j), at="float", min=0.0, max=1.0, dv=positions[j], k=True) cmds.connectAttr("{0}.position{1}".format(arrow, j), "{0}.falloffCurve[{1}].falloffCurve_Position".format(sftmod, j)) for j in range(5): cmds.addAttr(arrow, ln="value{0}".format(j), at="float", min=-1.0, max=1.0, dv=values[j], k=True) cmds.connectAttr("{0}.value{1}".format(arrow, j), "{0}.falloffCurve[{1}].falloffCurve_FloatValue".format(sftmod, j)) cmds.setAttr("{0}.position{1}".format(arrow, j), l=True) cmds.setAttr("{0}.value{1}".format(arrow, j), l=True)
def positionsAlongCurve(crv="", numPts = 3, *args): """ returns list of numPts evenly distributed world positions along given nurbs crv """ if not crv: return if isType(crv, "nurbsCurve"): posList = [] shp = cmds.listRelatives(crv, s=True)[0] poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo") cmds.connectAttr("{}.local".format(shp), "{}.inputCurve".format(poc)) cmds.setAttr("{}.turnOnPercentage".format(poc), 1) lineLen = cmds.arclen(crv, ch=False) dist = float(numPts)/lineLen for x in range(0, numPts+1): perc = 1.0/numPts cmds.setAttr("{}.parameter".format(poc),x*perc) print x*perc pos = cmds.getAttr("{}.position".format(poc))[0] posList.append(pos) cmds.delete(poc) return(posList)
def connect_transforms(source="", target = "", t=True, r=True, s=True, *args): """ simple direct connection between transform attrs Args: source (string): object connections come FROM target (string): object connections go to t (bool): do translates? r (bool): do rotations? s (bool): do scales? Return: None """ if source and target: if t: cmds.connectAttr("{0}.t".format(source), "{0}.t".format(target)) if r: cmds.connectAttr("{0}.r".format(source), "{0}.r".format(target)) if s: cmds.connectAttr("{0}.s".format(source), "{0}.s".format(target))
def createJointsAlongCurve(crv="", numJnts=3, *args): jnts = [] crvShp = cmds.listRelatives(crv, s=True)[0] poc = cmds.shadingNode("pointOnCurveInfo", asUtility=True, name="tmpPOCInfo") cmds.connectAttr("{}.local".format(crvShp), "{}.inputCurve".format(poc)) cmds.setAttr("{}.turnOnPercentage".format(poc), 1) lineLen = cmds.arclen(crv) dist = float(numJnts)/lineLen for x in range(0, numJnts+1): perc = 1.0/numJnts cmds.setAttr("{}.parameter".format(poc),x*perc) print x*perc pos = cmds.getAttr("{}.position".format(poc))[0] jnt = cmds.joint(p=pos) jnts.append(jnt) # add one joint at the end to orient return(jnts)
def connect_param(src, tgt, attrType, prm, force=False, *args): """ connects the indiv chnls based on the checkbox sorting in connect_attrs args: src (string): source object tgt (string): target object attrType (string): attr short name (t, r, s) prm (string): specific channel name (x, y, z) force (bool): value for force flag. Defaults to False return: None """ try: cmds.connectAttr("{0}.{1}{2}".format(src, attrType, prm), "{0}.{1}{2}".format(tgt, attrType, prm), force=force) except: cmds.warning( "there was an issue connecting to {0}{1} of {2}. Make sure the channels are free!".format(attrType, prm, tgt))
def connectShapeVis(*args): """Connects the attr from the assoc. text field to the shape Visibility of selected objects""" sel = cmds.ls(sl=True, type="transform") driver = cmds.textFieldButtonGrp(widgets["toShapeVis"], q=True, tx=True) if sel: if driver: for obj in sel: shapes = cmds.listRelatives(obj, s=True) for shape in shapes: try: cmds.connectAttr(driver, "%s.v" % shape, f=True) cmds.warning("Connected %s to %s" % (driver, shape)) except: cmds.warning("Couldn't connect %s to %s. Sorry! Check the Script Editor." % (driver, shape)) else: cmds.warning("You need to select an object to connect the shape.vis!")
def doit(cage_tgt=None): if not cage_tgt: cage_tgt = cmds.ls(sl=True, o=True) cage = cage_tgt[0] tgt = cage_tgt[1:] cmds.loadPlugin('greenCageDeformer.py', qt=True) deformer = cmds.deformer(tgt, type='greenCageDeformer')[0] freezer = cmds.createNode('transformGeometry') cmds.connectAttr(cage + '.o', freezer + '.ig') cmds.connectAttr(cage + '.wm', freezer + '.txf') cmds.connectAttr(freezer + '.og', deformer + '.bc') cmds.disconnectAttr(freezer + '.og', deformer + '.bc') cmds.delete(freezer) cmds.connectAttr(cage + '.w', deformer + '.ic') cmds.dgeval(cmds.listConnections(deformer + '.og', s=False, d=True, sh=True, p=True)) #doit([cmds.polyCube(w=2.5, d=2.5, h=2.5)[0], cmds.polySphere()[0]])
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 combine(nodes): """Produce a new mesh with the contents of `nodes` Arguments: nodes (list): Path to shapes """ unite = cmds.createNode("polyUnite", n=nodes[0] + "_polyUnite") count = 0 for node in nodes: # Are we dealing with transforms, or shapes directly? shapes = cmds.listRelatives(node, shapes=True) or [node] for shape in shapes: try: cmds.connectAttr(shape + ".outMesh", unite + ".inputPoly[%s]" % count, force=True) cmds.connectAttr(shape + ".worldMatrix", unite + ".inputMat[%s]" % count, force=True) count += 1 except Exception: cmds.warning("'%s' is not a polygonal mesh" % shape) if count: output = cmds.createNode("mesh", n=nodes[0] + "_combinedShape") cmds.connectAttr(unite + ".output", output + ".inMesh", force=True) return output else: cmds.delete(unite) return None
def connect_matching_attributes(source, target): """Connect matching attributes from source to target Arguments: source (str): Absolute path to node from which to connect target (str): Target node Example: >>> # Select two matching nodes >>> source = cmds.createNode("transform", name="source") >>> target = cmds.createNode("transform", name="target") >>> cmds.select([source, target], replace=True) >>> source, target = cmds.ls(selection=True) >>> connect_matching_attributes(source, target) """ dsts = cmds.listAttr(target, keyable=True) for src in cmds.listAttr(source, keyable=True): if src not in dsts: continue try: src = "." + src cmds.connectAttr(source + src, target + src, force=True) except RuntimeError as e: cmds.warning("Could not connect %s: %s" % (src, e))
def create_ncloth(input_mesh): """Replace Create nCloth menu item This performs the identical option of nCloth -> Create nCloth with the following changes. 1. Input mesh not made intermediate 2. Current mesh and shape named "currentMesh" Arguments: input_mesh (str): Path to shape """ assert cmds.nodeType(input_mesh) == "mesh", ( "%s was not of type mesh" % input_mesh) nucleus = cmds.createNode("nucleus", name="nucleus1") ncloth = cmds.createNode("nCloth", name="nClothShape1") current_mesh = cmds.createNode("mesh", name="currentMesh") cmds.connectAttr(input_mesh + ".worldMesh[0]", ncloth + ".inputMesh") cmds.connectAttr(ncloth + ".outputMesh", current_mesh + ".inMesh") cmds.connectAttr("time1.outTime", nucleus + ".currentTime") cmds.connectAttr("time1.outTime", ncloth + ".currentTime") cmds.connectAttr(ncloth + ".currentState", nucleus + ".inputActive[0]") cmds.connectAttr(ncloth + ".startState", nucleus + ".inputActiveStart[0]") cmds.connectAttr(nucleus + ".outputObjects[0]", ncloth + ".nextState") cmds.connectAttr(nucleus + ".startFrame", ncloth + ".startFrame") # Assign default shader cmds.sets(current_mesh, addElement="initialShadingGroup") return current_mesh
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 get_knots(curve): """Gets the list of knots of a curve so it can be recreated. :param curve: Curve to query. :return: A list of knot values that can be passed into the curve creation command. """ curve = shortcuts.get_shape(curve) info = cmds.createNode('curveInfo') cmds.connectAttr('{0}.worldSpace'.format(curve), '{0}.inputCurve'.format(info)) knots = cmds.getAttr('{0}.knots[*]'.format(info)) cmds.delete(info) return knots
def create_transform_stack(node, count=2): """Creates a transform stack above the given node. Any previous transform stack will be deleted. :param node: Node to parent into a transform stack. :param count: Number of transforms to add in the stack. :return: A list of the transform nodes created starting from top to bottom. """ previous_parent = cmds.listRelatives(node, parent=True, path=True) if previous_parent: 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: cmds.parent(node, parent) parent = parent[0] else: cmds.parent(node, world=True) cmds.delete(previous_parent) previous_parent = parent nulls = [] for i in reversed(range(count)): name = '_'.join(node.split('_')[:-1]) name = '{0}_{1}nul'.format(name, i+1) null = cmds.createNode('transform', name=name) nulls.append(null) cmds.addAttr(null, ln=STACK_ATTRIBUTE, at='message') cmds.connectAttr('{0}.message'.format(node), '{0}.{1}'.format(null, STACK_ATTRIBUTE)) cmds.delete(cmds.parentConstraint(node, null)) if previous_parent: cmds.parent(null, previous_parent) previous_parent = null cmds.parent(node, previous_parent) return nulls
def BT_ConnectOutputs(index = 0, node = None, transform = None): if not transform: return False cmds.connectAttr(node +'.output[' +str(index) +'].outputT', transform +'.translate') cmds.connectAttr(node +'.output[' +str(index) +'].outputR', transform +'.rotate') cmds.connectAttr(node +'.output[' +str(index) +'].outputS', transform +'.scale') return True
def BT_DisconnectSetup(set = None): if not set: return False if not BT_IsSetupConnected(set = set): cmds.warning('Setup already disconnected!') return False btNode = cmds.getAttr(set +'.Blend_Node') if not btNode or not cmds.objExists(btNode): return False numOutputs = cmds.getAttr(btNode +'.output', size = True) print numOutputs tempMult = None for i in range(0, numOutputs): conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputT', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputT', conns[0] +'.translate') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputT', tempMult +'.input1') conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputR', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputR', conns[0] +'.rotate') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputR', tempMult +'.input1') conns = cmds.listConnections(btNode +'.output[' +str(i) +'].outputS', s = False, d = True) if conns: tempMult = cmds.createNode('multiplyDivide') cmds.disconnectAttr(btNode +'.output[' +str(i) +'].outputS', conns[0] +'.scale') cmds.connectAttr(btNode +'.output[' +str(i) +'].outputS', tempMult +'.input1') cmds.select(cl = True) return True
def conform_curve(source, destination): point_on_curve = cmds.createNode('nearestPointOnCurve') cmds.connectAttr(destination + '.worldSpace', point_on_curve + '.inputCurve') for i, point in enumerate(cmds.getAttr(source + '.cv[*]')): cmds.setAttr(point_on_curve + '.inPosition', point[0], point[1], point[2]) result_point = cmds.getAttr(point_on_curve + '.result.position')[0] cmds.setAttr('{}.cv[{}]'.format(source, i), result_point[0], result_point[1], result_point[2]) cmds.delete(point_on_curve)
def multi_curve_field(curve_shapes): positions, tangents = combine_curves(curve_shapes) field = cmds.createNode('pointCloudToField') cmds.connectAttr(positions + '.outArray', field + '.inPositionPP') cmds.connectAttr(tangents + '.outArray', field + '.inDirectionPP')
def inColor(self, texture_attr): cmds.connectAttr(texture_attr, self.attr('inColor'))
def connect(self, attr, nodes=None): nodes = nodes or cmds.ls(sl=True) if len(nodes) > len(self.get_uvs()): raise Exception('More nodes than uv samples') for i, node in enumerate(nodes): color_attr = self.attr('outColor', i) node_attr = node + '.' + attr cmds.connectAttr(color_attr, node_attr, force=True)
def get_nucleus(): selection = cmds.ls(sl=True, dag=True, leaf=True, type='nucleus') if selection: return selection[0] nucleus = cmds.ls(type='nucleus') if nucleus: return nucleus[0] nucleus = cmds.createNode('nucleus') cmds.connectAttr('time1.outTime', nucleus + '.currentTime') return nucleus
def add_follicle(follicle_shape, hair_system): hair_index = cmds.getAttr(hair_system + '.inputHair', size=True) input_hair = '{}.inputHair[{}]'.format(hair_system, hair_index) output_hair = '{}.outputHair[{}]'.format(hair_system, hair_index) cmds.connectAttr(follicle_shape + '.outHair', input_hair) cmds.connectAttr(output_hair, follicle_shape + '.currentPosition')
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 createMessage(host="none", attr="none", target="none", *args): """creates a message attr on object with target as value. Args are: 'host'-some object to hold the message attr, 'attr'-the name of the message attribute to create, and 'target'-the host to be the value of the message attr""" cmds.addAttr(host, at='message', ln=attr) cmds.connectAttr("%s.message"%target, "%s.%s"%(host, attr)) return("%s.%s"%(host, attr))
def createAdd(name, input1, input2): """creates an addDoubleLinear node with name, object.attr, object.attr as args""" adl = cmds.shadingNode("addDoubleLinear", asUtility=True, name=name) cmds.connectAttr(input1, "%s.input1"%adl) cmds.connectAttr(input2, "%s.input2"%adl) return(adl)
def blendRotation(blend="none", sourceA="none", sourceB="none", target="none", sourceValue="none"): #add input and *args? """name is first arg, then three objects. Blends rotation from first two selected into third selected. SourceValue (last input) is for the driving obj.attr. First source is active at '1', second at '2'""" if blend == "none": blend = "blendColors" if sourceA == "none": sel = getSelection() if len(sel) != 3: cmds.error("Error: blendRotation, select three transforms") #inert some kind of break here sourceA = sel[0] sourceB = sel[1] target = sel[2] blend = cmds.shadingNode("blendColors", asUtility=True, name=blend) sourceAOut = sourceA + ".rotate" sourceBOut = sourceB + ".rotate" targetIn = target + ".rotate" blend1 = blend + ".color1" blend2 = blend + ".color2" blendOut = blend + ".output" cmds.connectAttr(sourceAOut, blend1) cmds.connectAttr(sourceBOut, blend2) cmds.connectAttr(blendOut, targetIn) if not sourceValue == "none": cmds.connectAttr(sourceValue, "%s.blender"%blend) return(blend)
def blendTranslate(blend="none", sourceA="none", sourceB="none", target="none", sourceValue="none"): """name is first arg, then three objects. Blends translation from first two selected into third selected. SourceValue (last input) is for the driving obj.attr. First source is active at '1', second at '2'""" #add input and *args if blend == "none": blend = "blendColors" if sourceA == "none": sel = getSelection() if len(sel) != 3: cmds.error("Error: blendRotation, select three transforms") #inert some kind of break here sourceA = sel[0] sourceB = sel[1] target = sel[2] blend = cmds.shadingNode("blendColors", asUtility=True, name=blend) sourceAOut = sourceA + ".translate" sourceBOut = sourceB + ".translate" targetIn = target + ".translate" blend1 = blend + ".color1" blend2 = blend + ".color2" blendOut = blend + ".output" cmds.connectAttr(sourceAOut, blend1) cmds.connectAttr(sourceBOut, blend2) cmds.connectAttr(blendOut, targetIn) if not sourceValue == "none": cmds.connectAttr(sourceValue, "%s.blender"%blend) return(blend)
def measureDistance(mName="none", *args): """first the name of the measure node, then the 2 objects ORRRR select the two objects and run (will give name 'distanceBetween'""" objs = [] if mName == "none": mName = "distanceBetween" objs = getTwoSelection() else: for each in args: objs.append(each) #add check for 2 selectiont if len(objs) != 2: cmds.error("you must enter either a measure name and 2 objects OR no arguments and manually select 2 objs") dist = cmds.shadingNode("distanceBetween", asUtility=True, name=mName) objA = objs[0] objB = objs[1] objAMatrix = objA + ".worldMatrix" objBMatrix = objB + ".worldMatrix" objAPoint = objA + ".rotatePivot" objBPoint = objB + ".rotatePivot" distPoint1 = dist + ".point1" distPoint2 = dist + ".point2" distMatrix1 = dist + ".inMatrix1" distMatrix2 = dist + ".inMatrix2" cmds.connectAttr(objAPoint, distPoint1) cmds.connectAttr(objBPoint, distPoint2) cmds.connectAttr(objAMatrix, distMatrix1) cmds.connectAttr(objBMatrix, distMatrix2) cmds.select(clear=True) return(dist)
def scaleStretchIK(limbName="none", ikTop="none", ikMid="none", ikLow="none", jntMeasure="none", IKMeasure="none", IKCtrl="none", axis="none", *args): """creates a stretch setup for 3 joint IK chain. Inputs (strings) are the limbName, 3 ik joints (top to bottom), the measure input for the whole chain (add up from measure joints), the measure for the ikCtrl, the ik handle or ctrl (which must have 'scaleMin', 'upScale' and 'lowScale' attrs, the axis letter. Returns . . . """ ratioMult = cmds.shadingNode("multiplyDivide", asUtility=True, n="%s_stretchRatioMult"%limbName) cmds.setAttr(ratioMult + ".operation", 2) cmds.connectAttr(jntMeasure, "%s.input2X"%ratioMult) cmds.connectAttr(IKMeasure, "%s.input1X"%ratioMult) #could put this default stuff (next two paragraphs) after the conditional and use another conditional so that minScale is bundled up in "autostretch" #create default setting of 1 when autostretch is off defaultMult = cmds.shadingNode("multiplyDivide", asUtility=True, n="%s_stretchDefaultMult"%limbName) cmds.setAttr("%s.input1X"%defaultMult, 1) #create blend node to blend ratio mult and default values, based on blender attr of ikctrl.autoStretch defaultBlend = cmds.shadingNode("blendColors", asUtility=True, n="%s_stretchBlend"%limbName) cmds.connectAttr("%s.outputX"%defaultMult, "%s.color2R"%defaultBlend) cmds.connectAttr("%s.outputX"%ratioMult, "%s.color1R"%defaultBlend) cmds.connectAttr("%s.autoStretch"%IKCtrl, "%s.blender"%defaultBlend) #blend goes into condition node - firstTerm, secondTerm=ikctrl scaleMin value, operation=2(greaterthan), colorIfTrue is blend, colorIfFalse is scaleMin attr conditional = cmds.shadingNode("condition", asUtility=True, n="%s_upStretchCondition"%limbName) cmds.setAttr("%s.operation"%conditional, 2) cmds.connectAttr("%s.outputR"%defaultBlend, "%s.firstTerm"%conditional) cmds.connectAttr("%s.scaleMin"%IKCtrl, "%s.secondTerm"%conditional) cmds.connectAttr("%s.outputR"%defaultBlend, "%s.colorIfTrueR"%conditional) cmds.connectAttr("%s.scaleMin"%IKCtrl, "%s.colorIfFalseR"%conditional) #factor in the upScale/lowScale attrs upScaleMult = cmds.shadingNode('multiplyDivide', asUtility=True, n="%s_upScaleMult"%limbName) cmds.connectAttr("%s.outColorR"%conditional, "%s.input1X"%upScaleMult) cmds.connectAttr("%s.upScale"%IKCtrl, "%s.input2X"%upScaleMult) loScaleMult = cmds.shadingNode('multiplyDivide', asUtility=True, n="%s_loScaleMult"%limbName) cmds.connectAttr("%s.outColorR"%conditional, "%s.input1X"%loScaleMult) cmds.connectAttr("%s.lowScale"%IKCtrl, "%s.input2X"%loScaleMult) #hook up the scales of the joints cmds.connectAttr("%s.outputX"%upScaleMult, "%s.s%s"%(ikTop, axis)) cmds.connectAttr("%s.outputX"%loScaleMult, "%s.s%s"%(ikMid, axis)) return(ratioMult, defaultMult, defaultBlend, conditional, upScaleMult, loScaleMult)
def zbw_mmChangeConnectAttr(base, attr, obj, *args): #get that from the text field newAttr = cmds.textFieldGrp("zbw_mmChangeAttrTFG", q=True, tx=True) #delete old attr cmds.deleteAttr(attr) #create new attr cmds.addAttr(base, at="message", ln=newAttr) #create connection to obj in new attr cmds.connectAttr((obj+".message"), (base+"."+newAttr), f=True) #when you delete, then run the whole proc again afterwards (to clean up the nums) cmds.deleteUI('zbw_mmChangeAttrUI', window=True) cmds.windowPref('zbw_mmChangeAttrUI', remove=True) cmds.deleteUI("mmRCListLayout") zbw_mmListCurrentMessages("mmListMessages")
def zbw_mmChangeConnectObj(base, attr, obj, *args): #get that from the text field newObj = cmds.textFieldGrp("zbw_mmChangeObjTFBG", q=True, tx=True) #create connection to obj in new attr cmds.connectAttr((newObj+".message"), attr, f=True) #delete this window, delete mmRCListLayout and call the list again cmds.deleteUI('zbw_mmChangeObjUI', window=True) cmds.windowPref('zbw_mmChangeObjUI', remove=True) cmds.deleteUI("mmRCListLayout") zbw_mmListCurrentMessages("mmListMessages")
def connectTexture(*args): sel = cmds.ls(sl=True) ctrl = sel[0] # repeatMult = cmds.connectionInfo("{}.repeatMult".format(ctrl), sourceFromDestination=True).partition(".")[0] # parameterMult = cmds.connectionInfo("{}.parameterMult".format(ctrl), sourceFromDestination=True).partition(".")[0] # print repeatMult, parameterMult if len(sel) > 1: p2ds = sel[1:] for node in p2ds: cmds.connectAttr("{}.rptHolder".format(ctrl), "{}.repeatV".format(node))
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 transfer_attrs(*args): """ transfers attrs and connections from second obj to first object selected """ tgt, src = get_source_and_targets() if not tgt or len(src) > 1: cmds.warning("Select only one target then one source obj to transfer the attributes and connections!") return () attrs = cmds.channelBox('mainChannelBox', q=True, selectedMainAttributes=True) if not attrs: cmds.warning("You have to select at least one attr on last object selected to transfer!") return () for attr in attrs: attrType, hasMin, attrMin, hasMax, attrMax, value, inConnection, outConnection, locked = get_channel_attributes( src[0], attr) if not attrType == "enum": # create attribute if not cmds.attributeQuery(attr, node=tgt, exists=True): if hasMin and not hasMax: cmds.addAttr(tgt, ln=attr, at=attrType, min=attrMin[0], dv=value, k=True) elif hasMax and not hasMin: cmds.addAttr(tgt, ln=attr, at=attrType, max=attrMax[0], dv=value, k=True) elif hasMin and hasMax: cmds.addAttr(tgt, ln=attr, at=attrType, min=attrMin[0], max=attrMax[0], dv=value, k=True) else: cmds.addAttr(tgt, ln=attr, at=attrType, dv=value, k=True) else: cmds.warning("The attribute: {0} already exists. Skipping creation!".format(attr)) # lock if locked: cmds.setAttr("{0}.{1}".format(tgt, attr), l=True) else: cmds.warning("I don't do enums at the moment!") # connect tgt attr to connection, forced if inConnection: cmds.connectAttr(inConnection[0], "{0}.{1}".format(tgt, attr)) if outConnection: for conn in outConnection: cmds.connectAttr("{0}.{1}".format(tgt, attr), conn, force=True)
def connect_transform(driver, driven, source=WorldSpace, compensate=False): """Connect translation, rotation and scale via decomposeMatrix Arguments: driver (str): Absolute path to driver driven (str): Absolute path to driven source (str, optional): Either WorldSpace or LocalSpace, default WorldSpace compensate (bool, optional): Whether or not to take into account the current transform, default False. Returns: output (list): Newly created nodes """ outputattr = ".matrix" if source == LocalSpace else ".worldMatrix[0]" assert cmds.objExists(driver), "%s not found" % driver assert cmds.objExists(driven), "%s not found" % driven decompose = driver + "_decompose" output = [decompose] if not cmds.objExists(decompose): decompose = cmds.createNode("decomposeMatrix", name=decompose) if compensate: multMatrix = cmds.createNode( "multMatrix", name=driver + "_multMatrix") # Compensate for drivens parentMatrix. cmds.connectAttr(driver + outputattr, multMatrix + ".matrixIn[0]") cmds.connectAttr(driven + ".parentInverseMatrix", multMatrix + ".matrixIn[1]") cmds.connectAttr(multMatrix + ".matrixSum", decompose + ".inputMatrix") output.append(multMatrix) else: cmds.connectAttr(driver + outputattr, decompose + ".inputMatrix") # Drive driven with compensated driver. cmds.connectAttr(decompose + ".outputTranslate", driven + ".t") cmds.connectAttr(decompose + ".outputRotate", driven + ".r") cmds.connectAttr(decompose + ".outputScale", driven + ".s") return output
def clone(shape, worldspace=False): """Clone `shape` Arguments: shape (str): Absolute path to shape worldspace (bool, optional): Whether or not to consider worldspace Returns: node (str): Newly created clone """ type = cmds.nodeType(shape) assert type in ("mesh", "nurbsSurface", "nurbsCurve"), ( "clone() works on polygonal and nurbs surfaces") src, dst = { "mesh": (".outMesh", ".inMesh"), "nurbsSurface": (".local", ".create"), "nurbsCurve": (".local", ".create"), }[type] nodetype = cmds.nodeType(shape) name = lib.unique(name=shape.rsplit("|")[-1]) clone = cmds.createNode(nodetype, name=name) cmds.connectAttr(shape + src, clone + dst, force=True) if worldspace: transform = cmds.createNode("transformGeometry", name=name + "_transformGeometry") cmds.connectAttr(shape + src, transform + ".inputGeometry", force=True) cmds.connectAttr(shape + ".worldMatrix[0]", transform + ".transform", force=True) cmds.connectAttr(transform + ".outputGeometry", clone + dst, force=True) # Assign default shader cmds.sets(clone, addElement="initialShadingGroup") return clone
def follicle(*args): supported = ["mesh", "nurbsSurface"] selection = cmds.ls(sl=1) new_follicles = [] for sel in selection: uv = lib.uv_from_element(sel) geometry_shape = lib.shape_from_element(sel) geometry_transform = cmds.listRelatives(geometry_shape, parent=True)[0] # Figure out output connection inputs = [".inputMesh", ".inputSurface"] outputs = [".outMesh", ".local"] failed = False type = cmds.nodeType(geometry_shape) if type not in supported: failed = True shapes = cmds.listRelatives(geometry_shape, shapes=True) if shapes: geometry_shape = shapes[0] type = cmds.nodeType(geometry_shape) if type in supported: failed = False if failed: cmds.error("Skipping '%s': Type not accepted" % type) return input = inputs[supported.index(type)] output = outputs[supported.index(type)] # Make follicle follicle = cmds.createNode("follicle", name=geometry_transform + "_follicleShape1") follicle_transform = cmds.listRelatives(follicle, parent=True)[0] follicle_transform = cmds.rename(follicle_transform, geometry_transform + "_follicle1") # Set U and V value cmds.setAttr(follicle + ".parameterU", uv[0]) cmds.setAttr(follicle + ".parameterV", uv[1]) # Make the connections cmds.connectAttr(follicle + ".outTranslate", follicle_transform + ".translate") cmds.connectAttr(follicle + ".outRotate", follicle_transform + ".rotate") cmds.connectAttr(geometry_shape + output, follicle + input) # Select last new_follicles.append(follicle_transform) # Select newly created follicles if new_follicles: cmds.select(new_follicles, r=1) return new_follicles
def create_spine(start_joint, end_joint, lower_control, upper_control, name='spine'): spline_chain, original_chain = shortcuts.duplicate_chain(start_joint, end_joint, prefix='ikSpine_') # Create the spline ik ikh, effector, curve = cmds.ikHandle( name='{0}_ikh'.format(name), solver='ikSplineSolver', startJoint=spline_chain[0], endEffector=spline_chain[-1], parentCurve=False, simplifyCurve=False) effector = cmds.rename(effector, '{0}_eff'.format(name)) curve = cmds.rename(curve, '{0}_crv'.format(name)) # Create the joints to skin the curve curve_start_joint = cmds.duplicate(start_joint, parentOnly=True, name='{0}CurveStart_jnt'.format(name)) cmds.parent(curve_start_joint, lower_control) curve_end_joint = cmds.duplicate(end_joint, parentOnly=True, name='{0}CurveEnd_jnt'.format(name)) cmds.parent(curve_end_joint, upper_control) # Skin curve cmds.skinCluster(curve_start_joint, curve_end_joint, curve, name='{0}_scl'.format(name), tsb=True) # Create stretch network curve_info = cmds.arclen(curve, constructionHistory=True) mdn = cmds.createNode('multiplyDivide', name='{0}Stretch_mdn'.format(name)) cmds.connectAttr('{0}.arcLength'.format(curve_info), '{0}.input1X'.format(mdn)) cmds.setAttr('{0}.input2X'.format(mdn), cmds.getAttr('{0}.arcLength'.format(curve_info))) cmds.setAttr('{0}.operation'.format(mdn), 2) # Divide # Connect to joints for joint in spline_chain[1:]: tx = cmds.getAttr('{0}.translateX'.format(joint)) mdl = cmds.createNode('multDoubleLinear', name='{0}Stretch_mdl'.format(joint)) cmds.setAttr('{0}.input1'.format(mdl), tx) cmds.connectAttr('{0}.outputX'.format(mdn), '{0}.input2'.format(mdl)) cmds.connectAttr('{0}.output'.format(mdl), '{0}.translateX'.format(joint)) # Setup advanced twist cmds.setAttr('{0}.dTwistControlEnable'.format(ikh), True) cmds.setAttr('{0}.dWorldUpType'.format(ikh), 4) # Object up cmds.setAttr('{0}.dWorldUpAxis'.format(ikh), 0) # Positive Y Up cmds.setAttr('{0}.dWorldUpVectorX'.format(ikh), 0) cmds.setAttr('{0}.dWorldUpVectorY'.format(ikh), 1) cmds.setAttr('{0}.dWorldUpVectorZ'.format(ikh), 0) cmds.setAttr('{0}.dWorldUpVectorEndX'.format(ikh), 0) cmds.setAttr('{0}.dWorldUpVectorEndY'.format(ikh), 1) cmds.setAttr('{0}.dWorldUpVectorEndZ'.format(ikh), 0) cmds.connectAttr('{0}.worldMatrix[0]'.format(lower_control), '{0}.dWorldUpMatrix'.format(ikh)) cmds.connectAttr('{0}.worldMatrix[0]'.format(upper_control), '{0}.dWorldUpMatrixEnd'.format(ikh)) # Constrain original chain back to spline chain for ik_joint, joint in zip(spline_chain, original_chain): if joint == end_joint: cmds.pointConstraint(ik_joint, joint, mo=True) cmds.orientConstraint(upper_control, joint, mo=True) else: cmds.parentConstraint(ik_joint, joint)