def makeSphere(pos = -1, r = 0.1, name = "temp", pos_list=-1 ) : if type(pos_list) is int : sp = pm.sphere(n = name, r=r)[0] pm.move(sp,[pos[0],pos[1],pos[2]]) else : sp = [] for p in pos_list : s = pm.sphere(n = name, r=r)[0] pm.move(s,[p[0],p[1],p[2]]) sp.append(s) return sp
def NSphere(self): shaderName = self._baseName + '_mtl' crv = pm.sphere(r=self.radius, n=self.name) #### set invisible to render crvShape = crv[0].getShape() crvShape.castsShadows.set(False) crvShape.receiveShadows.set(False) crvShape.motionBlur.set(False) crvShape.primaryVisibility.set(False) crvShape.smoothShading.set(False) crvShape.visibleInReflections.set(False) crvShape.visibleInRefractions.set(False) crvShape.doubleSided.set(False) #### set Shader shdr_name = '{}_{}'.format(shaderName, self.name) sg_name = '{}{}'.format(shdr_name, 'SG') if pm.objExists(shdr_name) or pm.objExists(sg_name): try: pm.delete(shdr_name) pm.delete(sg_name) except: pass shdr, sg = pm.createSurfaceShader('surfaceShader') pm.rename(shdr, shdr_name) pm.rename(sg, sg_name) shdr.outColor.set(self.color.rgb) shdr.outTransparency.set([self.color.a for i in range(3)]) pm.sets(sg, fe=crv[0]) return crv[0]
def setup(self): """creates the setup """ from anima.env.mayaEnv import auxiliary vtx_coord = pm.xform(self.pin_to_vertex, ws=1, t=1) self.pin_to_shape = self.pin_to_vertex.node() self.pin_uv = self.pin_to_shape.getUVAtPoint(vtx_coord, space='world') # create a sphere with the size of pin_size self.pin_transform, self.pin_shape = pm.sphere(radius=self.size) # create two axial correction groups self.compensation_group = \ auxiliary.axial_correction_group(self.pin_node) self.axial_correction_group = \ auxiliary.axial_correction_group(self.compensation_group) # create compensation setup decompose_matrix = pm.nt.DecomposeMatrix() self.pin_transform.inverseMatrix >> decompose_matrix.inputMatrix decompose_matrix.outputTranslate >> self.compensation_group.t decompose_matrix.outputRotate >> self.compensation_group.r decompose_matrix.outputScale >> self.compensation_group.s # create a follicle on the shape at the given uv self.follicle_transform, self.follicle_shape = \ auxiliary.create_follicle(self.pin_to_shape, self.pin_uv) # move the axial correction group pm.xform(self.axial_correction_group, ws=1, t=vtx_coord)
def cyan_control(name="", shape_type="sphere", translate=(0, 0, 0), parent_node=None): u"""蓝色的基础控制器组件 蓝色的控制器一般用来作为模块的主控制器 :return: """ base_ctrl = None if shape_type == "sphere": base_ctrl = pm.sphere(name=name, p=[0, 0, 0], ax=[0, 1, 0], ssw=0, esw=360, r=1, d=1, ut=0, tol=0.01, s=4, nsp=2, ch=0) pm.parent(base_ctrl, pm.createNode("transform", name="{}_Grp".format(name))) pm.PyNode("{}_Grp".format(name)).translate.set(translate) if parent_node is not None: if pm.objExists(parent_node): pm.parent("{}_Grp".format(name), parent_node) return "{}_Grp".format(name)
def press_cmd(self, *args) : ctx = self.ctx print "paramProgress_befor", self.paramProgress_befor pressPosition = cmds.draggerContext( ctx, query=True, anchorPoint=True) self.drag_star_point = pressPosition print ("Press: " + str(pressPosition)) #self.paramProgress = 0.0 pos = curvetool.getCurvePoint( self.cur, [self.paramProgress], "normal" )[0] # 第二引数でターゲットの初期位置を指定 self.moving_sph = pm.sphere(n = "moving_sph", r=0.1)[0] pm.move( self.moving_sph , [pos[0],pos[1],pos[2]] ) pm.refresh(f = 1) # ハイライト pm.hilite(self.cur) list = pm.ls(type = u'transform') for i in list : if "temp" in i.name() : pm.hilite(i)
def vizPoint(pos, name="point", color_index=16): """ Visuallize Points as Sphere """ point = pm.sphere(p=pos, name=name, radius=0.1)[0] # 6:blue, 16:white, 17:yellow if color_index: pm.setAttr("{0}.overrideEnabled".format(point.getShape()), 1) pm.setAttr("{0}.overrideColor".format(point.getShape()), color_index) return point
def _test_squash(): # ex:creating a bell-curve type squash cmds.file(new=True, f=True) transform, shape = pymel.sphere() stretch = transform.sy squash = parse("1 / (e^(x^2))", x=stretch) pymel.connectAttr(squash, transform.sx) pymel.connectAttr(squash, transform.sz) return True
def resampleSpline(amount=4): multiplyer = 1.00 / amount for i in range(amount): knob = pm.sphere(n='spine_knob%02d' % (i + 1), r=0.2) grp = pm.group(knob, name='spine_grp%02d' % (i + 1)) const = pm.parentConstraint(['Root_knob', 'Chest_knob'], grp, mo=0) pm.setAttr('%s.Root_knobW0' % const, (1 - (multiplyer * i))) pm.setAttr('%s.Chest_knobW1' % const, (multiplyer * i))
def viz_sphere(pos, name='sphere', color_index=16): sphere = pm.sphere(p=pos, name=name, radius=.1)[0] # 6:blue, 16:white, 17:yellow if (color_index): print(1231413541345) pm.setAttr('{0}.overrideEnabled'.format(sphere.getShape()), 1) pm.setAttr('{0}.overrideColor'.format(sphere.getShape()), color_index) return sphere
def left_leg_toe(side='l', basename='leg_toe', type='guide', radius=1): nameStructure = { 'Side': side, 'Basename': basename, 'Type': type, } _left_leg_toe = pm.sphere( n='{Side}__{Basename}__{Type}'.format(**nameStructure), r=radius)[0] _left_leg_toe.setTranslation((6, 0, 15), space='object') self.all_sphere.append(_left_leg_toe) return _left_leg_toe
def advSpaceSwitch(): # COMPLEX SPACE SWITCHING r = pmc.sphere(n="rightHand")[0] l = pmc.cylinder(n="leftHand")[0] w = pmc.cone(n="weapon")[0] ws = pmc.spaceLocator(n="worldLoc") locs = [ws] grps = [] names = ["World"] names.extend([s.name() for s in (r, l, w)]) for s in (r, l, w): grps.append(pmc.group(s, n=s.name() + "_space")) l = pmc.spaceLocator(n=s.name() + "_ws") l.setParent(s) locs.append(l) spaces = ":".join([n for n in names if n != s.name()]) s.addAttr("space", at="enum", k=True, enumName=spaces) for g in grps: spaceMat = pmc.nt.WtAddMatrix() spaceXform = pmc.nt.DecomposeMatrix() spaceMat.o >> spaceXform.inputMatrix spaceXform.ot >> g.t targets = [l for l in locs if not l.hasParent(g)] for i, t in enumerate(targets): driver = g.getChildren()[0] # uc = pmc.nt.UnitConversion() # t.wp >> uc.input # direct connection from l >> g, # modulated by enum value test = pmc.nt.FloatLogic() driver.space >> test.floatA test.floatB.set(i) cond = pmc.nt.FloatCondition() test.outBool >> cond.condition cond.floatA.set(0) cond.floatB.set(10) # cond.outFloat >> uc.nodeState hold = pmc.nt.HoldMatrix() t.wm >> hold.i cond.outFloat >> hold.nodeState # for second-round lookup # ensure no ping-ponging cond.message >> driver.childConditions cond.message >> t.getParent().parentConditions hold.o >> spaceMat.i[i].m test.outBool >> spaceMat.i[i].w
def loop_to_joints(s=0.025): """Convert a mesh loop edge selection to a nurbs curve that has joints (w/ tweak controls) at each vertex. Opens dialog for naming.""" edges = pmc.selected(flatten=True) cage = edges[0].node() try: n = make_dialog("Name of this curve/region?") + "{}" except TypeError: pmc.warning("Aborted.") return c = pmc.PyNode(pmc.polyToCurve(n=n.format("_rider"))[0]) verts = set([v for e in edges for v in e.connectedVertices()]) grp = pmc.group(em=True, n=n.format("_grp")) c.setParent(grp) jn = "" for i, v in enumerate(verts): pmc.select(c) pmc.selectMode(component=True) pmc.select(c.u[i]) pmc.refresh() jn = make_dialog("Name of this joint?", jn) poci = pmc.nt.PointOnCurveInfo(n=n.format(jn + "_poci")) c.ws >> poci.inputCurve poci.parameter.set(i) ctrl_grp = pmc.group(em=True, n=n.format(jn + "_offset")) ctrl_grp.setParent(grp) ctrl = pmc.sphere(r=s, s=1, nsp=1, ch=0, n=n.format(jn + "_tweakCtrl"))[0] ctrl.setParent(ctrl_grp) j = pmc.joint(n=n.format(jn + "_rig")) j.setParent(ctrl) j.hide() poci.position >> ctrl_grp.translate nCon = pmc.normalConstraint(cage, ctrl_grp) poci.nt >> nCon.worldUpVector # remove graph cluster nCon.crp.disconnect() nCon.crt.disconnect() nCon.cro.disconnect() nCon.cpim.disconnect() nCon.ct.disconnect() poci.position >> nCon.constraintTranslate grp.wim >> nCon.cpim pmc.selectMode(object=True)
def build(): defaults = { 'ax': (0, 1, 0), 'ssw': 0, 'esw': 360, 'd': 3, 'ut': 0, 'tol': 0.02, 'ch': False } ctrl = sphere(p=(0, 0.8333333, 0), r=0.166667, s=6, nsp=4, **defaults)[0] cyl = cylinder(p=(0, 0.345, 0), r=.08333333, hr=8.333333, s=4, nsp=1, **defaults)[0] cyl.rename('tube') points = [ # shaft [0, 0, 0], [0, 0.666667, 0], # circle [-0.11785101234662772, 0.71548248765337219, 0], [-0.166667, 0.833333, 0], [-0.11785101234662777, 0.95118451234662771, 0], [0, 1, 0], [0.1178510123466277, 0.95118451234662771, 0], [0.166667, 0.833333, 0], [0.11785101234662779, 0.71548248765337241, 0], [0, 0.666667, 0], # cross line [0.11785101234662779, 0.71548248765337241, 0], [-0.11785101234662777, 0.95118451234662771, 0], # transition [-0.166667, 0.833333, 0], # cross line [-0.11785101234662772, 0.71548248765337219, 0], [0.1178510123466277, 0.95118451234662771, 0], ] line = curve(p=points, d=1) line.rename('outline') line.getShape().setParent(ctrl, add=True, shape=True) cyl.getShape().setParent(ctrl, add=True, shape=True) delete(line, cyl) return ctrl
def _basic_setup(self): """Create the nurbs sphere and the necessary utility nodes. Connect the nodes to sample the color value on the closest point on the surface of the nurbs sphere. """ self.info_node = pm.createNode('transform', n='C_%s_GRP' % (self.name)) self.info_node.addAttr('outValue', min=-1, max=1, k=True) self.info_node.addAttr('coneAngle', min=0, max=180, dv=self.cone_angle, k=True) self.info_node.addAttr('visualize', at='bool', k=True, dv=1) self.sphere = pm.sphere(ch=False, n='C_%s_NRB' % (self.name))[0] pm.parent(self.sphere, self.info_node) self.point_on_surface = pm.createNode('closestPointOnSurface') mdl = pm.createNode('multDoubleLinear') self.ramp = pm.createNode('ramp') self.sphere.ws >> self.point_on_surface.inputSurface mdl.setAttr('input2', 0.25) self.point_on_surface.parameterU >> mdl.input1 mdl.output >> self.ramp.uCoord self.ramp.setAttr('type', 1) self.ramp.setAttr('colorEntryList[0].color', 0, 0, 0) self.ramp.setAttr('colorEntryList[1].position', 1) self.ramp.setAttr('colorEntryList[1].color', 1, 1, 1) self.ramp.setAttr('colorEntryList[2].position', 0) # Need to use maya.cmds here, because pymel does not allow to # set negative values on a color attribute cmds.setAttr('%s.colorEntryList[2].color' % self.ramp, -1, -1, -1, type='double3') self.ramp.setAttr('colorEntryList[3].color', 0, 0, 0) self.ramp.outColorR >> self.info_node.outValue # cone angle rmv = pm.createNode('remapValue', n='coneAngle') rmv.setAttr('inputMin', 0) rmv.setAttr('inputMax', 180) rmv.setAttr('outputMin', 1) rmv.setAttr('outputMax', 0.5) self.info_node.coneAngle >> rmv.inputValue rmv.outValue >> self.ramp.colorEntryList[0].position rvs = pm.createNode('reverse', n='coneAngle') rmv.outValue >> rvs.inputX rvs.outputX >> self.ramp.colorEntryList[3].position
def left_arm_hand(side='l', basename='arm_hand', type='guide', radius=1): nameStructure = { 'Side': side, 'Basename': basename, 'Type': type, } _left_arm_hand_gd = pm.sphere( n='{Side}__{Basename}__{Type}'.format(**nameStructure), r=radius)[0] _left_arm_hand_gd.setTranslation((43, 100, -1), space='object') self.all_sphere.append(_left_arm_hand_gd) return _left_arm_hand_gd
def right_leg_heel(side='r', basename='leg_heel', type='guide', radius=1): nameStructure = { 'Side': side, 'Basename': basename, 'Type': type, } _right_leg_heel = pm.sphere( n='{Side}__{Basename}__{Type}'.format(**nameStructure), r=radius)[0] _right_leg_heel.setTranslation((-6, 0, -6), space='object') self.all_sphere.append(_right_leg_heel) return _right_leg_heel
def right_arm_elbow(side='r', basename='arm_elbow', type='guide', radius=2): nameStructure = { 'Side': side, 'Basename': basename, 'Type': type, } _right_arm_elbow_gd = pm.sphere( n='{Side}__{Basename}__{Type}'.format(**nameStructure), r=radius)[0] _right_arm_elbow_gd.setTranslation((-28, 100, -1), space='object') self.all_sphere.append(_right_arm_elbow_gd) return _right_arm_elbow_gd
def build(): ''' It takes extra work to draw circle with a single line. This is accomplished by having the terminal point exactly where the curve must pass through and points very near it to give it the (almost) correct bend. This is repeated 3x, then that same technique is used to make a quarter arc, then an additional hoop. The first 3 hoops and transition are made vertical, which puts the transition ending back on the ground plane, where the 4th hoop remains. ''' ctrl = sphere(ax=[0, 1, 0], ssw=0, esw=360, r=0.49 * 0.9, d=3, s=6, nsp=4)[0] major = util.CirclePoints.major minor = util.CirclePoints.minor body = util.CirclePoints.body terminal = util.CirclePoints.terminal s = [-minor, 0, -major] e = [minor, 0, -major] hoop = [terminal, s, s] + body + [e, e, terminal] count = len(hoop) transArc = [terminal] + \ [[-minor, 0, -major]] * 2 + \ [body[0]] + \ [[-major, 0, -minor]] * 2 + \ [[-.5 * 0.9, 0, 0]] line = curve(p=hoop * 3 + transArc + hoop, d=3) rotate(line.cv[:count * 3 + len(transArc) - 1], [90, 0, 0]) rotate(line.cv[count:count * 2], [0, 60, 0]) rotate(line.cv[count * 2:count * 3], [0, -60, 0]) rotate(line.cv[count * 3 + len(transArc):], [0, 90, 0]) line.rename('outline') line.getShape().setParent(ctrl, add=True, shape=True) delete(line) return ctrl
def previous_pin(self, *args) : print u" - - - 前のピンへ移動します。- - - " if self.no_of_editing_pin != 0 : self.no_of_editing_pin -= 1 else : self.no_of_editing_pin = self.no_of_editing_pin_max - 1 print u"no_of_editing_pin :", self.no_of_editing_pin print u"parameter :", self.paramList[self.no_of_editing_pin] # 球を強調する index = self.constPinIndexList[self.no_of_editing_pin] v = pm.PyNode(self.base_name).vtx[index] try : pm.delete(pm.PyNode("tempmouth")) except : pass pos = pm.pointPosition(v) sp = pm.sphere(n = "tempmouth", r=0.3)[0] pm.move(sp,[pos[0],pos[1],pos[2]])
def press_cmd(self, *args) : ctx = self.ctx print "paramProgress_befor", self.paramProgress_befor pressPosition = cmds.draggerContext( ctx, query=True, anchorPoint=True) self.drag_star_point = pressPosition print ("Press: " + str(pressPosition)) #self.paramProgress = 0.0 pos = curvetool.getCurvePoint( self.cur, [self.paramProgress], "normal" )[0] # 第二引数でターゲットの初期位置を指定 self.moving_sph = pm.sphere(n = "temp_pineditor_moving_sph", r=0.1)[0] pm.move( self.moving_sph , [pos[0],pos[1],pos[2]] ) pm.refresh(f = 1)
def createManipIkAnimatedAndPoleVector(self): pm.select(cl = True) #manipIkAnimated #---------------------------------------------------- #create manipIkAnimated self.manipIkAnimated = pm.sphere(r = 1, n = self.prefix + '_manip_ik_animated', ch = False)[0] pm.select(cl = True) #grp ik animated self.manipIkAnimatedGrp = pm.group(n = self.prefix + '_manip_ik_animated_grp') pm.select(cl = True) pm.parent(self.manipIkAnimated, self.manipIkAnimatedGrp) pm.select(cl = True) #Move grp to appropiate place self.manipIkAnimatedGrp.translate.set(self.jointPositionList[-1]) pm.select(cl = True) #poleVector #---------------------------------------------------- #create poleVector self.manipIkAnimatedPoleVector = pm.spaceLocator(n = self.prefix + '_ik_animated_poleVector') pm.select(cl = True) #grp poleVector and translate self.manipIkAnimatedPoleVectorGrp = pm.group(n = self.prefix + '_ik_animated_poleVector_grp') pm.select(cl = True) pm.parent(self.manipIkAnimatedPoleVector, self.manipIkAnimatedPoleVectorGrp) pm.select(cl = True) #poleVectorGrp Translation zAxisDistance = 3 self.manipIkAnimatedPoleVectorGrp.translate.set(0, self.locatorDistance * 0.5, zAxisDistance) pm.select(cl = True)
def create(self, shape=None, pos=[0, 0, 0], parent=None, create_offset=True): if not self.node: if shape: self.node = pm.nt.Transform(name=self.name) shape = ul.get_node(shape) ul.parent_shape(shape, self.node) else: self.node = \ pm.sphere(ax=(0, 1, 0), ssw=0, esw=360, r=0.35, d=3, ut=False, tol=0.01, s=8, nsp=4, ch=False, n=self.name)[0] self.node.setTranslation(pos, 'world') self.WorldPosition = self.node.getTranslation('world') self.shape = ul.get_shape(self.node) for atr in [ 'castsShadows', 'receiveShadows', 'holdOut', 'motionBlur', 'primaryVisibility', 'smoothShading', 'visibleInReflections', 'visibleInRefractions', 'doubleSided' ]: self.shape.attr(atr).set(0) if not self.offset and create_offset: self.offset = pm.nt.Transform(name=self.offset_name) self.offset.setTranslation(self.WorldPosition, space='world') self.node.setParent(self.offset) if not self.root: self.root = pm.nt.Transform(name=self.root_name) self.root.setTranslation(self.WorldPosition, space='world') if self.offset: self.offset.setParent(self.root) else: self.node.setParent(self.root) self.root.setParent(parent) return self.node
def makeFacialJoint(self): ''' 顔にフェイシャルリグのテンプレートを生成する ''' lipCurve = [i for i in self.facialCurves if i[:].encode("ascii").find("lip") >= 0] noseCurve = [i for i in self.facialCurves if i[:].encode("ascii").find("nose") >= 0] otherCurves = [i for i in self.facialCurves if i[:].encode("ascii").find("lip") < 0 and i[:].encode("ascii").find("nose") < 0] locGroup=pm.group(name="locatorGrp") #鼻のカーブにコントローラを設定 for currentCurve in noseCurve: locatorData = pm.spaceLocator() locatorData.setScale([0.5,0.5,0.5]) pos = 1/float(2) dLib.dtLib.setToCurve(currentCurve, locatorData, position=pos) #crvをとったprefix部分を取得 namePrefix = currentCurve[:-3] locatorData.rename(namePrefix+"locator") #オフセットジョイントの作成 offsetJoint=pm.joint(p=[0,0,0]) offsetJoint.rename(namePrefix+"offsetJnt") #コントロール用のジョイント作成 controlJoint = pm.joint(p=[0,0,0]) controlJoint.rename(namePrefix+"controlJnt") radius = 0.3 controlSphere = pm.sphere(r=radius) sphereShape=controlSphere[0].getShape() pm.setAttr(sphereShape[:]+".primaryVisibility", 0) #ペアレント化 pm.parent(controlSphere[0].getShape(), controlJoint, relative=True, shape=True) pm.delete(controlSphere) pm.parent(controlJoint, offsetJoint) pm.parent(offsetJoint, locatorData) offsetJoint.setTranslation([0,0,0]) pm.parent(locatorData, locGroup) #唇のカーブにコントローラーを設定 for currentCurve in lipCurve: for i in range(0,5): locatorData = pm.spaceLocator() locatorData.setScale([0.5,0.5,0.5]) pos = i / float(4) dLib.dtLib.setToCurve(currentCurve, locatorData, position=pos) #crvをとったprefix部分を取得 namePrefix = currentCurve[:-3] locatorData.rename(namePrefix+"locator"+str(i+1)) #オフセットジョイントの作成 offsetJoint=pm.joint(p=[0,0,0]) offsetJoint.rename(namePrefix+"offsetJnt"+str(i+1)) #コントロール用のジョイント作成 controlJoint = pm.joint(p=[0,0,0]) controlJoint.rename(namePrefix+"controlJnt"+str(i+1)) radius = 0.3 controlSphere = pm.sphere(r=radius) sphereShape=controlSphere[0].getShape() pm.setAttr(sphereShape[:]+".primaryVisibility", 0) #ペアレント化 pm.parent(controlSphere[0].getShape(), controlJoint, relative=True, shape=True) pm.delete(controlSphere) pm.parent(controlJoint, offsetJoint) pm.parent(offsetJoint, locatorData) offsetJoint.setTranslation([0,0,0]) pm.parent(locatorData, locGroup) #他のカーブにコントローラーを設定 for currentCurve in otherCurves: for i in range(0,3): locatorData = pm.spaceLocator() locatorData.setScale([0.5,0.5,0.5]) pos = i / float(2) dLib.dtLib.setToCurve(currentCurve, locatorData, position=pos) #crvをとったprefix部分を取得 namePrefix = currentCurve[:-3] locatorData.rename(namePrefix+"locator"+str(i+1)) #オフセットジョイントの作成 offsetJoint=pm.joint(p=[0,0,0]) offsetJoint.rename(namePrefix+"offsetJnt"+str(i+1)) #コントロール用のジョイント作成 controlJoint = pm.joint(p=[0,0,0]) controlJoint.rename(namePrefix+"controlJnt"+str(i+1)) radius = 0.3 controlSphere = pm.sphere(r=radius) sphereShape=controlSphere[0].getShape() pm.setAttr(sphereShape[:]+".primaryVisibility", 0) #ペアレント化 pm.parent(controlSphere[0].getShape(), controlJoint, relative=True, shape=True) pm.delete(controlSphere) pm.parent(controlJoint, offsetJoint) pm.parent(offsetJoint, locatorData) offsetJoint.setTranslation([0,0,0]) pm.parent(locatorData, locGroup) self.imageScene = ivScene.imageViewScene() #顔の画像を画像ビューに入れる filePath = os.path.dirname(__file__) + "/data/image/tmp.jpg" self.imageScene.setSceneRect( QtCore.QRectF( self.renderView.rect() ) ) self.imageScene.setFile(filePath) ellipse = ivScene.GraphicsEllipseButton(120,50,50,50) ellipse.setCallback(callback=self.callbackFunc) ellipse.setBrush(QtGui.QBrush(QtGui.QColor('pink'))) self.imageScene.addItem(ellipse) self.renderView.setScene(self.imageScene) self.renderView.show()
from __future__ import print_function, division import pymel.core as pm pm.sphere(radius=2, name='Sphere1') # query the radius of the sphere named Sphere1 radius = pm.sphere('Sphere1', query=True, radius=True) print('The sphere radius =', radius) # modify the radius print('Increment the sphere\'s radius by one unit') pm.sphere('Sphere1', edit=True, radius=radius + 1) radius = pm.sphere('Sphere1', query=True, radius=True) print('The new sphere radius =', radius)
def createCtrl(ctrlName, type="locator", size=1, color=None, matchTarget=None, rotation=[0, 0, 0]): """ Create a controler. :param ctrlName: `string` controler name :param type: `string` controler type :param size: `float` controler size :param color: `string` controler color :param matchTarget: `PyNode` match the controler to the target object :return: `PyNode` controler object """ ctrlLib = { "locator": { "d": 1, "p": [(-1, 0, 0), (1, 0, 0), (0, 0, 0), (0, 0, -1), (0, 0, 1), (0, 0, 0), (0, 1, 0), (0, -1, 0)] }, "cube": { "d": 1, "p": [(-1, 1, -1), (-1, 1, 1), (-1, -1, 1), (-1, -1, -1), (-1, 1, -1), (1, 1, -1), (1, -1, -1), (-1, -1, -1), (-1, -1, 1), (1, -1, 1), (1, -1, -1), (1, 1, -1), (1, 1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1)] }, "circle": { "d": 3, "p": [(0, -0.783612, -0.783612), (0, 0, -1.108194), (0, 0.783612, -0.783612), (0, 1.108194, 0), (0, 0.783612, 0.783612), (0, 0, 1.108194), (0, -0.783612, 0.783612), (0, -1.108194, 0), (0, -0.783612, -0.783612), (0, 0, -1.108194), (0, 0.783612, -0.783612)], "k": [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }, "crossArrow": { "d": 1, "p": [(1, 0, 1), (3, 0, 1), (3, 0, 2), (5, 0, 0), (3, 0, -2), (3, 0, -1), (1, 0, -1), (1, 0, -3), (2, 0, -3), (0, 0, -5), (-2, 0, -3), (-1, 0, -3), (-1, 0, -1), (-3, 0, -1), (-3, 0, -2), (-5, 0, 0), (-3, 0, 2), (-3, 0, 1), (-1, 0, 1), (-1, 0, 3), (-2, 0, 3), (0, 0, 5), (2, 0, 3), (1, 0, 3), (1, 0, 1)], "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 ] }, "cross": { "d": 1, "p": [(0.4, 0, -0.4), (0.4, 0, -2), (-0.4, 0, -2), (-0.4, 0, -0.4), (-2, 0, -0.4), (-2, 0, 0.4), (-0.4, 0, 0.4), (-0.4, 0, 2), (0.4, 0, 2), (0.4, 0, 0.4), (2, 0, 0.4), (2, 0, -0.4), (0.4, 0, -0.4)], "k": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] }, "fatCross": { "d": 1, "p": [(-1, 0, -1), (-1, 0, -2), (1, 0, -2), (1, 0, -1), (2, 0, -1), (2, 0, 1), (1, 0, 1), (1, 0, 2), (-1, 0, 2), (-1, 0, 1), (-2, 0, 1), (-2, 0, -1), (-1, 0, -1)], "k": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] }, "hollowSphere": { "d": 1, "p": [(0, 1, 0), (0, 0.9239, 0.3827), (0, 0.7071, 0.7071), (0, 0.3827, 0.9239), (0, 0, 1), (0, -0.3827, 0.9239), (0, -0.7071, 0.7071), (0, -0.9239, 0.3827), (0, -1, 0), (0, -0.9239, -0.3827), (0, -0.7071, -0.7071), (0, -0.3827, -0.9239), (0, 0, -1), (0, 0.3827, -0.9239), (0, 0.7071, -0.7071), (0, 0.9239, -0.3827), (0, 1, 0), (0.3827, 0.9239, 0), (0.7071, 0.7071, 0), (0.9239, 0.3827, 0), (1, 0, 0), (0.9239, -0.3827, 0), (0.7071, -0.7071, 0), (0.3827, -0.9239, 0), (0, -1, 0), (-0.3827, -0.9239, 0), (-0.7071, -0.7071, 0), (-0.9239, -0.3827, 0), (-1, 0, 0), (-0.9239, 0.3827, 0), (-0.7071, 0.7071, 0), (-0.3827, 0.9239, 0), (0, 1, 0), (0, 0.9239, -0.3827), (0, 0.7071, -0.7071), (0, 0.3827, -0.9239), (0, 0, -1), (-0.3827, 0, -0.9239), (-0.7071, 0, -0.7071), (-0.9239, 0, -0.3827), (-1, 0, 0), (-0.9239, 0, 0.3827), (-0.7071, 0, 0.7071), (-0.3827, 0, 0.9239), (0, 0, 1), (0.3827, 0, 0.9239), (0.7071, 0, 0.7071), (0.9239, 0, 0.3827), (1, 0, 0), (0.9239, 0, -0.3827), (0.7071, 0, -0.7071), (0.3827, 0, -0.9239), (0, 0, -1)], } } try: if type == "sphere": ctrl = pm.sphere(n=ctrlName, r=0.5, ax=[0, 1, 0], ch=0)[0] else: ctrl = pm.curve(**ctrlLib[type]) ctrl.rename(ctrlName) except: print("error creating ctrl.") return None ctrl.s.set((size, size, size)) ctrl.r.set(rotation) pm.makeIdentity(ctrl, a=1) if matchTarget and ctrl: pm.delete(pm.parentConstraint(matchTarget, ctrl, mo=0)) if color: colorObject(ctrl, color) return ctrl
eyeMarkersDict = {} eyeMarkers = pm.ls('eye*', type='transform') i=0 for mark in eyeMarkers: markerDict = {} markerDict['name'] = mark.name() markPos = mark.getTranslation(space='world') markerDict['position'] = [markPos.x,markPos.y,markPos.z] eyeMarkersDict['Marker' + str(i)] = markerDict i+=1 eyeTemplate = {} eyeTemplate['Eye_Template'] = sorted(eyeMarkersDict.items()) with open('d:\\eye_template.json', mode='w') as f: json.dump(eyeTemplate, f, indent = 2) import pymel.core as pm import json with open('d:\\eye_template.json', 'r') as f: template = json.load( f) print template for token in template['Eye_Template']: tokenDict = token[1] markSphere = pm.sphere(name=tokenDict['name'],radius=0.3) markSphere[0].setTranslation(tokenDict['position'],space='world')
testSphere1.grow() testSphere2.grow() #--------------- #basic use of pymel to show how keeping track of instances can be useful #this is the python (maya.cmds) way of doing something import maya.cmds as cmds pythonSphere = cmds.sphere(n="pythonSphere") print pythonSphere print(type(pythonSphere)) #this is the pymel way of doing it import pymel.core as pm pymelSphere = pm.sphere(n="pymelSphere") print pymelSphere print(type(pymelSphere)) #now try to select them (then change their names and select them) cmds.select(pythonSphere[0]) pm.select(pymelSphere[0]) #-------------- #a couple of bigger uses of classes in maya import baseLimb as bl baseTest = bl.LimbUI() import armRig as ar armTest = ar.ArmUI()
def createManipulators(self): pm.select(cl = True) #manip_master #---------------------------------------------------- #create manip master self.manip_master = pm.circle(r = 1.5, name = self.prefix +'_manip_master', ch = False, nr=(0, 1, 0))[0] pm.select(cl = True) #create and parent under grp self.manip_master_grp = pm.group(n = self.prefix + '_manip_master_grp') pm.select(cl = True) pm.parent(self.manip_master, self.manip_master_grp) pm.select(cl = True) #translate self.manip_master_grp.translate.set(self.highResCurveCoordList[0]) pm.select(cl = True) #manip_ikSpline list #---------------------------------------------------- #manipIkSplineList self.manipIkSplineList = [] self.manipIkSplineGrpList = [] #iterate through low curve points list and create manip ik spline for index in range(len(self.lowResCurveCoordList)): pm.select(cl = True) #manipName manipName = self.prefix + '_manip_ik_spline_' + str(index + 1) if( index == 0 ): manipName = self.prefix + '_manip_ik_spline_' + 'base' if( index + 1 == len(self.lowResCurveCoordList) ): manipName = self.prefix + '_manip_ik_spline_' + 'tip' #Create manip manip_ik_spline = pm.sphere(r = 1, ch = False, n = manipName)[0] pm.select(cl = True) #create manip grp manip_ik_spline_grp = pm.group(n = manipName + '_grp') pm.select(cl = True) pm.parent(manip_ik_spline, manip_ik_spline_grp) pm.select(cl = True) #translate grp manip_ik_spline_grp.translate.set(self.lowResCurveCoordList[index]) pm.select(cl = True) #Append to lists self.manipIkSplineList.append(manip_ik_spline) self.manipIkSplineGrpList.append(manip_ik_spline_grp) pm.select(cl = True) #Create group for manip groups self.manipIkSplineTopGrp = pm.group(n = self.prefix +'_manip_ik_spline_top_grp') pm.select(cl = True) #parent all manips to top grp pm.parent(self.manipIkSplineGrpList, self.manipIkSplineTopGrp) pm.select(cl = True)
def load_to_maya(positions, names=None, parents=None, color=None, radius=0.1, thickness=5.0): import pymel.core as pm import maya.mel as mel if names is None: names = ['joint_%i' % i for i in xrange(positions.shape[1])] if color is None: color = (0.5, 0.5, 0.5) mpoints = [] frames = range(1, len(positions) + 1) for i, name in enumerate(names): #try: # point = pm.PyNode(name) #except pm.MayaNodeError: # point = pm.sphere(p=(0,0,0), n=name, radius=radius)[0] point = pm.sphere(p=(0, 0, 0), n=name, radius=radius)[0] jpositions = positions[:, i] for j, attr, attr_name in zip( xrange(3), [point.tx, point.ty, point.tz], ["_translateX", "_translateY", "_translateZ"]): conn = attr.listConnections() if len(conn) == 0: curve = pm.nodetypes.AnimCurveTU(n=name + attr_name) pm.connectAttr(curve.output, attr) else: curve = conn[0] curve.addKeys(frames, jpositions[:, j]) mpoints.append(point) if parents != None: for i, p in enumerate(parents): if p == -1: continue pointname = names[i] parntname = names[p] conn = pm.PyNode(pointname).t.listConnections() if len(conn) != 0: continue curve = pm.curve(p=[[0, 0, 0], [0, 1, 0]], d=1, n=names[i] + '_curve') pm.connectAttr(pointname + '.t', names[i] + '_curve.cv[0]') pm.connectAttr(parntname + '.t', names[i] + '_curve.cv[1]') pm.select(curve) pm.runtime.AttachBrushToCurves() stroke = pm.selected()[0] brush = pm.listConnections(stroke.getChildren()[0] + '.brush')[0] pm.setAttr(brush + '.color1', color) pm.setAttr(brush + '.globalScale', thickness) pm.setAttr(brush + '.endCaps', 1) pm.setAttr(brush + '.tubeSections', 20) mel.eval('doPaintEffectsToPoly(1,0,0,1,100000);') mpoints += [stroke, curve] return pm.group(mpoints, n='AnimationPositions'), mpoints
import pymel.core as pm """ Creating a nurbs sphere """ sphere = pm.sphere() # Create a poly cube cube = pm.polyCube()
# let's create a sphere import pymel.core as pm pm.sphere(radius=2, name='Sphere1') # query the radius of the sphere named Sphere1 radius = pm.sphere('Sphere1', query=True, radius=True) print 'The sphere radius =',radius # modify the radius print 'Increment the sphere\'s radius by one unit' pm.sphere('Sphere1', edit=True, radius=radius+1) radius = pm.sphere('Sphere1', query=True, radius=True) print 'The new sphere radius =', radius
def __init__(self): pm.sphere() print 'Creating a pivot'
import json import collections eyeMarkersDict = {} eyeMarkers = pm.ls('eye*', type='transform') i = 0 for mark in eyeMarkers: markerDict = {} markerDict['name'] = mark.name() markPos = mark.getTranslation(space='world') markerDict['position'] = [markPos.x, markPos.y, markPos.z] eyeMarkersDict['Marker' + str(i)] = markerDict i += 1 eyeTemplate = {} eyeTemplate['Eye_Template'] = sorted(eyeMarkersDict.items()) with open('d:\\eye_template.json', mode='w') as f: json.dump(eyeTemplate, f, indent=2) import pymel.core as pm import json with open('d:\\eye_template.json', 'r') as f: template = json.load(f) print template for token in template['Eye_Template']: tokenDict = token[1] markSphere = pm.sphere(name=tokenDict['name'], radius=0.3) markSphere[0].setTranslation(tokenDict['position'], space='world')
import pymel.core as pm pm.sphere()
def createJointNodeTemplate(self): ''' Create a Joint Node template type. ''' # Set the current namespace to root. cmds.namespace(setNamespace=':') # Create the main groups. self.groupNode = pm.group(empty=True, name=self.name + '_templateGrp') self.extraGroupNode = pm.group(empty=True, name=self.name + '_extrasGrp') pm.parent(self.extraGroupNode, self.groupNode) # Add a custom attributes to the template group to store template creation attributes. # number and length pm.addAttr(self.groupNode, attributeType='short', longName='numberOfNodes', defaultValue=self.numNodes, k=False) pm.addAttr(self.groupNode, attributeType='float', longName='templateLength', defaultValue=self.length, k=False) # orientaton _logger.debug('nodeOrient. %s' % self.groupNode) pm.addAttr(self.groupNode, dataType='string', longName='nodeOrient', keyable=False) pm.setAttr(self.groupNode + '.nodeOrient', self.aimAxis, type='string') # parent pm.addAttr(self.groupNode, dataType='string', longName='templateParent', keyable=False) pm.setAttr(self.groupNode + '.templateParent', 'None', type='string') pm.addAttr(self.groupNode, dataType='string', longName='onPlane', keyable=False) pm.setAttr(self.groupNode + '.onPlane', '+' + self.onPlane, type='string') # mirror pm.addAttr(self.groupNode, at='short', longName='mirrorStatus', keyable=False, dv=0) pm.addAttr(self.groupNode, dataType='string', longName='mirrorPlane', keyable=False) pm.setAttr(self.groupNode + '.mirrorPlane', '+' + self.mirrorPlane, type='string') # Move the joints group to the start position for the first joint node. pm.xform(self.groupNode, worldSpace=True, translation=self.initNodePosition) _logger.debug('Done crating main groups. %s' % self.groupNode) # calculate position offset = self.length / (self.numNodes - 1) _logger.debug(offset) for i in range(self.numNodes): knobname = '%s%02d_knob' % (self.name, i + 1) if i == 0: transform = 0 else: transform = offset * i knob = pm.sphere(n=knobname, r=3 * self.worldScale)[0] pm.move(knob, transform) # self.createKnob(knobname, position) self.assignMaterial(knob) _logger.debug('Done crating knobs. %s' % knob) self.nodeList.append(knob) if i > 0: connector = self.createConnector(pt1=self.nodeList[i - 1], pt2=self.nodeList[i], radius=1 * self.worldScale) self.assignMaterial(connector) _logger.debug('Done crating knobs. %s' % self.groupNode) return # Create the template nodes (joints) by their position and name them accordingly. for index, nodePos in enumerate(self.initNodePos): if index == 0: jointName = cmds.joint(name=self.templateTypespace + ':root_node_transform', position=nodePos, radius=0.0, scaleCompensate=False) elif nodePos == self.initNodePos[-1]: jointName = cmds.joint(name=self.templateTypespace + ':end_node_transform', position=nodePos, radius=0.0, scaleCompensate=False) else: jointName = cmds.joint(name=self.templateTypespace + ':node_%s_transform' % (index), position=nodePos, radius=0.0, scaleCompensate=False) cmds.setAttr(jointName + '.drawStyle', 2) mfunc.lockHideChannelAttrs(jointName, 'r', 's', 'v', 'radi', keyable=False) self.nodeList.append(jointName) # Orient the joints. cmds.select(self.nodeList[0], replace=True) # For orientation we'll use the axis perpendicular to the creation plane as the up axis for secondary axis orient. secondAxisOrientation = {'XY': 'z', 'YZ': 'x', 'XZ': 'y'}[self.onPlane] + 'up' cmds.joint(edit=True, orientJoint=self.aimAxis.lower(), secondaryAxisOrient=secondAxisOrientation, zeroScaleOrient=True, children=True) # Orient the end joint node, if the template contains more than one joint node. if self.numNodes > 1: cmds.setAttr(self.nodeList[-1] + '.jointOrientX', 0) cmds.setAttr(self.nodeList[-1] + '.jointOrientY', 0) cmds.setAttr(self.nodeList[-1] + '.jointOrientZ', 0) # Mirror the template node joints (for the mirrored template) if the template mirroring is enabled # and the current template to be created is a mirrored template on the -ve side of the creation plane, # and if the mirror rotation function is set to "Behaviour". if self.mirrorTemplate: mirrorPlane = {'XY': False, 'YZ': False, 'XZ': False} mirrorPlane[self.onPlane] = True mirroredJoints = cmds.mirrorJoint(self.nodeList[0], mirrorXY=mirrorPlane['XY'], mirrorYZ=mirrorPlane['YZ'], mirrorXZ=mirrorPlane['XZ'], mirrorBehavior=True if self.mirrorRotationFunc == 'Behaviour' else False) for joint in mirroredJoints: newJoint = cmds.rename(joint, self.templateTypespace + ':' + joint) self.nodeList.append(newJoint) # Clear selection after joint orientation. cmds.select(clear=True) # Create and position the template transform control. templateHandle = objects.createTemplateTransform(namespace=self.templateTypespace, scale=0.26) cmds.delete(cmds.pointConstraint(self.nodeList[0], templateHandle['transform'], maintainOffset=False)) self.templateTransform = templateHandle['transform'] self.collectedNodes.append(templateHandle['scaleFactor']) # Add the template transform to the template group. cmds.parent(templateHandle['preTransform'], self.groupNode, absolute=True) # Set up constraints for the template transform. template_node_parentConstraint = mfunc.parentConstraint(self.templateTransform, self.templateNodesGrp, maintainOffset=True, namespace=self.templateTypespace) template_node_scaleConstraint = mfunc.scaleConstraint(self.templateTransform, self.templateNodesGrp, maintainOffset=False, namespace=self.templateTypespace) # Create hierarchy/orientation representation on joint node(s), depending on number of nodes in the template. self.createJointNodeControlHandleRepr() if len(self.nodeList) == 1: self.templateSingleOrientationReprGrp = cmds.group(empty=True, name=self.templateTypespace + ':templateSingleOrientationReprGrp', parent=self.templateReprGrp) singleOrientationTransform = objects.createRawSingleOrientationRepresentation() cmds.setAttr(singleOrientationTransform + '.scale', 0.65, 0.65, 0.65, type='double3') cmds.makeIdentity(singleOrientationTransform, scale=True, apply=True) cmds.parent(singleOrientationTransform, self.templateSingleOrientationReprGrp, absolute=True) cmds.rename(singleOrientationTransform, self.templateTypespace + ':' + singleOrientationTransform) cmds.xform(self.templateSingleOrientationReprGrp, worldSpace=True, absolute=True, translation=cmds.xform(self.nodeList[0], query=True, worldSpace=True, translation=True)) mfunc.parentConstraint(self.nodeList[0], self.templateSingleOrientationReprGrp, maintainOffset=False, namespace=self.templateTypespace) mfunc.scaleConstraint(self.templateTransform, self.templateSingleOrientationReprGrp, maintainOffset=False, namespace=self.templateTypespace) nodeHandles = [] # Set the sizes for the template node handle shapes. for joint in self.nodeList: handle = objects.load_xhandleShape(transform=joint, colour=self.tmpHandleColour) cmds.setAttr(handle['shape'] + '.localScaleX', 0.089) cmds.setAttr(handle['shape'] + '.localScaleY', 0.089) cmds.setAttr(handle['shape'] + '.localScaleZ', 0.089) cmds.setAttr(handle['shape'] + '.ds', 5) nodeHandles.append(handle) # If there's more than one node, create orientation/hierarchy representations for all joints, except for # the end joint. Also unparent the individual joints in the oriented joint chain to the joint group. This # is needed only if there are more than one joint in the template; then the unparenting will begin from the # second joint, since the first (start) is already under joints group. if len(self.nodeList) > 1: for handle in nodeHandles[1:]: cmds.parent(handle['preTransform'], self.templateNodesGrp, absolute=True) self.createOrientationHierarchyReprOnNodes() # Clear selection. cmds.select(clear=True) # If the template contains only one node then delete the handle segment and orientation/hierarchy # representation groups, since they're not needed. if self.numNodes == 1: cmds.delete([self.templateHandleSegmentGrp, self.templateOrientationHierarchyReprGrp]) # Create template parenting representation objects. self.createHierarchySegmentForTemplateParentingRepr() # Create the proxy geometry for the template if it is enabled. if self.proxyGeoStatus: if self.proxyGeoElbow: self.createProxyGeo_elbows(self.proxyElbowType) if self.proxyGeoBones: self.createProxyGeo_bones() # Add the template group to the collected nodes list. self.collectedNodes.append(self.groupNode) # Add the collected nodes to the template container. mfunc.addNodesToContainer(self.templateContainer, self.collectedNodes, includeHierarchyBelow=True, includeShapes=True) # Publish contents to the container. # Publish the orientation representation control for template nodes. for joint in self.nodeList: jointName = mfunc.stripMRTNamespace(joint)[1] # Nice name for the joint, used as published name. cmds.container(self.templateContainer, edit=True, publishAndBind=[joint + '.translate', jointName + '_translate']) if joint != self.nodeList[-1]: jointOrientationRepr = joint + '_orient_repr_transform' jointOrientationRotateAxis = self.aimAxis[0] jointOrientationReprName = mfunc.stripMRTNamespace(jointOrientationRepr)[1] cmds.container(self.templateContainer, edit=True, publishAndBind=[jointOrientationRepr + '.rotate' + jointOrientationRotateAxis, jointOrientationReprName + '_rotate' + jointOrientationRotateAxis]) # Publish the attributes for the template transform. templateTransformName = mfunc.stripMRTNamespace(self.templateTransform)[1] cmds.container(self.templateContainer, edit=True, publishAndBind=[self.templateTransform + '.translate', templateTransformName + '_translate']) cmds.container(self.templateContainer, edit=True, publishAndBind=[self.templateTransform + '.rotate', templateTransformName + '_rotate']) cmds.container(self.templateContainer, edit=True, publishAndBind=[self.templateTransform + '.glzobalScale', templateTransformName + '_globalScale']) cmds.container(self.templateContainer, edit=True, publishAndBind=[self.templateTransform + '.scaleFactor', templateTransformName + '_scaleFactor']) # If the template contains only single node, publish its orientation control. if len(self.nodeList) == 1: singleOrientationTransform = self.templateTypespace + ':single_orient_repr_transform' cmds.container(self.templateContainer, edit=True, publishAndBind=[singleOrientationTransform + '.rotate', 'single_orient_repr_transform_rotate']) # Add and publish custom attributes on the template transform. self.addCustomAttributesOnTemplateTransform() # Connect template orientation representation objects to drive # orientation for template proxy geometry. if self.numNodes > 1: self.connectCustomOrientationReprToTemplateProxies() # Set the template pre-scale factor. This is used for adjusting the initial size of the template. cmds.setAttr(self.templateTransform + '.scaleFactor', 30)